@cadenza.io/service 2.20.0 → 2.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -39,15 +39,15 @@ __export(src_exports, {
39
39
  AUTHORITY_SERVICE_INSTANCE_TRANSPORT_REGISTER_TASK_NAME: () => AUTHORITY_SERVICE_INSTANCE_TRANSPORT_REGISTER_TASK_NAME,
40
40
  AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT: () => AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT,
41
41
  AUTHORITY_SERVICE_MANIFEST_UPDATED_SIGNAL: () => AUTHORITY_SERVICE_MANIFEST_UPDATED_SIGNAL,
42
- Actor: () => import_core6.Actor,
42
+ Actor: () => import_core7.Actor,
43
43
  DatabaseController: () => DatabaseController,
44
44
  DatabaseTask: () => DatabaseTask,
45
- DebounceTask: () => import_core6.DebounceTask,
45
+ DebounceTask: () => import_core7.DebounceTask,
46
46
  DeputyTask: () => DeputyTask,
47
47
  EXECUTION_PERSISTENCE_BUNDLE_SIGNAL: () => EXECUTION_PERSISTENCE_BUNDLE_SIGNAL,
48
- EphemeralTask: () => import_core6.EphemeralTask,
48
+ EphemeralTask: () => import_core7.EphemeralTask,
49
49
  GraphMetadataController: () => GraphMetadataController,
50
- GraphRoutine: () => import_core6.GraphRoutine,
50
+ GraphRoutine: () => import_core7.GraphRoutine,
51
51
  RUNTIME_STATUS_AUTHORITY_SYNC_REQUESTED_SIGNAL: () => RUNTIME_STATUS_AUTHORITY_SYNC_REQUESTED_SIGNAL,
52
52
  RUNTIME_VALIDATION_INTENTS: () => RUNTIME_VALIDATION_INTENTS,
53
53
  RUNTIME_VALIDATION_SIGNALS: () => RUNTIME_VALIDATION_SIGNALS,
@@ -56,7 +56,7 @@ __export(src_exports, {
56
56
  SignalController: () => SignalController,
57
57
  SignalTransmissionTask: () => SignalTransmissionTask,
58
58
  SocketController: () => SocketController,
59
- Task: () => import_core6.Task,
59
+ Task: () => import_core7.Task,
60
60
  buildAuthorityRuntimeStatusSignature: () => buildAuthorityRuntimeStatusSignature,
61
61
  buildExecutionPersistenceDependency: () => buildExecutionPersistenceDependency,
62
62
  buildExecutionPersistenceEnsureEvent: () => buildExecutionPersistenceEnsureEvent,
@@ -87,7 +87,7 @@ __export(src_exports, {
87
87
  module.exports = __toCommonJS(src_exports);
88
88
 
89
89
  // src/Cadenza.ts
90
- var import_core5 = __toESM(require("@cadenza.io/core"));
90
+ var import_core6 = __toESM(require("@cadenza.io/core"));
91
91
 
92
92
  // src/graph/definition/DeputyTask.ts
93
93
  var import_uuid2 = require("uuid");
@@ -105,6 +105,30 @@ var LOCAL_ROUTINE_PERSISTENCE_KEYS = [
105
105
  "__routineCreatedAt",
106
106
  "__routineIsMeta"
107
107
  ];
108
+ var BULKY_EXECUTION_PERSISTENCE_KEYS = [
109
+ "rows",
110
+ "joinedContexts",
111
+ "serviceInstances",
112
+ "serviceInstanceLeases",
113
+ "serviceInstanceTransports",
114
+ "serviceManifests",
115
+ "tasks",
116
+ "helpers",
117
+ "globals",
118
+ "signals",
119
+ "intents",
120
+ "actors",
121
+ "routines",
122
+ "directionalTaskMaps",
123
+ "actorTaskMaps",
124
+ "taskToRoutineMaps",
125
+ "taskToHelperMaps",
126
+ "helperToHelperMaps",
127
+ "taskToGlobalMaps",
128
+ "helperToGlobalMaps",
129
+ "signalToTaskMaps",
130
+ "intentToTaskMaps"
131
+ ];
108
132
  function readHintValue(source, key) {
109
133
  if (!source || typeof source !== "object") {
110
134
  return void 0;
@@ -131,8 +155,80 @@ function stripLocalRoutinePersistenceHints(input) {
131
155
  }
132
156
  return context;
133
157
  }
158
+ function summarizeQueryData(queryData) {
159
+ if (!queryData || typeof queryData !== "object") {
160
+ return void 0;
161
+ }
162
+ const summary = {};
163
+ if (queryData.data && typeof queryData.data === "object") {
164
+ summary.dataKeys = Object.keys(queryData.data).sort();
165
+ }
166
+ if (queryData.filter && typeof queryData.filter === "object") {
167
+ summary.filterKeys = Object.keys(queryData.filter).sort();
168
+ }
169
+ if (queryData.onConflict && typeof queryData.onConflict === "object") {
170
+ const onConflict = queryData.onConflict;
171
+ summary.onConflictTarget = Array.isArray(onConflict.target) ? [...onConflict.target] : onConflict.target ?? null;
172
+ }
173
+ return Object.keys(summary).length > 0 ? summary : void 0;
174
+ }
175
+ function sanitizeExecutionPersistenceContext(input) {
176
+ const context = stripLocalRoutinePersistenceHints(input);
177
+ for (const key of BULKY_EXECUTION_PERSISTENCE_KEYS) {
178
+ const value = context[key];
179
+ if (value === void 0) {
180
+ continue;
181
+ }
182
+ const countKey = `${key}Count`;
183
+ if (context[countKey] === void 0) {
184
+ if (Array.isArray(value)) {
185
+ context[countKey] = value.length;
186
+ } else if (value && typeof value === "object") {
187
+ context[countKey] = Object.keys(value).length;
188
+ }
189
+ }
190
+ delete context[key];
191
+ }
192
+ if (context.queryData && typeof context.queryData === "object") {
193
+ const queryDataSummary = summarizeQueryData(context.queryData);
194
+ if (queryDataSummary) {
195
+ context.queryData = queryDataSummary;
196
+ } else {
197
+ delete context.queryData;
198
+ }
199
+ }
200
+ return context;
201
+ }
202
+ function sanitizeExecutionPersistenceResultPayload(input) {
203
+ const payload = input && typeof input === "object" ? { ...input } : {};
204
+ const resultContext = payload.resultContext && typeof payload.resultContext === "object" ? sanitizeExecutionPersistenceContext(
205
+ payload.resultContext
206
+ ) : payload.resultContext;
207
+ const metaResultContext = payload.metaResultContext && typeof payload.metaResultContext === "object" ? sanitizeExecutionPersistenceContext(
208
+ payload.metaResultContext
209
+ ) : payload.metaResultContext;
210
+ const snakeResultContext = payload.result_context && typeof payload.result_context === "object" ? sanitizeExecutionPersistenceContext(
211
+ payload.result_context
212
+ ) : payload.result_context;
213
+ const snakeMetaResultContext = payload.meta_result_context && typeof payload.meta_result_context === "object" ? sanitizeExecutionPersistenceContext(
214
+ payload.meta_result_context
215
+ ) : payload.meta_result_context;
216
+ if (resultContext !== void 0) {
217
+ payload.resultContext = resultContext;
218
+ }
219
+ if (metaResultContext !== void 0) {
220
+ payload.metaResultContext = metaResultContext;
221
+ }
222
+ if (snakeResultContext !== void 0) {
223
+ payload.result_context = snakeResultContext;
224
+ }
225
+ if (snakeMetaResultContext !== void 0) {
226
+ payload.meta_result_context = snakeMetaResultContext;
227
+ }
228
+ return payload;
229
+ }
134
230
  function splitRoutinePersistenceContext(input) {
135
- const sanitized = stripLocalRoutinePersistenceHints(input);
231
+ const sanitized = sanitizeExecutionPersistenceContext(input);
136
232
  return {
137
233
  context: Object.fromEntries(
138
234
  Object.entries(sanitized).filter(([key]) => !key.startsWith("__"))
@@ -163,14 +259,55 @@ var ROOT_METADATA_PASSTHROUGH_KEYS = [
163
259
  "__inquirySourceRoutineExecutionId"
164
260
  ];
165
261
  var DELEGATION_REQUEST_SNAPSHOT_KEY = "__delegationRequestContext";
262
+ var DELEGATION_FAILURE_CONTEXT_KEYS = [
263
+ "__remoteRoutineName",
264
+ "__serviceName",
265
+ "__timeout",
266
+ "__localTaskName",
267
+ "__localTaskVersion",
268
+ "__localServiceName",
269
+ "__localRoutineExecId",
270
+ "__previousTaskExecutionId",
271
+ "__fetchId",
272
+ "fetchId",
273
+ "__routeKey",
274
+ "routeKey",
275
+ "__instance",
276
+ "__transportId",
277
+ "__transportOrigin",
278
+ "__transportProtocols",
279
+ "__transportProtocol",
280
+ "__retries",
281
+ "__triedInstances",
282
+ "__delegationRequestContext",
283
+ "__metadata",
284
+ "serviceName",
285
+ "serviceInstanceId",
286
+ "serviceTransportId",
287
+ "serviceOrigin",
288
+ "transportProtocols",
289
+ "transportProtocol"
290
+ ];
291
+ function isPlainObject(value) {
292
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
293
+ return false;
294
+ }
295
+ const prototype = Object.getPrototypeOf(value);
296
+ return prototype === Object.prototype || prototype === null;
297
+ }
166
298
  function cloneDelegationValue(value) {
299
+ if (value instanceof Date) {
300
+ return new Date(value.getTime());
301
+ }
167
302
  if (Array.isArray(value)) {
168
- return value.map(
169
- (item) => item && typeof item === "object" ? { ...item } : item
170
- );
303
+ return value.map((item) => cloneDelegationValue(item));
171
304
  }
172
- if (value && typeof value === "object") {
173
- return { ...value };
305
+ if (isPlainObject(value)) {
306
+ const clone = {};
307
+ for (const [key, nestedValue] of Object.entries(value)) {
308
+ clone[key] = cloneDelegationValue(nestedValue);
309
+ }
310
+ return clone;
174
311
  }
175
312
  return value;
176
313
  }
@@ -206,9 +343,9 @@ function attachDelegationRequestSnapshot(input) {
206
343
  function restoreDelegationRequestSnapshot(input) {
207
344
  const context = input && typeof input === "object" ? { ...input } : {};
208
345
  const mutableContext = context;
209
- const snapshotCandidate = mutableContext[DELEGATION_REQUEST_SNAPSHOT_KEY];
346
+ const snapshotCandidate = mutableContext[DELEGATION_REQUEST_SNAPSHOT_KEY] ?? (mutableContext.__metadata && typeof mutableContext.__metadata === "object" ? mutableContext.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY] : void 0);
210
347
  const snapshot = snapshotCandidate && typeof snapshotCandidate === "object" ? snapshotCandidate : null;
211
- const looksLikeDelegationResult = mutableContext.__status !== void 0 || mutableContext.__success !== void 0 || mutableContext.rowCount !== void 0 || mutableContext.__nextNodes !== void 0 || mutableContext.__isDeputy === true;
348
+ const looksLikeDelegationResult = mutableContext.__status !== void 0 || mutableContext.__success !== void 0 || mutableContext.rowCount !== void 0 || mutableContext.__nextNodes !== void 0 || mutableContext.__isDeputy === true || mutableContext.errored === true || mutableContext.failed === true || mutableContext.timedOut === true || mutableContext.__error !== void 0 || mutableContext.error !== void 0 || mutableContext.__inquiryMeta !== void 0;
212
349
  if (!snapshot || !looksLikeDelegationResult) {
213
350
  return context;
214
351
  }
@@ -229,6 +366,26 @@ function stripDelegationRequestSnapshot(input) {
229
366
  delete context[DELEGATION_REQUEST_SNAPSHOT_KEY];
230
367
  return context;
231
368
  }
369
+ function buildDelegationFailureContext(signalName, input, error) {
370
+ const source = input && typeof input === "object" ? { ...input } : {};
371
+ const slimContext = {};
372
+ for (const key of DELEGATION_FAILURE_CONTEXT_KEYS) {
373
+ if (source[key] !== void 0) {
374
+ slimContext[key] = cloneDelegationValue(source[key]);
375
+ }
376
+ }
377
+ if (slimContext[DELEGATION_REQUEST_SNAPSHOT_KEY] === void 0 && source.__metadata && typeof source.__metadata === "object" && source.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY] !== void 0) {
378
+ slimContext[DELEGATION_REQUEST_SNAPSHOT_KEY] = cloneDelegationValue(
379
+ source.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY]
380
+ );
381
+ }
382
+ return {
383
+ __signalName: signalName,
384
+ __error: error instanceof Error ? error.message : String(error ?? "Unknown error"),
385
+ errored: true,
386
+ ...slimContext
387
+ };
388
+ }
232
389
  function stripTransportSelectionRoutingContext(input) {
233
390
  const context = stripLocalRoutinePersistenceHints(
234
391
  input && typeof input === "object" ? { ...input } : {}
@@ -260,6 +417,90 @@ function ensureDelegationContextMetadata(input) {
260
417
 
261
418
  // src/graph/definition/DeputyTask.ts
262
419
  var SERVICE_REGISTRY_TRACE_SERVICE = (process.env.CADENZA_SERVICE_REGISTRY_TRACE_SERVICE ?? "").trim();
420
+ function deputyTaskExecutor(context, emit2, inquire, _tools, progressCallback) {
421
+ const task = this;
422
+ return new Promise((resolve, reject) => {
423
+ if (context.__metadata.__blockRemoteExecution) {
424
+ reject(new Error("Blocked remote execution"));
425
+ return;
426
+ }
427
+ if (context.__metadata.__skipRemoteExecution) {
428
+ resolve(context);
429
+ return;
430
+ }
431
+ const processId = (0, import_uuid2.v4)();
432
+ context.__metadata.__deputyExecId = processId;
433
+ if ((process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") && context.__remoteRoutineName === "Insert service_instance") {
434
+ console.log("[CADENZA_INSTANCE_DEBUG] deputy_delegation_requested", {
435
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
436
+ localTaskName: context.__localTaskName ?? null,
437
+ remoteRoutineName: context.__remoteRoutineName ?? null,
438
+ targetServiceName: context.__serviceName ?? null,
439
+ deputyExecId: processId,
440
+ dataKeys: context.data && typeof context.data === "object" ? Object.keys(context.data) : [],
441
+ queryDataKeys: context.queryData && typeof context.queryData === "object" ? Object.keys(context.queryData) : [],
442
+ queryDataDataKeys: context.queryData?.data && typeof context.queryData.data === "object" ? Object.keys(context.queryData.data) : []
443
+ });
444
+ }
445
+ emit2("meta.deputy.delegation_requested", {
446
+ ...context
447
+ });
448
+ CadenzaService.createEphemeralMetaTask(
449
+ `On progress deputy ${task.remoteRoutineName}`,
450
+ (ctx) => {
451
+ if (typeof progressCallback === "function" && ctx.progress) {
452
+ progressCallback(ctx.progress * ctx.weight);
453
+ }
454
+ },
455
+ `Ephemeral task for deputy process ${processId}`,
456
+ {
457
+ once: false,
458
+ destroyCondition: (ctx) => ctx.progress === 1 || ctx.progress === void 0,
459
+ register: false
460
+ }
461
+ ).doOn(
462
+ `meta.socket_client.delegation_progress:${processId}`,
463
+ `meta.socket_client.delegated:${processId}`,
464
+ `meta.fetch.delegated:${processId}`,
465
+ `meta.service_registry.load_balance_failed:${processId}`
466
+ );
467
+ CadenzaService.createEphemeralMetaTask(
468
+ `Resolve deputy ${task.remoteRoutineName}`,
469
+ (responseCtx) => {
470
+ const mergedResponseCtx = responseCtx && typeof responseCtx === "object" ? {
471
+ ...context,
472
+ ...responseCtx
473
+ } : responseCtx;
474
+ if (responseCtx?.errored) {
475
+ reject(new Error(responseCtx.__error));
476
+ } else {
477
+ if (SERVICE_REGISTRY_TRACE_SERVICE.length > 0 && CadenzaService.serviceRegistry.serviceName === SERVICE_REGISTRY_TRACE_SERVICE && context.__remoteRoutineName === "Insert service_instance") {
478
+ console.log(
479
+ "[CADENZA_SERVICE_REGISTRY_TRACE] deputy_insert_service_instance_resolved",
480
+ {
481
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
482
+ targetServiceName: context.__serviceName ?? null,
483
+ resolverRequestId: context.__resolverRequestId ?? null,
484
+ serviceInstanceId: mergedResponseCtx && typeof mergedResponseCtx === "object" ? mergedResponseCtx.__serviceInstanceId ?? mergedResponseCtx.uuid ?? mergedResponseCtx.data?.uuid ?? null : null,
485
+ hasResolverQueryData: mergedResponseCtx && typeof mergedResponseCtx === "object" && mergedResponseCtx.__resolverQueryData !== void 0
486
+ }
487
+ );
488
+ }
489
+ if (mergedResponseCtx && typeof mergedResponseCtx === "object") {
490
+ delete mergedResponseCtx.__isDeputy;
491
+ }
492
+ resolve(mergedResponseCtx);
493
+ }
494
+ },
495
+ `Ephemeral resolver for deputy process ${processId}`,
496
+ { register: false }
497
+ ).doOn(
498
+ `meta.socket_client.delegated:${processId}`,
499
+ `meta.fetch.delegated:${processId}`,
500
+ `meta.service_registry.load_balance_failed:${processId}`
501
+ );
502
+ });
503
+ }
263
504
  var DeputyTask = class extends import_core.Task {
264
505
  /**
265
506
  * Constructs a new instance of the class with the specified parameters.
@@ -287,87 +528,9 @@ var DeputyTask = class extends import_core.Task {
287
528
  * @return {void} This constructor does not return a value.
288
529
  */
289
530
  constructor(name, remoteRoutineName, serviceName = void 0, description = "", concurrency = 0, timeout = 0, register = true, isUnique = false, isMeta = false, isSubMeta = false, isHidden = false, getTagCallback = void 0, inputSchema = void 0, validateInputContext = false, outputSchema = void 0, validateOutputContext = false, retryCount = 0, retryDelay = 0, retryDelayMax = 0, retryDelayFactor = 1) {
290
- const taskFunction = (context, emit2, inquire, progressCallback) => {
291
- return new Promise((resolve, reject) => {
292
- if (context.__metadata.__blockRemoteExecution) {
293
- reject(new Error("Blocked remote execution"));
294
- return;
295
- }
296
- if (context.__metadata.__skipRemoteExecution) {
297
- resolve(context);
298
- return;
299
- }
300
- const processId = (0, import_uuid2.v4)();
301
- context.__metadata.__deputyExecId = processId;
302
- if ((process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") && context.__remoteRoutineName === "Insert service_instance") {
303
- console.log("[CADENZA_INSTANCE_DEBUG] deputy_delegation_requested", {
304
- localServiceName: CadenzaService.serviceRegistry.serviceName,
305
- localTaskName: context.__localTaskName ?? null,
306
- remoteRoutineName: context.__remoteRoutineName ?? null,
307
- targetServiceName: context.__serviceName ?? null,
308
- deputyExecId: processId,
309
- dataKeys: context.data && typeof context.data === "object" ? Object.keys(context.data) : [],
310
- queryDataKeys: context.queryData && typeof context.queryData === "object" ? Object.keys(context.queryData) : [],
311
- queryDataDataKeys: context.queryData?.data && typeof context.queryData.data === "object" ? Object.keys(context.queryData.data) : []
312
- });
313
- }
314
- emit2("meta.deputy.delegation_requested", {
315
- ...context
316
- });
317
- CadenzaService.createEphemeralMetaTask(
318
- `On progress deputy ${this.remoteRoutineName}`,
319
- (ctx) => {
320
- if (ctx.progress) progressCallback(ctx.progress * ctx.weight);
321
- },
322
- `Ephemeral task for deputy process ${processId}`,
323
- {
324
- once: false,
325
- destroyCondition: (ctx) => ctx.progress === 1 || ctx.progress === void 0,
326
- register: false
327
- }
328
- ).doOn(
329
- `meta.socket_client.delegation_progress:${processId}`,
330
- `meta.socket_client.delegated:${processId}`,
331
- `meta.fetch.delegated:${processId}`,
332
- `meta.service_registry.load_balance_failed:${processId}`
333
- );
334
- CadenzaService.createEphemeralMetaTask(
335
- `Resolve deputy ${this.remoteRoutineName}`,
336
- (responseCtx) => {
337
- const mergedResponseCtx = responseCtx && typeof responseCtx === "object" ? {
338
- ...context,
339
- ...responseCtx
340
- } : responseCtx;
341
- if (responseCtx?.errored) {
342
- reject(new Error(responseCtx.__error));
343
- } else {
344
- if (SERVICE_REGISTRY_TRACE_SERVICE.length > 0 && CadenzaService.serviceRegistry.serviceName === SERVICE_REGISTRY_TRACE_SERVICE && context.__remoteRoutineName === "Insert service_instance") {
345
- console.log("[CADENZA_SERVICE_REGISTRY_TRACE] deputy_insert_service_instance_resolved", {
346
- localServiceName: CadenzaService.serviceRegistry.serviceName,
347
- targetServiceName: context.__serviceName ?? null,
348
- resolverRequestId: context.__resolverRequestId ?? null,
349
- serviceInstanceId: mergedResponseCtx && typeof mergedResponseCtx === "object" ? mergedResponseCtx.__serviceInstanceId ?? mergedResponseCtx.uuid ?? mergedResponseCtx.data?.uuid ?? null : null,
350
- hasResolverQueryData: mergedResponseCtx && typeof mergedResponseCtx === "object" && mergedResponseCtx.__resolverQueryData !== void 0
351
- });
352
- }
353
- if (mergedResponseCtx && typeof mergedResponseCtx === "object") {
354
- delete mergedResponseCtx.__isDeputy;
355
- }
356
- resolve(mergedResponseCtx);
357
- }
358
- },
359
- `Ephemeral resolver for deputy process ${processId}`,
360
- { register: false }
361
- ).doOn(
362
- `meta.socket_client.delegated:${processId}`,
363
- `meta.fetch.delegated:${processId}`,
364
- `meta.service_registry.load_balance_failed:${processId}`
365
- );
366
- });
367
- };
368
531
  super(
369
532
  name,
370
- taskFunction,
533
+ deputyTaskExecutor,
371
534
  description,
372
535
  concurrency,
373
536
  timeout,
@@ -399,6 +562,11 @@ var DeputyTask = class extends import_core.Task {
399
562
  communicationType: "delegation"
400
563
  });
401
564
  }
565
+ clone() {
566
+ throw new Error(
567
+ `DeputyTask '${this.name}' does not support clone(). Create a new named deputy task or use a flow-specific meta task that performs an inquiry instead.`
568
+ );
569
+ }
402
570
  /**
403
571
  * Executes the specified task function within the provided execution context.
404
572
  *
@@ -442,12 +610,32 @@ var DeputyTask = class extends import_core.Task {
442
610
  })
443
611
  )
444
612
  );
445
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
613
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
614
+ this,
615
+ deputyContext,
616
+ emit2,
617
+ inquire,
618
+ progressCallback
619
+ ) : {
620
+ helpers: {},
621
+ globals: {}
622
+ };
623
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
624
+ };
625
+ return this.taskFunction(
626
+ deputyContext,
627
+ emit2,
628
+ inquire,
629
+ resolvedTools,
630
+ resolvedProgressCallback
631
+ );
446
632
  }
447
633
  };
448
634
 
449
635
  // src/graph/definition/DatabaseTask.ts
450
636
  var ACTOR_SESSION_TRACE_ENABLED = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
637
+ var actorSessionEmptyDelegationLogCount = 0;
638
+ var ACTOR_SESSION_EMPTY_DELEGATION_LOG_LIMIT = 40;
451
639
  var INSTANCE_TRACE_ENABLED = process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true";
452
640
  var EXECUTION_OBSERVABILITY_INSERT_ROUTINES = /* @__PURE__ */ new Set([
453
641
  "Insert execution_trace",
@@ -509,6 +697,11 @@ var DatabaseTask = class extends DeputyTask {
509
697
  );
510
698
  this.queryData = queryData;
511
699
  }
700
+ clone() {
701
+ throw new Error(
702
+ `DatabaseTask '${this.name}' does not support clone(). Create a new named database task or use a flow-specific meta task that performs the default database inquiry instead.`
703
+ );
704
+ }
512
705
  /**
513
706
  * Executes the specified task within the given context.
514
707
  *
@@ -549,15 +742,16 @@ var DatabaseTask = class extends DeputyTask {
549
742
  }
550
743
  delete ctx.__metadata;
551
744
  const isResolverExecution = typeof ctx.__resolverRequestId === "string" && ctx.__resolverRequestId.length > 0;
552
- const dynamicQueryData = isResolverExecution ? {} : ctx.__resolverQueryData && typeof ctx.__resolverQueryData === "object" ? ctx.__resolverQueryData : ctx.queryData ?? {};
745
+ const resolverQueryData = ctx.__resolverQueryData && typeof ctx.__resolverQueryData === "object" ? ctx.__resolverQueryData : null;
746
+ const dynamicQueryData = resolverQueryData ?? (ctx.queryData && typeof ctx.queryData === "object" ? ctx.queryData : {});
553
747
  delete ctx.queryData;
554
748
  const nextQueryData = {
555
749
  ...this.queryData,
556
- data: {
557
- ...ctx.data
558
- },
559
750
  ...dynamicQueryData
560
751
  };
752
+ if (dynamicQueryData.data === void 0 && ctx.data !== void 0) {
753
+ nextQueryData.data = ctx.data && typeof ctx.data === "object" && !Array.isArray(ctx.data) ? { ...ctx.data } : ctx.data;
754
+ }
561
755
  const deputyContext = attachDelegationRequestSnapshot(
562
756
  stripDelegationRequestSnapshot(
563
757
  hoistDelegationMetadataFields({
@@ -617,7 +811,41 @@ var DatabaseTask = class extends DeputyTask {
617
811
  rootKeys: Object.keys(rawContext)
618
812
  });
619
813
  }
620
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
814
+ if (this.remoteRoutineName === "Insert actor_session_state" && deputyContext.data === void 0 && deputyContext.queryData === void 0 && actorSessionEmptyDelegationLogCount < ACTOR_SESSION_EMPTY_DELEGATION_LOG_LIMIT) {
815
+ actorSessionEmptyDelegationLogCount += 1;
816
+ console.warn("[CADENZA_ACTOR_SESSION_EMPTY_DELEGATION]", {
817
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
818
+ localTaskName: this.name,
819
+ remoteRoutineName: this.remoteRoutineName,
820
+ hadSnapshotBeforeRestore: initialFullContext.__delegationRequestContext !== void 0 || initialFullContext.__metadata?.__delegationRequestContext !== void 0,
821
+ restoredRootKeys: Object.keys(rawContext),
822
+ deputyRootKeys: Object.keys(deputyContext),
823
+ signalName: rawContext.__signalName ?? rawContext.__metadata?.__signalName ?? null,
824
+ inquiryName: rawContext.__inquiryName ?? rawContext.__metadata?.__inquiryName ?? null,
825
+ sourceServiceName: rawContext.__localServiceName ?? rawContext.__metadata?.__localServiceName ?? null,
826
+ sourceRoutineName: rawContext.__routineName ?? rawContext.__metadata?.__routineName ?? null,
827
+ sourceTaskName: rawContext.__localTaskName ?? rawContext.__metadata?.__localTaskName ?? null
828
+ });
829
+ }
830
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
831
+ this,
832
+ deputyContext,
833
+ emit2,
834
+ inquire,
835
+ progressCallback
836
+ ) : {
837
+ helpers: {},
838
+ globals: {}
839
+ };
840
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
841
+ };
842
+ return this.taskFunction(
843
+ deputyContext,
844
+ emit2,
845
+ inquire,
846
+ resolvedTools,
847
+ resolvedProgressCallback
848
+ );
621
849
  }
622
850
  };
623
851
 
@@ -662,6 +890,26 @@ var AUTHORITY_SYNC_DEBUG_TASK_NAMES = /* @__PURE__ */ new Set([
662
890
  ]);
663
891
  var AUTHORITY_SYNC_DEBUG_ROUTINE_NAMES = /* @__PURE__ */ new Set(["Sync services"]);
664
892
  var INTENT_MAP_DEBUG_ENABLED = process.env.CADENZA_INTENT_MAP_DEBUG === "1" || process.env.CADENZA_INTENT_MAP_DEBUG === "true";
893
+ function normalizeQueryResultValue(value) {
894
+ if (value instanceof Date) {
895
+ return value.toISOString();
896
+ }
897
+ if (Array.isArray(value)) {
898
+ return value.map((entry) => normalizeQueryResultValue(entry));
899
+ }
900
+ if (value && typeof value === "object") {
901
+ const prototype = Object.getPrototypeOf(value);
902
+ if (prototype === Object.prototype || prototype === null) {
903
+ return Object.fromEntries(
904
+ Object.entries(value).map(([key, nestedValue]) => [
905
+ key,
906
+ normalizeQueryResultValue(nestedValue)
907
+ ])
908
+ );
909
+ }
910
+ }
911
+ return value;
912
+ }
665
913
  var POSTGRES_SETUP_DEBUG_ENABLED = process.env.CADENZA_POSTGRES_SETUP_DEBUG === "1" || process.env.CADENZA_POSTGRES_SETUP_DEBUG === "true";
666
914
  var ACTOR_SESSION_TRACE_ENABLED2 = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
667
915
  var ACTOR_SESSION_TRACE_LIMIT = 20;
@@ -959,14 +1207,14 @@ function errorMessage(error) {
959
1207
  }
960
1208
  return String(error);
961
1209
  }
962
- function isPlainObject(value) {
1210
+ function isPlainObject2(value) {
963
1211
  return typeof value === "object" && value !== null && !Array.isArray(value);
964
1212
  }
965
1213
  function stableStringify(value) {
966
1214
  if (Array.isArray(value)) {
967
1215
  return `[${value.map((item) => stableStringify(item)).join(",")}]`;
968
1216
  }
969
- if (isPlainObject(value)) {
1217
+ if (isPlainObject2(value)) {
970
1218
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
971
1219
  }
972
1220
  return JSON.stringify(value);
@@ -1082,7 +1330,23 @@ function resolveGeneratedTaskTag(tableName, actorToken, context, operation) {
1082
1330
  if (operation === "insert") {
1083
1331
  return `insert:${actorToken}:${tableName}`;
1084
1332
  }
1085
- return context?.__metadata?.__executionTraceId ?? context?.__executionTraceId ?? "default";
1333
+ const traceScopedTag = context?.__metadata?.__executionTraceId ?? context?.__executionTraceId ?? context?.__metadata?.__deputyExecId ?? context?.__deputyExecId ?? context?.__metadata?.__inquiryId ?? context?.__inquiryId ?? context?.__metadata?.__routineExecId ?? context?.__routineExecId ?? context?.__metadata?.__localRoutineExecId ?? context?.__localRoutineExecId;
1334
+ if (typeof traceScopedTag === "string" && traceScopedTag.length > 0) {
1335
+ return traceScopedTag;
1336
+ }
1337
+ const queryScope = {
1338
+ queryData: context?.queryData,
1339
+ filter: context?.filter,
1340
+ fields: context?.fields,
1341
+ joins: context?.joins,
1342
+ sort: context?.sort,
1343
+ limit: context?.limit,
1344
+ offset: context?.offset,
1345
+ queryMode: context?.queryMode,
1346
+ aggregates: context?.aggregates,
1347
+ groupBy: context?.groupBy
1348
+ };
1349
+ return `read:${actorToken}:${tableName}:${stableStringify(queryScope)}`;
1086
1350
  }
1087
1351
  function resolveExecutionObservabilitySafetyPolicyForTable(basePolicy, tableName) {
1088
1352
  if (!EXECUTION_OBSERVABILITY_TABLES.has(tableName)) {
@@ -1164,6 +1428,44 @@ function mergeTriggerQueryData(context, triggerQueryData) {
1164
1428
  ...triggerQueryData
1165
1429
  };
1166
1430
  }
1431
+ function isNonEmptyPlainObject(value) {
1432
+ return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0;
1433
+ }
1434
+ function isMissingInsertData(data) {
1435
+ return !data || Array.isArray(data) && data.length === 0 || typeof data === "object" && !Array.isArray(data) && Object.keys(data).length === 0;
1436
+ }
1437
+ function resolveActorSessionDelegationSnapshot(context) {
1438
+ const direct = context.__delegationRequestContext && typeof context.__delegationRequestContext === "object" ? context.__delegationRequestContext : null;
1439
+ if (direct) {
1440
+ return direct;
1441
+ }
1442
+ const metadata = context.__metadata && typeof context.__metadata === "object" ? context.__metadata : null;
1443
+ const nested = metadata?.__delegationRequestContext && typeof metadata.__delegationRequestContext === "object" ? metadata.__delegationRequestContext : null;
1444
+ return nested;
1445
+ }
1446
+ function recoverActorSessionInsertPayload(context, payload) {
1447
+ if (!isMissingInsertData(payload.data)) {
1448
+ return payload;
1449
+ }
1450
+ const snapshot = resolveActorSessionDelegationSnapshot(context);
1451
+ if (!snapshot) {
1452
+ return payload;
1453
+ }
1454
+ const snapshotQueryData = snapshot.queryData && typeof snapshot.queryData === "object" ? { ...snapshot.queryData } : {};
1455
+ const snapshotData = isNonEmptyPlainObject(snapshotQueryData.data) ? snapshotQueryData.data : isNonEmptyPlainObject(snapshot.data) ? snapshot.data : null;
1456
+ if (!snapshotData) {
1457
+ return payload;
1458
+ }
1459
+ const recoveredPayload = {
1460
+ ...snapshotQueryData,
1461
+ ...payload,
1462
+ data: snapshotData
1463
+ };
1464
+ if (recoveredPayload.onConflict === void 0 && snapshotQueryData.onConflict) {
1465
+ recoveredPayload.onConflict = snapshotQueryData.onConflict;
1466
+ }
1467
+ return recoveredPayload;
1468
+ }
1167
1469
  function resolveOperationPayload(context) {
1168
1470
  const queryData = typeof context.queryData === "object" && context.queryData ? context.queryData : {};
1169
1471
  return mergeTriggerQueryData(context, queryData);
@@ -1891,6 +2193,23 @@ var DatabaseController = class _DatabaseController {
1891
2193
  async insertFunction(registration, tableName, context) {
1892
2194
  const { data, transaction = true, fields = [], onConflict } = context;
1893
2195
  if (!data || Array.isArray(data) && data.length === 0) {
2196
+ if (tableName === "actor_session_state") {
2197
+ const rawContext = context;
2198
+ const rawMetadata = rawContext.__metadata && typeof rawContext.__metadata === "object" ? rawContext.__metadata : void 0;
2199
+ console.warn("[CADENZA_ACTOR_SESSION_EMPTY_INSERT]", {
2200
+ tableName,
2201
+ contextKeys: Object.keys(context ?? {}),
2202
+ queryDataKeys: [],
2203
+ hasDelegationSnapshot: rawContext.__delegationRequestContext !== void 0 || rawMetadata?.__delegationRequestContext !== void 0,
2204
+ localTaskName: typeof rawContext.__localTaskName === "string" ? rawContext.__localTaskName : void 0,
2205
+ remoteRoutineName: typeof rawContext.__remoteRoutineName === "string" ? rawContext.__remoteRoutineName : void 0,
2206
+ serviceName: typeof rawContext.__serviceName === "string" ? rawContext.__serviceName : void 0,
2207
+ actorName: typeof rawContext.actor_name === "string" ? rawContext.actor_name : void 0,
2208
+ actorKey: typeof rawContext.actor_key === "string" ? rawContext.actor_key : void 0,
2209
+ durableVersion: rawContext.durable_version,
2210
+ metadata: rawMetadata
2211
+ });
2212
+ }
1894
2213
  return {
1895
2214
  rowCount: 0,
1896
2215
  errored: true,
@@ -2960,9 +3279,18 @@ var DatabaseController = class _DatabaseController {
2960
3279
  }
2961
3280
  }
2962
3281
  }
2963
- const operationPayload = resolveOperationPayload(context);
3282
+ const initialOperationPayload = resolveOperationPayload(context);
3283
+ let operationPayload = initialOperationPayload;
3284
+ if (tableName === "actor_session_state" && op === "insert") {
3285
+ operationPayload = recoverActorSessionInsertPayload(
3286
+ context,
3287
+ operationPayload
3288
+ );
3289
+ }
2964
3290
  const actorSessionInsertData = operationPayload.data;
2965
- const actorSessionInsertMissingData = !actorSessionInsertData || Array.isArray(actorSessionInsertData) && actorSessionInsertData.length === 0 || typeof actorSessionInsertData === "object" && !Array.isArray(actorSessionInsertData) && Object.keys(actorSessionInsertData).length === 0;
3291
+ const actorSessionInsertMissingData = isMissingInsertData(
3292
+ actorSessionInsertData
3293
+ );
2966
3294
  if (tableName === "actor_session_state" && op === "insert" && actorSessionInsertMissingData) {
2967
3295
  logActorSessionTrace("empty_insert_payload", {
2968
3296
  taskName,
@@ -2978,7 +3306,10 @@ var DatabaseController = class _DatabaseController {
2978
3306
  payloadDataType: actorSessionInsertData === null ? "null" : Array.isArray(actorSessionInsertData) ? "array" : typeof actorSessionInsertData,
2979
3307
  payloadDataKeys: actorSessionInsertData && typeof actorSessionInsertData === "object" && !Array.isArray(actorSessionInsertData) ? Object.keys(actorSessionInsertData) : [],
2980
3308
  queryDataKeys: context.queryData && typeof context.queryData === "object" && !Array.isArray(context.queryData) ? Object.keys(context.queryData) : [],
2981
- rootKeys: Object.keys(context ?? {}).slice(0, 24)
3309
+ rootKeys: Object.keys(context ?? {}).slice(0, 24),
3310
+ initialPayloadMissingData: isMissingInsertData(
3311
+ initialOperationPayload.data
3312
+ )
2982
3313
  });
2983
3314
  }
2984
3315
  const shouldDebugAuthoritySync = shouldDebugAuthoritySyncPayload(
@@ -3273,7 +3604,7 @@ var DatabaseController = class _DatabaseController {
3273
3604
  return rows.map((row) => {
3274
3605
  const camelCasedRow = {};
3275
3606
  for (const [key, value] of Object.entries(row)) {
3276
- camelCasedRow[(0, import_lodash_es.camelCase)(key)] = value;
3607
+ camelCasedRow[(0, import_lodash_es.camelCase)(key)] = normalizeQueryResultValue(value);
3277
3608
  }
3278
3609
  return camelCasedRow;
3279
3610
  });
@@ -3708,14 +4039,14 @@ var META_INTENT_PREFIX = "meta-";
3708
4039
  var META_RUNTIME_TRANSPORT_DIAGNOSTICS_INTENT = "meta-runtime-transport-diagnostics";
3709
4040
  var META_RUNTIME_STATUS_INTENT = "meta-runtime-status";
3710
4041
  var META_READINESS_INTENT = "meta-readiness";
3711
- function isPlainObject2(value) {
4042
+ function isPlainObject3(value) {
3712
4043
  return typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
3713
4044
  }
3714
4045
  function deepMergeDeterministic(left, right) {
3715
4046
  if (Array.isArray(left) && Array.isArray(right)) {
3716
4047
  return [...left, ...right];
3717
4048
  }
3718
- if (isPlainObject2(left) && isPlainObject2(right)) {
4049
+ if (isPlainObject3(left) && isPlainObject3(right)) {
3719
4050
  const merged = { ...left };
3720
4051
  const keys = Array.from(/* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])).sort();
3721
4052
  for (const key of keys) {
@@ -3959,6 +4290,10 @@ function normalizeServiceInstanceDescriptor(value) {
3959
4290
  return null;
3960
4291
  }
3961
4292
  const transports = normalizeTransportArray(raw.transports, uuid10);
4293
+ const leaseStatusRaw = normalizeString2(raw.leaseStatus ?? raw.lease_status);
4294
+ const leaseStatus = leaseStatusRaw === "active" || leaseStatusRaw === "non_responsive" || leaseStatusRaw === "inactive" || leaseStatusRaw === "deleted" ? leaseStatusRaw : void 0;
4295
+ const isActive = leaseStatus === "active" ? true : leaseStatus === "non_responsive" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : Boolean(raw.isActive ?? raw.is_active ?? true);
4296
+ const isNonResponsive = leaseStatus === "non_responsive" ? true : leaseStatus === "active" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : Boolean(raw.isNonResponsive ?? raw.is_non_responsive ?? false);
3962
4297
  return {
3963
4298
  uuid: uuid10,
3964
4299
  serviceName,
@@ -3969,10 +4304,16 @@ function normalizeServiceInstanceDescriptor(value) {
3969
4304
  )
3970
4305
  ),
3971
4306
  isPrimary: Boolean(raw.isPrimary ?? raw.is_primary ?? false),
3972
- isActive: Boolean(raw.isActive ?? raw.is_active ?? true),
3973
- isNonResponsive: Boolean(
3974
- raw.isNonResponsive ?? raw.is_non_responsive ?? false
3975
- ),
4307
+ leaseStatus,
4308
+ leaseExpiresAt: typeof raw.leaseExpiresAt === "string" ? raw.leaseExpiresAt : typeof raw.lease_expires_at === "string" ? raw.lease_expires_at : void 0,
4309
+ lastLeaseRenewedAt: typeof raw.lastLeaseRenewedAt === "string" ? raw.lastLeaseRenewedAt : typeof raw.last_lease_renewed_at === "string" ? raw.last_lease_renewed_at : void 0,
4310
+ isReady: typeof raw.isReady === "boolean" ? raw.isReady : typeof raw.is_ready === "boolean" ? raw.is_ready : void 0,
4311
+ readinessReason: typeof raw.readinessReason === "string" ? raw.readinessReason : typeof raw.readiness_reason === "string" ? raw.readiness_reason : null,
4312
+ lastReadyAt: typeof raw.lastReadyAt === "string" ? raw.lastReadyAt : typeof raw.last_ready_at === "string" ? raw.last_ready_at : null,
4313
+ lastObservedTransportAt: typeof raw.lastObservedTransportAt === "string" ? raw.lastObservedTransportAt : typeof raw.last_observed_transport_at === "string" ? raw.last_observed_transport_at : null,
4314
+ shutdownRequestedAt: typeof raw.shutdownRequestedAt === "string" ? raw.shutdownRequestedAt : typeof raw.shutdown_requested_at === "string" ? raw.shutdown_requested_at : null,
4315
+ isActive,
4316
+ isNonResponsive,
3976
4317
  isBlocked: Boolean(raw.isBlocked ?? raw.is_blocked ?? false),
3977
4318
  runtimeState: raw.runtimeState === "healthy" || raw.runtimeState === "degraded" || raw.runtimeState === "overloaded" || raw.runtimeState === "unavailable" ? raw.runtimeState : void 0,
3978
4319
  acceptingWork: typeof raw.acceptingWork === "boolean" ? raw.acceptingWork : void 0,
@@ -4425,6 +4766,61 @@ function resolveHealthMetric(input, keys) {
4425
4766
  }
4426
4767
  return void 0;
4427
4768
  }
4769
+ function sanitizeRuntimeMetricsHealthDetail(value) {
4770
+ if (!value || typeof value !== "object") {
4771
+ return void 0;
4772
+ }
4773
+ const input = value;
4774
+ const sampledAt = typeof input.sampledAt === "string" && input.sampledAt.trim().length > 0 ? input.sampledAt : void 0;
4775
+ const cpuUsage = normalizeOptionalMetric(input.cpuUsage ?? input.cpu ?? input.cpuLoad);
4776
+ const memoryUsage = normalizeOptionalMetric(
4777
+ input.memoryUsage ?? input.memory ?? input.memoryPressure
4778
+ );
4779
+ const eventLoopLag = normalizeOptionalMetric(
4780
+ input.eventLoopLag ?? input.eventLoopLagMs
4781
+ );
4782
+ const rssBytes = normalizeOptionalMetric(input.rssBytes);
4783
+ const heapUsedBytes = normalizeOptionalMetric(input.heapUsedBytes);
4784
+ const heapTotalBytes = normalizeOptionalMetric(input.heapTotalBytes);
4785
+ const memoryLimitBytes = normalizeOptionalMetric(input.memoryLimitBytes);
4786
+ if (sampledAt === void 0 && cpuUsage === void 0 && memoryUsage === void 0 && eventLoopLag === void 0 && rssBytes === void 0 && heapUsedBytes === void 0 && heapTotalBytes === void 0 && memoryLimitBytes === void 0) {
4787
+ return void 0;
4788
+ }
4789
+ return {
4790
+ ...sampledAt !== void 0 ? { sampledAt } : {},
4791
+ ...cpuUsage !== void 0 ? { cpuUsage } : {},
4792
+ ...memoryUsage !== void 0 ? { memoryUsage } : {},
4793
+ ...eventLoopLag !== void 0 ? { eventLoopLag } : {},
4794
+ ...rssBytes !== void 0 ? { rssBytes } : {},
4795
+ ...heapUsedBytes !== void 0 ? { heapUsedBytes } : {},
4796
+ ...heapTotalBytes !== void 0 ? { heapTotalBytes } : {},
4797
+ ...memoryLimitBytes !== void 0 ? { memoryLimitBytes } : {}
4798
+ };
4799
+ }
4800
+ function sanitizeAuthorityRuntimeStatusHealth(health, options) {
4801
+ const input = health && typeof health === "object" ? health : {};
4802
+ const cpuUsage = options?.cpuUsage !== void 0 ? options.cpuUsage : normalizeOptionalMetric(input.cpuUsage ?? input.cpu ?? input.cpuLoad);
4803
+ const memoryUsage = options?.memoryUsage !== void 0 ? options.memoryUsage : normalizeOptionalMetric(
4804
+ input.memoryUsage ?? input.memory ?? input.memoryPressure
4805
+ );
4806
+ const eventLoopLag = options?.eventLoopLag !== void 0 ? options.eventLoopLag : normalizeOptionalMetric(input.eventLoopLag ?? input.eventLoopLagMs);
4807
+ const runtimeMetrics = sanitizeRuntimeMetricsHealthDetail(input.runtimeMetrics);
4808
+ const runtimeStatus = options?.state || options?.reportedAt || typeof options?.acceptingWork === "boolean" ? {
4809
+ ...options?.state ? { state: options.state } : {},
4810
+ ...typeof options?.acceptingWork === "boolean" ? { acceptingWork: options.acceptingWork } : {},
4811
+ ...options?.reportedAt ? { reportedAt: options.reportedAt } : {}
4812
+ } : void 0;
4813
+ if (cpuUsage === void 0 && memoryUsage === void 0 && eventLoopLag === void 0 && !runtimeMetrics && !runtimeStatus) {
4814
+ return void 0;
4815
+ }
4816
+ return {
4817
+ ...cpuUsage !== void 0 ? { cpuUsage } : {},
4818
+ ...memoryUsage !== void 0 ? { memoryUsage } : {},
4819
+ ...eventLoopLag !== void 0 ? { eventLoopLag } : {},
4820
+ ...runtimeMetrics ? { runtimeMetrics } : {},
4821
+ ...runtimeStatus ? { runtimeStatus } : {}
4822
+ };
4823
+ }
4428
4824
  function normalizeAuthorityRuntimeStatusReport(input) {
4429
4825
  if (!input || typeof input !== "object") {
4430
4826
  return null;
@@ -4453,6 +4849,17 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4453
4849
  (protocol) => protocol === "rest" || protocol === "socket"
4454
4850
  ) : [];
4455
4851
  const transportProtocols = transportProtocolList.length > 0 ? Array.from(new Set(transportProtocolList)) : void 0;
4852
+ const acceptingWork = Boolean(input.acceptingWork ?? input.accepting_work);
4853
+ const cpuUsage = resolveHealthMetric(input, ["cpuUsage", "cpu", "cpuLoad"]);
4854
+ const memoryUsage = resolveHealthMetric(input, [
4855
+ "memoryUsage",
4856
+ "memory",
4857
+ "memoryPressure"
4858
+ ]);
4859
+ const eventLoopLag = resolveHealthMetric(input, [
4860
+ "eventLoopLag",
4861
+ "eventLoopLagMs"
4862
+ ]);
4456
4863
  return {
4457
4864
  serviceName,
4458
4865
  serviceInstanceId,
@@ -4463,7 +4870,7 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4463
4870
  isFrontend: typeof input.isFrontend === "boolean" ? input.isFrontend : typeof input.is_frontend === "boolean" ? input.is_frontend : void 0,
4464
4871
  reportedAt,
4465
4872
  state,
4466
- acceptingWork: Boolean(input.acceptingWork ?? input.accepting_work),
4873
+ acceptingWork,
4467
4874
  numberOfRunningGraphs: Math.max(
4468
4875
  0,
4469
4876
  Math.trunc(
@@ -4472,22 +4879,22 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4472
4879
  ) || 0
4473
4880
  )
4474
4881
  ),
4475
- cpuUsage: resolveHealthMetric(input, ["cpuUsage", "cpu", "cpuLoad"]),
4476
- memoryUsage: resolveHealthMetric(input, [
4477
- "memoryUsage",
4478
- "memory",
4479
- "memoryPressure"
4480
- ]),
4481
- eventLoopLag: resolveHealthMetric(input, [
4482
- "eventLoopLag",
4483
- "eventLoopLagMs"
4484
- ]),
4882
+ cpuUsage,
4883
+ memoryUsage,
4884
+ eventLoopLag,
4485
4885
  isActive: Boolean(input.isActive ?? input.is_active ?? true),
4486
4886
  isNonResponsive: Boolean(
4487
4887
  input.isNonResponsive ?? input.is_non_responsive ?? false
4488
4888
  ),
4489
4889
  isBlocked: Boolean(input.isBlocked ?? input.is_blocked ?? false),
4490
- health: input.health && typeof input.health === "object" ? input.health : void 0
4890
+ health: sanitizeAuthorityRuntimeStatusHealth(input.health, {
4891
+ state,
4892
+ acceptingWork,
4893
+ reportedAt,
4894
+ cpuUsage,
4895
+ memoryUsage,
4896
+ eventLoopLag
4897
+ })
4491
4898
  };
4492
4899
  }
4493
4900
  function buildAuthorityRuntimeStatusSignature(report) {
@@ -4500,18 +4907,53 @@ function buildAuthorityRuntimeStatusSignature(report) {
4500
4907
  transportProtocols: report.transportProtocols ?? [],
4501
4908
  state: report.state,
4502
4909
  acceptingWork: report.acceptingWork,
4503
- numberOfRunningGraphs: report.numberOfRunningGraphs,
4504
- cpuUsage: report.cpuUsage ?? null,
4505
- memoryUsage: report.memoryUsage ?? null,
4506
- eventLoopLag: report.eventLoopLag ?? null,
4507
4910
  isActive: report.isActive,
4508
4911
  isNonResponsive: report.isNonResponsive,
4509
4912
  isBlocked: report.isBlocked,
4510
- isFrontend: report.isFrontend ?? null,
4511
- health: report.health ?? {}
4913
+ isFrontend: report.isFrontend ?? null
4512
4914
  });
4513
4915
  }
4514
4916
 
4917
+ // src/registry/runtimeJitter.ts
4918
+ function normalizeKey(key) {
4919
+ return key.trim() || "default";
4920
+ }
4921
+ function hashKeyToUnitInterval(key) {
4922
+ const normalizedKey = normalizeKey(key);
4923
+ let hash = 2166136261;
4924
+ for (let index = 0; index < normalizedKey.length; index += 1) {
4925
+ hash ^= normalizedKey.charCodeAt(index);
4926
+ hash = Math.imul(hash, 16777619);
4927
+ }
4928
+ return (hash >>> 0) / 4294967295;
4929
+ }
4930
+ function normalizeJitterRatio(value) {
4931
+ if (!Number.isFinite(value) || value <= 0) {
4932
+ return 0;
4933
+ }
4934
+ return Math.min(value, 1);
4935
+ }
4936
+ function buildDeterministicJitterOffsetMs(baseMs, ratio, key) {
4937
+ if (!Number.isFinite(baseMs) || baseMs <= 0) {
4938
+ return 0;
4939
+ }
4940
+ const normalizedRatio = normalizeJitterRatio(ratio);
4941
+ if (normalizedRatio <= 0) {
4942
+ return 0;
4943
+ }
4944
+ const maxOffsetMs = Math.round(baseMs * normalizedRatio);
4945
+ if (maxOffsetMs <= 0) {
4946
+ return 0;
4947
+ }
4948
+ return Math.round(hashKeyToUnitInterval(key) * maxOffsetMs);
4949
+ }
4950
+ function buildDeterministicJitteredDelayMs(baseMs, ratio, key) {
4951
+ return Math.max(
4952
+ 0,
4953
+ Math.round(baseMs) + buildDeterministicJitterOffsetMs(baseMs, ratio, key)
4954
+ );
4955
+ }
4956
+
4515
4957
  // src/registry/serviceManifestContract.ts
4516
4958
  var AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT = "meta-service-registry-authority-service-manifest-report";
4517
4959
  var AUTHORITY_SERVICE_MANIFEST_UPDATED_SIGNAL = "global.meta.cadenza_db.service_manifest_updated";
@@ -4537,16 +4979,23 @@ function normalizeServiceManifestSnapshot(input) {
4537
4979
  revision,
4538
4980
  manifestHash,
4539
4981
  publishedAt,
4982
+ publicationLayer: record.publicationLayer === "routing_capability" || record.publicationLayer === "business_structural" || record.publicationLayer === "local_meta_structural" ? record.publicationLayer : "business_structural",
4540
4983
  tasks: normalizeArray(record.tasks),
4541
4984
  signals: normalizeArray(record.signals),
4542
4985
  intents: normalizeArray(record.intents),
4543
4986
  actors: normalizeArray(record.actors),
4544
4987
  routines: normalizeArray(record.routines),
4988
+ helpers: normalizeArray(record.helpers),
4989
+ globals: normalizeArray(record.globals),
4545
4990
  directionalTaskMaps: normalizeArray(record.directionalTaskMaps),
4546
4991
  signalToTaskMaps: normalizeArray(record.signalToTaskMaps),
4547
4992
  intentToTaskMaps: normalizeArray(record.intentToTaskMaps),
4548
4993
  actorTaskMaps: normalizeArray(record.actorTaskMaps),
4549
- taskToRoutineMaps: normalizeArray(record.taskToRoutineMaps)
4994
+ taskToRoutineMaps: normalizeArray(record.taskToRoutineMaps),
4995
+ taskToHelperMaps: normalizeArray(record.taskToHelperMaps),
4996
+ helperToHelperMaps: normalizeArray(record.helperToHelperMaps),
4997
+ taskToGlobalMaps: normalizeArray(record.taskToGlobalMaps),
4998
+ helperToGlobalMaps: normalizeArray(record.helperToGlobalMaps)
4550
4999
  };
4551
5000
  }
4552
5001
  function selectLatestServiceManifestSnapshots(snapshots) {
@@ -4666,6 +5115,7 @@ function decomposeSignalName(signalName) {
4666
5115
  }
4667
5116
 
4668
5117
  // src/registry/serviceManifest.ts
5118
+ var import_core2 = __toESM(require("@cadenza.io/core"));
4669
5119
  var ACTOR_TASK_METADATA = /* @__PURE__ */ Symbol.for("@cadenza.io/core/actor-task-meta");
4670
5120
  function getActorTaskRuntimeMetadata(taskFunction) {
4671
5121
  if (typeof taskFunction !== "function") {
@@ -4809,15 +5259,90 @@ function buildRoutineDefinition(routine, serviceName) {
4809
5259
  is_meta: routine.isMeta === true
4810
5260
  };
4811
5261
  }
5262
+ function buildHelperDefinition(helper, serviceName) {
5263
+ return {
5264
+ name: helper.name,
5265
+ version: helper.version,
5266
+ description: helper.description,
5267
+ service_name: serviceName,
5268
+ is_meta: helper.isMeta === true,
5269
+ handler_source: helper.helperFunction.toString(),
5270
+ language: "js"
5271
+ };
5272
+ }
5273
+ function buildGlobalDefinition(globalDefinition, serviceName) {
5274
+ return {
5275
+ name: globalDefinition.name,
5276
+ version: globalDefinition.version,
5277
+ description: globalDefinition.description,
5278
+ service_name: serviceName,
5279
+ is_meta: globalDefinition.isMeta === true,
5280
+ value: sanitizeManifestValue(globalDefinition.value)
5281
+ };
5282
+ }
4812
5283
  function shouldExportTask(task) {
4813
- return !task.isDeputy && !task.isEphemeral;
5284
+ return task.register !== false && task.isHidden !== true && !task.isDeputy && !task.isEphemeral;
4814
5285
  }
4815
5286
  function shouldExportRoutine(routine) {
4816
5287
  return Boolean(String(routine?.name ?? "").trim());
4817
5288
  }
5289
+ function buildTaskKey(task) {
5290
+ return `${task.service_name}|${task.name}|${task.version}`;
5291
+ }
5292
+ function buildActorKey(actor) {
5293
+ return `${actor.service_name}|${actor.name}|${actor.version}`;
5294
+ }
5295
+ function buildRoutineKey(routine) {
5296
+ return `${routine.service_name}|${routine.name}|${routine.version}`;
5297
+ }
5298
+ function buildHelperKey(helper) {
5299
+ return `${helper.service_name}|${helper.name}|${helper.version}`;
5300
+ }
5301
+ function buildGlobalKey(globalDefinition) {
5302
+ return `${globalDefinition.service_name}|${globalDefinition.name}|${globalDefinition.version}`;
5303
+ }
5304
+ function listManifestTasks() {
5305
+ const registryTasks = Array.from(CadenzaService.registry.tasks.values()).filter(
5306
+ (task) => Boolean(task)
5307
+ );
5308
+ const cachedTasks = Array.from(
5309
+ import_core2.default.taskCache?.values?.() ?? []
5310
+ ).filter((task) => Boolean(task));
5311
+ return Array.from(
5312
+ new Map(
5313
+ [...registryTasks, ...cachedTasks].map((task) => [task.name, task])
5314
+ ).values()
5315
+ );
5316
+ }
5317
+ function listManifestHelpers() {
5318
+ const toolRuntime = CadenzaService;
5319
+ return (toolRuntime.getAllHelpers?.() ?? []).filter(
5320
+ (helper) => Boolean(helper && !helper.destroyed)
5321
+ );
5322
+ }
5323
+ function listManifestGlobals() {
5324
+ const toolRuntime = CadenzaService;
5325
+ return (toolRuntime.getAllGlobals?.() ?? []).filter(
5326
+ (globalDefinition) => Boolean(globalDefinition && !globalDefinition.destroyed)
5327
+ );
5328
+ }
5329
+ function isRoutingCriticalMetaSignal(_signal) {
5330
+ return false;
5331
+ }
5332
+ function isRoutingCriticalMetaIntent(_intent) {
5333
+ return false;
5334
+ }
4818
5335
  function buildServiceManifestSnapshot(params) {
4819
- const { serviceName, serviceInstanceId, revision, publishedAt } = params;
4820
- const tasks = Array.from(CadenzaService.registry.tasks.values()).filter((task) => Boolean(task)).filter(shouldExportTask);
5336
+ const {
5337
+ serviceName,
5338
+ serviceInstanceId,
5339
+ revision,
5340
+ publishedAt,
5341
+ publicationLayer = "business_structural"
5342
+ } = params;
5343
+ const tasks = listManifestTasks().filter(shouldExportTask);
5344
+ const helpers = listManifestHelpers();
5345
+ const globals = listManifestGlobals();
4821
5346
  const routines = Array.from(CadenzaService.registry.routines.values()).filter((routine) => Boolean(routine)).filter(shouldExportRoutine);
4822
5347
  const actors = CadenzaService.getAllActors();
4823
5348
  const taskDefinitions = tasks.map((task) => buildTaskDefinition(task, serviceName)).sort(
@@ -4829,6 +5354,10 @@ function buildServiceManifestSnapshot(params) {
4829
5354
  const directionalTaskMaps = /* @__PURE__ */ new Map();
4830
5355
  const actorTaskMaps = /* @__PURE__ */ new Map();
4831
5356
  const taskToRoutineMaps = /* @__PURE__ */ new Map();
5357
+ const helperTaskMaps = /* @__PURE__ */ new Map();
5358
+ const helperHelperMaps = /* @__PURE__ */ new Map();
5359
+ const taskGlobalMaps = /* @__PURE__ */ new Map();
5360
+ const helperGlobalMaps = /* @__PURE__ */ new Map();
4832
5361
  const registerSignal = (signalName) => {
4833
5362
  const normalizedSignalName = canonicalizeSignalName(signalName);
4834
5363
  if (!normalizedSignalName || signalDefinitions.has(normalizedSignalName)) {
@@ -4912,6 +5441,37 @@ function buildServiceManifestSnapshot(params) {
4912
5441
  is_meta: actorTaskMetadata.actorKind === "meta" || task.isMeta === true
4913
5442
  });
4914
5443
  }
5444
+ const taskTools = task;
5445
+ for (const [alias, helperName] of taskTools.helperAliases?.entries?.() ?? []) {
5446
+ const helper = CadenzaService.getHelper?.(helperName);
5447
+ if (!helper) {
5448
+ continue;
5449
+ }
5450
+ const key = `${task.name}|${task.version}|${alias}|${helper.name}|${helper.version}|${serviceName}`;
5451
+ helperTaskMaps.set(key, {
5452
+ task_name: task.name,
5453
+ task_version: task.version,
5454
+ service_name: serviceName,
5455
+ alias,
5456
+ helper_name: helper.name,
5457
+ helper_version: helper.version
5458
+ });
5459
+ }
5460
+ for (const [alias, globalName] of taskTools.globalAliases?.entries?.() ?? []) {
5461
+ const globalDefinition = CadenzaService.getGlobal?.(globalName);
5462
+ if (!globalDefinition) {
5463
+ continue;
5464
+ }
5465
+ const key = `${task.name}|${task.version}|${alias}|${globalDefinition.name}|${globalDefinition.version}|${serviceName}`;
5466
+ taskGlobalMaps.set(key, {
5467
+ task_name: task.name,
5468
+ task_version: task.version,
5469
+ service_name: serviceName,
5470
+ alias,
5471
+ global_name: globalDefinition.name,
5472
+ global_version: globalDefinition.version
5473
+ });
5474
+ }
4915
5475
  }
4916
5476
  const intentDefinitions = Array.from(CadenzaService.inquiryBroker.intents.values()).map((intent) => {
4917
5477
  const intentRecord = intent;
@@ -4943,18 +5503,56 @@ function buildServiceManifestSnapshot(params) {
4943
5503
  ).sort(
4944
5504
  (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
4945
5505
  );
4946
- for (const routine of routines) {
4947
- for (const task of routine.tasks) {
4948
- if (!task) {
5506
+ const helperDefinitions = helpers.map((helper) => buildHelperDefinition(helper, serviceName)).sort(
5507
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5508
+ );
5509
+ const globalDefinitions = globals.map((globalDefinition) => buildGlobalDefinition(globalDefinition, serviceName)).sort(
5510
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5511
+ );
5512
+ for (const helper of helpers) {
5513
+ for (const [alias, dependencyHelperName] of helper.helperAliases.entries()) {
5514
+ const dependencyHelper = CadenzaService.getHelper?.(dependencyHelperName);
5515
+ if (!dependencyHelper) {
4949
5516
  continue;
4950
5517
  }
4951
- const iterator = task.getIterator();
4952
- while (iterator.hasNext()) {
4953
- const nextTask = iterator.next();
4954
- if (!nextTask || !shouldExportTask(nextTask)) {
4955
- continue;
4956
- }
4957
- const key = `${routine.name}|${routine.version}|${nextTask.name}|${nextTask.version}|${serviceName}`;
5518
+ const key = `${helper.name}|${helper.version}|${alias}|${dependencyHelper.name}|${dependencyHelper.version}|${serviceName}`;
5519
+ helperHelperMaps.set(key, {
5520
+ helper_name: helper.name,
5521
+ helper_version: helper.version,
5522
+ service_name: serviceName,
5523
+ alias,
5524
+ dependency_helper_name: dependencyHelper.name,
5525
+ dependency_helper_version: dependencyHelper.version
5526
+ });
5527
+ }
5528
+ for (const [alias, globalName] of helper.globalAliases.entries()) {
5529
+ const globalDefinition = CadenzaService.getGlobal?.(globalName);
5530
+ if (!globalDefinition) {
5531
+ continue;
5532
+ }
5533
+ const key = `${helper.name}|${helper.version}|${alias}|${globalDefinition.name}|${globalDefinition.version}|${serviceName}`;
5534
+ helperGlobalMaps.set(key, {
5535
+ helper_name: helper.name,
5536
+ helper_version: helper.version,
5537
+ service_name: serviceName,
5538
+ alias,
5539
+ global_name: globalDefinition.name,
5540
+ global_version: globalDefinition.version
5541
+ });
5542
+ }
5543
+ }
5544
+ for (const routine of routines) {
5545
+ for (const task of routine.tasks) {
5546
+ if (!task) {
5547
+ continue;
5548
+ }
5549
+ const iterator = task.getIterator();
5550
+ while (iterator.hasNext()) {
5551
+ const nextTask = iterator.next();
5552
+ if (!nextTask || !shouldExportTask(nextTask)) {
5553
+ continue;
5554
+ }
5555
+ const key = `${routine.name}|${routine.version}|${nextTask.name}|${nextTask.version}|${serviceName}`;
4958
5556
  taskToRoutineMaps.set(key, {
4959
5557
  task_name: nextTask.name,
4960
5558
  task_version: nextTask.version,
@@ -4965,41 +5563,506 @@ function buildServiceManifestSnapshot(params) {
4965
5563
  }
4966
5564
  }
4967
5565
  }
4968
- const manifestBody = {
4969
- serviceName,
4970
- serviceInstanceId,
4971
- tasks: taskDefinitions,
4972
- signals: Array.from(signalDefinitions.values()).sort(
4973
- (left, right) => left.name.localeCompare(right.name)
4974
- ),
4975
- intents: intentDefinitions,
4976
- actors: actorDefinitions,
4977
- routines: routineDefinitions,
4978
- directionalTaskMaps: Array.from(directionalTaskMaps.values()).sort(
4979
- (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
4980
- `${right.predecessor_task_name}:${right.task_name}`
4981
- )
4982
- ),
4983
- signalToTaskMaps: Array.from(signalTaskMaps.values()).sort(
4984
- (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
4985
- `${right.signal_name}:${right.task_name}`
4986
- )
4987
- ),
4988
- intentToTaskMaps: Array.from(intentTaskMaps.values()).sort(
4989
- (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
4990
- `${right.intent_name}:${right.task_name}`
5566
+ const taskDefinitionsByKey = new Map(
5567
+ taskDefinitions.map((task) => [buildTaskKey(task), task])
5568
+ );
5569
+ const signalDefinitionsByName = new Map(
5570
+ Array.from(signalDefinitions.values()).map((signal) => [signal.name, signal])
5571
+ );
5572
+ const intentDefinitionsByName = new Map(
5573
+ intentDefinitions.map((intent) => [intent.name, intent])
5574
+ );
5575
+ const actorDefinitionsByKey = new Map(
5576
+ actorDefinitions.map((actor) => [buildActorKey(actor), actor])
5577
+ );
5578
+ const routineDefinitionsByKey = new Map(
5579
+ routineDefinitions.map((routine) => [buildRoutineKey(routine), routine])
5580
+ );
5581
+ const helperDefinitionsByKey = new Map(
5582
+ helperDefinitions.map((helper) => [buildHelperKey(helper), helper])
5583
+ );
5584
+ const globalDefinitionsByKey = new Map(
5585
+ globalDefinitions.map((globalDefinition) => [
5586
+ buildGlobalKey(globalDefinition),
5587
+ globalDefinition
5588
+ ])
5589
+ );
5590
+ const routingTaskKeys = /* @__PURE__ */ new Set();
5591
+ const routingSignalNames = /* @__PURE__ */ new Set();
5592
+ const routingIntentNames = /* @__PURE__ */ new Set();
5593
+ const publishedSignalTaskMaps = Array.from(signalTaskMaps.values()).filter((map) => {
5594
+ const signal = signalDefinitionsByName.get(map.signal_name);
5595
+ return signal?.is_meta !== true || (signal ? isRoutingCriticalMetaSignal(signal) : false);
5596
+ }).sort(
5597
+ (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
5598
+ `${right.signal_name}:${right.task_name}`
5599
+ )
5600
+ );
5601
+ const publishedIntentTaskMaps = Array.from(intentTaskMaps.values()).filter((map) => {
5602
+ const intent = intentDefinitionsByName.get(map.intent_name);
5603
+ return intent?.is_meta !== true || (intent ? isRoutingCriticalMetaIntent(intent) : false);
5604
+ }).sort(
5605
+ (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
5606
+ `${right.intent_name}:${right.task_name}`
5607
+ )
5608
+ );
5609
+ const localMetaSignalTaskMaps = Array.from(signalTaskMaps.values()).filter((map) => !publishedSignalTaskMaps.includes(map)).sort(
5610
+ (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
5611
+ `${right.signal_name}:${right.task_name}`
5612
+ )
5613
+ );
5614
+ const localMetaIntentTaskMaps = Array.from(intentTaskMaps.values()).filter((map) => !publishedIntentTaskMaps.includes(map)).sort(
5615
+ (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
5616
+ `${right.intent_name}:${right.task_name}`
5617
+ )
5618
+ );
5619
+ for (const map of publishedSignalTaskMaps) {
5620
+ routingTaskKeys.add(
5621
+ buildTaskKey({
5622
+ service_name: map.service_name,
5623
+ name: map.task_name,
5624
+ version: map.task_version
5625
+ })
5626
+ );
5627
+ routingSignalNames.add(map.signal_name);
5628
+ }
5629
+ for (const map of publishedIntentTaskMaps) {
5630
+ routingTaskKeys.add(
5631
+ buildTaskKey({
5632
+ service_name: map.service_name,
5633
+ name: map.task_name,
5634
+ version: map.task_version
5635
+ })
5636
+ );
5637
+ routingIntentNames.add(map.intent_name);
5638
+ }
5639
+ const routingTasks = Array.from(routingTaskKeys).map((key) => taskDefinitionsByKey.get(key) ?? null).filter((task) => task !== null).sort(
5640
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5641
+ );
5642
+ const routingSignals = Array.from(routingSignalNames).map((name) => signalDefinitionsByName.get(name) ?? null).filter((signal) => signal !== null).sort((left, right) => left.name.localeCompare(right.name));
5643
+ const routingIntents = Array.from(routingIntentNames).map((name) => intentDefinitionsByName.get(name) ?? null).filter((intent) => intent !== null).sort((left, right) => left.name.localeCompare(right.name));
5644
+ const businessTasks = taskDefinitions.filter((task) => task.is_meta !== true && task.is_sub_meta !== true).sort(
5645
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5646
+ );
5647
+ const businessSignals = Array.from(signalDefinitions.values()).filter((signal) => signal.is_meta !== true).sort((left, right) => left.name.localeCompare(right.name));
5648
+ const businessIntents = intentDefinitions.filter((intent) => intent.is_meta !== true).sort((left, right) => left.name.localeCompare(right.name));
5649
+ const businessActors = actorDefinitions.filter((actor) => actor.is_meta !== true).sort(
5650
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5651
+ );
5652
+ const businessRoutines = routineDefinitions.filter((routine) => routine.is_meta !== true).sort(
5653
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5654
+ );
5655
+ const businessDirectionalTaskMaps = Array.from(directionalTaskMaps.values()).filter((map) => {
5656
+ const predecessor = taskDefinitionsByKey.get(
5657
+ buildTaskKey({
5658
+ service_name: map.predecessor_service_name,
5659
+ name: map.predecessor_task_name,
5660
+ version: map.predecessor_task_version
5661
+ })
5662
+ );
5663
+ const task = taskDefinitionsByKey.get(
5664
+ buildTaskKey({
5665
+ service_name: map.service_name,
5666
+ name: map.task_name,
5667
+ version: map.task_version
5668
+ })
5669
+ );
5670
+ return predecessor?.is_meta !== true && predecessor?.is_sub_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
5671
+ }).sort(
5672
+ (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
5673
+ `${right.predecessor_task_name}:${right.task_name}`
5674
+ )
5675
+ );
5676
+ const businessActorTaskMaps = Array.from(actorTaskMaps.values()).filter((map) => {
5677
+ const actor = actorDefinitionsByKey.get(
5678
+ buildActorKey({
5679
+ service_name: map.service_name,
5680
+ name: map.actor_name,
5681
+ version: map.actor_version
5682
+ })
5683
+ );
5684
+ const task = taskDefinitionsByKey.get(
5685
+ buildTaskKey({
5686
+ service_name: map.service_name,
5687
+ name: map.task_name,
5688
+ version: map.task_version
5689
+ })
5690
+ );
5691
+ return actor?.is_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
5692
+ }).sort(
5693
+ (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
5694
+ `${right.actor_name}:${right.task_name}`
5695
+ )
5696
+ );
5697
+ const businessTaskToRoutineMaps = Array.from(taskToRoutineMaps.values()).filter((map) => {
5698
+ const routine = routineDefinitionsByKey.get(
5699
+ buildRoutineKey({
5700
+ service_name: map.service_name,
5701
+ name: map.routine_name,
5702
+ version: map.routine_version
5703
+ })
5704
+ );
5705
+ const task = taskDefinitionsByKey.get(
5706
+ buildTaskKey({
5707
+ service_name: map.service_name,
5708
+ name: map.task_name,
5709
+ version: map.task_version
5710
+ })
5711
+ );
5712
+ return routine?.is_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
5713
+ }).sort(
5714
+ (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
5715
+ `${right.routine_name}:${right.task_name}`
5716
+ )
5717
+ );
5718
+ const localMetaTasks = taskDefinitions.filter((task) => task.is_meta === true || task.is_sub_meta === true).sort(
5719
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5720
+ );
5721
+ const localMetaSignals = Array.from(signalDefinitions.values()).filter((signal) => signal.is_meta === true).sort((left, right) => left.name.localeCompare(right.name));
5722
+ const localMetaIntents = intentDefinitions.filter((intent) => intent.is_meta === true).sort((left, right) => left.name.localeCompare(right.name));
5723
+ const localMetaActors = actorDefinitions.filter((actor) => actor.is_meta === true).sort(
5724
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5725
+ );
5726
+ const localMetaRoutines = routineDefinitions.filter((routine) => routine.is_meta === true).sort(
5727
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5728
+ );
5729
+ const localMetaDirectionalTaskMaps = Array.from(directionalTaskMaps.values()).filter((map) => !businessDirectionalTaskMaps.includes(map)).sort(
5730
+ (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
5731
+ `${right.predecessor_task_name}:${right.task_name}`
5732
+ )
5733
+ );
5734
+ const localMetaActorTaskMaps = Array.from(actorTaskMaps.values()).filter((map) => !businessActorTaskMaps.includes(map)).sort(
5735
+ (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
5736
+ `${right.actor_name}:${right.task_name}`
5737
+ )
5738
+ );
5739
+ const localMetaTaskToRoutineMaps = Array.from(taskToRoutineMaps.values()).filter((map) => !businessTaskToRoutineMaps.includes(map)).sort(
5740
+ (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
5741
+ `${right.routine_name}:${right.task_name}`
5742
+ )
5743
+ );
5744
+ const businessLocalMetaTaskKeys = /* @__PURE__ */ new Set();
5745
+ const businessLocalMetaSignalNames = /* @__PURE__ */ new Set();
5746
+ const businessLocalMetaIntentNames = /* @__PURE__ */ new Set();
5747
+ const businessLocalMetaActorKeys = /* @__PURE__ */ new Set();
5748
+ const businessLocalMetaRoutineKeys = /* @__PURE__ */ new Set();
5749
+ for (const map of localMetaSignalTaskMaps) {
5750
+ businessLocalMetaSignalNames.add(map.signal_name);
5751
+ businessLocalMetaTaskKeys.add(
5752
+ buildTaskKey({
5753
+ service_name: map.service_name,
5754
+ name: map.task_name,
5755
+ version: map.task_version
5756
+ })
5757
+ );
5758
+ }
5759
+ for (const map of localMetaIntentTaskMaps) {
5760
+ businessLocalMetaIntentNames.add(map.intent_name);
5761
+ businessLocalMetaTaskKeys.add(
5762
+ buildTaskKey({
5763
+ service_name: map.service_name,
5764
+ name: map.task_name,
5765
+ version: map.task_version
5766
+ })
5767
+ );
5768
+ }
5769
+ for (const map of localMetaActorTaskMaps) {
5770
+ businessLocalMetaActorKeys.add(
5771
+ buildActorKey({
5772
+ service_name: map.service_name,
5773
+ name: map.actor_name,
5774
+ version: map.actor_version
5775
+ })
5776
+ );
5777
+ businessLocalMetaTaskKeys.add(
5778
+ buildTaskKey({
5779
+ service_name: map.service_name,
5780
+ name: map.task_name,
5781
+ version: map.task_version
5782
+ })
5783
+ );
5784
+ }
5785
+ for (const map of localMetaTaskToRoutineMaps) {
5786
+ businessLocalMetaRoutineKeys.add(
5787
+ buildRoutineKey({
5788
+ service_name: map.service_name,
5789
+ name: map.routine_name,
5790
+ version: map.routine_version
5791
+ })
5792
+ );
5793
+ businessLocalMetaTaskKeys.add(
5794
+ buildTaskKey({
5795
+ service_name: map.service_name,
5796
+ name: map.task_name,
5797
+ version: map.task_version
5798
+ })
5799
+ );
5800
+ }
5801
+ const businessLocalMetaTasks = Array.from(businessLocalMetaTaskKeys).map((key) => taskDefinitionsByKey.get(key) ?? null).filter(
5802
+ (task) => task !== null && (task.is_meta === true || task.is_sub_meta === true)
5803
+ ).sort(
5804
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5805
+ );
5806
+ const businessLocalMetaSignals = Array.from(businessLocalMetaSignalNames).map((name) => signalDefinitionsByName.get(name) ?? null).filter(
5807
+ (signal) => signal !== null && signal.is_meta === true
5808
+ ).sort((left, right) => left.name.localeCompare(right.name));
5809
+ const businessLocalMetaIntents = Array.from(businessLocalMetaIntentNames).map((name) => intentDefinitionsByName.get(name) ?? null).filter(
5810
+ (intent) => intent !== null && intent.is_meta === true
5811
+ ).sort((left, right) => left.name.localeCompare(right.name));
5812
+ const businessLocalMetaActors = Array.from(businessLocalMetaActorKeys).map((key) => actorDefinitionsByKey.get(key) ?? null).filter(
5813
+ (actor) => actor !== null && actor.is_meta === true
5814
+ ).sort(
5815
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5816
+ );
5817
+ const businessLocalMetaRoutines = Array.from(businessLocalMetaRoutineKeys).map((key) => routineDefinitionsByKey.get(key) ?? null).filter(
5818
+ (routine) => routine !== null && routine.is_meta === true
5819
+ ).sort(
5820
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5821
+ );
5822
+ const cumulativeTasks = publicationLayer === "routing_capability" ? routingTasks : publicationLayer === "business_structural" ? Array.from(
5823
+ new Map(
5824
+ [...routingTasks, ...businessTasks, ...businessLocalMetaTasks].map((task) => [
5825
+ buildTaskKey(task),
5826
+ task
5827
+ ])
5828
+ ).values()
5829
+ ).sort(
5830
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5831
+ ) : Array.from(
5832
+ new Map(
5833
+ [...routingTasks, ...businessTasks, ...localMetaTasks].map((task) => [
5834
+ buildTaskKey(task),
5835
+ task
5836
+ ])
5837
+ ).values()
5838
+ ).sort(
5839
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5840
+ );
5841
+ const cumulativeSignals = publicationLayer === "routing_capability" ? routingSignals : publicationLayer === "business_structural" ? Array.from(
5842
+ new Map(
5843
+ [...routingSignals, ...businessSignals, ...businessLocalMetaSignals].map(
5844
+ (signal) => [signal.name, signal]
4991
5845
  )
4992
- ),
4993
- actorTaskMaps: Array.from(actorTaskMaps.values()).sort(
4994
- (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
4995
- `${right.actor_name}:${right.task_name}`
5846
+ ).values()
5847
+ ).sort((left, right) => left.name.localeCompare(right.name)) : Array.from(
5848
+ new Map(
5849
+ [...routingSignals, ...businessSignals, ...localMetaSignals].map((signal) => [
5850
+ signal.name,
5851
+ signal
5852
+ ])
5853
+ ).values()
5854
+ ).sort((left, right) => left.name.localeCompare(right.name));
5855
+ const cumulativeIntents = publicationLayer === "routing_capability" ? routingIntents : publicationLayer === "business_structural" ? Array.from(
5856
+ new Map(
5857
+ [...routingIntents, ...businessIntents, ...businessLocalMetaIntents].map(
5858
+ (intent) => [intent.name, intent]
4996
5859
  )
4997
- ),
4998
- taskToRoutineMaps: Array.from(taskToRoutineMaps.values()).sort(
4999
- (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
5000
- `${right.routine_name}:${right.task_name}`
5860
+ ).values()
5861
+ ).sort((left, right) => left.name.localeCompare(right.name)) : Array.from(
5862
+ new Map(
5863
+ [...routingIntents, ...businessIntents, ...localMetaIntents].map((intent) => [
5864
+ intent.name,
5865
+ intent
5866
+ ])
5867
+ ).values()
5868
+ ).sort((left, right) => left.name.localeCompare(right.name));
5869
+ const cumulativeActors = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
5870
+ new Map(
5871
+ [...businessActors, ...businessLocalMetaActors].map((actor) => [
5872
+ buildActorKey(actor),
5873
+ actor
5874
+ ])
5875
+ ).values()
5876
+ ).sort(
5877
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5878
+ ) : Array.from(
5879
+ new Map(
5880
+ [...businessActors, ...localMetaActors].map((actor) => [
5881
+ buildActorKey(actor),
5882
+ actor
5883
+ ])
5884
+ ).values()
5885
+ ).sort(
5886
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5887
+ );
5888
+ const cumulativeRoutines = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
5889
+ new Map(
5890
+ [...businessRoutines, ...businessLocalMetaRoutines].map((routine) => [
5891
+ buildRoutineKey(routine),
5892
+ routine
5893
+ ])
5894
+ ).values()
5895
+ ).sort(
5896
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5897
+ ) : Array.from(
5898
+ new Map(
5899
+ [...businessRoutines, ...localMetaRoutines].map((routine) => [
5900
+ buildRoutineKey(routine),
5901
+ routine
5902
+ ])
5903
+ ).values()
5904
+ ).sort(
5905
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5906
+ );
5907
+ const businessHelpers = helperDefinitions.filter((helper) => helper.is_meta !== true).sort(
5908
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5909
+ );
5910
+ const localMetaHelpers = helperDefinitions.filter((helper) => helper.is_meta === true).sort(
5911
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5912
+ );
5913
+ const businessGlobals = globalDefinitions.filter((globalDefinition) => globalDefinition.is_meta !== true).sort(
5914
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5915
+ );
5916
+ const localMetaGlobals = globalDefinitions.filter((globalDefinition) => globalDefinition.is_meta === true).sort(
5917
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5918
+ );
5919
+ const businessTaskToHelperMaps = Array.from(helperTaskMaps.values()).filter((map) => {
5920
+ const task = taskDefinitionsByKey.get(
5921
+ buildTaskKey({
5922
+ service_name: map.service_name,
5923
+ name: map.task_name,
5924
+ version: map.task_version
5925
+ })
5926
+ );
5927
+ const helper = helperDefinitionsByKey.get(
5928
+ buildHelperKey({
5929
+ service_name: map.service_name,
5930
+ name: map.helper_name,
5931
+ version: map.helper_version
5932
+ })
5933
+ );
5934
+ return task?.is_meta !== true && task?.is_sub_meta !== true && helper?.is_meta !== true;
5935
+ }).sort(
5936
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5937
+ );
5938
+ const localMetaTaskToHelperMaps = Array.from(helperTaskMaps.values()).filter((map) => !businessTaskToHelperMaps.includes(map)).sort(
5939
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5940
+ );
5941
+ const businessHelperToHelperMaps = Array.from(helperHelperMaps.values()).filter((map) => {
5942
+ const helper = helperDefinitionsByKey.get(
5943
+ buildHelperKey({
5944
+ service_name: map.service_name,
5945
+ name: map.helper_name,
5946
+ version: map.helper_version
5947
+ })
5948
+ );
5949
+ const dependencyHelper = helperDefinitionsByKey.get(
5950
+ buildHelperKey({
5951
+ service_name: map.service_name,
5952
+ name: map.dependency_helper_name,
5953
+ version: map.dependency_helper_version
5954
+ })
5955
+ );
5956
+ return helper?.is_meta !== true && dependencyHelper?.is_meta !== true;
5957
+ }).sort(
5958
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5959
+ );
5960
+ const localMetaHelperToHelperMaps = Array.from(helperHelperMaps.values()).filter((map) => !businessHelperToHelperMaps.includes(map)).sort(
5961
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5962
+ );
5963
+ const businessTaskToGlobalMaps = Array.from(taskGlobalMaps.values()).filter((map) => {
5964
+ const task = taskDefinitionsByKey.get(
5965
+ buildTaskKey({
5966
+ service_name: map.service_name,
5967
+ name: map.task_name,
5968
+ version: map.task_version
5969
+ })
5970
+ );
5971
+ const globalDefinition = globalDefinitionsByKey.get(
5972
+ buildGlobalKey({
5973
+ service_name: map.service_name,
5974
+ name: map.global_name,
5975
+ version: map.global_version
5976
+ })
5977
+ );
5978
+ return task?.is_meta !== true && task?.is_sub_meta !== true && globalDefinition?.is_meta !== true;
5979
+ }).sort(
5980
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5981
+ );
5982
+ const localMetaTaskToGlobalMaps = Array.from(taskGlobalMaps.values()).filter((map) => !businessTaskToGlobalMaps.includes(map)).sort(
5983
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5984
+ );
5985
+ const businessHelperToGlobalMaps = Array.from(helperGlobalMaps.values()).filter((map) => {
5986
+ const helper = helperDefinitionsByKey.get(
5987
+ buildHelperKey({
5988
+ service_name: map.service_name,
5989
+ name: map.helper_name,
5990
+ version: map.helper_version
5991
+ })
5992
+ );
5993
+ const globalDefinition = globalDefinitionsByKey.get(
5994
+ buildGlobalKey({
5995
+ service_name: map.service_name,
5996
+ name: map.global_name,
5997
+ version: map.global_version
5998
+ })
5999
+ );
6000
+ return helper?.is_meta !== true && globalDefinition?.is_meta !== true;
6001
+ }).sort(
6002
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
6003
+ );
6004
+ const localMetaHelperToGlobalMaps = Array.from(helperGlobalMaps.values()).filter((map) => !businessHelperToGlobalMaps.includes(map)).sort(
6005
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
6006
+ );
6007
+ const cumulativeHelpers = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelpers : [...businessHelpers, ...localMetaHelpers];
6008
+ const cumulativeGlobals = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessGlobals : [...businessGlobals, ...localMetaGlobals];
6009
+ const cumulativeTaskToHelperMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToHelperMaps : [...businessTaskToHelperMaps, ...localMetaTaskToHelperMaps];
6010
+ const cumulativeHelperToHelperMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelperToHelperMaps : [...businessHelperToHelperMaps, ...localMetaHelperToHelperMaps];
6011
+ const cumulativeTaskToGlobalMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToGlobalMaps : [...businessTaskToGlobalMaps, ...localMetaTaskToGlobalMaps];
6012
+ const cumulativeHelperToGlobalMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelperToGlobalMaps : [...businessHelperToGlobalMaps, ...localMetaHelperToGlobalMaps];
6013
+ const cumulativeDirectionalTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessDirectionalTaskMaps : Array.from(
6014
+ new Map(
6015
+ [...businessDirectionalTaskMaps, ...localMetaDirectionalTaskMaps].map(
6016
+ (map) => [
6017
+ `${map.predecessor_service_name}|${map.predecessor_task_name}|${map.predecessor_task_version}|${map.service_name}|${map.task_name}|${map.task_version}`,
6018
+ map
6019
+ ]
5001
6020
  )
5002
- )
6021
+ ).values()
6022
+ );
6023
+ const cumulativeActorTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
6024
+ new Map(
6025
+ [...businessActorTaskMaps, ...localMetaActorTaskMaps].map((map) => [
6026
+ `${map.service_name}|${map.actor_name}|${map.actor_version}|${map.task_name}|${map.task_version}|${map.mode}`,
6027
+ map
6028
+ ])
6029
+ ).values()
6030
+ ) : Array.from(
6031
+ new Map(
6032
+ [...businessActorTaskMaps, ...localMetaActorTaskMaps].map((map) => [
6033
+ `${map.service_name}|${map.actor_name}|${map.actor_version}|${map.task_name}|${map.task_version}|${map.mode}`,
6034
+ map
6035
+ ])
6036
+ ).values()
6037
+ );
6038
+ const cumulativeTaskToRoutineMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToRoutineMaps : Array.from(
6039
+ new Map(
6040
+ [...businessTaskToRoutineMaps, ...localMetaTaskToRoutineMaps].map((map) => [
6041
+ `${map.service_name}|${map.task_name}|${map.task_version}|${map.routine_name}|${map.routine_version}`,
6042
+ map
6043
+ ])
6044
+ ).values()
6045
+ );
6046
+ const manifestBody = {
6047
+ serviceName,
6048
+ serviceInstanceId,
6049
+ publicationLayer,
6050
+ tasks: cumulativeTasks,
6051
+ signals: cumulativeSignals,
6052
+ intents: cumulativeIntents,
6053
+ actors: cumulativeActors,
6054
+ routines: cumulativeRoutines,
6055
+ helpers: cumulativeHelpers,
6056
+ globals: cumulativeGlobals,
6057
+ directionalTaskMaps: cumulativeDirectionalTaskMaps,
6058
+ signalToTaskMaps: publicationLayer === "routing_capability" ? publishedSignalTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps] : [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps],
6059
+ intentToTaskMaps: publicationLayer === "routing_capability" ? publishedIntentTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps] : [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps],
6060
+ actorTaskMaps: cumulativeActorTaskMaps,
6061
+ taskToRoutineMaps: cumulativeTaskToRoutineMaps,
6062
+ taskToHelperMaps: cumulativeTaskToHelperMaps,
6063
+ helperToHelperMaps: cumulativeHelperToHelperMaps,
6064
+ taskToGlobalMaps: cumulativeTaskToGlobalMaps,
6065
+ helperToGlobalMaps: cumulativeHelperToGlobalMaps
5003
6066
  };
5004
6067
  return {
5005
6068
  ...manifestBody,
@@ -5043,6 +6106,20 @@ function explodeServiceManifestSnapshots(snapshots) {
5043
6106
  `${right.service_name}|${right.name}|${right.version}`
5044
6107
  )
5045
6108
  );
6109
+ const helpers = dedupe(
6110
+ snapshots.flatMap((snapshot) => snapshot.helpers),
6111
+ (helper) => `${helper.service_name}|${helper.name}|${helper.version}`,
6112
+ (left, right) => `${left.service_name}|${left.name}|${left.version}`.localeCompare(
6113
+ `${right.service_name}|${right.name}|${right.version}`
6114
+ )
6115
+ );
6116
+ const globals = dedupe(
6117
+ snapshots.flatMap((snapshot) => snapshot.globals),
6118
+ (globalDefinition) => `${globalDefinition.service_name}|${globalDefinition.name}|${globalDefinition.version}`,
6119
+ (left, right) => `${left.service_name}|${left.name}|${left.version}`.localeCompare(
6120
+ `${right.service_name}|${right.name}|${right.version}`
6121
+ )
6122
+ );
5046
6123
  const directionalTaskMaps = dedupe(
5047
6124
  snapshots.flatMap((snapshot) => snapshot.directionalTaskMaps),
5048
6125
  (map) => `${map.predecessor_service_name}|${map.predecessor_task_name}|${map.predecessor_task_version}|${map.service_name}|${map.task_name}|${map.task_version}`,
@@ -5078,17 +6155,51 @@ function explodeServiceManifestSnapshots(snapshots) {
5078
6155
  `${right.routine_name}|${right.routine_version}|${right.service_name}|${right.task_name}|${right.task_version}`
5079
6156
  )
5080
6157
  );
6158
+ const taskToHelperMaps = dedupe(
6159
+ snapshots.flatMap((snapshot) => snapshot.taskToHelperMaps),
6160
+ (map) => `${map.service_name}|${map.task_name}|${map.task_version}|${map.alias}|${map.helper_name}|${map.helper_version}`,
6161
+ (left, right) => `${left.service_name}|${left.task_name}|${left.alias}|${left.helper_name}`.localeCompare(
6162
+ `${right.service_name}|${right.task_name}|${right.alias}|${right.helper_name}`
6163
+ )
6164
+ );
6165
+ const helperToHelperMaps = dedupe(
6166
+ snapshots.flatMap((snapshot) => snapshot.helperToHelperMaps),
6167
+ (map) => `${map.service_name}|${map.helper_name}|${map.helper_version}|${map.alias}|${map.dependency_helper_name}|${map.dependency_helper_version}`,
6168
+ (left, right) => `${left.service_name}|${left.helper_name}|${left.alias}|${left.dependency_helper_name}`.localeCompare(
6169
+ `${right.service_name}|${right.helper_name}|${right.alias}|${right.dependency_helper_name}`
6170
+ )
6171
+ );
6172
+ const taskToGlobalMaps = dedupe(
6173
+ snapshots.flatMap((snapshot) => snapshot.taskToGlobalMaps),
6174
+ (map) => `${map.service_name}|${map.task_name}|${map.task_version}|${map.alias}|${map.global_name}|${map.global_version}`,
6175
+ (left, right) => `${left.service_name}|${left.task_name}|${left.alias}|${left.global_name}`.localeCompare(
6176
+ `${right.service_name}|${right.task_name}|${right.alias}|${right.global_name}`
6177
+ )
6178
+ );
6179
+ const helperToGlobalMaps = dedupe(
6180
+ snapshots.flatMap((snapshot) => snapshot.helperToGlobalMaps),
6181
+ (map) => `${map.service_name}|${map.helper_name}|${map.helper_version}|${map.alias}|${map.global_name}|${map.global_version}`,
6182
+ (left, right) => `${left.service_name}|${left.helper_name}|${left.alias}|${left.global_name}`.localeCompare(
6183
+ `${right.service_name}|${right.helper_name}|${right.alias}|${right.global_name}`
6184
+ )
6185
+ );
5081
6186
  return {
5082
6187
  tasks,
5083
6188
  signals,
5084
6189
  intents,
5085
6190
  actors,
5086
6191
  routines,
6192
+ helpers,
6193
+ globals,
5087
6194
  directionalTaskMaps,
5088
6195
  signalToTaskMaps,
5089
6196
  intentToTaskMaps,
5090
6197
  actorTaskMaps,
5091
- taskToRoutineMaps
6198
+ taskToRoutineMaps,
6199
+ taskToHelperMaps,
6200
+ helperToHelperMaps,
6201
+ taskToGlobalMaps,
6202
+ helperToGlobalMaps
5092
6203
  };
5093
6204
  }
5094
6205
 
@@ -5137,7 +6248,53 @@ var SERVICE_REGISTRY_TRACE_SERVICE2 = (process.env.CADENZA_SERVICE_REGISTRY_TRAC
5137
6248
  function shouldTraceServiceRegistry(serviceName) {
5138
6249
  return SERVICE_REGISTRY_TRACE_SERVICE2.length > 0 && serviceName === SERVICE_REGISTRY_TRACE_SERVICE2;
5139
6250
  }
5140
- function buildServiceRegistryInsertQueryData(ctx, queryData) {
6251
+ function normalizeLeaseStatus(value) {
6252
+ const status = String(value ?? "").trim();
6253
+ if (status === "active" || status === "non_responsive" || status === "inactive" || status === "deleted") {
6254
+ return status;
6255
+ }
6256
+ return null;
6257
+ }
6258
+ function overlayServiceInstancesWithLeases(serviceInstances, serviceInstanceLeases) {
6259
+ if (serviceInstanceLeases.length === 0) {
6260
+ return serviceInstances;
6261
+ }
6262
+ const leasesByInstanceId = /* @__PURE__ */ new Map();
6263
+ for (const row of serviceInstanceLeases) {
6264
+ const serviceInstanceId = String(
6265
+ row.service_instance_id ?? row.serviceInstanceId ?? ""
6266
+ ).trim();
6267
+ if (!serviceInstanceId) {
6268
+ continue;
6269
+ }
6270
+ leasesByInstanceId.set(serviceInstanceId, row);
6271
+ }
6272
+ return serviceInstances.map((row) => {
6273
+ const serviceInstanceId = String(row.uuid ?? "").trim();
6274
+ const lease = serviceInstanceId ? leasesByInstanceId.get(serviceInstanceId) : void 0;
6275
+ if (!lease) {
6276
+ return row;
6277
+ }
6278
+ const leaseStatus = normalizeLeaseStatus(
6279
+ lease.status ?? lease.lease_status ?? lease.leaseStatus
6280
+ );
6281
+ return {
6282
+ ...row,
6283
+ lease_status: leaseStatus ?? void 0,
6284
+ is_ready: typeof lease.is_ready === "boolean" ? lease.is_ready : typeof lease.isReady === "boolean" ? lease.isReady : void 0,
6285
+ readiness_reason: typeof lease.readiness_reason === "string" ? lease.readiness_reason : typeof lease.readinessReason === "string" ? lease.readinessReason : null,
6286
+ lease_expires_at: typeof lease.lease_expires_at === "string" ? lease.lease_expires_at : typeof lease.leaseExpiresAt === "string" ? lease.leaseExpiresAt : null,
6287
+ last_lease_renewed_at: typeof lease.last_lease_renewed_at === "string" ? lease.last_lease_renewed_at : typeof lease.lastLeaseRenewedAt === "string" ? lease.lastLeaseRenewedAt : null,
6288
+ last_ready_at: typeof lease.last_ready_at === "string" ? lease.last_ready_at : typeof lease.lastReadyAt === "string" ? lease.lastReadyAt : null,
6289
+ last_observed_transport_at: typeof lease.last_observed_transport_at === "string" ? lease.last_observed_transport_at : typeof lease.lastObservedTransportAt === "string" ? lease.lastObservedTransportAt : null,
6290
+ shutdown_requested_at: typeof lease.shutdown_requested_at === "string" ? lease.shutdown_requested_at : typeof lease.shutdownRequestedAt === "string" ? lease.shutdownRequestedAt : null,
6291
+ is_active: leaseStatus === "active" ? true : leaseStatus === "non_responsive" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : row.is_active,
6292
+ is_non_responsive: leaseStatus === "non_responsive" ? true : leaseStatus === "active" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : row.is_non_responsive,
6293
+ deleted: leaseStatus === "deleted" ? true : Boolean(row.deleted ?? false)
6294
+ };
6295
+ });
6296
+ }
6297
+ function buildServiceRegistryInsertQueryData(tableName, ctx, queryData) {
5141
6298
  const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
5142
6299
  const getJoinedValue = (key) => {
5143
6300
  for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
@@ -5155,7 +6312,8 @@ function buildServiceRegistryInsertQueryData(ctx, queryData) {
5155
6312
  if (!Object.prototype.hasOwnProperty.call(queryData, "onConflict")) {
5156
6313
  delete nextQueryData.onConflict;
5157
6314
  }
5158
- const resolvedData = Object.prototype.hasOwnProperty.call(ctx, "data") || ctx.data !== void 0 ? ctx.data : getJoinedValue("data");
6315
+ const preferRegistrationData = tableName === "service" || tableName === "service_instance" || tableName === "service_instance_transport";
6316
+ const resolvedData = preferRegistrationData ? registrationData ?? (Object.prototype.hasOwnProperty.call(ctx, "data") || ctx.data !== void 0 ? ctx.data : getJoinedValue("data")) : Object.prototype.hasOwnProperty.call(ctx, "data") || ctx.data !== void 0 ? ctx.data : getJoinedValue("data");
5159
6317
  const resolvedBatch = Object.prototype.hasOwnProperty.call(ctx, "batch") || ctx.batch !== void 0 ? ctx.batch : getJoinedValue("batch");
5160
6318
  const nextData = resolvedData !== void 0 ? resolvedData && typeof resolvedData === "object" ? { ...resolvedData } : resolvedData : registrationData && typeof registrationData === "object" && !Array.isArray(registrationData) ? { ...registrationData } : registrationData;
5161
6319
  if (nextData !== void 0) {
@@ -5182,8 +6340,151 @@ function sanitizeServiceRegistryInsertExecutionContext(ctx) {
5182
6340
  delete sanitized.returnedValue;
5183
6341
  delete sanitized.queryData;
5184
6342
  delete sanitized.onConflict;
6343
+ delete sanitized.task;
6344
+ delete sanitized.routine;
6345
+ delete sanitized.httpServer;
6346
+ delete sanitized.service;
6347
+ delete sanitized.serviceInstance;
6348
+ delete sanitized.joinedContexts;
6349
+ delete sanitized.__declaredTransports;
6350
+ delete sanitized.__resolverOriginalContext;
6351
+ delete sanitized.__resolverQueryData;
6352
+ return sanitized;
6353
+ }
6354
+ function sanitizeAuthorityBootstrapDelegationContext(ctx) {
6355
+ const sanitized = stripDelegationRequestSnapshot({
6356
+ ...ctx
6357
+ });
6358
+ delete sanitized.__resolverOriginalContext;
6359
+ delete sanitized.__resolverQueryData;
6360
+ delete sanitized.joinedContexts;
6361
+ delete sanitized.httpServer;
6362
+ delete sanitized.service;
6363
+ delete sanitized.serviceInstance;
6364
+ delete sanitized.task;
6365
+ delete sanitized.routine;
6366
+ delete sanitized.__declaredTransports;
6367
+ const queryData = sanitized.queryData && typeof sanitized.queryData === "object" ? { ...sanitized.queryData } : null;
6368
+ if (queryData) {
6369
+ delete queryData.joinedContexts;
6370
+ sanitized.queryData = queryData;
6371
+ }
5185
6372
  return sanitized;
5186
6373
  }
6374
+ var BOOTSTRAP_DB_OPERATION_CONTEXT_KEYS = [
6375
+ "data",
6376
+ "batch",
6377
+ "transaction",
6378
+ "onConflict",
6379
+ "filter",
6380
+ "fields",
6381
+ "joins",
6382
+ "sort",
6383
+ "limit",
6384
+ "offset",
6385
+ "queryMode",
6386
+ "aggregates",
6387
+ "groupBy"
6388
+ ];
6389
+ function isBootstrapDbOperationRoutineName(value) {
6390
+ return /^(Insert|Update|Query|Delete)\s+/.test(String(value ?? "").trim());
6391
+ }
6392
+ function compactAuthorityBootstrapRequestBody(ctx) {
6393
+ if (!isBootstrapDbOperationRoutineName(ctx.__remoteRoutineName)) {
6394
+ return ctx;
6395
+ }
6396
+ const queryData = ctx.queryData && typeof ctx.queryData === "object" ? { ...ctx.queryData } : null;
6397
+ if (!queryData) {
6398
+ return ctx;
6399
+ }
6400
+ const compacted = {
6401
+ ...ctx,
6402
+ queryData
6403
+ };
6404
+ for (const key of BOOTSTRAP_DB_OPERATION_CONTEXT_KEYS) {
6405
+ if (Object.prototype.hasOwnProperty.call(queryData, key)) {
6406
+ delete compacted[key];
6407
+ }
6408
+ }
6409
+ return compacted;
6410
+ }
6411
+ function cloneServiceRegistryContextValue(value) {
6412
+ if (value instanceof Date) {
6413
+ return new Date(value.getTime());
6414
+ }
6415
+ if (Array.isArray(value)) {
6416
+ return value.map(
6417
+ (entry) => cloneServiceRegistryContextValue(entry)
6418
+ );
6419
+ }
6420
+ if (value && typeof value === "object") {
6421
+ const clone = {};
6422
+ for (const [key, nestedValue] of Object.entries(value)) {
6423
+ clone[key] = cloneServiceRegistryContextValue(nestedValue);
6424
+ }
6425
+ return clone;
6426
+ }
6427
+ return value;
6428
+ }
6429
+ function buildServiceRegistryResolverOriginalContext(tableName, ctx, queryData) {
6430
+ const originalContext = {};
6431
+ for (const key of [
6432
+ "__serviceName",
6433
+ "serviceName",
6434
+ "__serviceInstanceId",
6435
+ "serviceInstanceId",
6436
+ "__registrationData",
6437
+ "__reason",
6438
+ "__syncing",
6439
+ "__syncSourceServiceName",
6440
+ "__preferredTransportProtocol",
6441
+ "__networkMode",
6442
+ "__securityProfile",
6443
+ "__loadBalance",
6444
+ "__cadenzaDBConnect",
6445
+ "__isFrontend",
6446
+ "__isDatabase",
6447
+ "__retryCount",
6448
+ "__retries",
6449
+ "__triedInstances"
6450
+ ]) {
6451
+ if (ctx[key] !== void 0) {
6452
+ originalContext[key] = cloneServiceRegistryContextValue(ctx[key]);
6453
+ }
6454
+ }
6455
+ if (queryData.data !== void 0) {
6456
+ originalContext.data = cloneServiceRegistryContextValue(queryData.data);
6457
+ }
6458
+ if (queryData.batch !== void 0) {
6459
+ originalContext.batch = cloneServiceRegistryContextValue(queryData.batch);
6460
+ }
6461
+ if (Object.prototype.hasOwnProperty.call(queryData, "onConflict")) {
6462
+ originalContext.queryData = {
6463
+ data: queryData.data !== void 0 ? cloneServiceRegistryContextValue(queryData.data) : void 0,
6464
+ batch: queryData.batch !== void 0 ? cloneServiceRegistryContextValue(queryData.batch) : void 0,
6465
+ onConflict: cloneServiceRegistryContextValue(queryData.onConflict)
6466
+ };
6467
+ } else if (queryData.data !== void 0 || queryData.batch !== void 0) {
6468
+ originalContext.queryData = {
6469
+ data: queryData.data !== void 0 ? cloneServiceRegistryContextValue(queryData.data) : void 0,
6470
+ batch: queryData.batch !== void 0 ? cloneServiceRegistryContextValue(queryData.batch) : void 0
6471
+ };
6472
+ }
6473
+ if (tableName === "service_instance") {
6474
+ for (const key of [
6475
+ "__transportData",
6476
+ "transportData",
6477
+ "__useSocket",
6478
+ "__retryCount",
6479
+ "__isFrontend"
6480
+ ]) {
6481
+ if (ctx[key] !== void 0) {
6482
+ originalContext[key] = cloneServiceRegistryContextValue(ctx[key]);
6483
+ }
6484
+ }
6485
+ }
6486
+ return originalContext;
6487
+ }
5187
6488
  function clearTransientRoutingErrorState(context) {
5188
6489
  delete context.errored;
5189
6490
  delete context.failed;
@@ -5239,7 +6540,8 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
5239
6540
  delete result.__resolverOriginalContext;
5240
6541
  delete result.__resolverQueryData;
5241
6542
  const normalizedQueryData = result.queryData && typeof result.queryData === "object" ? { ...result.queryData } : { ...queryData };
5242
- const resolvedData = result.data ?? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData;
6543
+ const preferRequestedData = tableName === "service" || tableName === "service_instance" || tableName === "service_instance_transport";
6544
+ const resolvedData = preferRequestedData ? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData ?? result.data : result.data ?? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData;
5243
6545
  if (resolvedData !== void 0 && result.data === void 0) {
5244
6546
  result.data = resolvedData;
5245
6547
  }
@@ -5269,6 +6571,7 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
5269
6571
  ).trim();
5270
6572
  if (resolvedServiceName) {
5271
6573
  result.__serviceName = resolvedServiceName;
6574
+ result.serviceName = resolvedServiceName;
5272
6575
  }
5273
6576
  }
5274
6577
  const resolvedLocalServiceInstanceId = String(
@@ -5277,6 +6580,18 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
5277
6580
  if (resolvedLocalServiceInstanceId) {
5278
6581
  result.__serviceInstanceId = resolvedLocalServiceInstanceId;
5279
6582
  }
6583
+ if (tableName === "service_instance") {
6584
+ const resolvedServiceName = String(
6585
+ ctx.__serviceName ?? resolveServiceNameFromContext(ctx) ?? resolvedData?.service_name ?? resolvedData?.serviceName ?? ""
6586
+ ).trim();
6587
+ if (resolvedServiceName) {
6588
+ result.__serviceName = resolvedServiceName;
6589
+ result.serviceName = resolvedServiceName;
6590
+ }
6591
+ if (resolvedLocalServiceInstanceId) {
6592
+ result.serviceInstanceId = resolvedLocalServiceInstanceId;
6593
+ }
6594
+ }
5280
6595
  if (tableName === "service_instance" || tableName === "service_instance_transport") {
5281
6596
  const resolvedUuid = String(
5282
6597
  result.uuid ?? resolvedData?.uuid ?? ctx.__serviceInstanceId ?? ""
@@ -5376,9 +6691,15 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5376
6691
  ctx
5377
6692
  );
5378
6693
  const nextQueryData = buildServiceRegistryInsertQueryData(
6694
+ tableName,
5379
6695
  sanitizedContext,
5380
6696
  queryData
5381
6697
  );
6698
+ const resolverOriginalContext = buildServiceRegistryResolverOriginalContext(
6699
+ tableName,
6700
+ sanitizedContext,
6701
+ nextQueryData
6702
+ );
5382
6703
  const delegationContext = ensureDelegationContextMetadata({
5383
6704
  ...sanitizedContext,
5384
6705
  data: nextQueryData.data !== void 0 ? nextQueryData.data : sanitizedContext.data,
@@ -5391,9 +6712,7 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5391
6712
  delegationContext.__metadata.__blockRemoteExecution = delegationContext.__metadata.__blockRemoteExecution ?? delegationContext.__blockRemoteExecution ?? false;
5392
6713
  const nextContext = {
5393
6714
  ...delegationContext,
5394
- __resolverOriginalContext: {
5395
- ...sanitizedContext
5396
- },
6715
+ __resolverOriginalContext: resolverOriginalContext,
5397
6716
  __resolverQueryData: nextQueryData
5398
6717
  };
5399
6718
  if (tableName === "service_instance_transport" && shouldTraceServiceRegistry(
@@ -5445,108 +6764,6 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5445
6764
  `Resolve service registry insert for ${tableName}`,
5446
6765
  (ctx, emit2) => new Promise((resolve) => {
5447
6766
  const resolverRequestId = (0, import_uuid3.v4)();
5448
- CadenzaService.createEphemeralMetaTask(
5449
- `Resolve service registry insert execution for ${tableName} (${resolverRequestId})`,
5450
- (resultCtx) => {
5451
- if (tableName === "service_instance" && shouldTraceServiceRegistry(
5452
- resolveServiceNameFromContext(
5453
- resultCtx.__resolverOriginalContext ?? resultCtx ?? ctx
5454
- ) || CadenzaService.serviceRegistry.serviceName
5455
- )) {
5456
- console.log("[CADENZA_SERVICE_REGISTRY_TRACE] resolver_service_instance_signal", {
5457
- localServiceName: CadenzaService.serviceRegistry.serviceName,
5458
- resolverRequestId,
5459
- incomingResolverRequestId: resultCtx.__resolverRequestId ?? null,
5460
- keys: resultCtx && typeof resultCtx === "object" ? Object.keys(resultCtx) : []
5461
- });
5462
- }
5463
- if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
5464
- console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert_signal", {
5465
- tableName,
5466
- resolverRequestId,
5467
- incomingResolverRequestId: resultCtx.__resolverRequestId ?? null,
5468
- errored: resultCtx.errored === true,
5469
- error: resultCtx.__error ?? null,
5470
- keys: resultCtx && typeof resultCtx === "object" ? Object.keys(resultCtx) : []
5471
- });
5472
- }
5473
- if (resultCtx.__resolverRequestId !== resolverRequestId) {
5474
- return false;
5475
- }
5476
- const normalizedResult = normalizeServiceRegistryInsertResult(
5477
- tableName,
5478
- resultCtx.__resolverOriginalContext ?? ctx,
5479
- resultCtx.__resolverQueryData ?? resultCtx.queryData ?? ctx.queryData ?? {},
5480
- resultCtx
5481
- );
5482
- if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
5483
- console.log("[CADENZA_INSTANCE_DEBUG] finalize_service_registry_insert", {
5484
- tableName,
5485
- hasNormalized: !!normalizedResult,
5486
- normalizedKeys: normalizedResult && typeof normalizedResult === "object" ? Object.keys(normalizedResult) : [],
5487
- uuid: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.uuid ?? normalizedResult.data?.uuid ?? normalizedResult.queryData?.data?.uuid ?? null : null,
5488
- serviceName: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__serviceName ?? normalizedResult.data?.service_name ?? normalizedResult.queryData?.data?.service_name ?? null : null,
5489
- errored: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.errored === true : false,
5490
- error: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__error ?? null : null,
5491
- inquiryMeta: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__inquiryMeta ?? null : null
5492
- });
5493
- }
5494
- if (normalizedResult && typeof normalizedResult === "object" && tableName === "service_instance_transport" && shouldTraceServiceRegistry(
5495
- resolveServiceNameFromContext(
5496
- resultCtx.__resolverOriginalContext ?? resultCtx
5497
- ) || CadenzaService.serviceRegistry.serviceName
5498
- )) {
5499
- console.log("[CADENZA_SERVICE_REGISTRY_TRACE] finalize_transport_insert_execution", {
5500
- localServiceName: CadenzaService.serviceRegistry.serviceName,
5501
- serviceName: resolveServiceNameFromContext(
5502
- resultCtx.__resolverOriginalContext ?? resultCtx
5503
- ) || CadenzaService.serviceRegistry.serviceName,
5504
- uuid: normalizedResult.uuid ?? normalizedResult.data?.uuid ?? null,
5505
- errored: normalizedResult.errored === true,
5506
- error: normalizedResult.__error ?? null,
5507
- data: normalizedResult.data ?? normalizedResult.queryData?.data ?? null
5508
- });
5509
- }
5510
- if (normalizedResult && typeof normalizedResult === "object" && tableName === "service_instance") {
5511
- const traceServiceName = resolveServiceNameFromContext(
5512
- resultCtx.__resolverOriginalContext ?? resultCtx
5513
- ) || CadenzaService.serviceRegistry.serviceName;
5514
- if (shouldTraceServiceRegistry(traceServiceName)) {
5515
- console.log("[CADENZA_SERVICE_REGISTRY_TRACE] service_instance_insert_resolved", {
5516
- localServiceName: CadenzaService.serviceRegistry.serviceName,
5517
- serviceName: traceServiceName,
5518
- serviceInstanceId: normalizedResult.__serviceInstanceId ?? normalizedResult.uuid ?? normalizedResult.data?.uuid ?? null,
5519
- hasTransportData: Array.isArray(normalizedResult.__transportData) || Array.isArray(normalizedResult.transportData),
5520
- transportCount: Array.isArray(
5521
- normalizedResult.__transportData
5522
- ) ? normalizedResult.__transportData.length : Array.isArray(normalizedResult.transportData) ? normalizedResult.transportData.length : 0,
5523
- errored: normalizedResult.errored === true,
5524
- error: normalizedResult.__error ?? null
5525
- });
5526
- }
5527
- emit2(
5528
- META_SERVICE_INSTANCE_INSERT_RESOLVED_SIGNAL,
5529
- normalizedResult
5530
- );
5531
- }
5532
- if (!normalizedResult || typeof normalizedResult !== "object") {
5533
- resolve(normalizedResult);
5534
- return normalizedResult;
5535
- }
5536
- const resolvedResult = {
5537
- ...normalizedResult
5538
- };
5539
- delete resolvedResult.__resolverRequestId;
5540
- delete resolvedResult.__resolverOriginalContext;
5541
- delete resolvedResult.__resolverQueryData;
5542
- resolve(resolvedResult);
5543
- return resolvedResult;
5544
- },
5545
- `Resolves signal-driven ${tableName} service-registry insert execution.`,
5546
- {
5547
- register: false
5548
- }
5549
- ).doOn(executionResolvedSignal, executionFailedSignal);
5550
6767
  const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
5551
6768
  const bootstrapAuthorityInsertSpec = !localInsertTask && CadenzaService.serviceRegistry.connectsToCadenzaDB ? getAuthorityBootstrapInsertIntentSpecForTable(tableName) : null;
5552
6769
  const resolvedTargetServiceName = resolveServiceNameFromContext(ctx);
@@ -5565,6 +6782,7 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5565
6782
  if (bootstrapAuthorityInsertSpec) {
5566
6783
  const sanitizedContext = sanitizeServiceRegistryInsertExecutionContext(ctx);
5567
6784
  const nextQueryData = buildServiceRegistryInsertQueryData(
6785
+ tableName,
5568
6786
  sanitizedContext,
5569
6787
  queryData
5570
6788
  );
@@ -5632,6 +6850,110 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5632
6850
  wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
5633
6851
  wiredLocalTaskNames.add(localInsertTask.name);
5634
6852
  }
6853
+ CadenzaService.createEphemeralMetaTask(
6854
+ `Resolve service registry insert execution for ${tableName} (${resolverRequestId})`,
6855
+ (resultCtx) => {
6856
+ if (tableName === "service_instance" && shouldTraceServiceRegistry(
6857
+ resolveServiceNameFromContext(
6858
+ resultCtx.__resolverOriginalContext ?? resultCtx ?? ctx
6859
+ ) || CadenzaService.serviceRegistry.serviceName
6860
+ )) {
6861
+ console.log("[CADENZA_SERVICE_REGISTRY_TRACE] resolver_service_instance_signal", {
6862
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
6863
+ resolverRequestId,
6864
+ incomingResolverRequestId: resultCtx.__resolverRequestId ?? null,
6865
+ keys: resultCtx && typeof resultCtx === "object" ? Object.keys(resultCtx) : []
6866
+ });
6867
+ }
6868
+ if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
6869
+ console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert_signal", {
6870
+ tableName,
6871
+ resolverRequestId,
6872
+ incomingResolverRequestId: resultCtx.__resolverRequestId ?? null,
6873
+ errored: resultCtx.errored === true,
6874
+ error: resultCtx.__error ?? null,
6875
+ keys: resultCtx && typeof resultCtx === "object" ? Object.keys(resultCtx) : []
6876
+ });
6877
+ }
6878
+ if (resultCtx.__resolverRequestId !== resolverRequestId) {
6879
+ return false;
6880
+ }
6881
+ const normalizedResult = normalizeServiceRegistryInsertResult(
6882
+ tableName,
6883
+ resultCtx.__resolverOriginalContext ?? ctx,
6884
+ resultCtx.__resolverQueryData ?? resultCtx.queryData ?? ctx.queryData ?? {},
6885
+ resultCtx
6886
+ );
6887
+ if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
6888
+ console.log("[CADENZA_INSTANCE_DEBUG] finalize_service_registry_insert", {
6889
+ tableName,
6890
+ hasNormalized: !!normalizedResult,
6891
+ normalizedKeys: normalizedResult && typeof normalizedResult === "object" ? Object.keys(normalizedResult) : [],
6892
+ uuid: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.uuid ?? normalizedResult.data?.uuid ?? normalizedResult.queryData?.data?.uuid ?? null : null,
6893
+ serviceName: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__serviceName ?? normalizedResult.data?.service_name ?? normalizedResult.queryData?.data?.service_name ?? null : null,
6894
+ errored: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.errored === true : false,
6895
+ error: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__error ?? null : null,
6896
+ inquiryMeta: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__inquiryMeta ?? null : null
6897
+ });
6898
+ }
6899
+ if (normalizedResult && typeof normalizedResult === "object" && tableName === "service_instance_transport" && shouldTraceServiceRegistry(
6900
+ resolveServiceNameFromContext(
6901
+ resultCtx.__resolverOriginalContext ?? resultCtx
6902
+ ) || CadenzaService.serviceRegistry.serviceName
6903
+ )) {
6904
+ console.log("[CADENZA_SERVICE_REGISTRY_TRACE] finalize_transport_insert_execution", {
6905
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
6906
+ serviceName: resolveServiceNameFromContext(
6907
+ resultCtx.__resolverOriginalContext ?? resultCtx
6908
+ ) || CadenzaService.serviceRegistry.serviceName,
6909
+ uuid: normalizedResult.uuid ?? normalizedResult.data?.uuid ?? null,
6910
+ errored: normalizedResult.errored === true,
6911
+ error: normalizedResult.__error ?? null,
6912
+ data: normalizedResult.data ?? normalizedResult.queryData?.data ?? null
6913
+ });
6914
+ }
6915
+ if (normalizedResult && typeof normalizedResult === "object" && tableName === "service_instance") {
6916
+ const traceServiceName = resolveServiceNameFromContext(
6917
+ resultCtx.__resolverOriginalContext ?? resultCtx
6918
+ ) || CadenzaService.serviceRegistry.serviceName;
6919
+ if (shouldTraceServiceRegistry(traceServiceName)) {
6920
+ console.log("[CADENZA_SERVICE_REGISTRY_TRACE] service_instance_insert_resolved", {
6921
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
6922
+ serviceName: traceServiceName,
6923
+ serviceInstanceId: normalizedResult.__serviceInstanceId ?? normalizedResult.uuid ?? normalizedResult.data?.uuid ?? null,
6924
+ hasTransportData: Array.isArray(normalizedResult.__transportData) || Array.isArray(normalizedResult.transportData),
6925
+ transportCount: Array.isArray(
6926
+ normalizedResult.__transportData
6927
+ ) ? normalizedResult.__transportData.length : Array.isArray(normalizedResult.transportData) ? normalizedResult.transportData.length : 0,
6928
+ errored: normalizedResult.errored === true,
6929
+ error: normalizedResult.__error ?? null
6930
+ });
6931
+ }
6932
+ emit2(
6933
+ META_SERVICE_INSTANCE_INSERT_RESOLVED_SIGNAL,
6934
+ normalizedResult
6935
+ );
6936
+ }
6937
+ if (!normalizedResult || typeof normalizedResult !== "object") {
6938
+ resolve(normalizedResult);
6939
+ return normalizedResult;
6940
+ }
6941
+ const resolvedResult = {
6942
+ ...normalizedResult
6943
+ };
6944
+ delete resolvedResult.__resolverRequestId;
6945
+ delete resolvedResult.__resolverOriginalContext;
6946
+ delete resolvedResult.__resolverQueryData;
6947
+ resolve(resolvedResult);
6948
+ return resolvedResult;
6949
+ },
6950
+ `Resolves signal-driven ${tableName} service-registry insert execution.`,
6951
+ {
6952
+ register: false,
6953
+ once: false,
6954
+ destroyCondition: (result) => result !== false
6955
+ }
6956
+ ).doOn(executionResolvedSignal, executionFailedSignal);
5635
6957
  emit2(executionSignal, {
5636
6958
  ...ctx,
5637
6959
  __resolverRequestId: resolverRequestId
@@ -5656,6 +6978,17 @@ function readPositiveIntegerEnv(name, fallback) {
5656
6978
  }
5657
6979
  return normalized;
5658
6980
  }
6981
+ function readNonNegativeFloatEnv(name, fallback) {
6982
+ if (typeof process === "undefined") {
6983
+ return fallback;
6984
+ }
6985
+ const raw = process.env?.[name];
6986
+ const parsed = Number(raw);
6987
+ if (!Number.isFinite(parsed) || parsed < 0) {
6988
+ return fallback;
6989
+ }
6990
+ return parsed;
6991
+ }
5659
6992
  var ServiceRegistry = class _ServiceRegistry {
5660
6993
  /**
5661
6994
  * Initializes a private constructor for managing service instances, remote signals,
@@ -5705,6 +7038,9 @@ var ServiceRegistry = class _ServiceRegistry {
5705
7038
  "CADENZA_RUNTIME_STATUS_REST_REFRESH_MS",
5706
7039
  this.runtimeMetricsSampleIntervalMs
5707
7040
  );
7041
+ this.runtimeStatusLoopJitterRatio = normalizeJitterRatio(
7042
+ readNonNegativeFloatEnv("CADENZA_RUNTIME_STATUS_JITTER_RATIO", 0.2)
7043
+ );
5708
7044
  this.runtimeStatusMissThreshold = readPositiveIntegerEnv(
5709
7045
  "CADENZA_RUNTIME_STATUS_MISSED_HEARTBEATS",
5710
7046
  3
@@ -5753,6 +7089,18 @@ var ServiceRegistry = class _ServiceRegistry {
5753
7089
  "CADENZA_RUNTIME_STATUS_OVERLOADED_GRAPH_THRESHOLD",
5754
7090
  20
5755
7091
  );
7092
+ this.bootstrapFullSyncRetryJitterRatio = normalizeJitterRatio(
7093
+ readNonNegativeFloatEnv(
7094
+ "CADENZA_BOOTSTRAP_FULL_SYNC_RETRY_JITTER_RATIO",
7095
+ 0.2
7096
+ )
7097
+ );
7098
+ this.serviceCommunicationRetryJitterRatio = normalizeJitterRatio(
7099
+ readNonNegativeFloatEnv(
7100
+ "CADENZA_SERVICE_COMMUNICATION_RETRY_JITTER_RATIO",
7101
+ 0.2
7102
+ )
7103
+ );
5756
7104
  this.serviceName = null;
5757
7105
  this.serviceInstanceId = null;
5758
7106
  this.numberOfRunningGraphs = 0;
@@ -5999,6 +7347,9 @@ var ServiceRegistry = class _ServiceRegistry {
5999
7347
  ctx.deleted ?? ctx.serviceInstance?.deleted ?? ctx.data?.deleted
6000
7348
  );
6001
7349
  if (uuid10 === this.serviceInstanceId) return;
7350
+ if (serviceName === this.serviceName) {
7351
+ return false;
7352
+ }
6002
7353
  if (deleted) {
6003
7354
  const existingInstance = this.instances.get(serviceName)?.find((instance) => instance.uuid === uuid10);
6004
7355
  const indexToDelete = this.instances.get(serviceName)?.findIndex((i) => i.uuid === uuid10) ?? -1;
@@ -6085,9 +7436,6 @@ var ServiceRegistry = class _ServiceRegistry {
6085
7436
  emit2
6086
7437
  );
6087
7438
  }
6088
- if (this.serviceName === serviceName) {
6089
- return false;
6090
- }
6091
7439
  if (trackedInstance?.isFrontend) {
6092
7440
  return true;
6093
7441
  }
@@ -6141,6 +7489,9 @@ var ServiceRegistry = class _ServiceRegistry {
6141
7489
  if (!ownerInstance) {
6142
7490
  return false;
6143
7491
  }
7492
+ if (ownerInstance.serviceName === this.serviceName && ownerInstance.uuid !== this.serviceInstanceId) {
7493
+ return false;
7494
+ }
6144
7495
  if (transport.deleted) {
6145
7496
  this.clearTransportFailureState(ownerInstance.uuid, transport.uuid);
6146
7497
  const transportKey = this.buildTransportRouteKey(
@@ -6728,6 +8079,12 @@ var ServiceRegistry = class _ServiceRegistry {
6728
8079
  const tasks = this.readArrayPayload(inquiryResult, [
6729
8080
  "tasks"
6730
8081
  ]);
8082
+ const helpers = this.readArrayPayload(inquiryResult, [
8083
+ "helpers"
8084
+ ]);
8085
+ const globals = this.readArrayPayload(inquiryResult, [
8086
+ "globals"
8087
+ ]);
6731
8088
  const signals = this.readArrayPayload(inquiryResult, [
6732
8089
  "signals"
6733
8090
  ]);
@@ -6752,6 +8109,22 @@ var ServiceRegistry = class _ServiceRegistry {
6752
8109
  inquiryResult,
6753
8110
  ["taskToRoutineMaps", "task_to_routine_maps"]
6754
8111
  );
8112
+ const taskToHelperMaps = this.readArrayPayload(
8113
+ inquiryResult,
8114
+ ["taskToHelperMaps", "task_to_helper_maps"]
8115
+ );
8116
+ const helperToHelperMaps = this.readArrayPayload(
8117
+ inquiryResult,
8118
+ ["helperToHelperMaps", "helper_to_helper_maps"]
8119
+ );
8120
+ const taskToGlobalMaps = this.readArrayPayload(
8121
+ inquiryResult,
8122
+ ["taskToGlobalMaps", "task_to_global_maps"]
8123
+ );
8124
+ const helperToGlobalMaps = this.readArrayPayload(
8125
+ inquiryResult,
8126
+ ["helperToGlobalMaps", "helper_to_global_maps"]
8127
+ );
6755
8128
  const serviceInstances = this.normalizeServiceInstancesFromSync(
6756
8129
  inquiryResult
6757
8130
  );
@@ -6785,6 +8158,8 @@ var ServiceRegistry = class _ServiceRegistry {
6785
8158
  serviceInstanceTransports: serviceInstanceTransports.length,
6786
8159
  serviceManifests: serviceManifests.length,
6787
8160
  tasks: tasks.length,
8161
+ helpers: helpers.length,
8162
+ globals: globals.length,
6788
8163
  signals: signals.length,
6789
8164
  intents: intents.length,
6790
8165
  actors: actors.length,
@@ -6810,6 +8185,8 @@ var ServiceRegistry = class _ServiceRegistry {
6810
8185
  serviceInstanceTransports,
6811
8186
  serviceManifests,
6812
8187
  tasks,
8188
+ helpers,
8189
+ globals,
6813
8190
  signals,
6814
8191
  intents,
6815
8192
  actors,
@@ -6817,6 +8194,10 @@ var ServiceRegistry = class _ServiceRegistry {
6817
8194
  directionalTaskMaps,
6818
8195
  actorTaskMaps,
6819
8196
  taskToRoutineMaps,
8197
+ taskToHelperMaps,
8198
+ helperToHelperMaps,
8199
+ taskToGlobalMaps,
8200
+ helperToGlobalMaps,
6820
8201
  __inquiryMeta: inquiryResult.__inquiryMeta
6821
8202
  };
6822
8203
  },
@@ -7436,29 +8817,51 @@ var ServiceRegistry = class _ServiceRegistry {
7436
8817
  this.runtimeStatusHeartbeatStarted = true;
7437
8818
  if (!this.runtimeMetricsSamplingStarted) {
7438
8819
  this.runtimeMetricsSamplingStarted = true;
8820
+ CadenzaService.emit(META_RUNTIME_METRICS_SAMPLE_TICK_SIGNAL, {});
7439
8821
  CadenzaService.interval(
7440
8822
  META_RUNTIME_METRICS_SAMPLE_TICK_SIGNAL,
7441
8823
  {},
7442
8824
  this.runtimeMetricsSampleIntervalMs,
7443
- true
8825
+ false,
8826
+ this.buildJitteredIntervalStartDate(
8827
+ this.runtimeMetricsSampleIntervalMs,
8828
+ "runtime-metrics-sample"
8829
+ )
7444
8830
  );
7445
8831
  }
8832
+ CadenzaService.emit(META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL, {
8833
+ reason: "heartbeat"
8834
+ });
7446
8835
  CadenzaService.interval(
7447
8836
  META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL,
7448
8837
  { reason: "heartbeat" },
7449
8838
  this.runtimeStatusHeartbeatIntervalMs,
7450
- true
8839
+ false,
8840
+ this.buildJitteredIntervalStartDate(
8841
+ this.runtimeStatusHeartbeatIntervalMs,
8842
+ "runtime-status-heartbeat"
8843
+ )
7451
8844
  );
7452
8845
  CadenzaService.interval(
7453
8846
  META_RUNTIME_STATUS_MONITOR_TICK_SIGNAL,
7454
8847
  {},
7455
- this.runtimeStatusHeartbeatIntervalMs
8848
+ this.runtimeStatusHeartbeatIntervalMs,
8849
+ false,
8850
+ this.buildJitteredIntervalStartDate(
8851
+ this.runtimeStatusHeartbeatIntervalMs,
8852
+ "runtime-status-monitor"
8853
+ )
7456
8854
  );
8855
+ CadenzaService.emit(META_RUNTIME_STATUS_REST_REFRESH_TICK_SIGNAL, {});
7457
8856
  CadenzaService.interval(
7458
8857
  META_RUNTIME_STATUS_REST_REFRESH_TICK_SIGNAL,
7459
8858
  {},
7460
8859
  this.runtimeStatusRestRefreshIntervalMs,
7461
- true
8860
+ false,
8861
+ this.buildJitteredIntervalStartDate(
8862
+ this.runtimeStatusRestRefreshIntervalMs,
8863
+ "runtime-status-rest-refresh"
8864
+ )
7462
8865
  );
7463
8866
  return true;
7464
8867
  },
@@ -8463,11 +9866,14 @@ var ServiceRegistry = class _ServiceRegistry {
8463
9866
  }
8464
9867
  collectBootstrapFullSyncPayload(ctx) {
8465
9868
  const serviceInstances = [];
9869
+ const serviceInstanceLeases = [];
8466
9870
  const serviceInstanceTransports = [];
8467
9871
  const manifestSnapshots = [];
8468
9872
  const signalToTaskMaps = [];
8469
9873
  const intentToTaskMaps = [];
8470
9874
  const tasks = [];
9875
+ const helpers = [];
9876
+ const globals = [];
8471
9877
  const signals = [];
8472
9878
  const intents = [];
8473
9879
  const actors = [];
@@ -8475,11 +9881,18 @@ var ServiceRegistry = class _ServiceRegistry {
8475
9881
  const directionalTaskMaps = [];
8476
9882
  const actorTaskMaps = [];
8477
9883
  const taskToRoutineMaps = [];
9884
+ const taskToHelperMaps = [];
9885
+ const helperToHelperMaps = [];
9886
+ const taskToGlobalMaps = [];
9887
+ const helperToGlobalMaps = [];
8478
9888
  const seenServiceInstances = /* @__PURE__ */ new Set();
9889
+ const seenServiceInstanceLeases = /* @__PURE__ */ new Set();
8479
9890
  const seenServiceInstanceTransports = /* @__PURE__ */ new Set();
8480
9891
  const seenSignalMaps = /* @__PURE__ */ new Set();
8481
9892
  const seenIntentMaps = /* @__PURE__ */ new Set();
8482
9893
  const seenTasks = /* @__PURE__ */ new Set();
9894
+ const seenHelpers = /* @__PURE__ */ new Set();
9895
+ const seenGlobals = /* @__PURE__ */ new Set();
8483
9896
  const seenSignals = /* @__PURE__ */ new Set();
8484
9897
  const seenIntents = /* @__PURE__ */ new Set();
8485
9898
  const seenActors = /* @__PURE__ */ new Set();
@@ -8487,6 +9900,10 @@ var ServiceRegistry = class _ServiceRegistry {
8487
9900
  const seenDirectionalTaskMaps = /* @__PURE__ */ new Set();
8488
9901
  const seenActorTaskMaps = /* @__PURE__ */ new Set();
8489
9902
  const seenTaskToRoutineMaps = /* @__PURE__ */ new Set();
9903
+ const seenTaskToHelperMaps = /* @__PURE__ */ new Set();
9904
+ const seenHelperToHelperMaps = /* @__PURE__ */ new Set();
9905
+ const seenTaskToGlobalMaps = /* @__PURE__ */ new Set();
9906
+ const seenHelperToGlobalMaps = /* @__PURE__ */ new Set();
8490
9907
  const contexts = Array.isArray(ctx.joinedContexts) ? [ctx, ...ctx.joinedContexts] : [ctx];
8491
9908
  const pushUnique = (rows, target, seen, keyResolver) => {
8492
9909
  for (const row of rows) {
@@ -8517,6 +9934,12 @@ var ServiceRegistry = class _ServiceRegistry {
8517
9934
  "serviceInstance",
8518
9935
  "service_instance"
8519
9936
  ]);
9937
+ const serviceInstanceLeaseRows = readDirectArrayPayload(candidate, [
9938
+ "serviceInstanceLeases",
9939
+ "service_instance_leases",
9940
+ "serviceInstanceLease",
9941
+ "service_instance_lease"
9942
+ ]);
8520
9943
  const serviceInstanceTransportRows = readDirectArrayPayload(candidate, [
8521
9944
  "serviceInstanceTransports",
8522
9945
  "service_instance_transports",
@@ -8547,6 +9970,12 @@ var ServiceRegistry = class _ServiceRegistry {
8547
9970
  seenServiceInstances,
8548
9971
  (row) => String(row.uuid ?? "").trim()
8549
9972
  );
9973
+ pushUnique(
9974
+ serviceInstanceLeaseRows,
9975
+ serviceInstanceLeases,
9976
+ seenServiceInstanceLeases,
9977
+ (row) => String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
9978
+ );
8550
9979
  pushUnique(
8551
9980
  serviceInstanceTransportRows,
8552
9981
  serviceInstanceTransports,
@@ -8567,6 +9996,8 @@ var ServiceRegistry = class _ServiceRegistry {
8567
9996
  seenSignalMaps,
8568
9997
  (row) => `${String(row.service_name ?? row.serviceName ?? "").trim()}|${String(
8569
9998
  row.signal_name ?? row.signalName ?? ""
9999
+ ).trim()}|${String(row.task_name ?? row.taskName ?? "").trim()}|${String(
10000
+ row.task_version ?? row.taskVersion ?? 1
8570
10001
  ).trim()}`
8571
10002
  );
8572
10003
  pushUnique(
@@ -8601,10 +10032,23 @@ var ServiceRegistry = class _ServiceRegistry {
8601
10032
  seenSignalMaps,
8602
10033
  (entry) => `${String(entry.service_name ?? entry.serviceName ?? "").trim()}|${String(
8603
10034
  entry.signal_name ?? entry.signalName ?? ""
10035
+ ).trim()}|${String(entry.task_name ?? entry.taskName ?? "").trim()}|${String(
10036
+ entry.task_version ?? entry.taskVersion ?? 1
8604
10037
  ).trim()}`
8605
10038
  );
8606
10039
  continue;
8607
10040
  }
10041
+ if (row.status !== void 0 && (row.service_instance_id !== void 0 || row.serviceInstanceId !== void 0)) {
10042
+ pushUnique(
10043
+ [row],
10044
+ serviceInstanceLeases,
10045
+ seenServiceInstanceLeases,
10046
+ (entry) => String(
10047
+ entry.service_instance_id ?? entry.serviceInstanceId ?? ""
10048
+ ).trim()
10049
+ );
10050
+ continue;
10051
+ }
8608
10052
  if (row.service_instance_id !== void 0 || row.serviceInstanceId !== void 0) {
8609
10053
  pushUnique(
8610
10054
  [row],
@@ -8633,9 +10077,40 @@ var ServiceRegistry = class _ServiceRegistry {
8633
10077
  }
8634
10078
  }
8635
10079
  }
8636
- const hasExplicitSignalRoutingRows = signalToTaskMaps.length > 0;
8637
- const hasExplicitIntentRoutingRows = intentToTaskMaps.length > 0;
8638
- const latestManifestSnapshots = selectLatestServiceManifestSnapshots(manifestSnapshots);
10080
+ const mergedServiceInstances = overlayServiceInstancesWithLeases(
10081
+ serviceInstances,
10082
+ serviceInstanceLeases
10083
+ );
10084
+ const activeServiceInstanceIds = new Set(
10085
+ mergedServiceInstances.filter((row) => row.is_active === true || row.isActive === true).map((row) => String(row.uuid ?? "").trim()).filter((uuid10) => uuid10.length > 0)
10086
+ );
10087
+ const filteredServiceInstances = activeServiceInstanceIds.size > 0 ? mergedServiceInstances.filter(
10088
+ (row) => activeServiceInstanceIds.has(String(row.uuid ?? "").trim())
10089
+ ) : mergedServiceInstances;
10090
+ const filteredServiceInstanceTransports = activeServiceInstanceIds.size > 0 ? serviceInstanceTransports.filter(
10091
+ (row) => activeServiceInstanceIds.has(
10092
+ String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
10093
+ )
10094
+ ) : serviceInstanceTransports;
10095
+ const filteredManifestSnapshots = activeServiceInstanceIds.size > 0 ? manifestSnapshots.filter(
10096
+ (snapshot) => activeServiceInstanceIds.has(snapshot.serviceInstanceId)
10097
+ ) : manifestSnapshots;
10098
+ const activeServiceNames = new Set(
10099
+ filteredServiceInstances.map((row) => String(row.service_name ?? row.serviceName ?? "").trim()).filter((serviceName) => serviceName.length > 0)
10100
+ );
10101
+ const filteredSignalToTaskMaps = activeServiceNames.size > 0 ? signalToTaskMaps.filter(
10102
+ (row) => activeServiceNames.has(
10103
+ String(row.service_name ?? row.serviceName ?? "").trim()
10104
+ )
10105
+ ) : signalToTaskMaps;
10106
+ const filteredIntentToTaskMaps = activeServiceNames.size > 0 ? intentToTaskMaps.filter(
10107
+ (row) => activeServiceNames.has(
10108
+ String(row.service_name ?? row.serviceName ?? "").trim()
10109
+ )
10110
+ ) : intentToTaskMaps;
10111
+ const hasExplicitSignalRoutingRows = filteredSignalToTaskMaps.length > 0;
10112
+ const hasExplicitIntentRoutingRows = filteredIntentToTaskMaps.length > 0;
10113
+ const latestManifestSnapshots = selectLatestServiceManifestSnapshots(filteredManifestSnapshots);
8639
10114
  const explodedManifest = explodeServiceManifestSnapshots(
8640
10115
  latestManifestSnapshots
8641
10116
  );
@@ -8655,6 +10130,22 @@ var ServiceRegistry = class _ServiceRegistry {
8655
10130
  row.version ?? 1
8656
10131
  ).trim()}`
8657
10132
  );
10133
+ pushUnique(
10134
+ explodedManifest.helpers,
10135
+ helpers,
10136
+ seenHelpers,
10137
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.name ?? "").trim()}|${String(
10138
+ row.version ?? 1
10139
+ ).trim()}`
10140
+ );
10141
+ pushUnique(
10142
+ explodedManifest.globals,
10143
+ globals,
10144
+ seenGlobals,
10145
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.name ?? "").trim()}|${String(
10146
+ row.version ?? 1
10147
+ ).trim()}`
10148
+ );
8658
10149
  pushUnique(
8659
10150
  explodedManifest.signals,
8660
10151
  signals,
@@ -8715,10 +10206,54 @@ var ServiceRegistry = class _ServiceRegistry {
8715
10206
  row.task_version ?? 1
8716
10207
  ).trim()}`
8717
10208
  );
10209
+ pushUnique(
10210
+ explodedManifest.taskToHelperMaps,
10211
+ taskToHelperMaps,
10212
+ seenTaskToHelperMaps,
10213
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.task_name ?? "").trim()}|${String(
10214
+ row.task_version ?? 1
10215
+ ).trim()}|${String(row.alias ?? "").trim()}|${String(
10216
+ row.helper_name ?? ""
10217
+ ).trim()}|${String(row.helper_version ?? 1).trim()}`
10218
+ );
10219
+ pushUnique(
10220
+ explodedManifest.helperToHelperMaps,
10221
+ helperToHelperMaps,
10222
+ seenHelperToHelperMaps,
10223
+ (row) => `${String(row.service_name ?? "").trim()}|${String(
10224
+ row.helper_name ?? ""
10225
+ ).trim()}|${String(row.helper_version ?? 1).trim()}|${String(
10226
+ row.alias ?? ""
10227
+ ).trim()}|${String(row.dependency_helper_name ?? "").trim()}|${String(
10228
+ row.dependency_helper_version ?? 1
10229
+ ).trim()}`
10230
+ );
10231
+ pushUnique(
10232
+ explodedManifest.taskToGlobalMaps,
10233
+ taskToGlobalMaps,
10234
+ seenTaskToGlobalMaps,
10235
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.task_name ?? "").trim()}|${String(
10236
+ row.task_version ?? 1
10237
+ ).trim()}|${String(row.alias ?? "").trim()}|${String(
10238
+ row.global_name ?? ""
10239
+ ).trim()}|${String(row.global_version ?? 1).trim()}`
10240
+ );
10241
+ pushUnique(
10242
+ explodedManifest.helperToGlobalMaps,
10243
+ helperToGlobalMaps,
10244
+ seenHelperToGlobalMaps,
10245
+ (row) => `${String(row.service_name ?? "").trim()}|${String(
10246
+ row.helper_name ?? ""
10247
+ ).trim()}|${String(row.helper_version ?? 1).trim()}|${String(
10248
+ row.alias ?? ""
10249
+ ).trim()}|${String(row.global_name ?? "").trim()}|${String(
10250
+ row.global_version ?? 1
10251
+ ).trim()}`
10252
+ );
8718
10253
  if (!hasExplicitSignalRoutingRows) {
8719
10254
  pushUnique(
8720
10255
  explodedManifest.signalToTaskMaps,
8721
- signalToTaskMaps,
10256
+ filteredSignalToTaskMaps,
8722
10257
  seenSignalMaps,
8723
10258
  (row) => `${String(row.signal_name ?? "").trim()}|${String(
8724
10259
  row.service_name ?? ""
@@ -8730,7 +10265,7 @@ var ServiceRegistry = class _ServiceRegistry {
8730
10265
  if (!hasExplicitIntentRoutingRows) {
8731
10266
  pushUnique(
8732
10267
  explodedManifest.intentToTaskMaps,
8733
- intentToTaskMaps,
10268
+ filteredIntentToTaskMaps,
8734
10269
  seenIntentMaps,
8735
10270
  (row) => `${String(row.intent_name ?? "").trim()}|${String(
8736
10271
  row.service_name ?? ""
@@ -8740,10 +10275,13 @@ var ServiceRegistry = class _ServiceRegistry {
8740
10275
  );
8741
10276
  }
8742
10277
  return {
8743
- serviceInstances,
8744
- serviceInstanceTransports,
10278
+ serviceInstances: filteredServiceInstances,
10279
+ serviceInstanceLeases,
10280
+ serviceInstanceTransports: filteredServiceInstanceTransports,
8745
10281
  serviceManifests,
8746
10282
  tasks,
10283
+ helpers,
10284
+ globals,
8747
10285
  signals,
8748
10286
  intents,
8749
10287
  actors,
@@ -8751,8 +10289,12 @@ var ServiceRegistry = class _ServiceRegistry {
8751
10289
  directionalTaskMaps,
8752
10290
  actorTaskMaps,
8753
10291
  taskToRoutineMaps,
8754
- signalToTaskMaps,
8755
- intentToTaskMaps
10292
+ taskToHelperMaps,
10293
+ helperToHelperMaps,
10294
+ taskToGlobalMaps,
10295
+ helperToGlobalMaps,
10296
+ signalToTaskMaps: filteredSignalToTaskMaps,
10297
+ intentToTaskMaps: filteredIntentToTaskMaps
8756
10298
  };
8757
10299
  }
8758
10300
  buildRemoteIntentDeputyKey(map) {
@@ -9181,29 +10723,32 @@ var ServiceRegistry = class _ServiceRegistry {
9181
10723
  const controller = typeof AbortController === "function" ? new AbortController() : null;
9182
10724
  const timeoutId = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
9183
10725
  try {
9184
- const requestBody = stripDelegationRequestSnapshot(
9185
- ensureDelegationContextMetadata(
9186
- attachDelegationRequestSnapshot({
9187
- ...context,
9188
- __remoteRoutineName: remoteRoutineName,
9189
- __serviceName: "CadenzaDB",
9190
- __localServiceName: this.serviceName,
9191
- __timeout: timeoutMs,
9192
- __syncing: true,
9193
- __transportOrigin: target.origin,
9194
- __transportProtocol: "rest",
9195
- __transportProtocols: ["rest"],
9196
- __routeKey: target.routeKey,
9197
- routeKey: target.routeKey,
9198
- __fetchId: target.fetchId,
9199
- fetchId: target.fetchId,
9200
- __metadata: {
9201
- ...context.__metadata && typeof context.__metadata === "object" ? context.__metadata : {},
10726
+ const sanitizedContext = sanitizeAuthorityBootstrapDelegationContext(context);
10727
+ const requestBody = compactAuthorityBootstrapRequestBody(
10728
+ stripDelegationRequestSnapshot(
10729
+ ensureDelegationContextMetadata(
10730
+ attachDelegationRequestSnapshot({
10731
+ ...sanitizedContext,
10732
+ __remoteRoutineName: remoteRoutineName,
10733
+ __serviceName: "CadenzaDB",
10734
+ __localServiceName: this.serviceName,
9202
10735
  __timeout: timeoutMs,
9203
10736
  __syncing: true,
9204
- __authorityBootstrapChannel: true
9205
- }
9206
- })
10737
+ __transportOrigin: target.origin,
10738
+ __transportProtocol: "rest",
10739
+ __transportProtocols: ["rest"],
10740
+ __routeKey: target.routeKey,
10741
+ routeKey: target.routeKey,
10742
+ __fetchId: target.fetchId,
10743
+ fetchId: target.fetchId,
10744
+ __metadata: {
10745
+ ...sanitizedContext.__metadata && typeof sanitizedContext.__metadata === "object" ? sanitizedContext.__metadata : {},
10746
+ __timeout: timeoutMs,
10747
+ __syncing: true,
10748
+ __authorityBootstrapChannel: true
10749
+ }
10750
+ })
10751
+ )
9207
10752
  )
9208
10753
  );
9209
10754
  const response = await globalThis.fetch(`${target.origin}/delegation`, {
@@ -9216,22 +10761,22 @@ var ServiceRegistry = class _ServiceRegistry {
9216
10761
  });
9217
10762
  if ("ok" in response && response.ok === false) {
9218
10763
  return {
9219
- ...context,
10764
+ ...sanitizedContext,
9220
10765
  __error: `Bootstrap authority delegation failed with HTTP ${response.status}`,
9221
10766
  errored: true
9222
10767
  };
9223
10768
  }
9224
10769
  const payload = typeof response.json === "function" ? await response.json() : response;
9225
10770
  return payload && typeof payload === "object" ? {
9226
- ...context,
10771
+ ...sanitizedContext,
9227
10772
  ...payload
9228
10773
  } : {
9229
- ...context,
10774
+ ...sanitizedContext,
9230
10775
  returnedValue: payload
9231
10776
  };
9232
10777
  } catch (error) {
9233
10778
  return {
9234
- ...context,
10779
+ ...sanitizeAuthorityBootstrapDelegationContext(context),
9235
10780
  __error: error instanceof Error ? error.message : String(error),
9236
10781
  errored: true
9237
10782
  };
@@ -9358,12 +10903,14 @@ var ServiceRegistry = class _ServiceRegistry {
9358
10903
  };
9359
10904
  const [
9360
10905
  serviceInstances,
10906
+ serviceInstanceLeases,
9361
10907
  serviceInstanceTransports,
9362
10908
  serviceManifests,
9363
10909
  signalToTaskMaps,
9364
10910
  intentToTaskMaps
9365
10911
  ] = await Promise.all([
9366
10912
  DatabaseController.instance.queryAuthorityTableRows("service_instance"),
10913
+ queryOptionalAuthorityRoutingRows("service_instance_lease"),
9367
10914
  DatabaseController.instance.queryAuthorityTableRows(
9368
10915
  "service_instance_transport"
9369
10916
  ),
@@ -9376,6 +10923,7 @@ var ServiceRegistry = class _ServiceRegistry {
9376
10923
  __syncing: true,
9377
10924
  ...this.collectBootstrapFullSyncPayload({
9378
10925
  serviceInstances,
10926
+ serviceInstanceLeases,
9379
10927
  serviceInstanceTransports,
9380
10928
  serviceManifests,
9381
10929
  signalToTaskMaps,
@@ -9408,9 +10956,14 @@ var ServiceRegistry = class _ServiceRegistry {
9408
10956
  return false;
9409
10957
  }
9410
10958
  const scheduleRetry = (reason, error) => {
9411
- const delayMs = SERVICE_COMMUNICATION_PERSIST_RETRY_DELAYS_MS[descriptor.retryAttempt];
10959
+ const baseDelayMs = SERVICE_COMMUNICATION_PERSIST_RETRY_DELAYS_MS[descriptor.retryAttempt];
9412
10960
  const nextAttempt = descriptor.retryAttempt + 1;
9413
- if (delayMs !== void 0) {
10961
+ if (baseDelayMs !== void 0) {
10962
+ const delayMs = buildDeterministicJitteredDelayMs(
10963
+ baseDelayMs,
10964
+ this.serviceCommunicationRetryJitterRatio,
10965
+ `${descriptor.serviceInstanceId}:${descriptor.communicationType}:${descriptor.retryAttempt}`
10966
+ );
9414
10967
  CadenzaService.schedule(
9415
10968
  retrySignal,
9416
10969
  buildServiceCommunicationRetryContext({
@@ -9558,6 +11111,31 @@ var ServiceRegistry = class _ServiceRegistry {
9558
11111
  })
9559
11112
  );
9560
11113
  }
11114
+ buildDeterministicInstanceJitterKey(scope) {
11115
+ const serviceName = String(this.serviceName ?? "").trim() || "unknown-service";
11116
+ const serviceInstanceId = String(this.serviceInstanceId ?? "").trim() || "pending-instance";
11117
+ return `${serviceName}:${serviceInstanceId}:${scope}`;
11118
+ }
11119
+ buildJitteredIntervalStartDate(intervalMs, scope) {
11120
+ const jitterOffsetMs = buildDeterministicJitterOffsetMs(
11121
+ intervalMs,
11122
+ this.runtimeStatusLoopJitterRatio,
11123
+ this.buildDeterministicInstanceJitterKey(scope)
11124
+ );
11125
+ if (jitterOffsetMs <= 0) {
11126
+ return void 0;
11127
+ }
11128
+ return new Date(Date.now() + intervalMs + jitterOffsetMs);
11129
+ }
11130
+ buildJitteredBootstrapRetryDelayMs(baseDelayMs, attempt) {
11131
+ return buildDeterministicJitteredDelayMs(
11132
+ baseDelayMs,
11133
+ this.bootstrapFullSyncRetryJitterRatio,
11134
+ this.buildDeterministicInstanceJitterKey(
11135
+ `bootstrap-full-sync-retry-${attempt}`
11136
+ )
11137
+ );
11138
+ }
9561
11139
  ensureAuthorityBootstrapSignalTransmissions() {
9562
11140
  if (this.serviceName !== "CadenzaDB") {
9563
11141
  return false;
@@ -9635,8 +11213,11 @@ var ServiceRegistry = class _ServiceRegistry {
9635
11213
  }
9636
11214
  const retryGeneration = this.bootstrapFullSyncRetryGeneration;
9637
11215
  const retryReason = this.bootstrapFullSyncRetryReason ?? "service_registry_bootstrap_retry";
9638
- const delayMs = EARLY_FULL_SYNC_DELAYS_MS[this.bootstrapFullSyncRetryIndex];
9639
11216
  const attempt = this.bootstrapFullSyncRetryIndex + 1;
11217
+ const delayMs = this.buildJitteredBootstrapRetryDelayMs(
11218
+ EARLY_FULL_SYNC_DELAYS_MS[this.bootstrapFullSyncRetryIndex],
11219
+ attempt
11220
+ );
9640
11221
  this.bootstrapFullSyncRetryIndex += 1;
9641
11222
  this.bootstrapFullSyncRetryTimer = setTimeout(() => {
9642
11223
  this.bootstrapFullSyncRetryTimer = null;
@@ -11539,6 +13120,18 @@ var ServiceRegistry = class _ServiceRegistry {
11539
13120
  isNonResponsive,
11540
13121
  isBlocked
11541
13122
  );
13123
+ const cpuUsage = this.readRuntimeStatusMetric(ctx, "cpuUsage", "cpu", "cpuLoad");
13124
+ const memoryUsage = this.readRuntimeStatusMetric(
13125
+ ctx,
13126
+ "memoryUsage",
13127
+ "memory",
13128
+ "memoryPressure"
13129
+ );
13130
+ const eventLoopLag = this.readRuntimeStatusMetric(
13131
+ ctx,
13132
+ "eventLoopLag",
13133
+ "eventLoopLagMs"
13134
+ );
11542
13135
  return {
11543
13136
  serviceName,
11544
13137
  serviceInstanceId,
@@ -11551,22 +13144,20 @@ var ServiceRegistry = class _ServiceRegistry {
11551
13144
  state: ctx.state === "healthy" || ctx.state === "degraded" || ctx.state === "overloaded" || ctx.state === "unavailable" ? ctx.state : resolved.state,
11552
13145
  acceptingWork: typeof ctx.acceptingWork === "boolean" ? ctx.acceptingWork : resolved.acceptingWork,
11553
13146
  numberOfRunningGraphs,
11554
- cpuUsage: this.readRuntimeStatusMetric(ctx, "cpuUsage", "cpu", "cpuLoad"),
11555
- memoryUsage: this.readRuntimeStatusMetric(
11556
- ctx,
11557
- "memoryUsage",
11558
- "memory",
11559
- "memoryPressure"
11560
- ),
11561
- eventLoopLag: this.readRuntimeStatusMetric(
11562
- ctx,
11563
- "eventLoopLag",
11564
- "eventLoopLagMs"
11565
- ),
13147
+ cpuUsage,
13148
+ memoryUsage,
13149
+ eventLoopLag,
11566
13150
  isActive,
11567
13151
  isNonResponsive,
11568
13152
  isBlocked,
11569
- health: ctx.health ?? ctx.__health ?? {}
13153
+ health: sanitizeAuthorityRuntimeStatusHealth(ctx.health ?? ctx.__health, {
13154
+ state: ctx.state === "healthy" || ctx.state === "degraded" || ctx.state === "overloaded" || ctx.state === "unavailable" ? ctx.state : resolved.state,
13155
+ acceptingWork: typeof ctx.acceptingWork === "boolean" ? ctx.acceptingWork : resolved.acceptingWork,
13156
+ reportedAt: ctx.reportedAt ?? (typeof ctx.__reportedAt === "string" ? ctx.__reportedAt : void 0) ?? (/* @__PURE__ */ new Date()).toISOString(),
13157
+ cpuUsage,
13158
+ memoryUsage,
13159
+ eventLoopLag
13160
+ })
11570
13161
  };
11571
13162
  }
11572
13163
  applyRuntimeStatusReport(report) {
@@ -11607,12 +13198,14 @@ var ServiceRegistry = class _ServiceRegistry {
11607
13198
  instance.isFrontend = report.isFrontend;
11608
13199
  }
11609
13200
  instance.numberOfRunningGraphs = report.numberOfRunningGraphs;
11610
- const runtimeMetricsHealth = {
13201
+ const runtimeStatusHealth = sanitizeAuthorityRuntimeStatusHealth(report.health, {
13202
+ state: report.state,
13203
+ acceptingWork: report.acceptingWork,
13204
+ reportedAt: report.reportedAt,
11611
13205
  cpuUsage: report.cpuUsage ?? null,
11612
13206
  memoryUsage: report.memoryUsage ?? null,
11613
- eventLoopLag: report.eventLoopLag ?? null,
11614
- runtimeMetrics: report.health?.runtimeMetrics && typeof report.health.runtimeMetrics === "object" ? report.health.runtimeMetrics : void 0
11615
- };
13207
+ eventLoopLag: report.eventLoopLag ?? null
13208
+ });
11616
13209
  instance.isActive = report.isActive;
11617
13210
  instance.isNonResponsive = report.isNonResponsive;
11618
13211
  instance.isBlocked = report.isBlocked;
@@ -11621,13 +13214,7 @@ var ServiceRegistry = class _ServiceRegistry {
11621
13214
  instance.reportedAt = report.reportedAt;
11622
13215
  instance.health = {
11623
13216
  ...instance.health ?? {},
11624
- ...report.health ?? {},
11625
- ...runtimeMetricsHealth,
11626
- runtimeStatus: {
11627
- state: report.state,
11628
- acceptingWork: report.acceptingWork,
11629
- reportedAt: report.reportedAt
11630
- }
13217
+ ...runtimeStatusHealth ?? {}
11631
13218
  };
11632
13219
  this.lastHeartbeatAtByInstance.set(report.serviceInstanceId, Date.now());
11633
13220
  this.missedHeartbeatsByInstance.set(report.serviceInstanceId, 0);
@@ -11799,15 +13386,20 @@ var ServiceRegistry = class _ServiceRegistry {
11799
13386
  isActive: snapshot.isActive,
11800
13387
  isNonResponsive: snapshot.isNonResponsive,
11801
13388
  isBlocked: snapshot.isBlocked,
11802
- health: {
11803
- ...localInstance.health ?? {},
11804
- ...this.buildRuntimeMetricsHealthPayload(runtimeMetricsSnapshot) ?? {},
11805
- runtimeStatus: {
13389
+ health: sanitizeAuthorityRuntimeStatusHealth(
13390
+ {
13391
+ ...localInstance.health ?? {},
13392
+ ...this.buildRuntimeMetricsHealthPayload(runtimeMetricsSnapshot) ?? {}
13393
+ },
13394
+ {
11806
13395
  state: snapshot.state,
11807
13396
  acceptingWork: snapshot.acceptingWork,
11808
- reportedAt
13397
+ reportedAt,
13398
+ cpuUsage: runtimeMetricsSnapshot?.cpuUsage ?? null,
13399
+ memoryUsage: runtimeMetricsSnapshot?.memoryUsage ?? null,
13400
+ eventLoopLag: runtimeMetricsSnapshot?.eventLoopLag ?? null
11809
13401
  }
11810
- }
13402
+ )
11811
13403
  };
11812
13404
  this.applyRuntimeStatusReport(report);
11813
13405
  return detailLevel === "full" ? report : this.stripRuntimeStatusReportForPeer(report);
@@ -12161,6 +13753,32 @@ var ServiceRegistry = class _ServiceRegistry {
12161
13753
  if (!instancePersisted) {
12162
13754
  return false;
12163
13755
  }
13756
+ await this.delegateAuthorityLifecycleUpdate(
13757
+ "Update service_instance_lease",
13758
+ {
13759
+ reason,
13760
+ graceful: true,
13761
+ data: {
13762
+ status: "inactive",
13763
+ is_ready: false,
13764
+ readiness_reason: "graceful_shutdown",
13765
+ lease_expires_at: reportedAt,
13766
+ last_lease_renewed_at: reportedAt,
13767
+ last_ready_at: null,
13768
+ last_observed_transport_at: reportedAt,
13769
+ shutdown_requested_at: reportedAt,
13770
+ deleted: false,
13771
+ modified: reportedAt
13772
+ },
13773
+ queryData: {
13774
+ filter: {
13775
+ service_instance_id: localInstance.uuid
13776
+ }
13777
+ },
13778
+ __serviceInstanceId: localInstance.uuid
13779
+ },
13780
+ Math.max(1e3, timeoutMs)
13781
+ );
12164
13782
  for (const transport of localInstance.transports) {
12165
13783
  if (!isPersistedUuid(transport.uuid)) {
12166
13784
  continue;
@@ -12312,6 +13930,7 @@ var ServiceRegistry = class _ServiceRegistry {
12312
13930
  };
12313
13931
  }
12314
13932
  reset() {
13933
+ this.clearBootstrapFullSyncRetryTimer();
12315
13934
  this.instances.clear();
12316
13935
  this.deputies.clear();
12317
13936
  this.remoteSignals.clear();
@@ -12335,13 +13954,30 @@ var ServiceRegistry = class _ServiceRegistry {
12335
13954
  this.lastRuntimeStatusSnapshot = null;
12336
13955
  this.isFrontend = false;
12337
13956
  this.localInstanceSeed = null;
13957
+ this.bootstrapFullSyncRetryIndex = 0;
13958
+ this.bootstrapFullSyncRetryGeneration = 0;
13959
+ this.bootstrapFullSyncSatisfied = false;
13960
+ this.bootstrapFullSyncRetryReason = null;
13961
+ this.knownGlobalSignalMaps.clear();
13962
+ this.authorityBootstrapRoute = {
13963
+ origin: null,
13964
+ role: "internal",
13965
+ routeKey: null,
13966
+ fetchId: null,
13967
+ serviceInstanceId: null,
13968
+ serviceTransportId: null,
13969
+ handshakeEstablished: false
13970
+ };
13971
+ this.authorityBootstrapHandshakeInFlight = false;
13972
+ this.authorityFullSyncResponderTask = null;
13973
+ this.authorityServiceCommunicationPersistenceTask = null;
12338
13974
  }
12339
13975
  };
12340
13976
 
12341
13977
  // src/graph/definition/SignalTransmissionTask.ts
12342
- var import_core2 = require("@cadenza.io/core");
13978
+ var import_core3 = require("@cadenza.io/core");
12343
13979
  var import_uuid4 = require("uuid");
12344
- var SignalTransmissionTask = class extends import_core2.Task {
13980
+ var SignalTransmissionTask = class extends import_core3.Task {
12345
13981
  /**
12346
13982
  * Constructs a new instance of the class and initializes it with the provided parameters.
12347
13983
  *
@@ -12443,7 +14079,25 @@ var SignalTransmissionTask = class extends import_core2.Task {
12443
14079
  ...ctx
12444
14080
  })
12445
14081
  );
12446
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
14082
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
14083
+ this,
14084
+ deputyContext,
14085
+ emit2,
14086
+ inquire,
14087
+ progressCallback
14088
+ ) : {
14089
+ helpers: {},
14090
+ globals: {}
14091
+ };
14092
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
14093
+ };
14094
+ return this.taskFunction(
14095
+ deputyContext,
14096
+ emit2,
14097
+ inquire,
14098
+ resolvedTools,
14099
+ resolvedProgressCallback
14100
+ );
12447
14101
  }
12448
14102
  };
12449
14103
 
@@ -12468,6 +14122,41 @@ var TRACED_INQUIRY_METADATA_SIGNALS = /* @__PURE__ */ new Set([
12468
14122
  "global.meta.graph_metadata.inquiry_updated"
12469
14123
  ]);
12470
14124
  var ACTOR_SESSION_TRACE_ENABLED3 = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
14125
+ function summarizeRequestBodyForLogging(body) {
14126
+ if (typeof body !== "string") {
14127
+ return body;
14128
+ }
14129
+ const summary = {
14130
+ bodyLength: body.length
14131
+ };
14132
+ try {
14133
+ const parsed = JSON.parse(body);
14134
+ const queryData = parsed.queryData && typeof parsed.queryData === "object" ? parsed.queryData : null;
14135
+ const queryDataData = queryData?.data && typeof queryData.data === "object" ? queryData.data : null;
14136
+ const data = parsed.data && typeof parsed.data === "object" ? parsed.data : null;
14137
+ summary.rootKeys = Object.keys(parsed).slice(0, 24);
14138
+ summary.remoteRoutineName = typeof parsed.__remoteRoutineName === "string" ? parsed.__remoteRoutineName : null;
14139
+ summary.serviceName = typeof parsed.__serviceName === "string" ? parsed.__serviceName : null;
14140
+ summary.authorityBootstrapChannel = parsed.__authorityBootstrapChannel === true || parsed.__metadata?.__authorityBootstrapChannel === true;
14141
+ summary.hasData = data !== null;
14142
+ summary.dataKeys = data ? Object.keys(data).slice(0, 24) : [];
14143
+ summary.hasQueryData = queryData !== null;
14144
+ summary.queryDataKeys = queryData ? Object.keys(queryData).slice(0, 24) : [];
14145
+ summary.queryDataDataKeys = queryDataData ? Object.keys(queryDataData).slice(0, 24) : [];
14146
+ } catch {
14147
+ summary.preview = body.slice(0, 240);
14148
+ }
14149
+ return summary;
14150
+ }
14151
+ function summarizeRequestInitForLogging(requestInit) {
14152
+ if (!requestInit || typeof requestInit !== "object") {
14153
+ return requestInit;
14154
+ }
14155
+ return {
14156
+ ...requestInit,
14157
+ body: summarizeRequestBodyForLogging(requestInit.body)
14158
+ };
14159
+ }
12471
14160
  var RestController = class _RestController {
12472
14161
  /**
12473
14162
  * Constructor for initializing the REST server and related configurations.
@@ -12501,16 +14190,17 @@ var RestController = class _RestController {
12501
14190
  const parsedResponse = await this.parseFetchResponse(response);
12502
14191
  return parsedResponse.data;
12503
14192
  } catch (error) {
14193
+ const loggedRequestInit = summarizeRequestInitForLogging(requestInit);
12504
14194
  if (error?.name === "AbortError") {
12505
14195
  CadenzaService.log(
12506
14196
  "Fetch request timed out.",
12507
- { error, URL: url, requestInit },
14197
+ { error, URL: url, requestInit: loggedRequestInit },
12508
14198
  "warning"
12509
14199
  );
12510
14200
  } else {
12511
14201
  CadenzaService.log(
12512
14202
  "Fetch request error.",
12513
- { error, URL: url, requestInit },
14203
+ { error, URL: url, requestInit: loggedRequestInit },
12514
14204
  "error"
12515
14205
  );
12516
14206
  }
@@ -12656,7 +14346,7 @@ var RestController = class _RestController {
12656
14346
  return { ...ctx, __app: app };
12657
14347
  },
12658
14348
  "Sets up the Express server according to the security profile"
12659
- ).attachSignal("meta.service_registry.instance_registration_requested").then(
14349
+ ).then(
12660
14350
  CadenzaService.createMetaTask(
12661
14351
  "Define RestServer",
12662
14352
  (ctx) => {
@@ -12736,16 +14426,16 @@ var RestController = class _RestController {
12736
14426
  };
12737
14427
  CadenzaService.createEphemeralMetaTask(
12738
14428
  "Resolve delegation",
12739
- (endCtx) => resolveDelegation(endCtx, "success"),
14429
+ (endCtx) => resolveDelegation(
14430
+ endCtx,
14431
+ endCtx?.errored || endCtx?.failed ? "error" : "success"
14432
+ ),
12740
14433
  "Resolves a delegation request",
12741
14434
  { register: false }
12742
- ).doOn(`meta.node.graph_completed:${deputyExecId}`).emits(`meta.rest.delegation_resolved:${deputyExecId}`);
12743
- CadenzaService.createEphemeralMetaTask(
12744
- "Resolve delegation target lookup failure",
12745
- (endCtx) => resolveDelegation(endCtx, "error"),
12746
- "Resolves delegation requests that cannot find a local task or routine",
12747
- { register: false }
12748
- ).doOn(targetNotFoundSignal);
14435
+ ).doOn(
14436
+ `meta.node.graph_completed:${deputyExecId}`,
14437
+ targetNotFoundSignal
14438
+ ).emits(`meta.rest.delegation_resolved:${deputyExecId}`);
12749
14439
  if (!CadenzaService.get(remoteRoutineName) && !CadenzaService.registry.routines.get(remoteRoutineName)) {
12750
14440
  CadenzaService.emit(targetNotFoundSignal, {
12751
14441
  ...ctx2,
@@ -13053,32 +14743,40 @@ var RestController = class _RestController {
13053
14743
  serviceName,
13054
14744
  URL2
13055
14745
  );
13056
- fetchDiagnostics.destroyed = false;
13057
- fetchDiagnostics.updatedAt = Date.now();
13058
14746
  if (CadenzaService.get(`Send Handshake to ${clientTaskSuffix}`)) {
13059
- console.error("Fetch client already exists", { URL: URL2, fetchId });
13060
- CadenzaService.schedule(
13061
- `meta.fetch.handshake_requested:${fetchId}`,
13062
- {
13063
- serviceInstanceId: ctx.serviceInstanceId,
13064
- serviceName,
13065
- communicationTypes: ctx.communicationTypes,
13066
- serviceTransportId: ctx.serviceTransportId,
13067
- serviceOrigin: URL2,
13068
- fetchId,
13069
- routeKey,
13070
- socketClientId: ctx.socketClientId ?? (routeKey ? buildTransportHandleKey(routeKey, "socket") : void 0),
13071
- transportProtocols: ctx.transportProtocols,
13072
- transportProtocol: "rest",
13073
- handshakeData: ctx.handshakeData
13074
- },
13075
- 0
13076
- );
14747
+ const shouldRetryHandshake = ctx.__forceHandshakeRecovery === true || fetchDiagnostics.destroyed === true || (fetchDiagnostics.connected !== true || typeof fetchDiagnostics.lastHandshakeError === "string") && fetchDiagnostics.handshakeInFlight !== true;
14748
+ if (shouldRetryHandshake) {
14749
+ fetchDiagnostics.destroyed = false;
14750
+ fetchDiagnostics.handshakeInFlight = true;
14751
+ fetchDiagnostics.updatedAt = Date.now();
14752
+ console.error("Fetch client already exists", { URL: URL2, fetchId });
14753
+ CadenzaService.debounce(
14754
+ `meta.fetch.handshake_requested:${fetchId}`,
14755
+ {
14756
+ serviceInstanceId: ctx.serviceInstanceId,
14757
+ serviceName,
14758
+ communicationTypes: ctx.communicationTypes,
14759
+ serviceTransportId: ctx.serviceTransportId,
14760
+ serviceOrigin: URL2,
14761
+ fetchId,
14762
+ routeKey,
14763
+ socketClientId: ctx.socketClientId ?? (routeKey ? buildTransportHandleKey(routeKey, "socket") : void 0),
14764
+ transportProtocols: ctx.transportProtocols,
14765
+ transportProtocol: "rest",
14766
+ handshakeData: ctx.handshakeData
14767
+ },
14768
+ 50
14769
+ );
14770
+ }
13077
14771
  return true;
13078
14772
  }
14773
+ fetchDiagnostics.destroyed = false;
14774
+ fetchDiagnostics.handshakeInFlight = false;
14775
+ fetchDiagnostics.updatedAt = Date.now();
13079
14776
  const handshakeTask = CadenzaService.createMetaTask(
13080
14777
  `Send Handshake to ${clientTaskSuffix}`,
13081
14778
  async (ctx2, emit2) => {
14779
+ fetchDiagnostics.handshakeInFlight = true;
13082
14780
  try {
13083
14781
  const response = await this.fetchDataWithTimeout(
13084
14782
  `${URL2}/handshake`,
@@ -13094,6 +14792,7 @@ var RestController = class _RestController {
13094
14792
  if (response.__status !== "success") {
13095
14793
  const error = response.__error ?? `Failed to connect to service ${serviceName} ${ctx2.serviceInstanceId}`;
13096
14794
  fetchDiagnostics.connected = false;
14795
+ fetchDiagnostics.handshakeInFlight = false;
13097
14796
  fetchDiagnostics.lastHandshakeError = error;
13098
14797
  fetchDiagnostics.updatedAt = Date.now();
13099
14798
  this.recordFetchClientError(fetchId, serviceName, URL2, error);
@@ -13113,6 +14812,7 @@ var RestController = class _RestController {
13113
14812
  ctx2.serviceInstanceId = response.__serviceInstanceId;
13114
14813
  fetchDiagnostics.connected = true;
13115
14814
  fetchDiagnostics.destroyed = false;
14815
+ fetchDiagnostics.handshakeInFlight = false;
13116
14816
  fetchDiagnostics.lastHandshakeAt = (/* @__PURE__ */ new Date()).toISOString();
13117
14817
  fetchDiagnostics.lastHandshakeError = null;
13118
14818
  fetchDiagnostics.updatedAt = Date.now();
@@ -13141,6 +14841,7 @@ var RestController = class _RestController {
13141
14841
  }
13142
14842
  } catch (e) {
13143
14843
  fetchDiagnostics.connected = false;
14844
+ fetchDiagnostics.handshakeInFlight = false;
13144
14845
  fetchDiagnostics.lastHandshakeError = this.getErrorMessage(e);
13145
14846
  fetchDiagnostics.updatedAt = Date.now();
13146
14847
  this.recordFetchClientError(fetchId, serviceName, URL2, e);
@@ -13173,8 +14874,8 @@ var RestController = class _RestController {
13173
14874
  }
13174
14875
  const routedDelegateCtx = stripTransportSelectionRoutingContext(ctx2);
13175
14876
  const delegateCtx = ensureDelegationContextMetadata(
13176
- attachDelegationRequestSnapshot(
13177
- stripDelegationRequestSnapshot(routedDelegateCtx)
14877
+ restoreDelegationRequestSnapshot(
14878
+ attachDelegationRequestSnapshot(routedDelegateCtx)
13178
14879
  )
13179
14880
  );
13180
14881
  const deputyExecId = delegateCtx.__metadata.__deputyExecId;
@@ -13233,14 +14934,12 @@ var RestController = class _RestController {
13233
14934
  console.error("Error in delegation", e);
13234
14935
  fetchDiagnostics.delegationFailures++;
13235
14936
  fetchDiagnostics.updatedAt = Date.now();
13236
- this.recordFetchClientError(fetchId, serviceName, URL2, e);
13237
- resultContext = {
13238
- __signalName: "meta.fetch.delegate_failed",
13239
- __error: `Error: ${e}`,
13240
- errored: true,
13241
- ...delegateCtx,
13242
- ...delegateCtx.__metadata
13243
- };
14937
+ this.recordFetchClientError(fetchId, serviceName, URL2, e);
14938
+ resultContext = buildDelegationFailureContext(
14939
+ "meta.fetch.delegate_failed",
14940
+ delegateCtx,
14941
+ e
14942
+ );
13244
14943
  routeOutcome = "failure";
13245
14944
  emit2("meta.fetch.delegate_failed", resultContext);
13246
14945
  } finally {
@@ -13406,6 +15105,7 @@ var RestController = class _RestController {
13406
15105
  return false;
13407
15106
  }
13408
15107
  fetchDiagnostics.connected = false;
15108
+ fetchDiagnostics.handshakeInFlight = false;
13409
15109
  fetchDiagnostics.destroyed = true;
13410
15110
  fetchDiagnostics.updatedAt = Date.now();
13411
15111
  CadenzaService.log("Destroying fetch client", { URL: URL2, serviceName });
@@ -13445,7 +15145,15 @@ var RestController = class _RestController {
13445
15145
  const fetchId = String(
13446
15146
  ctx.fetchId ?? ctx.__fetchId ?? (routeKey ? buildTransportHandleKey(routeKey, "rest") : serviceTransportId ?? "")
13447
15147
  );
13448
- CadenzaService.schedule(`meta.fetch.handshake_requested:${fetchId}`, {
15148
+ const fetchDiagnostics = this.ensureFetchClientDiagnostics(
15149
+ fetchId,
15150
+ String(serviceName ?? ""),
15151
+ String(serviceOrigin ?? "")
15152
+ );
15153
+ if (fetchDiagnostics.handshakeInFlight !== true) {
15154
+ fetchDiagnostics.handshakeInFlight = true;
15155
+ }
15156
+ CadenzaService.debounce(`meta.fetch.handshake_requested:${fetchId}`, {
13449
15157
  serviceInstanceId,
13450
15158
  serviceName,
13451
15159
  communicationTypes,
@@ -13461,7 +15169,7 @@ var RestController = class _RestController {
13461
15169
  serviceName: CadenzaService.serviceRegistry.serviceName
13462
15170
  // JWT token...
13463
15171
  }
13464
- }, 0);
15172
+ }, 50);
13465
15173
  return true;
13466
15174
  },
13467
15175
  "Prepares handshake"
@@ -13515,6 +15223,7 @@ var RestController = class _RestController {
13515
15223
  serviceName,
13516
15224
  url,
13517
15225
  connected: false,
15226
+ handshakeInFlight: false,
13518
15227
  destroyed: false,
13519
15228
  lastHandshakeAt: null,
13520
15229
  lastHandshakeError: null,
@@ -14952,8 +16661,8 @@ var SocketController = class _SocketController {
14952
16661
  }
14953
16662
  const routedDelegateCtx = stripTransportSelectionRoutingContext(delegateCtx);
14954
16663
  const normalizedDelegateCtx = ensureDelegationContextMetadata(
14955
- attachDelegationRequestSnapshot(
14956
- stripDelegationRequestSnapshot(routedDelegateCtx)
16664
+ restoreDelegationRequestSnapshot(
16665
+ attachDelegationRequestSnapshot(routedDelegateCtx)
14957
16666
  )
14958
16667
  );
14959
16668
  delete normalizedDelegateCtx.__isSubMeta;
@@ -15026,13 +16735,11 @@ var SocketController = class _SocketController {
15026
16735
  return resolvedResultContext;
15027
16736
  } catch (error) {
15028
16737
  const message = error instanceof Error ? error.message : String(error);
15029
- const failedContext = {
15030
- __signalName: "meta.socket_client.delegate_failed",
15031
- errored: true,
15032
- __error: message,
15033
- ...normalizedDelegateCtx,
15034
- ...normalizedDelegateCtx.__metadata
15035
- };
16738
+ const failedContext = buildDelegationFailureContext(
16739
+ "meta.socket_client.delegate_failed",
16740
+ normalizedDelegateCtx,
16741
+ error
16742
+ );
15036
16743
  if (deputyExecId) {
15037
16744
  emitter(`meta.socket_client.delegated:${deputyExecId}`, {
15038
16745
  ...failedContext,
@@ -15719,7 +17426,7 @@ var SignalController = class _SignalController {
15719
17426
  }
15720
17427
  const traceContext = { ...ctx };
15721
17428
  delete traceContext.__traceCreatedBySignalBroker;
15722
- const sanitizedTraceContext = stripLocalRoutinePersistenceHints(traceContext);
17429
+ const sanitizedTraceContext = sanitizeExecutionPersistenceContext(traceContext);
15723
17430
  const routineMetadata = resolveRoutinePersistenceMetadata(traceContext);
15724
17431
  const { context: routineContext, metaContext: routineMetaContext } = splitRoutinePersistenceContext(traceContext);
15725
17432
  const traceCreatedBySignalBroker = ctx.__traceCreatedBySignalBroker === true || signalEmission.__traceCreatedBySignalBroker === true;
@@ -16037,10 +17744,55 @@ var RuntimeValidationController = class _RuntimeValidationController {
16037
17744
  };
16038
17745
 
16039
17746
  // src/graph/controllers/registerActorSessionPersistence.ts
16040
- var import_core3 = require("@cadenza.io/core");
17747
+ var import_core4 = require("@cadenza.io/core");
16041
17748
  var ACTOR_SESSION_STATE_PERSIST_CONCURRENCY = 20;
16042
17749
  var META_ACTOR_SESSION_STATE_HYDRATE_INTENT = "meta-actor-session-state-hydrate";
16043
17750
  var ACTOR_SESSION_TRACE_ENABLED4 = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
17751
+ function findNestedContextValue(ctx, key) {
17752
+ if (!ctx || typeof ctx !== "object") {
17753
+ return void 0;
17754
+ }
17755
+ if (Object.prototype.hasOwnProperty.call(ctx, key) || ctx[key] !== void 0) {
17756
+ return ctx[key];
17757
+ }
17758
+ const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
17759
+ for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
17760
+ const nested = joinedContexts[index];
17761
+ if (!nested || typeof nested !== "object") {
17762
+ continue;
17763
+ }
17764
+ const nestedValue = findNestedContextValue(nested, key);
17765
+ if (nestedValue !== void 0) {
17766
+ return nestedValue;
17767
+ }
17768
+ }
17769
+ return void 0;
17770
+ }
17771
+ function resolveActorSessionStateRow(ctx) {
17772
+ const singular = findNestedContextValue(ctx, "actorSessionState");
17773
+ if (singular && typeof singular === "object" && !Array.isArray(singular)) {
17774
+ return singular;
17775
+ }
17776
+ const plural = findNestedContextValue(ctx, "actorSessionStates");
17777
+ if (Array.isArray(plural)) {
17778
+ const first = plural.find(
17779
+ (entry) => entry && typeof entry === "object" && !Array.isArray(entry)
17780
+ );
17781
+ if (first) {
17782
+ return first;
17783
+ }
17784
+ }
17785
+ const rows = findNestedContextValue(ctx, "rows");
17786
+ if (Array.isArray(rows)) {
17787
+ const first = rows.find(
17788
+ (entry) => entry && typeof entry === "object" && !Array.isArray(entry)
17789
+ );
17790
+ if (first) {
17791
+ return first;
17792
+ }
17793
+ }
17794
+ return null;
17795
+ }
16044
17796
  function shouldAssumeSuccessfulActorSessionRowCount(ctx) {
16045
17797
  return ctx.__success === true && ctx.rowCount === void 0 && ctx.__status === "success" && ctx.__serviceName === "CadenzaDB" && ctx.__localTaskName === "Insert actor_session_state in CadenzaDB";
16046
17798
  }
@@ -16113,7 +17865,7 @@ function registerActorSessionPersistenceTasks() {
16113
17865
  )
16114
17866
  );
16115
17867
  }
16116
- const row = ctx.actorSessionState && typeof ctx.actorSessionState === "object" && !Array.isArray(ctx.actorSessionState) ? ctx.actorSessionState : null;
17868
+ const row = resolveActorSessionStateRow(ctx);
16117
17869
  if (!row) {
16118
17870
  return {
16119
17871
  __success: true,
@@ -16291,11 +18043,11 @@ function registerActorSessionPersistenceTasks() {
16291
18043
  },
16292
18044
  "Validates and prepares actor_session_state payload for strict write-through persistence.",
16293
18045
  localActorSessionTaskOptions
16294
- ).then(insertAndValidateActorSessionStateTask).respondsTo(import_core3.META_ACTOR_SESSION_STATE_PERSIST_INTENT);
18046
+ ).then(insertAndValidateActorSessionStateTask).respondsTo(import_core4.META_ACTOR_SESSION_STATE_PERSIST_INTENT);
16295
18047
  }
16296
18048
 
16297
18049
  // src/graph/controllers/GraphSyncController.ts
16298
- var import_core4 = require("@cadenza.io/core");
18050
+ var import_core5 = require("@cadenza.io/core");
16299
18051
  var import_uuid7 = require("uuid");
16300
18052
  var ACTOR_TASK_METADATA2 = /* @__PURE__ */ Symbol.for("@cadenza.io/core/actor-task-meta");
16301
18053
  function getActorTaskRuntimeMetadata2(taskFunction) {
@@ -16356,6 +18108,16 @@ function buildActorRegistrationData(actor) {
16356
18108
  version: 1
16357
18109
  };
16358
18110
  }
18111
+ function sanitizePersistedTaskSourceFields(task, data) {
18112
+ if (!task.isMeta && !task.isDeputy) {
18113
+ return data;
18114
+ }
18115
+ return {
18116
+ ...data,
18117
+ function_string: "",
18118
+ tag_id_getter: null
18119
+ };
18120
+ }
16359
18121
  function resolveSyncServiceName(task) {
16360
18122
  const ownerServiceName = typeof task?.ownerServiceName === "string" ? task.ownerServiceName.trim() : "";
16361
18123
  const taskServiceName = typeof task?.serviceName === "string" ? task.serviceName.trim() : "";
@@ -16379,7 +18141,7 @@ function buildIntentRegistryData(intent) {
16379
18141
  };
16380
18142
  }
16381
18143
  function isLocalOnlySyncIntent(intentName) {
16382
- return intentName === import_core4.META_ACTOR_SESSION_STATE_PERSIST_INTENT;
18144
+ return intentName === import_core5.META_ACTOR_SESSION_STATE_PERSIST_INTENT;
16383
18145
  }
16384
18146
  function getJoinedContextValue(ctx, key) {
16385
18147
  const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
@@ -16518,16 +18280,20 @@ function resolveSyncInsertTask(isCadenzaDBReady, tableName, queryData = {}, opti
16518
18280
  ctx,
16519
18281
  queryData
16520
18282
  );
16521
- if ((tableName === "signal_registry" || tableName === "directional_task_graph_map") && originalQueryData.data && typeof originalQueryData.data === "object" && !Array.isArray(originalQueryData.data) && Object.keys(originalQueryData.data).length === 0) {
16522
- console.warn(
16523
- "[CADENZA_SYNC_EMPTY_INSERT]",
16524
- {
16525
- tableName,
16526
- queryData: originalQueryData,
16527
- ctx,
16528
- joinedContexts: Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : []
16529
- }
16530
- );
18283
+ const hasEmptyObjectData = originalQueryData.data && typeof originalQueryData.data === "object" && !Array.isArray(originalQueryData.data) && Object.keys(originalQueryData.data).length === 0;
18284
+ const hasMissingData = originalQueryData.data === void 0;
18285
+ if ((tableName === "task" || tableName === "signal_registry" || tableName === "directional_task_graph_map") && (hasEmptyObjectData || hasMissingData)) {
18286
+ console.warn("[CADENZA_SYNC_EMPTY_INSERT]", {
18287
+ tableName,
18288
+ hasMissingData,
18289
+ hasEmptyObjectData,
18290
+ taskName: typeof ctx.__taskName === "string" ? ctx.__taskName : void 0,
18291
+ reason: typeof ctx.__reason === "string" ? ctx.__reason : void 0,
18292
+ syncSourceServiceName: typeof ctx.__syncSourceServiceName === "string" ? ctx.__syncSourceServiceName : void 0,
18293
+ queryData: originalQueryData,
18294
+ ctx,
18295
+ joinedContexts: Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : []
18296
+ });
16531
18297
  }
16532
18298
  return buildSyncExecutionEnvelope(
16533
18299
  ctx,
@@ -16618,7 +18384,7 @@ function isBootstrapLocalOnlyActorName(actorName) {
16618
18384
  return BOOTSTRAP_LOCAL_ONLY_ACTOR_NAMES.has(actorName);
16619
18385
  }
16620
18386
  function isBootstrapLocalOnlySignal(signalName) {
16621
- return signalName.startsWith("meta.") || signalName === "meta.service_registry.insert_execution_requested" || signalName === "meta.service_registry.routeable_transport_missing" || signalName === "meta.signal_broker.added" || signalName === "meta.rest.handshake" || signalName === "meta.rest.delegation_target_not_found" || signalName === "meta.socket.handshake" || signalName === "meta.socket.delegation_target_not_found" || signalName === "meta.fetch.handshake_complete" || signalName === "sub_meta.signal_broker.new_trace" || signalName.startsWith("meta.task.") || signalName.startsWith("meta.sync_controller.") || isLocalServiceReadySignal(signalName);
18387
+ return signalName.startsWith("meta.") || signalName.startsWith("global.meta.") || signalName === "meta.service_registry.insert_execution_requested" || signalName === "meta.service_registry.routeable_transport_missing" || signalName === "meta.signal_broker.added" || signalName === "meta.rest.handshake" || signalName === "meta.rest.delegation_target_not_found" || signalName === "meta.socket.handshake" || signalName === "meta.socket.delegation_target_not_found" || signalName === "meta.fetch.handshake_complete" || signalName === "sub_meta.signal_broker.new_trace" || signalName.startsWith("meta.task.") || signalName.startsWith("meta.sync_controller.") || isLocalServiceReadySignal(signalName);
16622
18388
  }
16623
18389
  function hasNonZeroPending(summary) {
16624
18390
  return Object.values(summary).some((value) => Number(value) > 0);
@@ -16846,6 +18612,12 @@ function resolveLocalRoutineFromSyncContext(ctx) {
16846
18612
  );
16847
18613
  return routineName ? CadenzaService.getRoutine(routineName) : void 0;
16848
18614
  }
18615
+ function shouldTrackDirectionalTaskMapForBootstrap(predecessorTask, nextTask) {
18616
+ if (!predecessorTask || !nextTask) {
18617
+ return false;
18618
+ }
18619
+ return predecessorTask.isMeta !== true && predecessorTask.isSubMeta !== true && nextTask.isMeta !== true && nextTask.isSubMeta !== true;
18620
+ }
16849
18621
  function resolveSignalNameFromSyncContext(ctx) {
16850
18622
  const candidateSignalNames = [
16851
18623
  ctx.signalName,
@@ -17463,40 +19235,41 @@ var GraphSyncController = class _GraphSyncController {
17463
19235
  if (task.registered) continue;
17464
19236
  const { __functionString, __getTagCallback } = task.export();
17465
19237
  this.tasksSynced = false;
19238
+ const taskRegistrationData = sanitizePersistedTaskSourceFields(task, {
19239
+ name: task.name,
19240
+ version: task.version,
19241
+ description: task.description,
19242
+ function_string: __functionString,
19243
+ tag_id_getter: __getTagCallback,
19244
+ layer_index: task.layerIndex,
19245
+ concurrency: task.concurrency,
19246
+ timeout: task.timeout,
19247
+ is_unique: task.isUnique,
19248
+ is_signal: task.isSignal,
19249
+ is_throttled: task.isThrottled,
19250
+ is_debounce: task.isDebounce,
19251
+ is_ephemeral: task.isEphemeral,
19252
+ is_meta: task.isMeta,
19253
+ is_sub_meta: task.isSubMeta,
19254
+ is_hidden: task.isHidden,
19255
+ validate_input_context: task.validateInputContext,
19256
+ validate_output_context: task.validateOutputContext,
19257
+ retry_count: task.retryCount,
19258
+ retry_delay: task.retryDelay,
19259
+ retry_delay_max: task.retryDelayMax,
19260
+ retry_delay_factor: task.retryDelayFactor,
19261
+ service_name: serviceName2,
19262
+ signals: {
19263
+ emits: Array.from(task.emitsSignals),
19264
+ signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
19265
+ signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
19266
+ observed: Array.from(task.observedSignals)
19267
+ },
19268
+ intents: Array.from(task.handlesIntents)
19269
+ });
17466
19270
  yield {
17467
19271
  __syncing: ctx.__syncing,
17468
- data: {
17469
- name: task.name,
17470
- version: task.version,
17471
- description: task.description,
17472
- function_string: __functionString,
17473
- tag_id_getter: __getTagCallback,
17474
- layer_index: task.layerIndex,
17475
- concurrency: task.concurrency,
17476
- timeout: task.timeout,
17477
- is_unique: task.isUnique,
17478
- is_signal: task.isSignal,
17479
- is_throttled: task.isThrottled,
17480
- is_debounce: task.isDebounce,
17481
- is_ephemeral: task.isEphemeral,
17482
- is_meta: task.isMeta,
17483
- is_sub_meta: task.isSubMeta,
17484
- is_hidden: task.isHidden,
17485
- validate_input_context: task.validateInputContext,
17486
- validate_output_context: task.validateOutputContext,
17487
- retry_count: task.retryCount,
17488
- retry_delay: task.retryDelay,
17489
- retry_delay_max: task.retryDelayMax,
17490
- retry_delay_factor: task.retryDelayFactor,
17491
- service_name: serviceName2,
17492
- signals: {
17493
- emits: Array.from(task.emitsSignals),
17494
- signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
17495
- signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
17496
- observed: Array.from(task.observedSignals)
17497
- },
17498
- intents: Array.from(task.handlesIntents)
17499
- },
19272
+ data: taskRegistrationData,
17500
19273
  __taskName: task.name
17501
19274
  };
17502
19275
  }
@@ -17922,7 +19695,7 @@ var GraphSyncController = class _GraphSyncController {
17922
19695
  return;
17923
19696
  }
17924
19697
  for (const t of task.nextTasks) {
17925
- if (task.taskMapRegistration.has(t.name) || t.hidden || !t.register || !t.registered) {
19698
+ if (task.taskMapRegistration.has(t.name) || t.hidden || !t.register || !t.registered || !shouldTrackDirectionalTaskMapForBootstrap(task, t)) {
17926
19699
  continue;
17927
19700
  }
17928
19701
  const serviceName2 = resolveSyncServiceName(t);
@@ -17990,7 +19763,7 @@ var GraphSyncController = class _GraphSyncController {
17990
19763
  return false;
17991
19764
  }
17992
19765
  for (const nextTask of task.nextTasks) {
17993
- if (task.taskMapRegistration.has(nextTask.name) || nextTask.isHidden || !nextTask.register || !nextTask.registered) {
19766
+ if (task.taskMapRegistration.has(nextTask.name) || nextTask.isHidden || !nextTask.register || !nextTask.registered || !shouldTrackDirectionalTaskMapForBootstrap(task, nextTask)) {
17994
19767
  continue;
17995
19768
  }
17996
19769
  if (resolveSyncServiceName(nextTask)) {
@@ -18655,13 +20428,50 @@ var GraphSyncController = class _GraphSyncController {
18655
20428
  startActorPrimitiveSyncTask,
18656
20429
  startRoutinePrimitiveSyncTask
18657
20430
  );
18658
- const getAllTasksForSyncTask = CadenzaService.registry.getAllTasks.clone();
20431
+ const getAllTasksForSyncTask = CadenzaService.createMetaTask(
20432
+ "Get all tasks for sync",
20433
+ (ctx) => ({
20434
+ ...ctx,
20435
+ tasks: Array.from(CadenzaService.registry.tasks.values())
20436
+ }),
20437
+ "Collects local tasks for the primitive sync phase.",
20438
+ {
20439
+ register: false,
20440
+ isHidden: true
20441
+ }
20442
+ );
18659
20443
  startTaskPrimitiveSyncTask.then(
18660
20444
  getAllTasksForSyncTask,
18661
20445
  gatherTaskRegistrationTask
18662
20446
  );
18663
20447
  getAllTasksForSyncTask.then(this.splitTasksForRegistration);
18664
- const getSignalsForSyncTask = CadenzaService.signalBroker.getSignalsTask.clone();
20448
+ const getSignalsForSyncTask = CadenzaService.createMetaTask(
20449
+ "Get signals for sync",
20450
+ (ctx) => {
20451
+ const uniqueSignals = Array.from(
20452
+ /* @__PURE__ */ new Set([
20453
+ ...CadenzaService.signalBroker.signalObservers.keys(),
20454
+ ...CadenzaService.signalBroker.emittedSignalsRegistry
20455
+ ])
20456
+ ).filter((signal) => !signal.includes(":"));
20457
+ const processedSignals = uniqueSignals.map((signal) => ({
20458
+ signal,
20459
+ data: {
20460
+ registered: CadenzaService.signalBroker.signalObservers.get(signal)?.registered ?? false,
20461
+ metadata: CadenzaService.signalBroker.getSignalMetadata(signal) ?? null
20462
+ }
20463
+ }));
20464
+ return {
20465
+ ...ctx,
20466
+ signals: processedSignals
20467
+ };
20468
+ },
20469
+ "Collects local signals for the primitive sync phase.",
20470
+ {
20471
+ register: false,
20472
+ isHidden: true
20473
+ }
20474
+ );
18665
20475
  startSignalPrimitiveSyncTask.then(
18666
20476
  getSignalsForSyncTask,
18667
20477
  gatherSignalRegistrationTask
@@ -18703,40 +20513,110 @@ var GraphSyncController = class _GraphSyncController {
18703
20513
  gatherActorRegistrationTask
18704
20514
  );
18705
20515
  getAllActorsForSyncTask.then(this.splitActorsForRegistration);
18706
- const getAllRoutinesForSyncTask = CadenzaService.registry.getAllRoutines.clone();
20516
+ const getAllRoutinesForSyncTask = CadenzaService.createMetaTask(
20517
+ "Get all routines for sync",
20518
+ (ctx) => ({
20519
+ ...ctx,
20520
+ routines: Array.from(CadenzaService.registry.routines.values())
20521
+ }),
20522
+ "Collects local routines for the primitive sync phase.",
20523
+ {
20524
+ register: false,
20525
+ isHidden: true
20526
+ }
20527
+ );
18707
20528
  startRoutinePrimitiveSyncTask.then(
18708
20529
  getAllRoutinesForSyncTask,
18709
20530
  gatherRoutineRegistrationTask
18710
20531
  );
18711
20532
  getAllRoutinesForSyncTask.then(this.splitRoutinesTask);
18712
- const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20533
+ const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.createMetaTask(
20534
+ "Iterate tasks for directional task map sync",
20535
+ function* (ctx) {
20536
+ for (const task of CadenzaService.registry.tasks.values()) {
20537
+ yield { ...ctx, task };
20538
+ }
20539
+ },
20540
+ "Iterates local tasks for directional task-map sync.",
20541
+ {
20542
+ register: false,
20543
+ isHidden: true
20544
+ }
20545
+ );
18713
20546
  startDirectionalTaskMapSyncTask.then(
18714
20547
  iterateTasksForDirectionalTaskMapSyncTask,
18715
20548
  gatherDirectionalTaskMapRegistrationTask
18716
20549
  );
18717
20550
  iterateTasksForDirectionalTaskMapSyncTask.then(this.registerTaskMapTask);
18718
20551
  recordTaskMapRegistrationTask.then(gatherDirectionalTaskMapRegistrationTask);
18719
- const iterateTasksForSignalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20552
+ const iterateTasksForSignalTaskMapSyncTask = CadenzaService.createMetaTask(
20553
+ "Iterate tasks for signal task map sync",
20554
+ function* (ctx) {
20555
+ for (const task of CadenzaService.registry.tasks.values()) {
20556
+ yield { ...ctx, task };
20557
+ }
20558
+ },
20559
+ "Iterates local tasks for signal-to-task map sync.",
20560
+ {
20561
+ register: false,
20562
+ isHidden: true
20563
+ }
20564
+ );
18720
20565
  startSignalTaskMapSyncTask.then(
18721
20566
  iterateTasksForSignalTaskMapSyncTask,
18722
20567
  gatherSignalTaskMapRegistrationTask
18723
20568
  );
18724
20569
  iterateTasksForSignalTaskMapSyncTask.then(this.registerSignalToTaskMapTask);
18725
20570
  this.registerSignalToTaskMapTask.then(gatherSignalTaskMapRegistrationTask);
18726
- const iterateTasksForIntentTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20571
+ const iterateTasksForIntentTaskMapSyncTask = CadenzaService.createMetaTask(
20572
+ "Iterate tasks for intent task map sync",
20573
+ function* (ctx) {
20574
+ for (const task of CadenzaService.registry.tasks.values()) {
20575
+ yield { ...ctx, task };
20576
+ }
20577
+ },
20578
+ "Iterates local tasks for intent-to-task map sync.",
20579
+ {
20580
+ register: false,
20581
+ isHidden: true
20582
+ }
20583
+ );
18727
20584
  startIntentTaskMapSyncTask.then(
18728
20585
  iterateTasksForIntentTaskMapSyncTask,
18729
20586
  gatherIntentTaskMapRegistrationTask
18730
20587
  );
18731
20588
  iterateTasksForIntentTaskMapSyncTask.then(this.registerIntentToTaskMapTask);
18732
20589
  this.registerIntentToTaskMapTask.then(gatherIntentTaskMapRegistrationTask);
18733
- const iterateTasksForActorTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20590
+ const iterateTasksForActorTaskMapSyncTask = CadenzaService.createMetaTask(
20591
+ "Iterate tasks for actor task map sync",
20592
+ function* (ctx) {
20593
+ for (const task of CadenzaService.registry.tasks.values()) {
20594
+ yield { ...ctx, task };
20595
+ }
20596
+ },
20597
+ "Iterates local tasks for actor-to-task map sync.",
20598
+ {
20599
+ register: false,
20600
+ isHidden: true
20601
+ }
20602
+ );
18734
20603
  startActorTaskMapSyncTask.then(
18735
20604
  iterateTasksForActorTaskMapSyncTask,
18736
20605
  gatherActorTaskMapRegistrationTask
18737
20606
  );
18738
20607
  iterateTasksForActorTaskMapSyncTask.then(this.registerActorTaskMapTask);
18739
- const getAllRoutinesForTaskMapSyncTask = CadenzaService.registry.getAllRoutines.clone();
20608
+ const getAllRoutinesForTaskMapSyncTask = CadenzaService.createMetaTask(
20609
+ "Get all routines for task map sync",
20610
+ (ctx) => ({
20611
+ ...ctx,
20612
+ routines: Array.from(CadenzaService.registry.routines.values())
20613
+ }),
20614
+ "Collects local routines for routine-to-task map sync.",
20615
+ {
20616
+ register: false,
20617
+ isHidden: true
20618
+ }
20619
+ );
18740
20620
  startRoutineTaskMapSyncTask.then(
18741
20621
  getAllRoutinesForTaskMapSyncTask,
18742
20622
  gatherRoutineTaskMapRegistrationTask
@@ -18812,11 +20692,37 @@ function resolveTaskByName(name) {
18812
20692
  const taskName = String(name ?? "");
18813
20693
  return taskName ? CadenzaService.get(taskName) : void 0;
18814
20694
  }
20695
+ function resolveHelperFromMetadataContext(ctx) {
20696
+ const toolRuntime = CadenzaService;
20697
+ const helperName = String(
20698
+ ctx?.helperName ?? ctx?.data?.helperName ?? ctx?.data?.helper_name ?? ctx?.filter?.helperName ?? ctx?.filter?.helper_name ?? ""
20699
+ );
20700
+ return helperName ? toolRuntime.getHelper?.(helperName) : void 0;
20701
+ }
20702
+ function resolveGlobalFromMetadataContext(ctx) {
20703
+ const toolRuntime = CadenzaService;
20704
+ const globalName = String(
20705
+ ctx?.globalName ?? ctx?.data?.globalName ?? ctx?.data?.global_name ?? ctx?.filter?.globalName ?? ctx?.filter?.global_name ?? ""
20706
+ );
20707
+ return globalName ? toolRuntime.getGlobal?.(globalName) : void 0;
20708
+ }
18815
20709
  function resolvePredecessorTaskFromMetadataContext(ctx) {
18816
20710
  return resolveTaskByName(
18817
20711
  ctx?.predecessorTaskName ?? ctx?.data?.predecessorTaskName ?? ctx?.data?.predecessor_task_name ?? ctx?.filter?.predecessorTaskName ?? ctx?.filter?.predecessor_task_name
18818
20712
  );
18819
20713
  }
20714
+ function sanitizePersistedTaskSourceFields2(task, data) {
20715
+ if (!task?.isMeta && !task?.isDeputy) {
20716
+ return data;
20717
+ }
20718
+ return {
20719
+ ...data,
20720
+ functionString: "",
20721
+ function_string: "",
20722
+ tagIdGetter: null,
20723
+ tag_id_getter: null
20724
+ };
20725
+ }
18820
20726
  function shouldSkipDirectTaskMetadata(task) {
18821
20727
  return !task || !task.register || task.isHidden || task.isDeputy;
18822
20728
  }
@@ -18894,6 +20800,9 @@ function shouldPersistBusinessInquiryCompletion(ctx) {
18894
20800
  const inquiryName = String(ctx?.data?.metadata?.inquiryMeta?.inquiry ?? "");
18895
20801
  return inquiryName.length > 0 && !isMetaIntentName(inquiryName);
18896
20802
  }
20803
+ function shouldPersistExecutionTrace(ctx) {
20804
+ return ctx?.data?.isMeta !== true && ctx?.data?.is_meta !== true;
20805
+ }
18897
20806
  function shouldPersistRoutineExecution(ctx) {
18898
20807
  if (ctx?.data?.isMeta === true || ctx?.data?.is_meta === true) {
18899
20808
  return false;
@@ -18957,10 +20866,10 @@ var GraphMetadataController = class _GraphMetadataController {
18957
20866
  task.registrationRequested = true;
18958
20867
  }
18959
20868
  return buildDatabaseTriggerContext(
18960
- {
20869
+ sanitizePersistedTaskSourceFields2(task, {
18961
20870
  ...ctx.data,
18962
20871
  serviceName: CadenzaService.serviceRegistry.serviceName
18963
- },
20872
+ }),
18964
20873
  void 0,
18965
20874
  { onConflict },
18966
20875
  { onConflict }
@@ -19063,6 +20972,88 @@ var GraphMetadataController = class _GraphMetadataController {
19063
20972
  serviceName: CadenzaService.serviceRegistry.serviceName
19064
20973
  });
19065
20974
  }).doOn("meta.task.intent_associated").emits("global.meta.graph_metadata.task_intent_associated");
20975
+ const buildHelperMetadataContext = (ctx) => {
20976
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20977
+ return false;
20978
+ }
20979
+ const helper = resolveHelperFromMetadataContext(ctx);
20980
+ if (!helper) {
20981
+ return false;
20982
+ }
20983
+ return buildDatabaseTriggerContext({
20984
+ ...ctx.data,
20985
+ serviceName: CadenzaService.serviceRegistry.serviceName
20986
+ });
20987
+ };
20988
+ createLocalGraphMetadataTask("Handle helper creation", buildHelperMetadataContext).doOn("meta.helper.created").emits("global.meta.graph_metadata.helper_created");
20989
+ createLocalGraphMetadataTask("Handle helper update", buildHelperMetadataContext).doOn("meta.helper.updated").emits("global.meta.graph_metadata.helper_updated");
20990
+ const buildGlobalMetadataContext = (ctx) => {
20991
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20992
+ return false;
20993
+ }
20994
+ const globalDefinition = resolveGlobalFromMetadataContext(ctx);
20995
+ if (!globalDefinition) {
20996
+ return false;
20997
+ }
20998
+ return buildDatabaseTriggerContext({
20999
+ ...ctx.data,
21000
+ serviceName: CadenzaService.serviceRegistry.serviceName
21001
+ });
21002
+ };
21003
+ createLocalGraphMetadataTask("Handle global creation", buildGlobalMetadataContext).doOn("meta.global.created").emits("global.meta.graph_metadata.global_created");
21004
+ createLocalGraphMetadataTask("Handle global update", buildGlobalMetadataContext).doOn("meta.global.updated").emits("global.meta.graph_metadata.global_updated");
21005
+ createLocalGraphMetadataTask("Handle task helper association", (ctx) => {
21006
+ if (!shouldEmitDirectPrimitiveMetadata()) {
21007
+ return false;
21008
+ }
21009
+ const task = resolveTaskFromMetadataContext(ctx);
21010
+ if (shouldSkipDirectTaskMetadata(task)) {
21011
+ return false;
21012
+ }
21013
+ return buildDatabaseTriggerContext({
21014
+ ...ctx.data,
21015
+ serviceName: CadenzaService.serviceRegistry.serviceName
21016
+ });
21017
+ }).doOn("meta.task.helper_associated").emits("global.meta.graph_metadata.task_helper_associated");
21018
+ createLocalGraphMetadataTask("Handle helper helper association", (ctx) => {
21019
+ if (!shouldEmitDirectPrimitiveMetadata()) {
21020
+ return false;
21021
+ }
21022
+ const helper = resolveHelperFromMetadataContext(ctx);
21023
+ if (!helper) {
21024
+ return false;
21025
+ }
21026
+ return buildDatabaseTriggerContext({
21027
+ ...ctx.data,
21028
+ serviceName: CadenzaService.serviceRegistry.serviceName
21029
+ });
21030
+ }).doOn("meta.helper.helper_associated").emits("global.meta.graph_metadata.helper_helper_associated");
21031
+ createLocalGraphMetadataTask("Handle task global association", (ctx) => {
21032
+ if (!shouldEmitDirectPrimitiveMetadata()) {
21033
+ return false;
21034
+ }
21035
+ const task = resolveTaskFromMetadataContext(ctx);
21036
+ if (shouldSkipDirectTaskMetadata(task)) {
21037
+ return false;
21038
+ }
21039
+ return buildDatabaseTriggerContext({
21040
+ ...ctx.data,
21041
+ serviceName: CadenzaService.serviceRegistry.serviceName
21042
+ });
21043
+ }).doOn("meta.task.global_associated").emits("global.meta.graph_metadata.task_global_associated");
21044
+ createLocalGraphMetadataTask("Handle helper global association", (ctx) => {
21045
+ if (!shouldEmitDirectPrimitiveMetadata()) {
21046
+ return false;
21047
+ }
21048
+ const helper = resolveHelperFromMetadataContext(ctx);
21049
+ if (!helper) {
21050
+ return false;
21051
+ }
21052
+ return buildDatabaseTriggerContext({
21053
+ ...ctx.data,
21054
+ serviceName: CadenzaService.serviceRegistry.serviceName
21055
+ });
21056
+ }).doOn("meta.helper.global_associated").emits("global.meta.graph_metadata.helper_global_associated");
19066
21057
  createLocalGraphMetadataTask("Handle task unsubscribing signal", (ctx) => {
19067
21058
  if (!shouldEmitDirectPrimitiveMetadata()) {
19068
21059
  return false;
@@ -19130,6 +21121,9 @@ var GraphMetadataController = class _GraphMetadataController {
19130
21121
  });
19131
21122
  }).doOn("meta.routine.task_added").emits("global.meta.graph_metadata.task_added_to_routine");
19132
21123
  createLocalGraphMetadataTask("Handle new trace", (ctx) => {
21124
+ if (!shouldPersistExecutionTrace(ctx)) {
21125
+ return false;
21126
+ }
19133
21127
  return buildDatabaseTriggerContext({
19134
21128
  ...ctx.data,
19135
21129
  service_name: CadenzaService.serviceRegistry.serviceName,
@@ -19143,10 +21137,10 @@ var GraphMetadataController = class _GraphMetadataController {
19143
21137
  return false;
19144
21138
  }
19145
21139
  const routineData = ctx.data ?? {};
19146
- const sanitizedRoutineContext = stripLocalRoutinePersistenceHints(
21140
+ const sanitizedRoutineContext = sanitizeExecutionPersistenceContext(
19147
21141
  routineData.context ?? {}
19148
21142
  );
19149
- const sanitizedRoutineMetaContext = stripLocalRoutinePersistenceHints(
21143
+ const sanitizedRoutineMetaContext = sanitizeExecutionPersistenceContext(
19150
21144
  routineData.metaContext ?? {}
19151
21145
  );
19152
21146
  const routineExecutionRow = {
@@ -19281,12 +21275,13 @@ var GraphMetadataController = class _GraphMetadataController {
19281
21275
  createLocalGraphMetadataTask(
19282
21276
  "Handle routine execution ended",
19283
21277
  (ctx) => {
21278
+ const sanitizedData = sanitizeExecutionPersistenceResultPayload({
21279
+ ...ctx.data,
21280
+ serviceName: CadenzaService.serviceRegistry.serviceName,
21281
+ serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
21282
+ });
19284
21283
  return buildDatabaseTriggerContext(
19285
- {
19286
- ...ctx.data,
19287
- serviceName: CadenzaService.serviceRegistry.serviceName,
19288
- serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
19289
- },
21284
+ sanitizedData,
19290
21285
  ctx.filter ?? void 0
19291
21286
  );
19292
21287
  },
@@ -19300,10 +21295,10 @@ var GraphMetadataController = class _GraphMetadataController {
19300
21295
  return false;
19301
21296
  }
19302
21297
  const taskExecutionData = ctx.data ?? {};
19303
- const sanitizedTaskContext = stripLocalRoutinePersistenceHints(
21298
+ const sanitizedTaskContext = sanitizeExecutionPersistenceContext(
19304
21299
  taskExecutionData.context ?? {}
19305
21300
  );
19306
- const sanitizedTaskMetaContext = stripLocalRoutinePersistenceHints(
21301
+ const sanitizedTaskMetaContext = sanitizeExecutionPersistenceContext(
19307
21302
  taskExecutionData.metaContext ?? {}
19308
21303
  );
19309
21304
  const routineMetadata = resolveRoutinePersistenceMetadata(
@@ -19536,12 +21531,13 @@ var GraphMetadataController = class _GraphMetadataController {
19536
21531
  if (!shouldPersistTaskExecutionMetadata(ctx)) {
19537
21532
  return false;
19538
21533
  }
21534
+ const sanitizedData = sanitizeExecutionPersistenceResultPayload({
21535
+ ...ctx.data,
21536
+ serviceName: CadenzaService.serviceRegistry.serviceName,
21537
+ serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
21538
+ });
19539
21539
  return buildDatabaseTriggerContext(
19540
- {
19541
- ...ctx.data,
19542
- serviceName: CadenzaService.serviceRegistry.serviceName,
19543
- serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
19544
- },
21540
+ sanitizedData,
19545
21541
  ctx.filter ?? void 0
19546
21542
  );
19547
21543
  },
@@ -20308,6 +22304,15 @@ var DEFAULT_DEPUTY_TASK_CONCURRENCY = 50;
20308
22304
  var DEFAULT_DEPUTY_TASK_TIMEOUT_MS = 12e4;
20309
22305
  var DEFAULT_DATABASE_PROXY_TASK_CONCURRENCY = 50;
20310
22306
  var DEFAULT_DATABASE_PROXY_TASK_TIMEOUT_MS = 12e4;
22307
+ var SERVICE_MANIFEST_PUBLICATION_ORDER = [
22308
+ "routing_capability",
22309
+ "business_structural",
22310
+ "local_meta_structural"
22311
+ ];
22312
+ function getServiceManifestPublicationLayerRank(layer) {
22313
+ const index = SERVICE_MANIFEST_PUBLICATION_ORDER.indexOf(layer);
22314
+ return index >= 0 ? index : SERVICE_MANIFEST_PUBLICATION_ORDER.length - 1;
22315
+ }
20311
22316
  var CadenzaService = class {
20312
22317
  static unregisterGracefulShutdownHandlers() {
20313
22318
  for (const cleanup of this.shutdownHandlerCleanup) {
@@ -20434,7 +22439,15 @@ var CadenzaService = class {
20434
22439
  this.replayRegisteredTaskSignalObservations();
20435
22440
  this.replayRegisteredTaskIntentAssociations();
20436
22441
  }
20437
- static requestServiceManifestPublication(reason, immediate = false) {
22442
+ static normalizeServiceManifestPublicationLayer(value, fallback = "business_structural") {
22443
+ return value === "routing_capability" || value === "business_structural" || value === "local_meta_structural" ? value : fallback;
22444
+ }
22445
+ static mergeServiceManifestPublicationRequest(reason, targetLayer) {
22446
+ this.serviceManifestPublicationPendingReason = reason;
22447
+ const currentTargetLayer = this.serviceManifestPublicationPendingLayer ?? "routing_capability";
22448
+ this.serviceManifestPublicationPendingLayer = getServiceManifestPublicationLayerRank(targetLayer) >= getServiceManifestPublicationLayerRank(currentTargetLayer) ? targetLayer : currentTargetLayer;
22449
+ }
22450
+ static requestServiceManifestPublication(reason, immediate = false, targetLayer = "business_structural") {
20438
22451
  if (!this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
20439
22452
  return;
20440
22453
  }
@@ -20442,7 +22455,8 @@ var CadenzaService = class {
20442
22455
  const payload = {
20443
22456
  __reason: reason,
20444
22457
  __serviceName: this.serviceRegistry.serviceName,
20445
- __serviceInstanceId: this.serviceRegistry.serviceInstanceId
22458
+ __serviceInstanceId: this.serviceRegistry.serviceInstanceId,
22459
+ __publicationLayer: targetLayer
20446
22460
  };
20447
22461
  if (immediate) {
20448
22462
  this.emit(signalName, payload);
@@ -20450,32 +22464,53 @@ var CadenzaService = class {
20450
22464
  }
20451
22465
  this.debounce(signalName, payload, 100);
20452
22466
  }
20453
- static scheduleServiceManifestPublicationRetry(reason) {
22467
+ static scheduleServiceManifestPublicationRetry(reason, targetLayer = "business_structural") {
20454
22468
  if (!this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
20455
22469
  return;
20456
22470
  }
20457
22471
  setTimeout(() => {
20458
- this.requestServiceManifestPublication(reason, false);
22472
+ this.requestServiceManifestPublication(reason, false, targetLayer);
20459
22473
  }, 1e3);
20460
22474
  }
20461
- static async publishServiceManifestIfNeeded(reason) {
22475
+ static async publishServiceManifestIfNeeded(reason, targetLayer = "business_structural") {
20462
22476
  if (!this.serviceRegistry.connectsToCadenzaDB || !this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
20463
22477
  return false;
20464
22478
  }
20465
22479
  const publishReason = typeof reason === "string" && reason.trim().length > 0 ? reason.trim() : "service_manifest_publish";
22480
+ const publishTargetLayer = this.normalizeServiceManifestPublicationLayer(
22481
+ targetLayer
22482
+ );
20466
22483
  if (this.serviceManifestPublicationInFlight) {
20467
- this.serviceManifestPublicationPendingReason = publishReason;
22484
+ this.mergeServiceManifestPublicationRequest(
22485
+ publishReason,
22486
+ publishTargetLayer
22487
+ );
20468
22488
  return false;
20469
22489
  }
20470
- const snapshot = buildServiceManifestSnapshot({
20471
- serviceName: this.serviceRegistry.serviceName,
20472
- serviceInstanceId: this.serviceRegistry.serviceInstanceId,
20473
- revision: this.serviceManifestRevision + 1,
20474
- publishedAt: (/* @__PURE__ */ new Date()).toISOString()
22490
+ const publicationPlan = SERVICE_MANIFEST_PUBLICATION_ORDER.filter(
22491
+ (layer) => getServiceManifestPublicationLayerRank(layer) <= getServiceManifestPublicationLayerRank(publishTargetLayer)
22492
+ ).map((layer) => {
22493
+ const snapshot2 = buildServiceManifestSnapshot({
22494
+ serviceName: this.serviceRegistry.serviceName,
22495
+ serviceInstanceId: this.serviceRegistry.serviceInstanceId,
22496
+ revision: this.serviceManifestRevision + 1,
22497
+ publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
22498
+ publicationLayer: layer
22499
+ });
22500
+ return {
22501
+ layer,
22502
+ snapshot: snapshot2,
22503
+ changed: this.lastPublishedServiceManifestHashes[layer] !== snapshot2.manifestHash
22504
+ };
20475
22505
  });
20476
- if (this.lastPublishedServiceManifestHash && this.lastPublishedServiceManifestHash === snapshot.manifestHash) {
22506
+ const nextPublication = publicationPlan.find((entry) => entry.changed);
22507
+ if (!nextPublication) {
20477
22508
  return false;
20478
22509
  }
22510
+ const { layer: publicationLayer, snapshot } = nextPublication;
22511
+ const hasPendingFollowupLayer = publicationPlan.some(
22512
+ (entry) => entry.changed && getServiceManifestPublicationLayerRank(entry.layer) > getServiceManifestPublicationLayerRank(publicationLayer)
22513
+ );
20479
22514
  this.serviceManifestPublicationInFlight = true;
20480
22515
  try {
20481
22516
  this.serviceRegistry.ensureBootstrapAuthorityControlPlaneForInquiry(
@@ -20483,7 +22518,10 @@ var CadenzaService = class {
20483
22518
  snapshot
20484
22519
  );
20485
22520
  if (!this.serviceRegistry.hasAuthorityBootstrapHandshakeEstablished()) {
20486
- this.scheduleServiceManifestPublicationRetry(publishReason);
22521
+ this.scheduleServiceManifestPublicationRetry(
22522
+ publishReason,
22523
+ publishTargetLayer
22524
+ );
20487
22525
  return false;
20488
22526
  }
20489
22527
  await this.inquire(AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT, snapshot, {
@@ -20491,32 +22529,48 @@ var CadenzaService = class {
20491
22529
  requireComplete: true
20492
22530
  });
20493
22531
  this.serviceManifestRevision = snapshot.revision;
20494
- this.lastPublishedServiceManifestHash = snapshot.manifestHash;
22532
+ this.lastPublishedServiceManifestHashes[publicationLayer] = snapshot.manifestHash;
22533
+ if (hasPendingFollowupLayer) {
22534
+ this.mergeServiceManifestPublicationRequest(
22535
+ publishReason,
22536
+ publishTargetLayer
22537
+ );
22538
+ }
20495
22539
  return {
20496
22540
  serviceManifest: snapshot,
20497
- published: true
22541
+ published: true,
22542
+ publicationLayer
20498
22543
  };
20499
22544
  } catch (error) {
20500
22545
  this.log("Service manifest publication failed. Scheduling retry.", {
20501
22546
  serviceName: this.serviceRegistry.serviceName,
20502
22547
  serviceInstanceId: this.serviceRegistry.serviceInstanceId,
20503
22548
  reason: publishReason,
22549
+ publicationLayer,
20504
22550
  error: resolveInquiryFailureError(
20505
22551
  AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT,
20506
22552
  error
20507
22553
  ),
20508
22554
  inquiryMeta: error && typeof error === "object" && "__inquiryMeta" in error ? error.__inquiryMeta : null
20509
22555
  });
20510
- this.scheduleServiceManifestPublicationRetry(publishReason);
22556
+ this.scheduleServiceManifestPublicationRetry(
22557
+ publishReason,
22558
+ publishTargetLayer
22559
+ );
20511
22560
  return false;
20512
22561
  } finally {
20513
22562
  this.serviceManifestPublicationInFlight = false;
20514
- if (this.serviceManifestPublicationPendingReason) {
22563
+ if (this.serviceManifestPublicationPendingReason && this.serviceManifestPublicationPendingLayer) {
20515
22564
  const pendingReason = this.serviceManifestPublicationPendingReason;
22565
+ const pendingLayer = this.serviceManifestPublicationPendingLayer;
20516
22566
  this.serviceManifestPublicationPendingReason = null;
22567
+ this.serviceManifestPublicationPendingLayer = null;
20517
22568
  this.debounce(
20518
22569
  "meta.service_manifest.publish_requested",
20519
- { __reason: pendingReason },
22570
+ {
22571
+ __reason: pendingReason,
22572
+ __publicationLayer: pendingLayer
22573
+ },
20520
22574
  100
20521
22575
  );
20522
22576
  }
@@ -20529,9 +22583,13 @@ var CadenzaService = class {
20529
22583
  this.createMetaTask(
20530
22584
  "Publish service manifest",
20531
22585
  async (ctx) => this.publishServiceManifestIfNeeded(
20532
- typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0 ? ctx.__reason.trim() : "service_manifest_publish"
22586
+ typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0 ? ctx.__reason.trim() : "service_manifest_publish",
22587
+ this.normalizeServiceManifestPublicationLayer(
22588
+ ctx.__publicationLayer,
22589
+ "business_structural"
22590
+ )
20533
22591
  ),
20534
- "Publishes a full static manifest snapshot to authority when the manifest hash changes.",
22592
+ "Publishes staged static manifest snapshots to authority when the manifest hash changes.",
20535
22593
  {
20536
22594
  register: false,
20537
22595
  isHidden: true
@@ -20541,13 +22599,18 @@ var CadenzaService = class {
20541
22599
  "Request manifest publication after structural change",
20542
22600
  (ctx) => {
20543
22601
  const reason = typeof ctx.signal === "string" && ctx.signal.trim().length > 0 ? ctx.signal : typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0 ? ctx.__reason : "manifest_structural_update";
22602
+ const targetLayer = reason === "meta.service_registry.instance_inserted" ? "business_structural" : this.normalizeServiceManifestPublicationLayer(
22603
+ ctx.__publicationLayer,
22604
+ "business_structural"
22605
+ );
20544
22606
  this.requestServiceManifestPublication(
20545
22607
  reason,
20546
- reason === "meta.service_registry.instance_inserted"
22608
+ reason === "meta.service_registry.instance_inserted",
22609
+ targetLayer
20547
22610
  );
20548
22611
  return true;
20549
22612
  },
20550
- "Requests a manifest publication when a static service primitive changes.",
22613
+ "Requests staged manifest publication when a static service primitive changes.",
20551
22614
  {
20552
22615
  register: false,
20553
22616
  isHidden: true
@@ -20559,9 +22622,17 @@ var CadenzaService = class {
20559
22622
  "meta.task.relationship_added",
20560
22623
  "meta.task.relationship_removed",
20561
22624
  "meta.task.intent_associated",
22625
+ "meta.task.helper_associated",
22626
+ "meta.task.global_associated",
20562
22627
  "meta.task.observed_signal",
20563
22628
  "meta.task.attached_signal",
20564
22629
  "meta.task.detached_signal",
22630
+ "meta.helper.created",
22631
+ "meta.helper.updated",
22632
+ "meta.global.created",
22633
+ "meta.global.updated",
22634
+ "meta.helper.helper_associated",
22635
+ "meta.helper.global_associated",
20565
22636
  "meta.actor.created",
20566
22637
  "meta.actor.task_associated",
20567
22638
  "meta.fetch.handshake_complete",
@@ -20590,19 +22661,19 @@ var CadenzaService = class {
20590
22661
  static bootstrap() {
20591
22662
  if (this.isBootstrapped) return;
20592
22663
  this.isBootstrapped = true;
20593
- import_core5.default.bootstrap();
20594
- import_core5.default.setRuntimeInquiryDelegate(
22664
+ import_core6.default.bootstrap();
22665
+ import_core6.default.setRuntimeInquiryDelegate(
20595
22666
  (inquiry, context, options) => this.inquire(
20596
22667
  inquiry,
20597
22668
  context,
20598
22669
  options ?? {}
20599
22670
  )
20600
22671
  );
20601
- this.signalBroker = import_core5.default.signalBroker;
20602
- this.inquiryBroker = import_core5.default.inquiryBroker;
20603
- this.runner = import_core5.default.runner;
20604
- this.metaRunner = import_core5.default.metaRunner;
20605
- this.registry = import_core5.default.registry;
22672
+ this.signalBroker = import_core6.default.signalBroker;
22673
+ this.inquiryBroker = import_core6.default.inquiryBroker;
22674
+ this.runner = import_core6.default.runner;
22675
+ this.metaRunner = import_core6.default.metaRunner;
22676
+ this.registry = import_core6.default.registry;
20606
22677
  this.serviceRegistry = ServiceRegistry.instance;
20607
22678
  RestController.instance;
20608
22679
  SocketController.instance;
@@ -20636,8 +22707,8 @@ var CadenzaService = class {
20636
22707
  return;
20637
22708
  }
20638
22709
  this.frontendSyncScheduled = true;
20639
- import_core5.default.interval("meta.sync_requested", { __syncing: false }, 18e4);
20640
- import_core5.default.schedule("meta.sync_requested", { __syncing: false }, 250);
22710
+ import_core6.default.interval("meta.sync_requested", { __syncing: false }, 18e4);
22711
+ import_core6.default.schedule("meta.sync_requested", { __syncing: false }, 250);
20641
22712
  }
20642
22713
  static normalizeDeclaredTransports(transports, serviceId, useSocket) {
20643
22714
  return (transports ?? []).map((transport) => normalizeServiceTransportConfig(transport)).filter(
@@ -20695,7 +22766,7 @@ var CadenzaService = class {
20695
22766
  * @return {void} Does not return any value.
20696
22767
  */
20697
22768
  static validateName(name) {
20698
- import_core5.default.validateName(name);
22769
+ import_core6.default.validateName(name);
20699
22770
  }
20700
22771
  /**
20701
22772
  * Gets the current run strategy from the Cadenza configuration.
@@ -20703,7 +22774,7 @@ var CadenzaService = class {
20703
22774
  * @return {Function} The run strategy function defined in the Cadenza configuration.
20704
22775
  */
20705
22776
  static get runStrategy() {
20706
- return import_core5.default.runStrategy;
22777
+ return import_core6.default.runStrategy;
20707
22778
  }
20708
22779
  /**
20709
22780
  * Sets the mode for the Cadenza application.
@@ -20712,7 +22783,7 @@ var CadenzaService = class {
20712
22783
  * @return {void} This method does not return a value.
20713
22784
  */
20714
22785
  static setMode(mode) {
20715
- import_core5.default.setMode(mode);
22786
+ import_core6.default.setMode(mode);
20716
22787
  }
20717
22788
  static hasCompletedBootstrapSync() {
20718
22789
  return !this.serviceCreated || this.bootstrapSyncCompleted;
@@ -20755,16 +22826,16 @@ var CadenzaService = class {
20755
22826
  * ```
20756
22827
  */
20757
22828
  static emit(signal, data = {}, options = {}) {
20758
- import_core5.default.emit(signal, data, options);
22829
+ import_core6.default.emit(signal, data, options);
20759
22830
  }
20760
22831
  static debounce(signal, context = {}, delayMs = 500) {
20761
- import_core5.default.debounce(signal, context, delayMs);
22832
+ import_core6.default.debounce(signal, context, delayMs);
20762
22833
  }
20763
22834
  static schedule(signal, context, timeoutMs, exactDateTime) {
20764
- import_core5.default.schedule(signal, context, timeoutMs, exactDateTime);
22835
+ import_core6.default.schedule(signal, context, timeoutMs, exactDateTime);
20765
22836
  }
20766
22837
  static interval(signal, context, intervalMs, leading = false, startDateTime) {
20767
- import_core5.default.interval(signal, context, intervalMs, leading, startDateTime);
22838
+ import_core6.default.interval(signal, context, intervalMs, leading, startDateTime);
20768
22839
  }
20769
22840
  static defineIntent(intent) {
20770
22841
  this.inquiryBroker?.addIntent(intent);
@@ -20772,35 +22843,35 @@ var CadenzaService = class {
20772
22843
  }
20773
22844
  static getRuntimeValidationPolicy() {
20774
22845
  this.bootstrap();
20775
- return import_core5.default.getRuntimeValidationPolicy();
22846
+ return import_core6.default.getRuntimeValidationPolicy();
20776
22847
  }
20777
22848
  static setRuntimeValidationPolicy(policy = {}) {
20778
22849
  this.bootstrap();
20779
- return import_core5.default.setRuntimeValidationPolicy(policy);
22850
+ return import_core6.default.setRuntimeValidationPolicy(policy);
20780
22851
  }
20781
22852
  static replaceRuntimeValidationPolicy(policy = {}) {
20782
22853
  this.bootstrap();
20783
- return import_core5.default.replaceRuntimeValidationPolicy(policy);
22854
+ return import_core6.default.replaceRuntimeValidationPolicy(policy);
20784
22855
  }
20785
22856
  static clearRuntimeValidationPolicy() {
20786
22857
  this.bootstrap();
20787
- import_core5.default.clearRuntimeValidationPolicy();
22858
+ import_core6.default.clearRuntimeValidationPolicy();
20788
22859
  }
20789
22860
  static getRuntimeValidationScopes() {
20790
22861
  this.bootstrap();
20791
- return import_core5.default.getRuntimeValidationScopes();
22862
+ return import_core6.default.getRuntimeValidationScopes();
20792
22863
  }
20793
22864
  static upsertRuntimeValidationScope(scope) {
20794
22865
  this.bootstrap();
20795
- return import_core5.default.upsertRuntimeValidationScope(scope);
22866
+ return import_core6.default.upsertRuntimeValidationScope(scope);
20796
22867
  }
20797
22868
  static removeRuntimeValidationScope(id) {
20798
22869
  this.bootstrap();
20799
- import_core5.default.removeRuntimeValidationScope(id);
22870
+ import_core6.default.removeRuntimeValidationScope(id);
20800
22871
  }
20801
22872
  static clearRuntimeValidationScopes() {
20802
22873
  this.bootstrap();
20803
- import_core5.default.clearRuntimeValidationScopes();
22874
+ import_core6.default.clearRuntimeValidationScopes();
20804
22875
  }
20805
22876
  static getInquiryResponderDescriptor(task) {
20806
22877
  return this.serviceRegistry.getInquiryResponderDescriptor(task);
@@ -21162,7 +23233,7 @@ var CadenzaService = class {
21162
23233
  });
21163
23234
  }
21164
23235
  static get(taskName) {
21165
- return import_core5.default.get(taskName);
23236
+ return import_core6.default.get(taskName);
21166
23237
  }
21167
23238
  static getLocalCadenzaDBTask(tableName, operation) {
21168
23239
  const generatedTaskName = this.buildGeneratedLocalCadenzaDBTaskName(
@@ -21173,7 +23244,7 @@ var CadenzaService = class {
21173
23244
  tableName,
21174
23245
  operation
21175
23246
  );
21176
- return import_core5.default.get(generatedTaskName) ?? import_core5.default.get(legacyTaskName);
23247
+ return import_core6.default.get(generatedTaskName) ?? import_core6.default.get(legacyTaskName);
21177
23248
  }
21178
23249
  static getLocalCadenzaDBInsertTask(tableName) {
21179
23250
  return this.getLocalCadenzaDBTask(tableName, "insert");
@@ -21182,15 +23253,15 @@ var CadenzaService = class {
21182
23253
  return this.getLocalCadenzaDBTask(tableName, "query");
21183
23254
  }
21184
23255
  static getActor(actorName) {
21185
- const cadenzaWithActors = import_core5.default;
23256
+ const cadenzaWithActors = import_core6.default;
21186
23257
  return cadenzaWithActors.getActor?.(actorName);
21187
23258
  }
21188
23259
  static getAllActors() {
21189
- const cadenzaWithActors = import_core5.default;
23260
+ const cadenzaWithActors = import_core6.default;
21190
23261
  return cadenzaWithActors.getAllActors?.() ?? [];
21191
23262
  }
21192
23263
  static getRoutine(routineName) {
21193
- return import_core5.default.getRoutine(routineName);
23264
+ return import_core6.default.getRoutine(routineName);
21194
23265
  }
21195
23266
  /**
21196
23267
  * Creates a new DeputyTask instance based on the provided routine name, service name, and options.
@@ -21802,10 +23873,28 @@ var CadenzaService = class {
21802
23873
  __isFrontend: isFrontend,
21803
23874
  __declaredTransports: declaredTransports
21804
23875
  };
23876
+ let bootstrapServiceCreationRequested = false;
21805
23877
  if (options.cadenzaDB?.connect) {
21806
- this.createEphemeralMetaTask("Create service", async (context, emit2) => {
21807
- emit2("meta.create_service_requested", initContext);
21808
- }).doOn("meta.fetch.handshake_complete");
23878
+ this.createMetaTask(
23879
+ "Create service",
23880
+ async (context, emit2) => {
23881
+ const handshakeServiceName = String(context?.serviceName ?? "").trim();
23882
+ if (handshakeServiceName !== "CadenzaDB") {
23883
+ return false;
23884
+ }
23885
+ if (bootstrapServiceCreationRequested) {
23886
+ return false;
23887
+ }
23888
+ bootstrapServiceCreationRequested = true;
23889
+ emit2("meta.create_service_requested", initContext);
23890
+ return true;
23891
+ },
23892
+ "Requests local service creation only once after the initial authority bootstrap handshake completes.",
23893
+ {
23894
+ register: false,
23895
+ isHidden: true
23896
+ }
23897
+ ).doOn("meta.fetch.handshake_complete");
21809
23898
  } else {
21810
23899
  this.emit("meta.create_service_requested", initContext);
21811
23900
  this.createMetaTask("Create signal transmission for sync", (ctx, emit2) => {
@@ -21818,10 +23907,33 @@ var CadenzaService = class {
21818
23907
  );
21819
23908
  }).doOn("meta.rest.handshake", "meta.socket.handshake");
21820
23909
  }
23910
+ let serviceSetupCompletedHandled = false;
21821
23911
  this.createMetaTask("Handle service setup completion", (ctx, emit2) => {
23912
+ if (serviceSetupCompletedHandled) {
23913
+ return false;
23914
+ }
23915
+ const insertedServiceInstanceId = String(
23916
+ ctx?.serviceInstanceId ?? ctx?.service_instance_id ?? ctx?.serviceInstance?.uuid ?? ctx?.serviceInstance?.serviceInstanceId ?? ""
23917
+ ).trim();
23918
+ const insertedServiceName = String(
23919
+ ctx?.serviceName ?? ctx?.service_name ?? ctx?.serviceInstance?.serviceName ?? ctx?.serviceInstance?.service_name ?? ""
23920
+ ).trim();
23921
+ if (!insertedServiceInstanceId && !insertedServiceName) {
23922
+ return false;
23923
+ }
23924
+ if (insertedServiceInstanceId && insertedServiceInstanceId !== serviceId) {
23925
+ return false;
23926
+ }
23927
+ if (!insertedServiceInstanceId && insertedServiceName && insertedServiceName !== serviceName) {
23928
+ return false;
23929
+ }
23930
+ serviceSetupCompletedHandled = true;
21822
23931
  if (options.cadenzaDB?.connect) {
21823
23932
  this.serviceRegistry.bootstrapFullSync(emit2, ctx, "service_setup_completed");
21824
- void this.publishServiceManifestIfNeeded("service_setup_completed");
23933
+ void this.publishServiceManifestIfNeeded(
23934
+ "service_setup_completed",
23935
+ "business_structural"
23936
+ );
21825
23937
  }
21826
23938
  if (isFrontend) {
21827
23939
  registerActorSessionPersistenceTasks();
@@ -21831,7 +23943,7 @@ var CadenzaService = class {
21831
23943
  return true;
21832
23944
  }).doOn("meta.service_registry.instance_inserted");
21833
23945
  if (!options.cadenzaDB?.connect) {
21834
- import_core5.default.schedule(
23946
+ import_core6.default.schedule(
21835
23947
  "meta.service_registry.instance_registration_requested",
21836
23948
  {
21837
23949
  data: {
@@ -21876,7 +23988,11 @@ var CadenzaService = class {
21876
23988
  );
21877
23989
  }
21878
23990
  this.serviceCreated = true;
21879
- this.requestServiceManifestPublication("service_created", true);
23991
+ this.requestServiceManifestPublication(
23992
+ "service_created",
23993
+ true,
23994
+ "routing_capability"
23995
+ );
21880
23996
  }
21881
23997
  /**
21882
23998
  * Creates a Cadenza metadata service with the specified name, description, and options.
@@ -22137,7 +24253,7 @@ var CadenzaService = class {
22137
24253
  }
22138
24254
  static createActor(spec, options = {}) {
22139
24255
  this.bootstrap();
22140
- return import_core5.default.createActor(
24256
+ return import_core6.default.createActor(
22141
24257
  spec,
22142
24258
  this.withActorSessionHydration(
22143
24259
  spec,
@@ -22147,7 +24263,7 @@ var CadenzaService = class {
22147
24263
  }
22148
24264
  static createActorFromDefinition(definition, options = {}) {
22149
24265
  this.bootstrap();
22150
- return import_core5.default.createActorFromDefinition(
24266
+ return import_core6.default.createActorFromDefinition(
22151
24267
  definition,
22152
24268
  this.withActorSessionHydration(
22153
24269
  {
@@ -22185,7 +24301,7 @@ var CadenzaService = class {
22185
24301
  ...options,
22186
24302
  hydrateDurableState: async (actorKey) => {
22187
24303
  registerActorSessionPersistenceTasks();
22188
- const response = await import_core5.default.inquire(
24304
+ const response = await import_core6.default.inquire(
22189
24305
  META_ACTOR_SESSION_STATE_HYDRATE_INTENT,
22190
24306
  {
22191
24307
  actor_name: actorName,
@@ -22288,7 +24404,7 @@ var CadenzaService = class {
22288
24404
  */
22289
24405
  static createTask(name, func, description, options = {}) {
22290
24406
  this.bootstrap();
22291
- return import_core5.default.createTask(name, func, description, options);
24407
+ return import_core6.default.createTask(name, func, description, options);
22292
24408
  }
22293
24409
  /**
22294
24410
  * Creates a meta task with the specified name, functionality, description, and options.
@@ -22304,7 +24420,7 @@ var CadenzaService = class {
22304
24420
  */
22305
24421
  static createMetaTask(name, func, description, options = {}) {
22306
24422
  this.bootstrap();
22307
- return import_core5.default.createMetaTask(name, func, description, options);
24423
+ return import_core6.default.createMetaTask(name, func, description, options);
22308
24424
  }
22309
24425
  /**
22310
24426
  * Creates a unique task by wrapping the provided task function with a uniqueness constraint.
@@ -22354,7 +24470,7 @@ var CadenzaService = class {
22354
24470
  */
22355
24471
  static createUniqueTask(name, func, description, options = {}) {
22356
24472
  this.bootstrap();
22357
- return import_core5.default.createUniqueTask(name, func, description, options);
24473
+ return import_core6.default.createUniqueTask(name, func, description, options);
22358
24474
  }
22359
24475
  /**
22360
24476
  * Creates a unique meta task with the specified name, function, description, and options.
@@ -22368,7 +24484,7 @@ var CadenzaService = class {
22368
24484
  */
22369
24485
  static createUniqueMetaTask(name, func, description, options = {}) {
22370
24486
  this.bootstrap();
22371
- return import_core5.default.createUniqueMetaTask(name, func, description, options);
24487
+ return import_core6.default.createUniqueMetaTask(name, func, description, options);
22372
24488
  }
22373
24489
  /**
22374
24490
  * Creates a throttled task with a concurrency limit of 1, ensuring that only one instance of the task can run at a time for a specific throttle tag.
@@ -22401,7 +24517,7 @@ var CadenzaService = class {
22401
24517
  */
22402
24518
  static createThrottledTask(name, func, throttledIdGetter = () => "default", description, options = {}) {
22403
24519
  this.bootstrap();
22404
- return import_core5.default.createThrottledTask(
24520
+ return import_core6.default.createThrottledTask(
22405
24521
  name,
22406
24522
  func,
22407
24523
  throttledIdGetter,
@@ -22422,7 +24538,7 @@ var CadenzaService = class {
22422
24538
  */
22423
24539
  static createThrottledMetaTask(name, func, throttledIdGetter = () => "default", description, options = {}) {
22424
24540
  this.bootstrap();
22425
- return import_core5.default.createThrottledMetaTask(
24541
+ return import_core6.default.createThrottledMetaTask(
22426
24542
  name,
22427
24543
  func,
22428
24544
  throttledIdGetter,
@@ -22465,7 +24581,7 @@ var CadenzaService = class {
22465
24581
  */
22466
24582
  static createDebounceTask(name, func, description, debounceTime = 1e3, options = {}) {
22467
24583
  this.bootstrap();
22468
- return import_core5.default.createDebounceTask(
24584
+ return import_core6.default.createDebounceTask(
22469
24585
  name,
22470
24586
  func,
22471
24587
  description,
@@ -22486,7 +24602,7 @@ var CadenzaService = class {
22486
24602
  */
22487
24603
  static createDebounceMetaTask(name, func, description, debounceTime = 1e3, options = {}) {
22488
24604
  this.bootstrap();
22489
- return import_core5.default.createDebounceMetaTask(
24605
+ return import_core6.default.createDebounceMetaTask(
22490
24606
  name,
22491
24607
  func,
22492
24608
  description,
@@ -22556,7 +24672,7 @@ var CadenzaService = class {
22556
24672
  */
22557
24673
  static createEphemeralTask(name, func, description, options = {}) {
22558
24674
  this.bootstrap();
22559
- return import_core5.default.createEphemeralTask(name, func, description, options);
24675
+ return import_core6.default.createEphemeralTask(name, func, description, options);
22560
24676
  }
22561
24677
  /**
22562
24678
  * Creates an ephemeral meta-task with the specified name, function, description, and options.
@@ -22570,7 +24686,7 @@ var CadenzaService = class {
22570
24686
  */
22571
24687
  static createEphemeralMetaTask(name, func, description, options = {}) {
22572
24688
  this.bootstrap();
22573
- return import_core5.default.createEphemeralMetaTask(name, func, description, options);
24689
+ return import_core6.default.createEphemeralMetaTask(name, func, description, options);
22574
24690
  }
22575
24691
  /**
22576
24692
  * Creates a new routine with the specified name, tasks, and an optional description.
@@ -22602,7 +24718,7 @@ var CadenzaService = class {
22602
24718
  */
22603
24719
  static createRoutine(name, tasks, description = "") {
22604
24720
  this.bootstrap();
22605
- return import_core5.default.createRoutine(name, tasks, description);
24721
+ return import_core6.default.createRoutine(name, tasks, description);
22606
24722
  }
22607
24723
  /**
22608
24724
  * Creates a meta routine with a given name, tasks, and optional description.
@@ -22617,10 +24733,10 @@ var CadenzaService = class {
22617
24733
  */
22618
24734
  static createMetaRoutine(name, tasks, description = "") {
22619
24735
  this.bootstrap();
22620
- return import_core5.default.createMetaRoutine(name, tasks, description);
24736
+ return import_core6.default.createMetaRoutine(name, tasks, description);
22621
24737
  }
22622
24738
  static reset() {
22623
- import_core5.default.reset();
24739
+ import_core6.default.reset();
22624
24740
  this.serviceRegistry?.reset();
22625
24741
  this.unregisterGracefulShutdownHandlers();
22626
24742
  this.isBootstrapped = false;
@@ -22632,6 +24748,11 @@ var CadenzaService = class {
22632
24748
  this.warnedInvalidMetaIntentResponderKeys = /* @__PURE__ */ new Set();
22633
24749
  this.hydratedInquiryResults = /* @__PURE__ */ new Map();
22634
24750
  this.frontendSyncScheduled = false;
24751
+ this.serviceManifestRevision = 0;
24752
+ this.lastPublishedServiceManifestHashes = {};
24753
+ this.serviceManifestPublicationInFlight = false;
24754
+ this.serviceManifestPublicationPendingReason = null;
24755
+ this.serviceManifestPublicationPendingLayer = null;
22635
24756
  resetBrowserRuntimeActorHandles();
22636
24757
  }
22637
24758
  };
@@ -22645,15 +24766,16 @@ CadenzaService.warnedInvalidMetaIntentResponderKeys = /* @__PURE__ */ new Set();
22645
24766
  CadenzaService.hydratedInquiryResults = /* @__PURE__ */ new Map();
22646
24767
  CadenzaService.frontendSyncScheduled = false;
22647
24768
  CadenzaService.serviceManifestRevision = 0;
22648
- CadenzaService.lastPublishedServiceManifestHash = null;
24769
+ CadenzaService.lastPublishedServiceManifestHashes = {};
22649
24770
  CadenzaService.serviceManifestPublicationInFlight = false;
22650
24771
  CadenzaService.serviceManifestPublicationPendingReason = null;
24772
+ CadenzaService.serviceManifestPublicationPendingLayer = null;
22651
24773
  CadenzaService.shutdownHandlersRegistered = false;
22652
24774
  CadenzaService.shutdownInFlight = false;
22653
24775
  CadenzaService.shutdownHandlerCleanup = [];
22654
24776
 
22655
24777
  // src/index.ts
22656
- var import_core6 = require("@cadenza.io/core");
24778
+ var import_core7 = require("@cadenza.io/core");
22657
24779
 
22658
24780
  // src/ssr/createSSRInquiryBridge.ts
22659
24781
  var import_uuid9 = require("uuid");
@@ -22675,6 +24797,17 @@ function normalizeArrayResponse(value, keys) {
22675
24797
  if (Array.isArray(value?.data)) {
22676
24798
  return value.data;
22677
24799
  }
24800
+ const joinedContexts = Array.isArray(value?.joinedContexts) ? value.joinedContexts : [];
24801
+ for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
24802
+ const nested = joinedContexts[index];
24803
+ if (!nested || typeof nested !== "object") {
24804
+ continue;
24805
+ }
24806
+ const rows = normalizeArrayResponse(nested, keys);
24807
+ if (rows.length > 0) {
24808
+ return rows;
24809
+ }
24810
+ }
22678
24811
  return [];
22679
24812
  }
22680
24813
  function buildQueryResponseKeys(tableName) {