@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.mjs CHANGED
@@ -21,6 +21,30 @@ var LOCAL_ROUTINE_PERSISTENCE_KEYS = [
21
21
  "__routineCreatedAt",
22
22
  "__routineIsMeta"
23
23
  ];
24
+ var BULKY_EXECUTION_PERSISTENCE_KEYS = [
25
+ "rows",
26
+ "joinedContexts",
27
+ "serviceInstances",
28
+ "serviceInstanceLeases",
29
+ "serviceInstanceTransports",
30
+ "serviceManifests",
31
+ "tasks",
32
+ "helpers",
33
+ "globals",
34
+ "signals",
35
+ "intents",
36
+ "actors",
37
+ "routines",
38
+ "directionalTaskMaps",
39
+ "actorTaskMaps",
40
+ "taskToRoutineMaps",
41
+ "taskToHelperMaps",
42
+ "helperToHelperMaps",
43
+ "taskToGlobalMaps",
44
+ "helperToGlobalMaps",
45
+ "signalToTaskMaps",
46
+ "intentToTaskMaps"
47
+ ];
24
48
  function readHintValue(source, key) {
25
49
  if (!source || typeof source !== "object") {
26
50
  return void 0;
@@ -47,8 +71,80 @@ function stripLocalRoutinePersistenceHints(input) {
47
71
  }
48
72
  return context;
49
73
  }
74
+ function summarizeQueryData(queryData) {
75
+ if (!queryData || typeof queryData !== "object") {
76
+ return void 0;
77
+ }
78
+ const summary = {};
79
+ if (queryData.data && typeof queryData.data === "object") {
80
+ summary.dataKeys = Object.keys(queryData.data).sort();
81
+ }
82
+ if (queryData.filter && typeof queryData.filter === "object") {
83
+ summary.filterKeys = Object.keys(queryData.filter).sort();
84
+ }
85
+ if (queryData.onConflict && typeof queryData.onConflict === "object") {
86
+ const onConflict = queryData.onConflict;
87
+ summary.onConflictTarget = Array.isArray(onConflict.target) ? [...onConflict.target] : onConflict.target ?? null;
88
+ }
89
+ return Object.keys(summary).length > 0 ? summary : void 0;
90
+ }
91
+ function sanitizeExecutionPersistenceContext(input) {
92
+ const context = stripLocalRoutinePersistenceHints(input);
93
+ for (const key of BULKY_EXECUTION_PERSISTENCE_KEYS) {
94
+ const value = context[key];
95
+ if (value === void 0) {
96
+ continue;
97
+ }
98
+ const countKey = `${key}Count`;
99
+ if (context[countKey] === void 0) {
100
+ if (Array.isArray(value)) {
101
+ context[countKey] = value.length;
102
+ } else if (value && typeof value === "object") {
103
+ context[countKey] = Object.keys(value).length;
104
+ }
105
+ }
106
+ delete context[key];
107
+ }
108
+ if (context.queryData && typeof context.queryData === "object") {
109
+ const queryDataSummary = summarizeQueryData(context.queryData);
110
+ if (queryDataSummary) {
111
+ context.queryData = queryDataSummary;
112
+ } else {
113
+ delete context.queryData;
114
+ }
115
+ }
116
+ return context;
117
+ }
118
+ function sanitizeExecutionPersistenceResultPayload(input) {
119
+ const payload = input && typeof input === "object" ? { ...input } : {};
120
+ const resultContext = payload.resultContext && typeof payload.resultContext === "object" ? sanitizeExecutionPersistenceContext(
121
+ payload.resultContext
122
+ ) : payload.resultContext;
123
+ const metaResultContext = payload.metaResultContext && typeof payload.metaResultContext === "object" ? sanitizeExecutionPersistenceContext(
124
+ payload.metaResultContext
125
+ ) : payload.metaResultContext;
126
+ const snakeResultContext = payload.result_context && typeof payload.result_context === "object" ? sanitizeExecutionPersistenceContext(
127
+ payload.result_context
128
+ ) : payload.result_context;
129
+ const snakeMetaResultContext = payload.meta_result_context && typeof payload.meta_result_context === "object" ? sanitizeExecutionPersistenceContext(
130
+ payload.meta_result_context
131
+ ) : payload.meta_result_context;
132
+ if (resultContext !== void 0) {
133
+ payload.resultContext = resultContext;
134
+ }
135
+ if (metaResultContext !== void 0) {
136
+ payload.metaResultContext = metaResultContext;
137
+ }
138
+ if (snakeResultContext !== void 0) {
139
+ payload.result_context = snakeResultContext;
140
+ }
141
+ if (snakeMetaResultContext !== void 0) {
142
+ payload.meta_result_context = snakeMetaResultContext;
143
+ }
144
+ return payload;
145
+ }
50
146
  function splitRoutinePersistenceContext(input) {
51
- const sanitized = stripLocalRoutinePersistenceHints(input);
147
+ const sanitized = sanitizeExecutionPersistenceContext(input);
52
148
  return {
53
149
  context: Object.fromEntries(
54
150
  Object.entries(sanitized).filter(([key]) => !key.startsWith("__"))
@@ -79,14 +175,55 @@ var ROOT_METADATA_PASSTHROUGH_KEYS = [
79
175
  "__inquirySourceRoutineExecutionId"
80
176
  ];
81
177
  var DELEGATION_REQUEST_SNAPSHOT_KEY = "__delegationRequestContext";
178
+ var DELEGATION_FAILURE_CONTEXT_KEYS = [
179
+ "__remoteRoutineName",
180
+ "__serviceName",
181
+ "__timeout",
182
+ "__localTaskName",
183
+ "__localTaskVersion",
184
+ "__localServiceName",
185
+ "__localRoutineExecId",
186
+ "__previousTaskExecutionId",
187
+ "__fetchId",
188
+ "fetchId",
189
+ "__routeKey",
190
+ "routeKey",
191
+ "__instance",
192
+ "__transportId",
193
+ "__transportOrigin",
194
+ "__transportProtocols",
195
+ "__transportProtocol",
196
+ "__retries",
197
+ "__triedInstances",
198
+ "__delegationRequestContext",
199
+ "__metadata",
200
+ "serviceName",
201
+ "serviceInstanceId",
202
+ "serviceTransportId",
203
+ "serviceOrigin",
204
+ "transportProtocols",
205
+ "transportProtocol"
206
+ ];
207
+ function isPlainObject(value) {
208
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
209
+ return false;
210
+ }
211
+ const prototype = Object.getPrototypeOf(value);
212
+ return prototype === Object.prototype || prototype === null;
213
+ }
82
214
  function cloneDelegationValue(value) {
215
+ if (value instanceof Date) {
216
+ return new Date(value.getTime());
217
+ }
83
218
  if (Array.isArray(value)) {
84
- return value.map(
85
- (item) => item && typeof item === "object" ? { ...item } : item
86
- );
219
+ return value.map((item) => cloneDelegationValue(item));
87
220
  }
88
- if (value && typeof value === "object") {
89
- return { ...value };
221
+ if (isPlainObject(value)) {
222
+ const clone = {};
223
+ for (const [key, nestedValue] of Object.entries(value)) {
224
+ clone[key] = cloneDelegationValue(nestedValue);
225
+ }
226
+ return clone;
90
227
  }
91
228
  return value;
92
229
  }
@@ -122,9 +259,9 @@ function attachDelegationRequestSnapshot(input) {
122
259
  function restoreDelegationRequestSnapshot(input) {
123
260
  const context = input && typeof input === "object" ? { ...input } : {};
124
261
  const mutableContext = context;
125
- const snapshotCandidate = mutableContext[DELEGATION_REQUEST_SNAPSHOT_KEY];
262
+ const snapshotCandidate = mutableContext[DELEGATION_REQUEST_SNAPSHOT_KEY] ?? (mutableContext.__metadata && typeof mutableContext.__metadata === "object" ? mutableContext.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY] : void 0);
126
263
  const snapshot = snapshotCandidate && typeof snapshotCandidate === "object" ? snapshotCandidate : null;
127
- const looksLikeDelegationResult = mutableContext.__status !== void 0 || mutableContext.__success !== void 0 || mutableContext.rowCount !== void 0 || mutableContext.__nextNodes !== void 0 || mutableContext.__isDeputy === true;
264
+ 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;
128
265
  if (!snapshot || !looksLikeDelegationResult) {
129
266
  return context;
130
267
  }
@@ -145,6 +282,26 @@ function stripDelegationRequestSnapshot(input) {
145
282
  delete context[DELEGATION_REQUEST_SNAPSHOT_KEY];
146
283
  return context;
147
284
  }
285
+ function buildDelegationFailureContext(signalName, input, error) {
286
+ const source = input && typeof input === "object" ? { ...input } : {};
287
+ const slimContext = {};
288
+ for (const key of DELEGATION_FAILURE_CONTEXT_KEYS) {
289
+ if (source[key] !== void 0) {
290
+ slimContext[key] = cloneDelegationValue(source[key]);
291
+ }
292
+ }
293
+ if (slimContext[DELEGATION_REQUEST_SNAPSHOT_KEY] === void 0 && source.__metadata && typeof source.__metadata === "object" && source.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY] !== void 0) {
294
+ slimContext[DELEGATION_REQUEST_SNAPSHOT_KEY] = cloneDelegationValue(
295
+ source.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY]
296
+ );
297
+ }
298
+ return {
299
+ __signalName: signalName,
300
+ __error: error instanceof Error ? error.message : String(error ?? "Unknown error"),
301
+ errored: true,
302
+ ...slimContext
303
+ };
304
+ }
148
305
  function stripTransportSelectionRoutingContext(input) {
149
306
  const context = stripLocalRoutinePersistenceHints(
150
307
  input && typeof input === "object" ? { ...input } : {}
@@ -176,6 +333,90 @@ function ensureDelegationContextMetadata(input) {
176
333
 
177
334
  // src/graph/definition/DeputyTask.ts
178
335
  var SERVICE_REGISTRY_TRACE_SERVICE = (process.env.CADENZA_SERVICE_REGISTRY_TRACE_SERVICE ?? "").trim();
336
+ function deputyTaskExecutor(context, emit2, inquire, _tools, progressCallback) {
337
+ const task = this;
338
+ return new Promise((resolve, reject) => {
339
+ if (context.__metadata.__blockRemoteExecution) {
340
+ reject(new Error("Blocked remote execution"));
341
+ return;
342
+ }
343
+ if (context.__metadata.__skipRemoteExecution) {
344
+ resolve(context);
345
+ return;
346
+ }
347
+ const processId = uuid2();
348
+ context.__metadata.__deputyExecId = processId;
349
+ if ((process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") && context.__remoteRoutineName === "Insert service_instance") {
350
+ console.log("[CADENZA_INSTANCE_DEBUG] deputy_delegation_requested", {
351
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
352
+ localTaskName: context.__localTaskName ?? null,
353
+ remoteRoutineName: context.__remoteRoutineName ?? null,
354
+ targetServiceName: context.__serviceName ?? null,
355
+ deputyExecId: processId,
356
+ dataKeys: context.data && typeof context.data === "object" ? Object.keys(context.data) : [],
357
+ queryDataKeys: context.queryData && typeof context.queryData === "object" ? Object.keys(context.queryData) : [],
358
+ queryDataDataKeys: context.queryData?.data && typeof context.queryData.data === "object" ? Object.keys(context.queryData.data) : []
359
+ });
360
+ }
361
+ emit2("meta.deputy.delegation_requested", {
362
+ ...context
363
+ });
364
+ CadenzaService.createEphemeralMetaTask(
365
+ `On progress deputy ${task.remoteRoutineName}`,
366
+ (ctx) => {
367
+ if (typeof progressCallback === "function" && ctx.progress) {
368
+ progressCallback(ctx.progress * ctx.weight);
369
+ }
370
+ },
371
+ `Ephemeral task for deputy process ${processId}`,
372
+ {
373
+ once: false,
374
+ destroyCondition: (ctx) => ctx.progress === 1 || ctx.progress === void 0,
375
+ register: false
376
+ }
377
+ ).doOn(
378
+ `meta.socket_client.delegation_progress:${processId}`,
379
+ `meta.socket_client.delegated:${processId}`,
380
+ `meta.fetch.delegated:${processId}`,
381
+ `meta.service_registry.load_balance_failed:${processId}`
382
+ );
383
+ CadenzaService.createEphemeralMetaTask(
384
+ `Resolve deputy ${task.remoteRoutineName}`,
385
+ (responseCtx) => {
386
+ const mergedResponseCtx = responseCtx && typeof responseCtx === "object" ? {
387
+ ...context,
388
+ ...responseCtx
389
+ } : responseCtx;
390
+ if (responseCtx?.errored) {
391
+ reject(new Error(responseCtx.__error));
392
+ } else {
393
+ if (SERVICE_REGISTRY_TRACE_SERVICE.length > 0 && CadenzaService.serviceRegistry.serviceName === SERVICE_REGISTRY_TRACE_SERVICE && context.__remoteRoutineName === "Insert service_instance") {
394
+ console.log(
395
+ "[CADENZA_SERVICE_REGISTRY_TRACE] deputy_insert_service_instance_resolved",
396
+ {
397
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
398
+ targetServiceName: context.__serviceName ?? null,
399
+ resolverRequestId: context.__resolverRequestId ?? null,
400
+ serviceInstanceId: mergedResponseCtx && typeof mergedResponseCtx === "object" ? mergedResponseCtx.__serviceInstanceId ?? mergedResponseCtx.uuid ?? mergedResponseCtx.data?.uuid ?? null : null,
401
+ hasResolverQueryData: mergedResponseCtx && typeof mergedResponseCtx === "object" && mergedResponseCtx.__resolverQueryData !== void 0
402
+ }
403
+ );
404
+ }
405
+ if (mergedResponseCtx && typeof mergedResponseCtx === "object") {
406
+ delete mergedResponseCtx.__isDeputy;
407
+ }
408
+ resolve(mergedResponseCtx);
409
+ }
410
+ },
411
+ `Ephemeral resolver for deputy process ${processId}`,
412
+ { register: false }
413
+ ).doOn(
414
+ `meta.socket_client.delegated:${processId}`,
415
+ `meta.fetch.delegated:${processId}`,
416
+ `meta.service_registry.load_balance_failed:${processId}`
417
+ );
418
+ });
419
+ }
179
420
  var DeputyTask = class extends Task {
180
421
  /**
181
422
  * Constructs a new instance of the class with the specified parameters.
@@ -203,87 +444,9 @@ var DeputyTask = class extends Task {
203
444
  * @return {void} This constructor does not return a value.
204
445
  */
205
446
  constructor(name, remoteRoutineName, serviceName = void 0, description = "", concurrency = 0, timeout = 0, register = true, isUnique = false, isMeta = false, isSubMeta = false, isHidden = false, getTagCallback = void 0, inputSchema = void 0, validateInputContext = false, outputSchema = void 0, validateOutputContext = false, retryCount = 0, retryDelay = 0, retryDelayMax = 0, retryDelayFactor = 1) {
206
- const taskFunction = (context, emit2, inquire, progressCallback) => {
207
- return new Promise((resolve, reject) => {
208
- if (context.__metadata.__blockRemoteExecution) {
209
- reject(new Error("Blocked remote execution"));
210
- return;
211
- }
212
- if (context.__metadata.__skipRemoteExecution) {
213
- resolve(context);
214
- return;
215
- }
216
- const processId = uuid2();
217
- context.__metadata.__deputyExecId = processId;
218
- if ((process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") && context.__remoteRoutineName === "Insert service_instance") {
219
- console.log("[CADENZA_INSTANCE_DEBUG] deputy_delegation_requested", {
220
- localServiceName: CadenzaService.serviceRegistry.serviceName,
221
- localTaskName: context.__localTaskName ?? null,
222
- remoteRoutineName: context.__remoteRoutineName ?? null,
223
- targetServiceName: context.__serviceName ?? null,
224
- deputyExecId: processId,
225
- dataKeys: context.data && typeof context.data === "object" ? Object.keys(context.data) : [],
226
- queryDataKeys: context.queryData && typeof context.queryData === "object" ? Object.keys(context.queryData) : [],
227
- queryDataDataKeys: context.queryData?.data && typeof context.queryData.data === "object" ? Object.keys(context.queryData.data) : []
228
- });
229
- }
230
- emit2("meta.deputy.delegation_requested", {
231
- ...context
232
- });
233
- CadenzaService.createEphemeralMetaTask(
234
- `On progress deputy ${this.remoteRoutineName}`,
235
- (ctx) => {
236
- if (ctx.progress) progressCallback(ctx.progress * ctx.weight);
237
- },
238
- `Ephemeral task for deputy process ${processId}`,
239
- {
240
- once: false,
241
- destroyCondition: (ctx) => ctx.progress === 1 || ctx.progress === void 0,
242
- register: false
243
- }
244
- ).doOn(
245
- `meta.socket_client.delegation_progress:${processId}`,
246
- `meta.socket_client.delegated:${processId}`,
247
- `meta.fetch.delegated:${processId}`,
248
- `meta.service_registry.load_balance_failed:${processId}`
249
- );
250
- CadenzaService.createEphemeralMetaTask(
251
- `Resolve deputy ${this.remoteRoutineName}`,
252
- (responseCtx) => {
253
- const mergedResponseCtx = responseCtx && typeof responseCtx === "object" ? {
254
- ...context,
255
- ...responseCtx
256
- } : responseCtx;
257
- if (responseCtx?.errored) {
258
- reject(new Error(responseCtx.__error));
259
- } else {
260
- if (SERVICE_REGISTRY_TRACE_SERVICE.length > 0 && CadenzaService.serviceRegistry.serviceName === SERVICE_REGISTRY_TRACE_SERVICE && context.__remoteRoutineName === "Insert service_instance") {
261
- console.log("[CADENZA_SERVICE_REGISTRY_TRACE] deputy_insert_service_instance_resolved", {
262
- localServiceName: CadenzaService.serviceRegistry.serviceName,
263
- targetServiceName: context.__serviceName ?? null,
264
- resolverRequestId: context.__resolverRequestId ?? null,
265
- serviceInstanceId: mergedResponseCtx && typeof mergedResponseCtx === "object" ? mergedResponseCtx.__serviceInstanceId ?? mergedResponseCtx.uuid ?? mergedResponseCtx.data?.uuid ?? null : null,
266
- hasResolverQueryData: mergedResponseCtx && typeof mergedResponseCtx === "object" && mergedResponseCtx.__resolverQueryData !== void 0
267
- });
268
- }
269
- if (mergedResponseCtx && typeof mergedResponseCtx === "object") {
270
- delete mergedResponseCtx.__isDeputy;
271
- }
272
- resolve(mergedResponseCtx);
273
- }
274
- },
275
- `Ephemeral resolver for deputy process ${processId}`,
276
- { register: false }
277
- ).doOn(
278
- `meta.socket_client.delegated:${processId}`,
279
- `meta.fetch.delegated:${processId}`,
280
- `meta.service_registry.load_balance_failed:${processId}`
281
- );
282
- });
283
- };
284
447
  super(
285
448
  name,
286
- taskFunction,
449
+ deputyTaskExecutor,
287
450
  description,
288
451
  concurrency,
289
452
  timeout,
@@ -315,6 +478,11 @@ var DeputyTask = class extends Task {
315
478
  communicationType: "delegation"
316
479
  });
317
480
  }
481
+ clone() {
482
+ throw new Error(
483
+ `DeputyTask '${this.name}' does not support clone(). Create a new named deputy task or use a flow-specific meta task that performs an inquiry instead.`
484
+ );
485
+ }
318
486
  /**
319
487
  * Executes the specified task function within the provided execution context.
320
488
  *
@@ -358,12 +526,32 @@ var DeputyTask = class extends Task {
358
526
  })
359
527
  )
360
528
  );
361
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
529
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
530
+ this,
531
+ deputyContext,
532
+ emit2,
533
+ inquire,
534
+ progressCallback
535
+ ) : {
536
+ helpers: {},
537
+ globals: {}
538
+ };
539
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
540
+ };
541
+ return this.taskFunction(
542
+ deputyContext,
543
+ emit2,
544
+ inquire,
545
+ resolvedTools,
546
+ resolvedProgressCallback
547
+ );
362
548
  }
363
549
  };
364
550
 
365
551
  // src/graph/definition/DatabaseTask.ts
366
552
  var ACTOR_SESSION_TRACE_ENABLED = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
553
+ var actorSessionEmptyDelegationLogCount = 0;
554
+ var ACTOR_SESSION_EMPTY_DELEGATION_LOG_LIMIT = 40;
367
555
  var INSTANCE_TRACE_ENABLED = process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true";
368
556
  var EXECUTION_OBSERVABILITY_INSERT_ROUTINES = /* @__PURE__ */ new Set([
369
557
  "Insert execution_trace",
@@ -425,6 +613,11 @@ var DatabaseTask = class extends DeputyTask {
425
613
  );
426
614
  this.queryData = queryData;
427
615
  }
616
+ clone() {
617
+ throw new Error(
618
+ `DatabaseTask '${this.name}' does not support clone(). Create a new named database task or use a flow-specific meta task that performs the default database inquiry instead.`
619
+ );
620
+ }
428
621
  /**
429
622
  * Executes the specified task within the given context.
430
623
  *
@@ -465,15 +658,16 @@ var DatabaseTask = class extends DeputyTask {
465
658
  }
466
659
  delete ctx.__metadata;
467
660
  const isResolverExecution = typeof ctx.__resolverRequestId === "string" && ctx.__resolverRequestId.length > 0;
468
- const dynamicQueryData = isResolverExecution ? {} : ctx.__resolverQueryData && typeof ctx.__resolverQueryData === "object" ? ctx.__resolverQueryData : ctx.queryData ?? {};
661
+ const resolverQueryData = ctx.__resolverQueryData && typeof ctx.__resolverQueryData === "object" ? ctx.__resolverQueryData : null;
662
+ const dynamicQueryData = resolverQueryData ?? (ctx.queryData && typeof ctx.queryData === "object" ? ctx.queryData : {});
469
663
  delete ctx.queryData;
470
664
  const nextQueryData = {
471
665
  ...this.queryData,
472
- data: {
473
- ...ctx.data
474
- },
475
666
  ...dynamicQueryData
476
667
  };
668
+ if (dynamicQueryData.data === void 0 && ctx.data !== void 0) {
669
+ nextQueryData.data = ctx.data && typeof ctx.data === "object" && !Array.isArray(ctx.data) ? { ...ctx.data } : ctx.data;
670
+ }
477
671
  const deputyContext = attachDelegationRequestSnapshot(
478
672
  stripDelegationRequestSnapshot(
479
673
  hoistDelegationMetadataFields({
@@ -533,7 +727,41 @@ var DatabaseTask = class extends DeputyTask {
533
727
  rootKeys: Object.keys(rawContext)
534
728
  });
535
729
  }
536
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
730
+ if (this.remoteRoutineName === "Insert actor_session_state" && deputyContext.data === void 0 && deputyContext.queryData === void 0 && actorSessionEmptyDelegationLogCount < ACTOR_SESSION_EMPTY_DELEGATION_LOG_LIMIT) {
731
+ actorSessionEmptyDelegationLogCount += 1;
732
+ console.warn("[CADENZA_ACTOR_SESSION_EMPTY_DELEGATION]", {
733
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
734
+ localTaskName: this.name,
735
+ remoteRoutineName: this.remoteRoutineName,
736
+ hadSnapshotBeforeRestore: initialFullContext.__delegationRequestContext !== void 0 || initialFullContext.__metadata?.__delegationRequestContext !== void 0,
737
+ restoredRootKeys: Object.keys(rawContext),
738
+ deputyRootKeys: Object.keys(deputyContext),
739
+ signalName: rawContext.__signalName ?? rawContext.__metadata?.__signalName ?? null,
740
+ inquiryName: rawContext.__inquiryName ?? rawContext.__metadata?.__inquiryName ?? null,
741
+ sourceServiceName: rawContext.__localServiceName ?? rawContext.__metadata?.__localServiceName ?? null,
742
+ sourceRoutineName: rawContext.__routineName ?? rawContext.__metadata?.__routineName ?? null,
743
+ sourceTaskName: rawContext.__localTaskName ?? rawContext.__metadata?.__localTaskName ?? null
744
+ });
745
+ }
746
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
747
+ this,
748
+ deputyContext,
749
+ emit2,
750
+ inquire,
751
+ progressCallback
752
+ ) : {
753
+ helpers: {},
754
+ globals: {}
755
+ };
756
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
757
+ };
758
+ return this.taskFunction(
759
+ deputyContext,
760
+ emit2,
761
+ inquire,
762
+ resolvedTools,
763
+ resolvedProgressCallback
764
+ );
537
765
  }
538
766
  };
539
767
 
@@ -578,6 +806,26 @@ var AUTHORITY_SYNC_DEBUG_TASK_NAMES = /* @__PURE__ */ new Set([
578
806
  ]);
579
807
  var AUTHORITY_SYNC_DEBUG_ROUTINE_NAMES = /* @__PURE__ */ new Set(["Sync services"]);
580
808
  var INTENT_MAP_DEBUG_ENABLED = process.env.CADENZA_INTENT_MAP_DEBUG === "1" || process.env.CADENZA_INTENT_MAP_DEBUG === "true";
809
+ function normalizeQueryResultValue(value) {
810
+ if (value instanceof Date) {
811
+ return value.toISOString();
812
+ }
813
+ if (Array.isArray(value)) {
814
+ return value.map((entry) => normalizeQueryResultValue(entry));
815
+ }
816
+ if (value && typeof value === "object") {
817
+ const prototype = Object.getPrototypeOf(value);
818
+ if (prototype === Object.prototype || prototype === null) {
819
+ return Object.fromEntries(
820
+ Object.entries(value).map(([key, nestedValue]) => [
821
+ key,
822
+ normalizeQueryResultValue(nestedValue)
823
+ ])
824
+ );
825
+ }
826
+ }
827
+ return value;
828
+ }
581
829
  var POSTGRES_SETUP_DEBUG_ENABLED = process.env.CADENZA_POSTGRES_SETUP_DEBUG === "1" || process.env.CADENZA_POSTGRES_SETUP_DEBUG === "true";
582
830
  var ACTOR_SESSION_TRACE_ENABLED2 = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
583
831
  var ACTOR_SESSION_TRACE_LIMIT = 20;
@@ -875,14 +1123,14 @@ function errorMessage(error) {
875
1123
  }
876
1124
  return String(error);
877
1125
  }
878
- function isPlainObject(value) {
1126
+ function isPlainObject2(value) {
879
1127
  return typeof value === "object" && value !== null && !Array.isArray(value);
880
1128
  }
881
1129
  function stableStringify(value) {
882
1130
  if (Array.isArray(value)) {
883
1131
  return `[${value.map((item) => stableStringify(item)).join(",")}]`;
884
1132
  }
885
- if (isPlainObject(value)) {
1133
+ if (isPlainObject2(value)) {
886
1134
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
887
1135
  }
888
1136
  return JSON.stringify(value);
@@ -998,7 +1246,23 @@ function resolveGeneratedTaskTag(tableName, actorToken, context, operation) {
998
1246
  if (operation === "insert") {
999
1247
  return `insert:${actorToken}:${tableName}`;
1000
1248
  }
1001
- return context?.__metadata?.__executionTraceId ?? context?.__executionTraceId ?? "default";
1249
+ 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;
1250
+ if (typeof traceScopedTag === "string" && traceScopedTag.length > 0) {
1251
+ return traceScopedTag;
1252
+ }
1253
+ const queryScope = {
1254
+ queryData: context?.queryData,
1255
+ filter: context?.filter,
1256
+ fields: context?.fields,
1257
+ joins: context?.joins,
1258
+ sort: context?.sort,
1259
+ limit: context?.limit,
1260
+ offset: context?.offset,
1261
+ queryMode: context?.queryMode,
1262
+ aggregates: context?.aggregates,
1263
+ groupBy: context?.groupBy
1264
+ };
1265
+ return `read:${actorToken}:${tableName}:${stableStringify(queryScope)}`;
1002
1266
  }
1003
1267
  function resolveExecutionObservabilitySafetyPolicyForTable(basePolicy, tableName) {
1004
1268
  if (!EXECUTION_OBSERVABILITY_TABLES.has(tableName)) {
@@ -1080,6 +1344,44 @@ function mergeTriggerQueryData(context, triggerQueryData) {
1080
1344
  ...triggerQueryData
1081
1345
  };
1082
1346
  }
1347
+ function isNonEmptyPlainObject(value) {
1348
+ return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0;
1349
+ }
1350
+ function isMissingInsertData(data) {
1351
+ return !data || Array.isArray(data) && data.length === 0 || typeof data === "object" && !Array.isArray(data) && Object.keys(data).length === 0;
1352
+ }
1353
+ function resolveActorSessionDelegationSnapshot(context) {
1354
+ const direct = context.__delegationRequestContext && typeof context.__delegationRequestContext === "object" ? context.__delegationRequestContext : null;
1355
+ if (direct) {
1356
+ return direct;
1357
+ }
1358
+ const metadata = context.__metadata && typeof context.__metadata === "object" ? context.__metadata : null;
1359
+ const nested = metadata?.__delegationRequestContext && typeof metadata.__delegationRequestContext === "object" ? metadata.__delegationRequestContext : null;
1360
+ return nested;
1361
+ }
1362
+ function recoverActorSessionInsertPayload(context, payload) {
1363
+ if (!isMissingInsertData(payload.data)) {
1364
+ return payload;
1365
+ }
1366
+ const snapshot = resolveActorSessionDelegationSnapshot(context);
1367
+ if (!snapshot) {
1368
+ return payload;
1369
+ }
1370
+ const snapshotQueryData = snapshot.queryData && typeof snapshot.queryData === "object" ? { ...snapshot.queryData } : {};
1371
+ const snapshotData = isNonEmptyPlainObject(snapshotQueryData.data) ? snapshotQueryData.data : isNonEmptyPlainObject(snapshot.data) ? snapshot.data : null;
1372
+ if (!snapshotData) {
1373
+ return payload;
1374
+ }
1375
+ const recoveredPayload = {
1376
+ ...snapshotQueryData,
1377
+ ...payload,
1378
+ data: snapshotData
1379
+ };
1380
+ if (recoveredPayload.onConflict === void 0 && snapshotQueryData.onConflict) {
1381
+ recoveredPayload.onConflict = snapshotQueryData.onConflict;
1382
+ }
1383
+ return recoveredPayload;
1384
+ }
1083
1385
  function resolveOperationPayload(context) {
1084
1386
  const queryData = typeof context.queryData === "object" && context.queryData ? context.queryData : {};
1085
1387
  return mergeTriggerQueryData(context, queryData);
@@ -1807,6 +2109,23 @@ var DatabaseController = class _DatabaseController {
1807
2109
  async insertFunction(registration, tableName, context) {
1808
2110
  const { data, transaction = true, fields = [], onConflict } = context;
1809
2111
  if (!data || Array.isArray(data) && data.length === 0) {
2112
+ if (tableName === "actor_session_state") {
2113
+ const rawContext = context;
2114
+ const rawMetadata = rawContext.__metadata && typeof rawContext.__metadata === "object" ? rawContext.__metadata : void 0;
2115
+ console.warn("[CADENZA_ACTOR_SESSION_EMPTY_INSERT]", {
2116
+ tableName,
2117
+ contextKeys: Object.keys(context ?? {}),
2118
+ queryDataKeys: [],
2119
+ hasDelegationSnapshot: rawContext.__delegationRequestContext !== void 0 || rawMetadata?.__delegationRequestContext !== void 0,
2120
+ localTaskName: typeof rawContext.__localTaskName === "string" ? rawContext.__localTaskName : void 0,
2121
+ remoteRoutineName: typeof rawContext.__remoteRoutineName === "string" ? rawContext.__remoteRoutineName : void 0,
2122
+ serviceName: typeof rawContext.__serviceName === "string" ? rawContext.__serviceName : void 0,
2123
+ actorName: typeof rawContext.actor_name === "string" ? rawContext.actor_name : void 0,
2124
+ actorKey: typeof rawContext.actor_key === "string" ? rawContext.actor_key : void 0,
2125
+ durableVersion: rawContext.durable_version,
2126
+ metadata: rawMetadata
2127
+ });
2128
+ }
1810
2129
  return {
1811
2130
  rowCount: 0,
1812
2131
  errored: true,
@@ -2876,9 +3195,18 @@ var DatabaseController = class _DatabaseController {
2876
3195
  }
2877
3196
  }
2878
3197
  }
2879
- const operationPayload = resolveOperationPayload(context);
3198
+ const initialOperationPayload = resolveOperationPayload(context);
3199
+ let operationPayload = initialOperationPayload;
3200
+ if (tableName === "actor_session_state" && op === "insert") {
3201
+ operationPayload = recoverActorSessionInsertPayload(
3202
+ context,
3203
+ operationPayload
3204
+ );
3205
+ }
2880
3206
  const actorSessionInsertData = operationPayload.data;
2881
- const actorSessionInsertMissingData = !actorSessionInsertData || Array.isArray(actorSessionInsertData) && actorSessionInsertData.length === 0 || typeof actorSessionInsertData === "object" && !Array.isArray(actorSessionInsertData) && Object.keys(actorSessionInsertData).length === 0;
3207
+ const actorSessionInsertMissingData = isMissingInsertData(
3208
+ actorSessionInsertData
3209
+ );
2882
3210
  if (tableName === "actor_session_state" && op === "insert" && actorSessionInsertMissingData) {
2883
3211
  logActorSessionTrace("empty_insert_payload", {
2884
3212
  taskName,
@@ -2894,7 +3222,10 @@ var DatabaseController = class _DatabaseController {
2894
3222
  payloadDataType: actorSessionInsertData === null ? "null" : Array.isArray(actorSessionInsertData) ? "array" : typeof actorSessionInsertData,
2895
3223
  payloadDataKeys: actorSessionInsertData && typeof actorSessionInsertData === "object" && !Array.isArray(actorSessionInsertData) ? Object.keys(actorSessionInsertData) : [],
2896
3224
  queryDataKeys: context.queryData && typeof context.queryData === "object" && !Array.isArray(context.queryData) ? Object.keys(context.queryData) : [],
2897
- rootKeys: Object.keys(context ?? {}).slice(0, 24)
3225
+ rootKeys: Object.keys(context ?? {}).slice(0, 24),
3226
+ initialPayloadMissingData: isMissingInsertData(
3227
+ initialOperationPayload.data
3228
+ )
2898
3229
  });
2899
3230
  }
2900
3231
  const shouldDebugAuthoritySync = shouldDebugAuthoritySyncPayload(
@@ -3189,7 +3520,7 @@ var DatabaseController = class _DatabaseController {
3189
3520
  return rows.map((row) => {
3190
3521
  const camelCasedRow = {};
3191
3522
  for (const [key, value] of Object.entries(row)) {
3192
- camelCasedRow[camelCase(key)] = value;
3523
+ camelCasedRow[camelCase(key)] = normalizeQueryResultValue(value);
3193
3524
  }
3194
3525
  return camelCasedRow;
3195
3526
  });
@@ -3624,14 +3955,14 @@ var META_INTENT_PREFIX = "meta-";
3624
3955
  var META_RUNTIME_TRANSPORT_DIAGNOSTICS_INTENT = "meta-runtime-transport-diagnostics";
3625
3956
  var META_RUNTIME_STATUS_INTENT = "meta-runtime-status";
3626
3957
  var META_READINESS_INTENT = "meta-readiness";
3627
- function isPlainObject2(value) {
3958
+ function isPlainObject3(value) {
3628
3959
  return typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
3629
3960
  }
3630
3961
  function deepMergeDeterministic(left, right) {
3631
3962
  if (Array.isArray(left) && Array.isArray(right)) {
3632
3963
  return [...left, ...right];
3633
3964
  }
3634
- if (isPlainObject2(left) && isPlainObject2(right)) {
3965
+ if (isPlainObject3(left) && isPlainObject3(right)) {
3635
3966
  const merged = { ...left };
3636
3967
  const keys = Array.from(/* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])).sort();
3637
3968
  for (const key of keys) {
@@ -3875,6 +4206,10 @@ function normalizeServiceInstanceDescriptor(value) {
3875
4206
  return null;
3876
4207
  }
3877
4208
  const transports = normalizeTransportArray(raw.transports, uuid10);
4209
+ const leaseStatusRaw = normalizeString2(raw.leaseStatus ?? raw.lease_status);
4210
+ const leaseStatus = leaseStatusRaw === "active" || leaseStatusRaw === "non_responsive" || leaseStatusRaw === "inactive" || leaseStatusRaw === "deleted" ? leaseStatusRaw : void 0;
4211
+ const isActive = leaseStatus === "active" ? true : leaseStatus === "non_responsive" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : Boolean(raw.isActive ?? raw.is_active ?? true);
4212
+ const isNonResponsive = leaseStatus === "non_responsive" ? true : leaseStatus === "active" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : Boolean(raw.isNonResponsive ?? raw.is_non_responsive ?? false);
3878
4213
  return {
3879
4214
  uuid: uuid10,
3880
4215
  serviceName,
@@ -3885,10 +4220,16 @@ function normalizeServiceInstanceDescriptor(value) {
3885
4220
  )
3886
4221
  ),
3887
4222
  isPrimary: Boolean(raw.isPrimary ?? raw.is_primary ?? false),
3888
- isActive: Boolean(raw.isActive ?? raw.is_active ?? true),
3889
- isNonResponsive: Boolean(
3890
- raw.isNonResponsive ?? raw.is_non_responsive ?? false
3891
- ),
4223
+ leaseStatus,
4224
+ leaseExpiresAt: typeof raw.leaseExpiresAt === "string" ? raw.leaseExpiresAt : typeof raw.lease_expires_at === "string" ? raw.lease_expires_at : void 0,
4225
+ lastLeaseRenewedAt: typeof raw.lastLeaseRenewedAt === "string" ? raw.lastLeaseRenewedAt : typeof raw.last_lease_renewed_at === "string" ? raw.last_lease_renewed_at : void 0,
4226
+ isReady: typeof raw.isReady === "boolean" ? raw.isReady : typeof raw.is_ready === "boolean" ? raw.is_ready : void 0,
4227
+ readinessReason: typeof raw.readinessReason === "string" ? raw.readinessReason : typeof raw.readiness_reason === "string" ? raw.readiness_reason : null,
4228
+ lastReadyAt: typeof raw.lastReadyAt === "string" ? raw.lastReadyAt : typeof raw.last_ready_at === "string" ? raw.last_ready_at : null,
4229
+ lastObservedTransportAt: typeof raw.lastObservedTransportAt === "string" ? raw.lastObservedTransportAt : typeof raw.last_observed_transport_at === "string" ? raw.last_observed_transport_at : null,
4230
+ shutdownRequestedAt: typeof raw.shutdownRequestedAt === "string" ? raw.shutdownRequestedAt : typeof raw.shutdown_requested_at === "string" ? raw.shutdown_requested_at : null,
4231
+ isActive,
4232
+ isNonResponsive,
3892
4233
  isBlocked: Boolean(raw.isBlocked ?? raw.is_blocked ?? false),
3893
4234
  runtimeState: raw.runtimeState === "healthy" || raw.runtimeState === "degraded" || raw.runtimeState === "overloaded" || raw.runtimeState === "unavailable" ? raw.runtimeState : void 0,
3894
4235
  acceptingWork: typeof raw.acceptingWork === "boolean" ? raw.acceptingWork : void 0,
@@ -4341,6 +4682,61 @@ function resolveHealthMetric(input, keys) {
4341
4682
  }
4342
4683
  return void 0;
4343
4684
  }
4685
+ function sanitizeRuntimeMetricsHealthDetail(value) {
4686
+ if (!value || typeof value !== "object") {
4687
+ return void 0;
4688
+ }
4689
+ const input = value;
4690
+ const sampledAt = typeof input.sampledAt === "string" && input.sampledAt.trim().length > 0 ? input.sampledAt : void 0;
4691
+ const cpuUsage = normalizeOptionalMetric(input.cpuUsage ?? input.cpu ?? input.cpuLoad);
4692
+ const memoryUsage = normalizeOptionalMetric(
4693
+ input.memoryUsage ?? input.memory ?? input.memoryPressure
4694
+ );
4695
+ const eventLoopLag = normalizeOptionalMetric(
4696
+ input.eventLoopLag ?? input.eventLoopLagMs
4697
+ );
4698
+ const rssBytes = normalizeOptionalMetric(input.rssBytes);
4699
+ const heapUsedBytes = normalizeOptionalMetric(input.heapUsedBytes);
4700
+ const heapTotalBytes = normalizeOptionalMetric(input.heapTotalBytes);
4701
+ const memoryLimitBytes = normalizeOptionalMetric(input.memoryLimitBytes);
4702
+ if (sampledAt === void 0 && cpuUsage === void 0 && memoryUsage === void 0 && eventLoopLag === void 0 && rssBytes === void 0 && heapUsedBytes === void 0 && heapTotalBytes === void 0 && memoryLimitBytes === void 0) {
4703
+ return void 0;
4704
+ }
4705
+ return {
4706
+ ...sampledAt !== void 0 ? { sampledAt } : {},
4707
+ ...cpuUsage !== void 0 ? { cpuUsage } : {},
4708
+ ...memoryUsage !== void 0 ? { memoryUsage } : {},
4709
+ ...eventLoopLag !== void 0 ? { eventLoopLag } : {},
4710
+ ...rssBytes !== void 0 ? { rssBytes } : {},
4711
+ ...heapUsedBytes !== void 0 ? { heapUsedBytes } : {},
4712
+ ...heapTotalBytes !== void 0 ? { heapTotalBytes } : {},
4713
+ ...memoryLimitBytes !== void 0 ? { memoryLimitBytes } : {}
4714
+ };
4715
+ }
4716
+ function sanitizeAuthorityRuntimeStatusHealth(health, options) {
4717
+ const input = health && typeof health === "object" ? health : {};
4718
+ const cpuUsage = options?.cpuUsage !== void 0 ? options.cpuUsage : normalizeOptionalMetric(input.cpuUsage ?? input.cpu ?? input.cpuLoad);
4719
+ const memoryUsage = options?.memoryUsage !== void 0 ? options.memoryUsage : normalizeOptionalMetric(
4720
+ input.memoryUsage ?? input.memory ?? input.memoryPressure
4721
+ );
4722
+ const eventLoopLag = options?.eventLoopLag !== void 0 ? options.eventLoopLag : normalizeOptionalMetric(input.eventLoopLag ?? input.eventLoopLagMs);
4723
+ const runtimeMetrics = sanitizeRuntimeMetricsHealthDetail(input.runtimeMetrics);
4724
+ const runtimeStatus = options?.state || options?.reportedAt || typeof options?.acceptingWork === "boolean" ? {
4725
+ ...options?.state ? { state: options.state } : {},
4726
+ ...typeof options?.acceptingWork === "boolean" ? { acceptingWork: options.acceptingWork } : {},
4727
+ ...options?.reportedAt ? { reportedAt: options.reportedAt } : {}
4728
+ } : void 0;
4729
+ if (cpuUsage === void 0 && memoryUsage === void 0 && eventLoopLag === void 0 && !runtimeMetrics && !runtimeStatus) {
4730
+ return void 0;
4731
+ }
4732
+ return {
4733
+ ...cpuUsage !== void 0 ? { cpuUsage } : {},
4734
+ ...memoryUsage !== void 0 ? { memoryUsage } : {},
4735
+ ...eventLoopLag !== void 0 ? { eventLoopLag } : {},
4736
+ ...runtimeMetrics ? { runtimeMetrics } : {},
4737
+ ...runtimeStatus ? { runtimeStatus } : {}
4738
+ };
4739
+ }
4344
4740
  function normalizeAuthorityRuntimeStatusReport(input) {
4345
4741
  if (!input || typeof input !== "object") {
4346
4742
  return null;
@@ -4369,6 +4765,17 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4369
4765
  (protocol) => protocol === "rest" || protocol === "socket"
4370
4766
  ) : [];
4371
4767
  const transportProtocols = transportProtocolList.length > 0 ? Array.from(new Set(transportProtocolList)) : void 0;
4768
+ const acceptingWork = Boolean(input.acceptingWork ?? input.accepting_work);
4769
+ const cpuUsage = resolveHealthMetric(input, ["cpuUsage", "cpu", "cpuLoad"]);
4770
+ const memoryUsage = resolveHealthMetric(input, [
4771
+ "memoryUsage",
4772
+ "memory",
4773
+ "memoryPressure"
4774
+ ]);
4775
+ const eventLoopLag = resolveHealthMetric(input, [
4776
+ "eventLoopLag",
4777
+ "eventLoopLagMs"
4778
+ ]);
4372
4779
  return {
4373
4780
  serviceName,
4374
4781
  serviceInstanceId,
@@ -4379,7 +4786,7 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4379
4786
  isFrontend: typeof input.isFrontend === "boolean" ? input.isFrontend : typeof input.is_frontend === "boolean" ? input.is_frontend : void 0,
4380
4787
  reportedAt,
4381
4788
  state,
4382
- acceptingWork: Boolean(input.acceptingWork ?? input.accepting_work),
4789
+ acceptingWork,
4383
4790
  numberOfRunningGraphs: Math.max(
4384
4791
  0,
4385
4792
  Math.trunc(
@@ -4388,22 +4795,22 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4388
4795
  ) || 0
4389
4796
  )
4390
4797
  ),
4391
- cpuUsage: resolveHealthMetric(input, ["cpuUsage", "cpu", "cpuLoad"]),
4392
- memoryUsage: resolveHealthMetric(input, [
4393
- "memoryUsage",
4394
- "memory",
4395
- "memoryPressure"
4396
- ]),
4397
- eventLoopLag: resolveHealthMetric(input, [
4398
- "eventLoopLag",
4399
- "eventLoopLagMs"
4400
- ]),
4798
+ cpuUsage,
4799
+ memoryUsage,
4800
+ eventLoopLag,
4401
4801
  isActive: Boolean(input.isActive ?? input.is_active ?? true),
4402
4802
  isNonResponsive: Boolean(
4403
4803
  input.isNonResponsive ?? input.is_non_responsive ?? false
4404
4804
  ),
4405
4805
  isBlocked: Boolean(input.isBlocked ?? input.is_blocked ?? false),
4406
- health: input.health && typeof input.health === "object" ? input.health : void 0
4806
+ health: sanitizeAuthorityRuntimeStatusHealth(input.health, {
4807
+ state,
4808
+ acceptingWork,
4809
+ reportedAt,
4810
+ cpuUsage,
4811
+ memoryUsage,
4812
+ eventLoopLag
4813
+ })
4407
4814
  };
4408
4815
  }
4409
4816
  function buildAuthorityRuntimeStatusSignature(report) {
@@ -4416,18 +4823,53 @@ function buildAuthorityRuntimeStatusSignature(report) {
4416
4823
  transportProtocols: report.transportProtocols ?? [],
4417
4824
  state: report.state,
4418
4825
  acceptingWork: report.acceptingWork,
4419
- numberOfRunningGraphs: report.numberOfRunningGraphs,
4420
- cpuUsage: report.cpuUsage ?? null,
4421
- memoryUsage: report.memoryUsage ?? null,
4422
- eventLoopLag: report.eventLoopLag ?? null,
4423
4826
  isActive: report.isActive,
4424
4827
  isNonResponsive: report.isNonResponsive,
4425
4828
  isBlocked: report.isBlocked,
4426
- isFrontend: report.isFrontend ?? null,
4427
- health: report.health ?? {}
4829
+ isFrontend: report.isFrontend ?? null
4428
4830
  });
4429
4831
  }
4430
4832
 
4833
+ // src/registry/runtimeJitter.ts
4834
+ function normalizeKey(key) {
4835
+ return key.trim() || "default";
4836
+ }
4837
+ function hashKeyToUnitInterval(key) {
4838
+ const normalizedKey = normalizeKey(key);
4839
+ let hash = 2166136261;
4840
+ for (let index = 0; index < normalizedKey.length; index += 1) {
4841
+ hash ^= normalizedKey.charCodeAt(index);
4842
+ hash = Math.imul(hash, 16777619);
4843
+ }
4844
+ return (hash >>> 0) / 4294967295;
4845
+ }
4846
+ function normalizeJitterRatio(value) {
4847
+ if (!Number.isFinite(value) || value <= 0) {
4848
+ return 0;
4849
+ }
4850
+ return Math.min(value, 1);
4851
+ }
4852
+ function buildDeterministicJitterOffsetMs(baseMs, ratio, key) {
4853
+ if (!Number.isFinite(baseMs) || baseMs <= 0) {
4854
+ return 0;
4855
+ }
4856
+ const normalizedRatio = normalizeJitterRatio(ratio);
4857
+ if (normalizedRatio <= 0) {
4858
+ return 0;
4859
+ }
4860
+ const maxOffsetMs = Math.round(baseMs * normalizedRatio);
4861
+ if (maxOffsetMs <= 0) {
4862
+ return 0;
4863
+ }
4864
+ return Math.round(hashKeyToUnitInterval(key) * maxOffsetMs);
4865
+ }
4866
+ function buildDeterministicJitteredDelayMs(baseMs, ratio, key) {
4867
+ return Math.max(
4868
+ 0,
4869
+ Math.round(baseMs) + buildDeterministicJitterOffsetMs(baseMs, ratio, key)
4870
+ );
4871
+ }
4872
+
4431
4873
  // src/registry/serviceManifestContract.ts
4432
4874
  var AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT = "meta-service-registry-authority-service-manifest-report";
4433
4875
  var AUTHORITY_SERVICE_MANIFEST_UPDATED_SIGNAL = "global.meta.cadenza_db.service_manifest_updated";
@@ -4453,16 +4895,23 @@ function normalizeServiceManifestSnapshot(input) {
4453
4895
  revision,
4454
4896
  manifestHash,
4455
4897
  publishedAt,
4898
+ publicationLayer: record.publicationLayer === "routing_capability" || record.publicationLayer === "business_structural" || record.publicationLayer === "local_meta_structural" ? record.publicationLayer : "business_structural",
4456
4899
  tasks: normalizeArray(record.tasks),
4457
4900
  signals: normalizeArray(record.signals),
4458
4901
  intents: normalizeArray(record.intents),
4459
4902
  actors: normalizeArray(record.actors),
4460
4903
  routines: normalizeArray(record.routines),
4904
+ helpers: normalizeArray(record.helpers),
4905
+ globals: normalizeArray(record.globals),
4461
4906
  directionalTaskMaps: normalizeArray(record.directionalTaskMaps),
4462
4907
  signalToTaskMaps: normalizeArray(record.signalToTaskMaps),
4463
4908
  intentToTaskMaps: normalizeArray(record.intentToTaskMaps),
4464
4909
  actorTaskMaps: normalizeArray(record.actorTaskMaps),
4465
- taskToRoutineMaps: normalizeArray(record.taskToRoutineMaps)
4910
+ taskToRoutineMaps: normalizeArray(record.taskToRoutineMaps),
4911
+ taskToHelperMaps: normalizeArray(record.taskToHelperMaps),
4912
+ helperToHelperMaps: normalizeArray(record.helperToHelperMaps),
4913
+ taskToGlobalMaps: normalizeArray(record.taskToGlobalMaps),
4914
+ helperToGlobalMaps: normalizeArray(record.helperToGlobalMaps)
4466
4915
  };
4467
4916
  }
4468
4917
  function selectLatestServiceManifestSnapshots(snapshots) {
@@ -4582,6 +5031,7 @@ function decomposeSignalName(signalName) {
4582
5031
  }
4583
5032
 
4584
5033
  // src/registry/serviceManifest.ts
5034
+ import CoreCadenza from "@cadenza.io/core";
4585
5035
  var ACTOR_TASK_METADATA = /* @__PURE__ */ Symbol.for("@cadenza.io/core/actor-task-meta");
4586
5036
  function getActorTaskRuntimeMetadata(taskFunction) {
4587
5037
  if (typeof taskFunction !== "function") {
@@ -4725,15 +5175,90 @@ function buildRoutineDefinition(routine, serviceName) {
4725
5175
  is_meta: routine.isMeta === true
4726
5176
  };
4727
5177
  }
5178
+ function buildHelperDefinition(helper, serviceName) {
5179
+ return {
5180
+ name: helper.name,
5181
+ version: helper.version,
5182
+ description: helper.description,
5183
+ service_name: serviceName,
5184
+ is_meta: helper.isMeta === true,
5185
+ handler_source: helper.helperFunction.toString(),
5186
+ language: "js"
5187
+ };
5188
+ }
5189
+ function buildGlobalDefinition(globalDefinition, serviceName) {
5190
+ return {
5191
+ name: globalDefinition.name,
5192
+ version: globalDefinition.version,
5193
+ description: globalDefinition.description,
5194
+ service_name: serviceName,
5195
+ is_meta: globalDefinition.isMeta === true,
5196
+ value: sanitizeManifestValue(globalDefinition.value)
5197
+ };
5198
+ }
4728
5199
  function shouldExportTask(task) {
4729
- return !task.isDeputy && !task.isEphemeral;
5200
+ return task.register !== false && task.isHidden !== true && !task.isDeputy && !task.isEphemeral;
4730
5201
  }
4731
5202
  function shouldExportRoutine(routine) {
4732
5203
  return Boolean(String(routine?.name ?? "").trim());
4733
5204
  }
5205
+ function buildTaskKey(task) {
5206
+ return `${task.service_name}|${task.name}|${task.version}`;
5207
+ }
5208
+ function buildActorKey(actor) {
5209
+ return `${actor.service_name}|${actor.name}|${actor.version}`;
5210
+ }
5211
+ function buildRoutineKey(routine) {
5212
+ return `${routine.service_name}|${routine.name}|${routine.version}`;
5213
+ }
5214
+ function buildHelperKey(helper) {
5215
+ return `${helper.service_name}|${helper.name}|${helper.version}`;
5216
+ }
5217
+ function buildGlobalKey(globalDefinition) {
5218
+ return `${globalDefinition.service_name}|${globalDefinition.name}|${globalDefinition.version}`;
5219
+ }
5220
+ function listManifestTasks() {
5221
+ const registryTasks = Array.from(CadenzaService.registry.tasks.values()).filter(
5222
+ (task) => Boolean(task)
5223
+ );
5224
+ const cachedTasks = Array.from(
5225
+ CoreCadenza.taskCache?.values?.() ?? []
5226
+ ).filter((task) => Boolean(task));
5227
+ return Array.from(
5228
+ new Map(
5229
+ [...registryTasks, ...cachedTasks].map((task) => [task.name, task])
5230
+ ).values()
5231
+ );
5232
+ }
5233
+ function listManifestHelpers() {
5234
+ const toolRuntime = CadenzaService;
5235
+ return (toolRuntime.getAllHelpers?.() ?? []).filter(
5236
+ (helper) => Boolean(helper && !helper.destroyed)
5237
+ );
5238
+ }
5239
+ function listManifestGlobals() {
5240
+ const toolRuntime = CadenzaService;
5241
+ return (toolRuntime.getAllGlobals?.() ?? []).filter(
5242
+ (globalDefinition) => Boolean(globalDefinition && !globalDefinition.destroyed)
5243
+ );
5244
+ }
5245
+ function isRoutingCriticalMetaSignal(_signal) {
5246
+ return false;
5247
+ }
5248
+ function isRoutingCriticalMetaIntent(_intent) {
5249
+ return false;
5250
+ }
4734
5251
  function buildServiceManifestSnapshot(params) {
4735
- const { serviceName, serviceInstanceId, revision, publishedAt } = params;
4736
- const tasks = Array.from(CadenzaService.registry.tasks.values()).filter((task) => Boolean(task)).filter(shouldExportTask);
5252
+ const {
5253
+ serviceName,
5254
+ serviceInstanceId,
5255
+ revision,
5256
+ publishedAt,
5257
+ publicationLayer = "business_structural"
5258
+ } = params;
5259
+ const tasks = listManifestTasks().filter(shouldExportTask);
5260
+ const helpers = listManifestHelpers();
5261
+ const globals = listManifestGlobals();
4737
5262
  const routines = Array.from(CadenzaService.registry.routines.values()).filter((routine) => Boolean(routine)).filter(shouldExportRoutine);
4738
5263
  const actors = CadenzaService.getAllActors();
4739
5264
  const taskDefinitions = tasks.map((task) => buildTaskDefinition(task, serviceName)).sort(
@@ -4745,6 +5270,10 @@ function buildServiceManifestSnapshot(params) {
4745
5270
  const directionalTaskMaps = /* @__PURE__ */ new Map();
4746
5271
  const actorTaskMaps = /* @__PURE__ */ new Map();
4747
5272
  const taskToRoutineMaps = /* @__PURE__ */ new Map();
5273
+ const helperTaskMaps = /* @__PURE__ */ new Map();
5274
+ const helperHelperMaps = /* @__PURE__ */ new Map();
5275
+ const taskGlobalMaps = /* @__PURE__ */ new Map();
5276
+ const helperGlobalMaps = /* @__PURE__ */ new Map();
4748
5277
  const registerSignal = (signalName) => {
4749
5278
  const normalizedSignalName = canonicalizeSignalName(signalName);
4750
5279
  if (!normalizedSignalName || signalDefinitions.has(normalizedSignalName)) {
@@ -4828,6 +5357,37 @@ function buildServiceManifestSnapshot(params) {
4828
5357
  is_meta: actorTaskMetadata.actorKind === "meta" || task.isMeta === true
4829
5358
  });
4830
5359
  }
5360
+ const taskTools = task;
5361
+ for (const [alias, helperName] of taskTools.helperAliases?.entries?.() ?? []) {
5362
+ const helper = CadenzaService.getHelper?.(helperName);
5363
+ if (!helper) {
5364
+ continue;
5365
+ }
5366
+ const key = `${task.name}|${task.version}|${alias}|${helper.name}|${helper.version}|${serviceName}`;
5367
+ helperTaskMaps.set(key, {
5368
+ task_name: task.name,
5369
+ task_version: task.version,
5370
+ service_name: serviceName,
5371
+ alias,
5372
+ helper_name: helper.name,
5373
+ helper_version: helper.version
5374
+ });
5375
+ }
5376
+ for (const [alias, globalName] of taskTools.globalAliases?.entries?.() ?? []) {
5377
+ const globalDefinition = CadenzaService.getGlobal?.(globalName);
5378
+ if (!globalDefinition) {
5379
+ continue;
5380
+ }
5381
+ const key = `${task.name}|${task.version}|${alias}|${globalDefinition.name}|${globalDefinition.version}|${serviceName}`;
5382
+ taskGlobalMaps.set(key, {
5383
+ task_name: task.name,
5384
+ task_version: task.version,
5385
+ service_name: serviceName,
5386
+ alias,
5387
+ global_name: globalDefinition.name,
5388
+ global_version: globalDefinition.version
5389
+ });
5390
+ }
4831
5391
  }
4832
5392
  const intentDefinitions = Array.from(CadenzaService.inquiryBroker.intents.values()).map((intent) => {
4833
5393
  const intentRecord = intent;
@@ -4859,18 +5419,56 @@ function buildServiceManifestSnapshot(params) {
4859
5419
  ).sort(
4860
5420
  (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
4861
5421
  );
4862
- for (const routine of routines) {
4863
- for (const task of routine.tasks) {
4864
- if (!task) {
5422
+ const helperDefinitions = helpers.map((helper) => buildHelperDefinition(helper, serviceName)).sort(
5423
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5424
+ );
5425
+ const globalDefinitions = globals.map((globalDefinition) => buildGlobalDefinition(globalDefinition, serviceName)).sort(
5426
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5427
+ );
5428
+ for (const helper of helpers) {
5429
+ for (const [alias, dependencyHelperName] of helper.helperAliases.entries()) {
5430
+ const dependencyHelper = CadenzaService.getHelper?.(dependencyHelperName);
5431
+ if (!dependencyHelper) {
4865
5432
  continue;
4866
5433
  }
4867
- const iterator = task.getIterator();
4868
- while (iterator.hasNext()) {
4869
- const nextTask = iterator.next();
4870
- if (!nextTask || !shouldExportTask(nextTask)) {
4871
- continue;
4872
- }
4873
- const key = `${routine.name}|${routine.version}|${nextTask.name}|${nextTask.version}|${serviceName}`;
5434
+ const key = `${helper.name}|${helper.version}|${alias}|${dependencyHelper.name}|${dependencyHelper.version}|${serviceName}`;
5435
+ helperHelperMaps.set(key, {
5436
+ helper_name: helper.name,
5437
+ helper_version: helper.version,
5438
+ service_name: serviceName,
5439
+ alias,
5440
+ dependency_helper_name: dependencyHelper.name,
5441
+ dependency_helper_version: dependencyHelper.version
5442
+ });
5443
+ }
5444
+ for (const [alias, globalName] of helper.globalAliases.entries()) {
5445
+ const globalDefinition = CadenzaService.getGlobal?.(globalName);
5446
+ if (!globalDefinition) {
5447
+ continue;
5448
+ }
5449
+ const key = `${helper.name}|${helper.version}|${alias}|${globalDefinition.name}|${globalDefinition.version}|${serviceName}`;
5450
+ helperGlobalMaps.set(key, {
5451
+ helper_name: helper.name,
5452
+ helper_version: helper.version,
5453
+ service_name: serviceName,
5454
+ alias,
5455
+ global_name: globalDefinition.name,
5456
+ global_version: globalDefinition.version
5457
+ });
5458
+ }
5459
+ }
5460
+ for (const routine of routines) {
5461
+ for (const task of routine.tasks) {
5462
+ if (!task) {
5463
+ continue;
5464
+ }
5465
+ const iterator = task.getIterator();
5466
+ while (iterator.hasNext()) {
5467
+ const nextTask = iterator.next();
5468
+ if (!nextTask || !shouldExportTask(nextTask)) {
5469
+ continue;
5470
+ }
5471
+ const key = `${routine.name}|${routine.version}|${nextTask.name}|${nextTask.version}|${serviceName}`;
4874
5472
  taskToRoutineMaps.set(key, {
4875
5473
  task_name: nextTask.name,
4876
5474
  task_version: nextTask.version,
@@ -4881,41 +5479,506 @@ function buildServiceManifestSnapshot(params) {
4881
5479
  }
4882
5480
  }
4883
5481
  }
4884
- const manifestBody = {
4885
- serviceName,
4886
- serviceInstanceId,
4887
- tasks: taskDefinitions,
4888
- signals: Array.from(signalDefinitions.values()).sort(
4889
- (left, right) => left.name.localeCompare(right.name)
4890
- ),
4891
- intents: intentDefinitions,
4892
- actors: actorDefinitions,
4893
- routines: routineDefinitions,
4894
- directionalTaskMaps: Array.from(directionalTaskMaps.values()).sort(
4895
- (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
4896
- `${right.predecessor_task_name}:${right.task_name}`
4897
- )
4898
- ),
4899
- signalToTaskMaps: Array.from(signalTaskMaps.values()).sort(
4900
- (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
4901
- `${right.signal_name}:${right.task_name}`
4902
- )
4903
- ),
4904
- intentToTaskMaps: Array.from(intentTaskMaps.values()).sort(
4905
- (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
4906
- `${right.intent_name}:${right.task_name}`
5482
+ const taskDefinitionsByKey = new Map(
5483
+ taskDefinitions.map((task) => [buildTaskKey(task), task])
5484
+ );
5485
+ const signalDefinitionsByName = new Map(
5486
+ Array.from(signalDefinitions.values()).map((signal) => [signal.name, signal])
5487
+ );
5488
+ const intentDefinitionsByName = new Map(
5489
+ intentDefinitions.map((intent) => [intent.name, intent])
5490
+ );
5491
+ const actorDefinitionsByKey = new Map(
5492
+ actorDefinitions.map((actor) => [buildActorKey(actor), actor])
5493
+ );
5494
+ const routineDefinitionsByKey = new Map(
5495
+ routineDefinitions.map((routine) => [buildRoutineKey(routine), routine])
5496
+ );
5497
+ const helperDefinitionsByKey = new Map(
5498
+ helperDefinitions.map((helper) => [buildHelperKey(helper), helper])
5499
+ );
5500
+ const globalDefinitionsByKey = new Map(
5501
+ globalDefinitions.map((globalDefinition) => [
5502
+ buildGlobalKey(globalDefinition),
5503
+ globalDefinition
5504
+ ])
5505
+ );
5506
+ const routingTaskKeys = /* @__PURE__ */ new Set();
5507
+ const routingSignalNames = /* @__PURE__ */ new Set();
5508
+ const routingIntentNames = /* @__PURE__ */ new Set();
5509
+ const publishedSignalTaskMaps = Array.from(signalTaskMaps.values()).filter((map) => {
5510
+ const signal = signalDefinitionsByName.get(map.signal_name);
5511
+ return signal?.is_meta !== true || (signal ? isRoutingCriticalMetaSignal(signal) : false);
5512
+ }).sort(
5513
+ (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
5514
+ `${right.signal_name}:${right.task_name}`
5515
+ )
5516
+ );
5517
+ const publishedIntentTaskMaps = Array.from(intentTaskMaps.values()).filter((map) => {
5518
+ const intent = intentDefinitionsByName.get(map.intent_name);
5519
+ return intent?.is_meta !== true || (intent ? isRoutingCriticalMetaIntent(intent) : false);
5520
+ }).sort(
5521
+ (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
5522
+ `${right.intent_name}:${right.task_name}`
5523
+ )
5524
+ );
5525
+ const localMetaSignalTaskMaps = Array.from(signalTaskMaps.values()).filter((map) => !publishedSignalTaskMaps.includes(map)).sort(
5526
+ (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
5527
+ `${right.signal_name}:${right.task_name}`
5528
+ )
5529
+ );
5530
+ const localMetaIntentTaskMaps = Array.from(intentTaskMaps.values()).filter((map) => !publishedIntentTaskMaps.includes(map)).sort(
5531
+ (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
5532
+ `${right.intent_name}:${right.task_name}`
5533
+ )
5534
+ );
5535
+ for (const map of publishedSignalTaskMaps) {
5536
+ routingTaskKeys.add(
5537
+ buildTaskKey({
5538
+ service_name: map.service_name,
5539
+ name: map.task_name,
5540
+ version: map.task_version
5541
+ })
5542
+ );
5543
+ routingSignalNames.add(map.signal_name);
5544
+ }
5545
+ for (const map of publishedIntentTaskMaps) {
5546
+ routingTaskKeys.add(
5547
+ buildTaskKey({
5548
+ service_name: map.service_name,
5549
+ name: map.task_name,
5550
+ version: map.task_version
5551
+ })
5552
+ );
5553
+ routingIntentNames.add(map.intent_name);
5554
+ }
5555
+ const routingTasks = Array.from(routingTaskKeys).map((key) => taskDefinitionsByKey.get(key) ?? null).filter((task) => task !== null).sort(
5556
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5557
+ );
5558
+ const routingSignals = Array.from(routingSignalNames).map((name) => signalDefinitionsByName.get(name) ?? null).filter((signal) => signal !== null).sort((left, right) => left.name.localeCompare(right.name));
5559
+ const routingIntents = Array.from(routingIntentNames).map((name) => intentDefinitionsByName.get(name) ?? null).filter((intent) => intent !== null).sort((left, right) => left.name.localeCompare(right.name));
5560
+ const businessTasks = taskDefinitions.filter((task) => task.is_meta !== true && task.is_sub_meta !== true).sort(
5561
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5562
+ );
5563
+ const businessSignals = Array.from(signalDefinitions.values()).filter((signal) => signal.is_meta !== true).sort((left, right) => left.name.localeCompare(right.name));
5564
+ const businessIntents = intentDefinitions.filter((intent) => intent.is_meta !== true).sort((left, right) => left.name.localeCompare(right.name));
5565
+ const businessActors = actorDefinitions.filter((actor) => actor.is_meta !== true).sort(
5566
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5567
+ );
5568
+ const businessRoutines = routineDefinitions.filter((routine) => routine.is_meta !== true).sort(
5569
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5570
+ );
5571
+ const businessDirectionalTaskMaps = Array.from(directionalTaskMaps.values()).filter((map) => {
5572
+ const predecessor = taskDefinitionsByKey.get(
5573
+ buildTaskKey({
5574
+ service_name: map.predecessor_service_name,
5575
+ name: map.predecessor_task_name,
5576
+ version: map.predecessor_task_version
5577
+ })
5578
+ );
5579
+ const task = taskDefinitionsByKey.get(
5580
+ buildTaskKey({
5581
+ service_name: map.service_name,
5582
+ name: map.task_name,
5583
+ version: map.task_version
5584
+ })
5585
+ );
5586
+ return predecessor?.is_meta !== true && predecessor?.is_sub_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
5587
+ }).sort(
5588
+ (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
5589
+ `${right.predecessor_task_name}:${right.task_name}`
5590
+ )
5591
+ );
5592
+ const businessActorTaskMaps = Array.from(actorTaskMaps.values()).filter((map) => {
5593
+ const actor = actorDefinitionsByKey.get(
5594
+ buildActorKey({
5595
+ service_name: map.service_name,
5596
+ name: map.actor_name,
5597
+ version: map.actor_version
5598
+ })
5599
+ );
5600
+ const task = taskDefinitionsByKey.get(
5601
+ buildTaskKey({
5602
+ service_name: map.service_name,
5603
+ name: map.task_name,
5604
+ version: map.task_version
5605
+ })
5606
+ );
5607
+ return actor?.is_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
5608
+ }).sort(
5609
+ (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
5610
+ `${right.actor_name}:${right.task_name}`
5611
+ )
5612
+ );
5613
+ const businessTaskToRoutineMaps = Array.from(taskToRoutineMaps.values()).filter((map) => {
5614
+ const routine = routineDefinitionsByKey.get(
5615
+ buildRoutineKey({
5616
+ service_name: map.service_name,
5617
+ name: map.routine_name,
5618
+ version: map.routine_version
5619
+ })
5620
+ );
5621
+ const task = taskDefinitionsByKey.get(
5622
+ buildTaskKey({
5623
+ service_name: map.service_name,
5624
+ name: map.task_name,
5625
+ version: map.task_version
5626
+ })
5627
+ );
5628
+ return routine?.is_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
5629
+ }).sort(
5630
+ (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
5631
+ `${right.routine_name}:${right.task_name}`
5632
+ )
5633
+ );
5634
+ const localMetaTasks = taskDefinitions.filter((task) => task.is_meta === true || task.is_sub_meta === true).sort(
5635
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5636
+ );
5637
+ const localMetaSignals = Array.from(signalDefinitions.values()).filter((signal) => signal.is_meta === true).sort((left, right) => left.name.localeCompare(right.name));
5638
+ const localMetaIntents = intentDefinitions.filter((intent) => intent.is_meta === true).sort((left, right) => left.name.localeCompare(right.name));
5639
+ const localMetaActors = actorDefinitions.filter((actor) => actor.is_meta === true).sort(
5640
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5641
+ );
5642
+ const localMetaRoutines = routineDefinitions.filter((routine) => routine.is_meta === true).sort(
5643
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5644
+ );
5645
+ const localMetaDirectionalTaskMaps = Array.from(directionalTaskMaps.values()).filter((map) => !businessDirectionalTaskMaps.includes(map)).sort(
5646
+ (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
5647
+ `${right.predecessor_task_name}:${right.task_name}`
5648
+ )
5649
+ );
5650
+ const localMetaActorTaskMaps = Array.from(actorTaskMaps.values()).filter((map) => !businessActorTaskMaps.includes(map)).sort(
5651
+ (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
5652
+ `${right.actor_name}:${right.task_name}`
5653
+ )
5654
+ );
5655
+ const localMetaTaskToRoutineMaps = Array.from(taskToRoutineMaps.values()).filter((map) => !businessTaskToRoutineMaps.includes(map)).sort(
5656
+ (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
5657
+ `${right.routine_name}:${right.task_name}`
5658
+ )
5659
+ );
5660
+ const businessLocalMetaTaskKeys = /* @__PURE__ */ new Set();
5661
+ const businessLocalMetaSignalNames = /* @__PURE__ */ new Set();
5662
+ const businessLocalMetaIntentNames = /* @__PURE__ */ new Set();
5663
+ const businessLocalMetaActorKeys = /* @__PURE__ */ new Set();
5664
+ const businessLocalMetaRoutineKeys = /* @__PURE__ */ new Set();
5665
+ for (const map of localMetaSignalTaskMaps) {
5666
+ businessLocalMetaSignalNames.add(map.signal_name);
5667
+ businessLocalMetaTaskKeys.add(
5668
+ buildTaskKey({
5669
+ service_name: map.service_name,
5670
+ name: map.task_name,
5671
+ version: map.task_version
5672
+ })
5673
+ );
5674
+ }
5675
+ for (const map of localMetaIntentTaskMaps) {
5676
+ businessLocalMetaIntentNames.add(map.intent_name);
5677
+ businessLocalMetaTaskKeys.add(
5678
+ buildTaskKey({
5679
+ service_name: map.service_name,
5680
+ name: map.task_name,
5681
+ version: map.task_version
5682
+ })
5683
+ );
5684
+ }
5685
+ for (const map of localMetaActorTaskMaps) {
5686
+ businessLocalMetaActorKeys.add(
5687
+ buildActorKey({
5688
+ service_name: map.service_name,
5689
+ name: map.actor_name,
5690
+ version: map.actor_version
5691
+ })
5692
+ );
5693
+ businessLocalMetaTaskKeys.add(
5694
+ buildTaskKey({
5695
+ service_name: map.service_name,
5696
+ name: map.task_name,
5697
+ version: map.task_version
5698
+ })
5699
+ );
5700
+ }
5701
+ for (const map of localMetaTaskToRoutineMaps) {
5702
+ businessLocalMetaRoutineKeys.add(
5703
+ buildRoutineKey({
5704
+ service_name: map.service_name,
5705
+ name: map.routine_name,
5706
+ version: map.routine_version
5707
+ })
5708
+ );
5709
+ businessLocalMetaTaskKeys.add(
5710
+ buildTaskKey({
5711
+ service_name: map.service_name,
5712
+ name: map.task_name,
5713
+ version: map.task_version
5714
+ })
5715
+ );
5716
+ }
5717
+ const businessLocalMetaTasks = Array.from(businessLocalMetaTaskKeys).map((key) => taskDefinitionsByKey.get(key) ?? null).filter(
5718
+ (task) => task !== null && (task.is_meta === true || task.is_sub_meta === true)
5719
+ ).sort(
5720
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5721
+ );
5722
+ const businessLocalMetaSignals = Array.from(businessLocalMetaSignalNames).map((name) => signalDefinitionsByName.get(name) ?? null).filter(
5723
+ (signal) => signal !== null && signal.is_meta === true
5724
+ ).sort((left, right) => left.name.localeCompare(right.name));
5725
+ const businessLocalMetaIntents = Array.from(businessLocalMetaIntentNames).map((name) => intentDefinitionsByName.get(name) ?? null).filter(
5726
+ (intent) => intent !== null && intent.is_meta === true
5727
+ ).sort((left, right) => left.name.localeCompare(right.name));
5728
+ const businessLocalMetaActors = Array.from(businessLocalMetaActorKeys).map((key) => actorDefinitionsByKey.get(key) ?? null).filter(
5729
+ (actor) => actor !== null && actor.is_meta === true
5730
+ ).sort(
5731
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5732
+ );
5733
+ const businessLocalMetaRoutines = Array.from(businessLocalMetaRoutineKeys).map((key) => routineDefinitionsByKey.get(key) ?? null).filter(
5734
+ (routine) => routine !== null && routine.is_meta === true
5735
+ ).sort(
5736
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5737
+ );
5738
+ const cumulativeTasks = publicationLayer === "routing_capability" ? routingTasks : publicationLayer === "business_structural" ? Array.from(
5739
+ new Map(
5740
+ [...routingTasks, ...businessTasks, ...businessLocalMetaTasks].map((task) => [
5741
+ buildTaskKey(task),
5742
+ task
5743
+ ])
5744
+ ).values()
5745
+ ).sort(
5746
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5747
+ ) : Array.from(
5748
+ new Map(
5749
+ [...routingTasks, ...businessTasks, ...localMetaTasks].map((task) => [
5750
+ buildTaskKey(task),
5751
+ task
5752
+ ])
5753
+ ).values()
5754
+ ).sort(
5755
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5756
+ );
5757
+ const cumulativeSignals = publicationLayer === "routing_capability" ? routingSignals : publicationLayer === "business_structural" ? Array.from(
5758
+ new Map(
5759
+ [...routingSignals, ...businessSignals, ...businessLocalMetaSignals].map(
5760
+ (signal) => [signal.name, signal]
4907
5761
  )
4908
- ),
4909
- actorTaskMaps: Array.from(actorTaskMaps.values()).sort(
4910
- (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
4911
- `${right.actor_name}:${right.task_name}`
5762
+ ).values()
5763
+ ).sort((left, right) => left.name.localeCompare(right.name)) : Array.from(
5764
+ new Map(
5765
+ [...routingSignals, ...businessSignals, ...localMetaSignals].map((signal) => [
5766
+ signal.name,
5767
+ signal
5768
+ ])
5769
+ ).values()
5770
+ ).sort((left, right) => left.name.localeCompare(right.name));
5771
+ const cumulativeIntents = publicationLayer === "routing_capability" ? routingIntents : publicationLayer === "business_structural" ? Array.from(
5772
+ new Map(
5773
+ [...routingIntents, ...businessIntents, ...businessLocalMetaIntents].map(
5774
+ (intent) => [intent.name, intent]
4912
5775
  )
4913
- ),
4914
- taskToRoutineMaps: Array.from(taskToRoutineMaps.values()).sort(
4915
- (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
4916
- `${right.routine_name}:${right.task_name}`
5776
+ ).values()
5777
+ ).sort((left, right) => left.name.localeCompare(right.name)) : Array.from(
5778
+ new Map(
5779
+ [...routingIntents, ...businessIntents, ...localMetaIntents].map((intent) => [
5780
+ intent.name,
5781
+ intent
5782
+ ])
5783
+ ).values()
5784
+ ).sort((left, right) => left.name.localeCompare(right.name));
5785
+ const cumulativeActors = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
5786
+ new Map(
5787
+ [...businessActors, ...businessLocalMetaActors].map((actor) => [
5788
+ buildActorKey(actor),
5789
+ actor
5790
+ ])
5791
+ ).values()
5792
+ ).sort(
5793
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5794
+ ) : Array.from(
5795
+ new Map(
5796
+ [...businessActors, ...localMetaActors].map((actor) => [
5797
+ buildActorKey(actor),
5798
+ actor
5799
+ ])
5800
+ ).values()
5801
+ ).sort(
5802
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5803
+ );
5804
+ const cumulativeRoutines = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
5805
+ new Map(
5806
+ [...businessRoutines, ...businessLocalMetaRoutines].map((routine) => [
5807
+ buildRoutineKey(routine),
5808
+ routine
5809
+ ])
5810
+ ).values()
5811
+ ).sort(
5812
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5813
+ ) : Array.from(
5814
+ new Map(
5815
+ [...businessRoutines, ...localMetaRoutines].map((routine) => [
5816
+ buildRoutineKey(routine),
5817
+ routine
5818
+ ])
5819
+ ).values()
5820
+ ).sort(
5821
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5822
+ );
5823
+ const businessHelpers = helperDefinitions.filter((helper) => helper.is_meta !== true).sort(
5824
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5825
+ );
5826
+ const localMetaHelpers = helperDefinitions.filter((helper) => helper.is_meta === true).sort(
5827
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5828
+ );
5829
+ const businessGlobals = globalDefinitions.filter((globalDefinition) => globalDefinition.is_meta !== true).sort(
5830
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5831
+ );
5832
+ const localMetaGlobals = globalDefinitions.filter((globalDefinition) => globalDefinition.is_meta === true).sort(
5833
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5834
+ );
5835
+ const businessTaskToHelperMaps = Array.from(helperTaskMaps.values()).filter((map) => {
5836
+ const task = taskDefinitionsByKey.get(
5837
+ buildTaskKey({
5838
+ service_name: map.service_name,
5839
+ name: map.task_name,
5840
+ version: map.task_version
5841
+ })
5842
+ );
5843
+ const helper = helperDefinitionsByKey.get(
5844
+ buildHelperKey({
5845
+ service_name: map.service_name,
5846
+ name: map.helper_name,
5847
+ version: map.helper_version
5848
+ })
5849
+ );
5850
+ return task?.is_meta !== true && task?.is_sub_meta !== true && helper?.is_meta !== true;
5851
+ }).sort(
5852
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5853
+ );
5854
+ const localMetaTaskToHelperMaps = Array.from(helperTaskMaps.values()).filter((map) => !businessTaskToHelperMaps.includes(map)).sort(
5855
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5856
+ );
5857
+ const businessHelperToHelperMaps = Array.from(helperHelperMaps.values()).filter((map) => {
5858
+ const helper = helperDefinitionsByKey.get(
5859
+ buildHelperKey({
5860
+ service_name: map.service_name,
5861
+ name: map.helper_name,
5862
+ version: map.helper_version
5863
+ })
5864
+ );
5865
+ const dependencyHelper = helperDefinitionsByKey.get(
5866
+ buildHelperKey({
5867
+ service_name: map.service_name,
5868
+ name: map.dependency_helper_name,
5869
+ version: map.dependency_helper_version
5870
+ })
5871
+ );
5872
+ return helper?.is_meta !== true && dependencyHelper?.is_meta !== true;
5873
+ }).sort(
5874
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5875
+ );
5876
+ const localMetaHelperToHelperMaps = Array.from(helperHelperMaps.values()).filter((map) => !businessHelperToHelperMaps.includes(map)).sort(
5877
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5878
+ );
5879
+ const businessTaskToGlobalMaps = Array.from(taskGlobalMaps.values()).filter((map) => {
5880
+ const task = taskDefinitionsByKey.get(
5881
+ buildTaskKey({
5882
+ service_name: map.service_name,
5883
+ name: map.task_name,
5884
+ version: map.task_version
5885
+ })
5886
+ );
5887
+ const globalDefinition = globalDefinitionsByKey.get(
5888
+ buildGlobalKey({
5889
+ service_name: map.service_name,
5890
+ name: map.global_name,
5891
+ version: map.global_version
5892
+ })
5893
+ );
5894
+ return task?.is_meta !== true && task?.is_sub_meta !== true && globalDefinition?.is_meta !== true;
5895
+ }).sort(
5896
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5897
+ );
5898
+ const localMetaTaskToGlobalMaps = Array.from(taskGlobalMaps.values()).filter((map) => !businessTaskToGlobalMaps.includes(map)).sort(
5899
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5900
+ );
5901
+ const businessHelperToGlobalMaps = Array.from(helperGlobalMaps.values()).filter((map) => {
5902
+ const helper = helperDefinitionsByKey.get(
5903
+ buildHelperKey({
5904
+ service_name: map.service_name,
5905
+ name: map.helper_name,
5906
+ version: map.helper_version
5907
+ })
5908
+ );
5909
+ const globalDefinition = globalDefinitionsByKey.get(
5910
+ buildGlobalKey({
5911
+ service_name: map.service_name,
5912
+ name: map.global_name,
5913
+ version: map.global_version
5914
+ })
5915
+ );
5916
+ return helper?.is_meta !== true && globalDefinition?.is_meta !== true;
5917
+ }).sort(
5918
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5919
+ );
5920
+ const localMetaHelperToGlobalMaps = Array.from(helperGlobalMaps.values()).filter((map) => !businessHelperToGlobalMaps.includes(map)).sort(
5921
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5922
+ );
5923
+ const cumulativeHelpers = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelpers : [...businessHelpers, ...localMetaHelpers];
5924
+ const cumulativeGlobals = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessGlobals : [...businessGlobals, ...localMetaGlobals];
5925
+ const cumulativeTaskToHelperMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToHelperMaps : [...businessTaskToHelperMaps, ...localMetaTaskToHelperMaps];
5926
+ const cumulativeHelperToHelperMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelperToHelperMaps : [...businessHelperToHelperMaps, ...localMetaHelperToHelperMaps];
5927
+ const cumulativeTaskToGlobalMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToGlobalMaps : [...businessTaskToGlobalMaps, ...localMetaTaskToGlobalMaps];
5928
+ const cumulativeHelperToGlobalMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelperToGlobalMaps : [...businessHelperToGlobalMaps, ...localMetaHelperToGlobalMaps];
5929
+ const cumulativeDirectionalTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessDirectionalTaskMaps : Array.from(
5930
+ new Map(
5931
+ [...businessDirectionalTaskMaps, ...localMetaDirectionalTaskMaps].map(
5932
+ (map) => [
5933
+ `${map.predecessor_service_name}|${map.predecessor_task_name}|${map.predecessor_task_version}|${map.service_name}|${map.task_name}|${map.task_version}`,
5934
+ map
5935
+ ]
4917
5936
  )
4918
- )
5937
+ ).values()
5938
+ );
5939
+ const cumulativeActorTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
5940
+ new Map(
5941
+ [...businessActorTaskMaps, ...localMetaActorTaskMaps].map((map) => [
5942
+ `${map.service_name}|${map.actor_name}|${map.actor_version}|${map.task_name}|${map.task_version}|${map.mode}`,
5943
+ map
5944
+ ])
5945
+ ).values()
5946
+ ) : Array.from(
5947
+ new Map(
5948
+ [...businessActorTaskMaps, ...localMetaActorTaskMaps].map((map) => [
5949
+ `${map.service_name}|${map.actor_name}|${map.actor_version}|${map.task_name}|${map.task_version}|${map.mode}`,
5950
+ map
5951
+ ])
5952
+ ).values()
5953
+ );
5954
+ const cumulativeTaskToRoutineMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToRoutineMaps : Array.from(
5955
+ new Map(
5956
+ [...businessTaskToRoutineMaps, ...localMetaTaskToRoutineMaps].map((map) => [
5957
+ `${map.service_name}|${map.task_name}|${map.task_version}|${map.routine_name}|${map.routine_version}`,
5958
+ map
5959
+ ])
5960
+ ).values()
5961
+ );
5962
+ const manifestBody = {
5963
+ serviceName,
5964
+ serviceInstanceId,
5965
+ publicationLayer,
5966
+ tasks: cumulativeTasks,
5967
+ signals: cumulativeSignals,
5968
+ intents: cumulativeIntents,
5969
+ actors: cumulativeActors,
5970
+ routines: cumulativeRoutines,
5971
+ helpers: cumulativeHelpers,
5972
+ globals: cumulativeGlobals,
5973
+ directionalTaskMaps: cumulativeDirectionalTaskMaps,
5974
+ signalToTaskMaps: publicationLayer === "routing_capability" ? publishedSignalTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps] : [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps],
5975
+ intentToTaskMaps: publicationLayer === "routing_capability" ? publishedIntentTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps] : [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps],
5976
+ actorTaskMaps: cumulativeActorTaskMaps,
5977
+ taskToRoutineMaps: cumulativeTaskToRoutineMaps,
5978
+ taskToHelperMaps: cumulativeTaskToHelperMaps,
5979
+ helperToHelperMaps: cumulativeHelperToHelperMaps,
5980
+ taskToGlobalMaps: cumulativeTaskToGlobalMaps,
5981
+ helperToGlobalMaps: cumulativeHelperToGlobalMaps
4919
5982
  };
4920
5983
  return {
4921
5984
  ...manifestBody,
@@ -4959,6 +6022,20 @@ function explodeServiceManifestSnapshots(snapshots) {
4959
6022
  `${right.service_name}|${right.name}|${right.version}`
4960
6023
  )
4961
6024
  );
6025
+ const helpers = dedupe(
6026
+ snapshots.flatMap((snapshot) => snapshot.helpers),
6027
+ (helper) => `${helper.service_name}|${helper.name}|${helper.version}`,
6028
+ (left, right) => `${left.service_name}|${left.name}|${left.version}`.localeCompare(
6029
+ `${right.service_name}|${right.name}|${right.version}`
6030
+ )
6031
+ );
6032
+ const globals = dedupe(
6033
+ snapshots.flatMap((snapshot) => snapshot.globals),
6034
+ (globalDefinition) => `${globalDefinition.service_name}|${globalDefinition.name}|${globalDefinition.version}`,
6035
+ (left, right) => `${left.service_name}|${left.name}|${left.version}`.localeCompare(
6036
+ `${right.service_name}|${right.name}|${right.version}`
6037
+ )
6038
+ );
4962
6039
  const directionalTaskMaps = dedupe(
4963
6040
  snapshots.flatMap((snapshot) => snapshot.directionalTaskMaps),
4964
6041
  (map) => `${map.predecessor_service_name}|${map.predecessor_task_name}|${map.predecessor_task_version}|${map.service_name}|${map.task_name}|${map.task_version}`,
@@ -4994,17 +6071,51 @@ function explodeServiceManifestSnapshots(snapshots) {
4994
6071
  `${right.routine_name}|${right.routine_version}|${right.service_name}|${right.task_name}|${right.task_version}`
4995
6072
  )
4996
6073
  );
6074
+ const taskToHelperMaps = dedupe(
6075
+ snapshots.flatMap((snapshot) => snapshot.taskToHelperMaps),
6076
+ (map) => `${map.service_name}|${map.task_name}|${map.task_version}|${map.alias}|${map.helper_name}|${map.helper_version}`,
6077
+ (left, right) => `${left.service_name}|${left.task_name}|${left.alias}|${left.helper_name}`.localeCompare(
6078
+ `${right.service_name}|${right.task_name}|${right.alias}|${right.helper_name}`
6079
+ )
6080
+ );
6081
+ const helperToHelperMaps = dedupe(
6082
+ snapshots.flatMap((snapshot) => snapshot.helperToHelperMaps),
6083
+ (map) => `${map.service_name}|${map.helper_name}|${map.helper_version}|${map.alias}|${map.dependency_helper_name}|${map.dependency_helper_version}`,
6084
+ (left, right) => `${left.service_name}|${left.helper_name}|${left.alias}|${left.dependency_helper_name}`.localeCompare(
6085
+ `${right.service_name}|${right.helper_name}|${right.alias}|${right.dependency_helper_name}`
6086
+ )
6087
+ );
6088
+ const taskToGlobalMaps = dedupe(
6089
+ snapshots.flatMap((snapshot) => snapshot.taskToGlobalMaps),
6090
+ (map) => `${map.service_name}|${map.task_name}|${map.task_version}|${map.alias}|${map.global_name}|${map.global_version}`,
6091
+ (left, right) => `${left.service_name}|${left.task_name}|${left.alias}|${left.global_name}`.localeCompare(
6092
+ `${right.service_name}|${right.task_name}|${right.alias}|${right.global_name}`
6093
+ )
6094
+ );
6095
+ const helperToGlobalMaps = dedupe(
6096
+ snapshots.flatMap((snapshot) => snapshot.helperToGlobalMaps),
6097
+ (map) => `${map.service_name}|${map.helper_name}|${map.helper_version}|${map.alias}|${map.global_name}|${map.global_version}`,
6098
+ (left, right) => `${left.service_name}|${left.helper_name}|${left.alias}|${left.global_name}`.localeCompare(
6099
+ `${right.service_name}|${right.helper_name}|${right.alias}|${right.global_name}`
6100
+ )
6101
+ );
4997
6102
  return {
4998
6103
  tasks,
4999
6104
  signals,
5000
6105
  intents,
5001
6106
  actors,
5002
6107
  routines,
6108
+ helpers,
6109
+ globals,
5003
6110
  directionalTaskMaps,
5004
6111
  signalToTaskMaps,
5005
6112
  intentToTaskMaps,
5006
6113
  actorTaskMaps,
5007
- taskToRoutineMaps
6114
+ taskToRoutineMaps,
6115
+ taskToHelperMaps,
6116
+ helperToHelperMaps,
6117
+ taskToGlobalMaps,
6118
+ helperToGlobalMaps
5008
6119
  };
5009
6120
  }
5010
6121
 
@@ -5053,7 +6164,53 @@ var SERVICE_REGISTRY_TRACE_SERVICE2 = (process.env.CADENZA_SERVICE_REGISTRY_TRAC
5053
6164
  function shouldTraceServiceRegistry(serviceName) {
5054
6165
  return SERVICE_REGISTRY_TRACE_SERVICE2.length > 0 && serviceName === SERVICE_REGISTRY_TRACE_SERVICE2;
5055
6166
  }
5056
- function buildServiceRegistryInsertQueryData(ctx, queryData) {
6167
+ function normalizeLeaseStatus(value) {
6168
+ const status = String(value ?? "").trim();
6169
+ if (status === "active" || status === "non_responsive" || status === "inactive" || status === "deleted") {
6170
+ return status;
6171
+ }
6172
+ return null;
6173
+ }
6174
+ function overlayServiceInstancesWithLeases(serviceInstances, serviceInstanceLeases) {
6175
+ if (serviceInstanceLeases.length === 0) {
6176
+ return serviceInstances;
6177
+ }
6178
+ const leasesByInstanceId = /* @__PURE__ */ new Map();
6179
+ for (const row of serviceInstanceLeases) {
6180
+ const serviceInstanceId = String(
6181
+ row.service_instance_id ?? row.serviceInstanceId ?? ""
6182
+ ).trim();
6183
+ if (!serviceInstanceId) {
6184
+ continue;
6185
+ }
6186
+ leasesByInstanceId.set(serviceInstanceId, row);
6187
+ }
6188
+ return serviceInstances.map((row) => {
6189
+ const serviceInstanceId = String(row.uuid ?? "").trim();
6190
+ const lease = serviceInstanceId ? leasesByInstanceId.get(serviceInstanceId) : void 0;
6191
+ if (!lease) {
6192
+ return row;
6193
+ }
6194
+ const leaseStatus = normalizeLeaseStatus(
6195
+ lease.status ?? lease.lease_status ?? lease.leaseStatus
6196
+ );
6197
+ return {
6198
+ ...row,
6199
+ lease_status: leaseStatus ?? void 0,
6200
+ is_ready: typeof lease.is_ready === "boolean" ? lease.is_ready : typeof lease.isReady === "boolean" ? lease.isReady : void 0,
6201
+ readiness_reason: typeof lease.readiness_reason === "string" ? lease.readiness_reason : typeof lease.readinessReason === "string" ? lease.readinessReason : null,
6202
+ lease_expires_at: typeof lease.lease_expires_at === "string" ? lease.lease_expires_at : typeof lease.leaseExpiresAt === "string" ? lease.leaseExpiresAt : null,
6203
+ last_lease_renewed_at: typeof lease.last_lease_renewed_at === "string" ? lease.last_lease_renewed_at : typeof lease.lastLeaseRenewedAt === "string" ? lease.lastLeaseRenewedAt : null,
6204
+ last_ready_at: typeof lease.last_ready_at === "string" ? lease.last_ready_at : typeof lease.lastReadyAt === "string" ? lease.lastReadyAt : null,
6205
+ last_observed_transport_at: typeof lease.last_observed_transport_at === "string" ? lease.last_observed_transport_at : typeof lease.lastObservedTransportAt === "string" ? lease.lastObservedTransportAt : null,
6206
+ shutdown_requested_at: typeof lease.shutdown_requested_at === "string" ? lease.shutdown_requested_at : typeof lease.shutdownRequestedAt === "string" ? lease.shutdownRequestedAt : null,
6207
+ is_active: leaseStatus === "active" ? true : leaseStatus === "non_responsive" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : row.is_active,
6208
+ is_non_responsive: leaseStatus === "non_responsive" ? true : leaseStatus === "active" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : row.is_non_responsive,
6209
+ deleted: leaseStatus === "deleted" ? true : Boolean(row.deleted ?? false)
6210
+ };
6211
+ });
6212
+ }
6213
+ function buildServiceRegistryInsertQueryData(tableName, ctx, queryData) {
5057
6214
  const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
5058
6215
  const getJoinedValue = (key) => {
5059
6216
  for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
@@ -5071,7 +6228,8 @@ function buildServiceRegistryInsertQueryData(ctx, queryData) {
5071
6228
  if (!Object.prototype.hasOwnProperty.call(queryData, "onConflict")) {
5072
6229
  delete nextQueryData.onConflict;
5073
6230
  }
5074
- const resolvedData = Object.prototype.hasOwnProperty.call(ctx, "data") || ctx.data !== void 0 ? ctx.data : getJoinedValue("data");
6231
+ const preferRegistrationData = tableName === "service" || tableName === "service_instance" || tableName === "service_instance_transport";
6232
+ 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");
5075
6233
  const resolvedBatch = Object.prototype.hasOwnProperty.call(ctx, "batch") || ctx.batch !== void 0 ? ctx.batch : getJoinedValue("batch");
5076
6234
  const nextData = resolvedData !== void 0 ? resolvedData && typeof resolvedData === "object" ? { ...resolvedData } : resolvedData : registrationData && typeof registrationData === "object" && !Array.isArray(registrationData) ? { ...registrationData } : registrationData;
5077
6235
  if (nextData !== void 0) {
@@ -5098,8 +6256,151 @@ function sanitizeServiceRegistryInsertExecutionContext(ctx) {
5098
6256
  delete sanitized.returnedValue;
5099
6257
  delete sanitized.queryData;
5100
6258
  delete sanitized.onConflict;
6259
+ delete sanitized.task;
6260
+ delete sanitized.routine;
6261
+ delete sanitized.httpServer;
6262
+ delete sanitized.service;
6263
+ delete sanitized.serviceInstance;
6264
+ delete sanitized.joinedContexts;
6265
+ delete sanitized.__declaredTransports;
6266
+ delete sanitized.__resolverOriginalContext;
6267
+ delete sanitized.__resolverQueryData;
5101
6268
  return sanitized;
5102
6269
  }
6270
+ function sanitizeAuthorityBootstrapDelegationContext(ctx) {
6271
+ const sanitized = stripDelegationRequestSnapshot({
6272
+ ...ctx
6273
+ });
6274
+ delete sanitized.__resolverOriginalContext;
6275
+ delete sanitized.__resolverQueryData;
6276
+ delete sanitized.joinedContexts;
6277
+ delete sanitized.httpServer;
6278
+ delete sanitized.service;
6279
+ delete sanitized.serviceInstance;
6280
+ delete sanitized.task;
6281
+ delete sanitized.routine;
6282
+ delete sanitized.__declaredTransports;
6283
+ const queryData = sanitized.queryData && typeof sanitized.queryData === "object" ? { ...sanitized.queryData } : null;
6284
+ if (queryData) {
6285
+ delete queryData.joinedContexts;
6286
+ sanitized.queryData = queryData;
6287
+ }
6288
+ return sanitized;
6289
+ }
6290
+ var BOOTSTRAP_DB_OPERATION_CONTEXT_KEYS = [
6291
+ "data",
6292
+ "batch",
6293
+ "transaction",
6294
+ "onConflict",
6295
+ "filter",
6296
+ "fields",
6297
+ "joins",
6298
+ "sort",
6299
+ "limit",
6300
+ "offset",
6301
+ "queryMode",
6302
+ "aggregates",
6303
+ "groupBy"
6304
+ ];
6305
+ function isBootstrapDbOperationRoutineName(value) {
6306
+ return /^(Insert|Update|Query|Delete)\s+/.test(String(value ?? "").trim());
6307
+ }
6308
+ function compactAuthorityBootstrapRequestBody(ctx) {
6309
+ if (!isBootstrapDbOperationRoutineName(ctx.__remoteRoutineName)) {
6310
+ return ctx;
6311
+ }
6312
+ const queryData = ctx.queryData && typeof ctx.queryData === "object" ? { ...ctx.queryData } : null;
6313
+ if (!queryData) {
6314
+ return ctx;
6315
+ }
6316
+ const compacted = {
6317
+ ...ctx,
6318
+ queryData
6319
+ };
6320
+ for (const key of BOOTSTRAP_DB_OPERATION_CONTEXT_KEYS) {
6321
+ if (Object.prototype.hasOwnProperty.call(queryData, key)) {
6322
+ delete compacted[key];
6323
+ }
6324
+ }
6325
+ return compacted;
6326
+ }
6327
+ function cloneServiceRegistryContextValue(value) {
6328
+ if (value instanceof Date) {
6329
+ return new Date(value.getTime());
6330
+ }
6331
+ if (Array.isArray(value)) {
6332
+ return value.map(
6333
+ (entry) => cloneServiceRegistryContextValue(entry)
6334
+ );
6335
+ }
6336
+ if (value && typeof value === "object") {
6337
+ const clone = {};
6338
+ for (const [key, nestedValue] of Object.entries(value)) {
6339
+ clone[key] = cloneServiceRegistryContextValue(nestedValue);
6340
+ }
6341
+ return clone;
6342
+ }
6343
+ return value;
6344
+ }
6345
+ function buildServiceRegistryResolverOriginalContext(tableName, ctx, queryData) {
6346
+ const originalContext = {};
6347
+ for (const key of [
6348
+ "__serviceName",
6349
+ "serviceName",
6350
+ "__serviceInstanceId",
6351
+ "serviceInstanceId",
6352
+ "__registrationData",
6353
+ "__reason",
6354
+ "__syncing",
6355
+ "__syncSourceServiceName",
6356
+ "__preferredTransportProtocol",
6357
+ "__networkMode",
6358
+ "__securityProfile",
6359
+ "__loadBalance",
6360
+ "__cadenzaDBConnect",
6361
+ "__isFrontend",
6362
+ "__isDatabase",
6363
+ "__retryCount",
6364
+ "__retries",
6365
+ "__triedInstances"
6366
+ ]) {
6367
+ if (ctx[key] !== void 0) {
6368
+ originalContext[key] = cloneServiceRegistryContextValue(ctx[key]);
6369
+ }
6370
+ }
6371
+ if (queryData.data !== void 0) {
6372
+ originalContext.data = cloneServiceRegistryContextValue(queryData.data);
6373
+ }
6374
+ if (queryData.batch !== void 0) {
6375
+ originalContext.batch = cloneServiceRegistryContextValue(queryData.batch);
6376
+ }
6377
+ if (Object.prototype.hasOwnProperty.call(queryData, "onConflict")) {
6378
+ originalContext.queryData = {
6379
+ data: queryData.data !== void 0 ? cloneServiceRegistryContextValue(queryData.data) : void 0,
6380
+ batch: queryData.batch !== void 0 ? cloneServiceRegistryContextValue(queryData.batch) : void 0,
6381
+ onConflict: cloneServiceRegistryContextValue(queryData.onConflict)
6382
+ };
6383
+ } else if (queryData.data !== void 0 || queryData.batch !== void 0) {
6384
+ originalContext.queryData = {
6385
+ data: queryData.data !== void 0 ? cloneServiceRegistryContextValue(queryData.data) : void 0,
6386
+ batch: queryData.batch !== void 0 ? cloneServiceRegistryContextValue(queryData.batch) : void 0
6387
+ };
6388
+ }
6389
+ if (tableName === "service_instance") {
6390
+ for (const key of [
6391
+ "__transportData",
6392
+ "transportData",
6393
+ "__useSocket",
6394
+ "__retryCount",
6395
+ "__isFrontend"
6396
+ ]) {
6397
+ if (ctx[key] !== void 0) {
6398
+ originalContext[key] = cloneServiceRegistryContextValue(ctx[key]);
6399
+ }
6400
+ }
6401
+ }
6402
+ return originalContext;
6403
+ }
5103
6404
  function clearTransientRoutingErrorState(context) {
5104
6405
  delete context.errored;
5105
6406
  delete context.failed;
@@ -5155,7 +6456,8 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
5155
6456
  delete result.__resolverOriginalContext;
5156
6457
  delete result.__resolverQueryData;
5157
6458
  const normalizedQueryData = result.queryData && typeof result.queryData === "object" ? { ...result.queryData } : { ...queryData };
5158
- const resolvedData = result.data ?? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData;
6459
+ const preferRequestedData = tableName === "service" || tableName === "service_instance" || tableName === "service_instance_transport";
6460
+ const resolvedData = preferRequestedData ? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData ?? result.data : result.data ?? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData;
5159
6461
  if (resolvedData !== void 0 && result.data === void 0) {
5160
6462
  result.data = resolvedData;
5161
6463
  }
@@ -5185,6 +6487,7 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
5185
6487
  ).trim();
5186
6488
  if (resolvedServiceName) {
5187
6489
  result.__serviceName = resolvedServiceName;
6490
+ result.serviceName = resolvedServiceName;
5188
6491
  }
5189
6492
  }
5190
6493
  const resolvedLocalServiceInstanceId = String(
@@ -5193,6 +6496,18 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
5193
6496
  if (resolvedLocalServiceInstanceId) {
5194
6497
  result.__serviceInstanceId = resolvedLocalServiceInstanceId;
5195
6498
  }
6499
+ if (tableName === "service_instance") {
6500
+ const resolvedServiceName = String(
6501
+ ctx.__serviceName ?? resolveServiceNameFromContext(ctx) ?? resolvedData?.service_name ?? resolvedData?.serviceName ?? ""
6502
+ ).trim();
6503
+ if (resolvedServiceName) {
6504
+ result.__serviceName = resolvedServiceName;
6505
+ result.serviceName = resolvedServiceName;
6506
+ }
6507
+ if (resolvedLocalServiceInstanceId) {
6508
+ result.serviceInstanceId = resolvedLocalServiceInstanceId;
6509
+ }
6510
+ }
5196
6511
  if (tableName === "service_instance" || tableName === "service_instance_transport") {
5197
6512
  const resolvedUuid = String(
5198
6513
  result.uuid ?? resolvedData?.uuid ?? ctx.__serviceInstanceId ?? ""
@@ -5292,9 +6607,15 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5292
6607
  ctx
5293
6608
  );
5294
6609
  const nextQueryData = buildServiceRegistryInsertQueryData(
6610
+ tableName,
5295
6611
  sanitizedContext,
5296
6612
  queryData
5297
6613
  );
6614
+ const resolverOriginalContext = buildServiceRegistryResolverOriginalContext(
6615
+ tableName,
6616
+ sanitizedContext,
6617
+ nextQueryData
6618
+ );
5298
6619
  const delegationContext = ensureDelegationContextMetadata({
5299
6620
  ...sanitizedContext,
5300
6621
  data: nextQueryData.data !== void 0 ? nextQueryData.data : sanitizedContext.data,
@@ -5307,9 +6628,7 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5307
6628
  delegationContext.__metadata.__blockRemoteExecution = delegationContext.__metadata.__blockRemoteExecution ?? delegationContext.__blockRemoteExecution ?? false;
5308
6629
  const nextContext = {
5309
6630
  ...delegationContext,
5310
- __resolverOriginalContext: {
5311
- ...sanitizedContext
5312
- },
6631
+ __resolverOriginalContext: resolverOriginalContext,
5313
6632
  __resolverQueryData: nextQueryData
5314
6633
  };
5315
6634
  if (tableName === "service_instance_transport" && shouldTraceServiceRegistry(
@@ -5361,108 +6680,6 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5361
6680
  `Resolve service registry insert for ${tableName}`,
5362
6681
  (ctx, emit2) => new Promise((resolve) => {
5363
6682
  const resolverRequestId = uuid3();
5364
- CadenzaService.createEphemeralMetaTask(
5365
- `Resolve service registry insert execution for ${tableName} (${resolverRequestId})`,
5366
- (resultCtx) => {
5367
- if (tableName === "service_instance" && shouldTraceServiceRegistry(
5368
- resolveServiceNameFromContext(
5369
- resultCtx.__resolverOriginalContext ?? resultCtx ?? ctx
5370
- ) || CadenzaService.serviceRegistry.serviceName
5371
- )) {
5372
- console.log("[CADENZA_SERVICE_REGISTRY_TRACE] resolver_service_instance_signal", {
5373
- localServiceName: CadenzaService.serviceRegistry.serviceName,
5374
- resolverRequestId,
5375
- incomingResolverRequestId: resultCtx.__resolverRequestId ?? null,
5376
- keys: resultCtx && typeof resultCtx === "object" ? Object.keys(resultCtx) : []
5377
- });
5378
- }
5379
- if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
5380
- console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert_signal", {
5381
- tableName,
5382
- resolverRequestId,
5383
- incomingResolverRequestId: resultCtx.__resolverRequestId ?? null,
5384
- errored: resultCtx.errored === true,
5385
- error: resultCtx.__error ?? null,
5386
- keys: resultCtx && typeof resultCtx === "object" ? Object.keys(resultCtx) : []
5387
- });
5388
- }
5389
- if (resultCtx.__resolverRequestId !== resolverRequestId) {
5390
- return false;
5391
- }
5392
- const normalizedResult = normalizeServiceRegistryInsertResult(
5393
- tableName,
5394
- resultCtx.__resolverOriginalContext ?? ctx,
5395
- resultCtx.__resolverQueryData ?? resultCtx.queryData ?? ctx.queryData ?? {},
5396
- resultCtx
5397
- );
5398
- if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
5399
- console.log("[CADENZA_INSTANCE_DEBUG] finalize_service_registry_insert", {
5400
- tableName,
5401
- hasNormalized: !!normalizedResult,
5402
- normalizedKeys: normalizedResult && typeof normalizedResult === "object" ? Object.keys(normalizedResult) : [],
5403
- uuid: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.uuid ?? normalizedResult.data?.uuid ?? normalizedResult.queryData?.data?.uuid ?? null : null,
5404
- serviceName: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__serviceName ?? normalizedResult.data?.service_name ?? normalizedResult.queryData?.data?.service_name ?? null : null,
5405
- errored: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.errored === true : false,
5406
- error: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__error ?? null : null,
5407
- inquiryMeta: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__inquiryMeta ?? null : null
5408
- });
5409
- }
5410
- if (normalizedResult && typeof normalizedResult === "object" && tableName === "service_instance_transport" && shouldTraceServiceRegistry(
5411
- resolveServiceNameFromContext(
5412
- resultCtx.__resolverOriginalContext ?? resultCtx
5413
- ) || CadenzaService.serviceRegistry.serviceName
5414
- )) {
5415
- console.log("[CADENZA_SERVICE_REGISTRY_TRACE] finalize_transport_insert_execution", {
5416
- localServiceName: CadenzaService.serviceRegistry.serviceName,
5417
- serviceName: resolveServiceNameFromContext(
5418
- resultCtx.__resolverOriginalContext ?? resultCtx
5419
- ) || CadenzaService.serviceRegistry.serviceName,
5420
- uuid: normalizedResult.uuid ?? normalizedResult.data?.uuid ?? null,
5421
- errored: normalizedResult.errored === true,
5422
- error: normalizedResult.__error ?? null,
5423
- data: normalizedResult.data ?? normalizedResult.queryData?.data ?? null
5424
- });
5425
- }
5426
- if (normalizedResult && typeof normalizedResult === "object" && tableName === "service_instance") {
5427
- const traceServiceName = resolveServiceNameFromContext(
5428
- resultCtx.__resolverOriginalContext ?? resultCtx
5429
- ) || CadenzaService.serviceRegistry.serviceName;
5430
- if (shouldTraceServiceRegistry(traceServiceName)) {
5431
- console.log("[CADENZA_SERVICE_REGISTRY_TRACE] service_instance_insert_resolved", {
5432
- localServiceName: CadenzaService.serviceRegistry.serviceName,
5433
- serviceName: traceServiceName,
5434
- serviceInstanceId: normalizedResult.__serviceInstanceId ?? normalizedResult.uuid ?? normalizedResult.data?.uuid ?? null,
5435
- hasTransportData: Array.isArray(normalizedResult.__transportData) || Array.isArray(normalizedResult.transportData),
5436
- transportCount: Array.isArray(
5437
- normalizedResult.__transportData
5438
- ) ? normalizedResult.__transportData.length : Array.isArray(normalizedResult.transportData) ? normalizedResult.transportData.length : 0,
5439
- errored: normalizedResult.errored === true,
5440
- error: normalizedResult.__error ?? null
5441
- });
5442
- }
5443
- emit2(
5444
- META_SERVICE_INSTANCE_INSERT_RESOLVED_SIGNAL,
5445
- normalizedResult
5446
- );
5447
- }
5448
- if (!normalizedResult || typeof normalizedResult !== "object") {
5449
- resolve(normalizedResult);
5450
- return normalizedResult;
5451
- }
5452
- const resolvedResult = {
5453
- ...normalizedResult
5454
- };
5455
- delete resolvedResult.__resolverRequestId;
5456
- delete resolvedResult.__resolverOriginalContext;
5457
- delete resolvedResult.__resolverQueryData;
5458
- resolve(resolvedResult);
5459
- return resolvedResult;
5460
- },
5461
- `Resolves signal-driven ${tableName} service-registry insert execution.`,
5462
- {
5463
- register: false
5464
- }
5465
- ).doOn(executionResolvedSignal, executionFailedSignal);
5466
6683
  const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
5467
6684
  const bootstrapAuthorityInsertSpec = !localInsertTask && CadenzaService.serviceRegistry.connectsToCadenzaDB ? getAuthorityBootstrapInsertIntentSpecForTable(tableName) : null;
5468
6685
  const resolvedTargetServiceName = resolveServiceNameFromContext(ctx);
@@ -5481,6 +6698,7 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5481
6698
  if (bootstrapAuthorityInsertSpec) {
5482
6699
  const sanitizedContext = sanitizeServiceRegistryInsertExecutionContext(ctx);
5483
6700
  const nextQueryData = buildServiceRegistryInsertQueryData(
6701
+ tableName,
5484
6702
  sanitizedContext,
5485
6703
  queryData
5486
6704
  );
@@ -5548,6 +6766,110 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5548
6766
  wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
5549
6767
  wiredLocalTaskNames.add(localInsertTask.name);
5550
6768
  }
6769
+ CadenzaService.createEphemeralMetaTask(
6770
+ `Resolve service registry insert execution for ${tableName} (${resolverRequestId})`,
6771
+ (resultCtx) => {
6772
+ if (tableName === "service_instance" && shouldTraceServiceRegistry(
6773
+ resolveServiceNameFromContext(
6774
+ resultCtx.__resolverOriginalContext ?? resultCtx ?? ctx
6775
+ ) || CadenzaService.serviceRegistry.serviceName
6776
+ )) {
6777
+ console.log("[CADENZA_SERVICE_REGISTRY_TRACE] resolver_service_instance_signal", {
6778
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
6779
+ resolverRequestId,
6780
+ incomingResolverRequestId: resultCtx.__resolverRequestId ?? null,
6781
+ keys: resultCtx && typeof resultCtx === "object" ? Object.keys(resultCtx) : []
6782
+ });
6783
+ }
6784
+ if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
6785
+ console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert_signal", {
6786
+ tableName,
6787
+ resolverRequestId,
6788
+ incomingResolverRequestId: resultCtx.__resolverRequestId ?? null,
6789
+ errored: resultCtx.errored === true,
6790
+ error: resultCtx.__error ?? null,
6791
+ keys: resultCtx && typeof resultCtx === "object" ? Object.keys(resultCtx) : []
6792
+ });
6793
+ }
6794
+ if (resultCtx.__resolverRequestId !== resolverRequestId) {
6795
+ return false;
6796
+ }
6797
+ const normalizedResult = normalizeServiceRegistryInsertResult(
6798
+ tableName,
6799
+ resultCtx.__resolverOriginalContext ?? ctx,
6800
+ resultCtx.__resolverQueryData ?? resultCtx.queryData ?? ctx.queryData ?? {},
6801
+ resultCtx
6802
+ );
6803
+ if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
6804
+ console.log("[CADENZA_INSTANCE_DEBUG] finalize_service_registry_insert", {
6805
+ tableName,
6806
+ hasNormalized: !!normalizedResult,
6807
+ normalizedKeys: normalizedResult && typeof normalizedResult === "object" ? Object.keys(normalizedResult) : [],
6808
+ uuid: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.uuid ?? normalizedResult.data?.uuid ?? normalizedResult.queryData?.data?.uuid ?? null : null,
6809
+ serviceName: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__serviceName ?? normalizedResult.data?.service_name ?? normalizedResult.queryData?.data?.service_name ?? null : null,
6810
+ errored: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.errored === true : false,
6811
+ error: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__error ?? null : null,
6812
+ inquiryMeta: normalizedResult && typeof normalizedResult === "object" ? normalizedResult.__inquiryMeta ?? null : null
6813
+ });
6814
+ }
6815
+ if (normalizedResult && typeof normalizedResult === "object" && tableName === "service_instance_transport" && shouldTraceServiceRegistry(
6816
+ resolveServiceNameFromContext(
6817
+ resultCtx.__resolverOriginalContext ?? resultCtx
6818
+ ) || CadenzaService.serviceRegistry.serviceName
6819
+ )) {
6820
+ console.log("[CADENZA_SERVICE_REGISTRY_TRACE] finalize_transport_insert_execution", {
6821
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
6822
+ serviceName: resolveServiceNameFromContext(
6823
+ resultCtx.__resolverOriginalContext ?? resultCtx
6824
+ ) || CadenzaService.serviceRegistry.serviceName,
6825
+ uuid: normalizedResult.uuid ?? normalizedResult.data?.uuid ?? null,
6826
+ errored: normalizedResult.errored === true,
6827
+ error: normalizedResult.__error ?? null,
6828
+ data: normalizedResult.data ?? normalizedResult.queryData?.data ?? null
6829
+ });
6830
+ }
6831
+ if (normalizedResult && typeof normalizedResult === "object" && tableName === "service_instance") {
6832
+ const traceServiceName = resolveServiceNameFromContext(
6833
+ resultCtx.__resolverOriginalContext ?? resultCtx
6834
+ ) || CadenzaService.serviceRegistry.serviceName;
6835
+ if (shouldTraceServiceRegistry(traceServiceName)) {
6836
+ console.log("[CADENZA_SERVICE_REGISTRY_TRACE] service_instance_insert_resolved", {
6837
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
6838
+ serviceName: traceServiceName,
6839
+ serviceInstanceId: normalizedResult.__serviceInstanceId ?? normalizedResult.uuid ?? normalizedResult.data?.uuid ?? null,
6840
+ hasTransportData: Array.isArray(normalizedResult.__transportData) || Array.isArray(normalizedResult.transportData),
6841
+ transportCount: Array.isArray(
6842
+ normalizedResult.__transportData
6843
+ ) ? normalizedResult.__transportData.length : Array.isArray(normalizedResult.transportData) ? normalizedResult.transportData.length : 0,
6844
+ errored: normalizedResult.errored === true,
6845
+ error: normalizedResult.__error ?? null
6846
+ });
6847
+ }
6848
+ emit2(
6849
+ META_SERVICE_INSTANCE_INSERT_RESOLVED_SIGNAL,
6850
+ normalizedResult
6851
+ );
6852
+ }
6853
+ if (!normalizedResult || typeof normalizedResult !== "object") {
6854
+ resolve(normalizedResult);
6855
+ return normalizedResult;
6856
+ }
6857
+ const resolvedResult = {
6858
+ ...normalizedResult
6859
+ };
6860
+ delete resolvedResult.__resolverRequestId;
6861
+ delete resolvedResult.__resolverOriginalContext;
6862
+ delete resolvedResult.__resolverQueryData;
6863
+ resolve(resolvedResult);
6864
+ return resolvedResult;
6865
+ },
6866
+ `Resolves signal-driven ${tableName} service-registry insert execution.`,
6867
+ {
6868
+ register: false,
6869
+ once: false,
6870
+ destroyCondition: (result) => result !== false
6871
+ }
6872
+ ).doOn(executionResolvedSignal, executionFailedSignal);
5551
6873
  emit2(executionSignal, {
5552
6874
  ...ctx,
5553
6875
  __resolverRequestId: resolverRequestId
@@ -5572,6 +6894,17 @@ function readPositiveIntegerEnv(name, fallback) {
5572
6894
  }
5573
6895
  return normalized;
5574
6896
  }
6897
+ function readNonNegativeFloatEnv(name, fallback) {
6898
+ if (typeof process === "undefined") {
6899
+ return fallback;
6900
+ }
6901
+ const raw = process.env?.[name];
6902
+ const parsed = Number(raw);
6903
+ if (!Number.isFinite(parsed) || parsed < 0) {
6904
+ return fallback;
6905
+ }
6906
+ return parsed;
6907
+ }
5575
6908
  var ServiceRegistry = class _ServiceRegistry {
5576
6909
  /**
5577
6910
  * Initializes a private constructor for managing service instances, remote signals,
@@ -5621,6 +6954,9 @@ var ServiceRegistry = class _ServiceRegistry {
5621
6954
  "CADENZA_RUNTIME_STATUS_REST_REFRESH_MS",
5622
6955
  this.runtimeMetricsSampleIntervalMs
5623
6956
  );
6957
+ this.runtimeStatusLoopJitterRatio = normalizeJitterRatio(
6958
+ readNonNegativeFloatEnv("CADENZA_RUNTIME_STATUS_JITTER_RATIO", 0.2)
6959
+ );
5624
6960
  this.runtimeStatusMissThreshold = readPositiveIntegerEnv(
5625
6961
  "CADENZA_RUNTIME_STATUS_MISSED_HEARTBEATS",
5626
6962
  3
@@ -5669,6 +7005,18 @@ var ServiceRegistry = class _ServiceRegistry {
5669
7005
  "CADENZA_RUNTIME_STATUS_OVERLOADED_GRAPH_THRESHOLD",
5670
7006
  20
5671
7007
  );
7008
+ this.bootstrapFullSyncRetryJitterRatio = normalizeJitterRatio(
7009
+ readNonNegativeFloatEnv(
7010
+ "CADENZA_BOOTSTRAP_FULL_SYNC_RETRY_JITTER_RATIO",
7011
+ 0.2
7012
+ )
7013
+ );
7014
+ this.serviceCommunicationRetryJitterRatio = normalizeJitterRatio(
7015
+ readNonNegativeFloatEnv(
7016
+ "CADENZA_SERVICE_COMMUNICATION_RETRY_JITTER_RATIO",
7017
+ 0.2
7018
+ )
7019
+ );
5672
7020
  this.serviceName = null;
5673
7021
  this.serviceInstanceId = null;
5674
7022
  this.numberOfRunningGraphs = 0;
@@ -5915,6 +7263,9 @@ var ServiceRegistry = class _ServiceRegistry {
5915
7263
  ctx.deleted ?? ctx.serviceInstance?.deleted ?? ctx.data?.deleted
5916
7264
  );
5917
7265
  if (uuid10 === this.serviceInstanceId) return;
7266
+ if (serviceName === this.serviceName) {
7267
+ return false;
7268
+ }
5918
7269
  if (deleted) {
5919
7270
  const existingInstance = this.instances.get(serviceName)?.find((instance) => instance.uuid === uuid10);
5920
7271
  const indexToDelete = this.instances.get(serviceName)?.findIndex((i) => i.uuid === uuid10) ?? -1;
@@ -6001,9 +7352,6 @@ var ServiceRegistry = class _ServiceRegistry {
6001
7352
  emit2
6002
7353
  );
6003
7354
  }
6004
- if (this.serviceName === serviceName) {
6005
- return false;
6006
- }
6007
7355
  if (trackedInstance?.isFrontend) {
6008
7356
  return true;
6009
7357
  }
@@ -6057,6 +7405,9 @@ var ServiceRegistry = class _ServiceRegistry {
6057
7405
  if (!ownerInstance) {
6058
7406
  return false;
6059
7407
  }
7408
+ if (ownerInstance.serviceName === this.serviceName && ownerInstance.uuid !== this.serviceInstanceId) {
7409
+ return false;
7410
+ }
6060
7411
  if (transport.deleted) {
6061
7412
  this.clearTransportFailureState(ownerInstance.uuid, transport.uuid);
6062
7413
  const transportKey = this.buildTransportRouteKey(
@@ -6644,6 +7995,12 @@ var ServiceRegistry = class _ServiceRegistry {
6644
7995
  const tasks = this.readArrayPayload(inquiryResult, [
6645
7996
  "tasks"
6646
7997
  ]);
7998
+ const helpers = this.readArrayPayload(inquiryResult, [
7999
+ "helpers"
8000
+ ]);
8001
+ const globals = this.readArrayPayload(inquiryResult, [
8002
+ "globals"
8003
+ ]);
6647
8004
  const signals = this.readArrayPayload(inquiryResult, [
6648
8005
  "signals"
6649
8006
  ]);
@@ -6668,6 +8025,22 @@ var ServiceRegistry = class _ServiceRegistry {
6668
8025
  inquiryResult,
6669
8026
  ["taskToRoutineMaps", "task_to_routine_maps"]
6670
8027
  );
8028
+ const taskToHelperMaps = this.readArrayPayload(
8029
+ inquiryResult,
8030
+ ["taskToHelperMaps", "task_to_helper_maps"]
8031
+ );
8032
+ const helperToHelperMaps = this.readArrayPayload(
8033
+ inquiryResult,
8034
+ ["helperToHelperMaps", "helper_to_helper_maps"]
8035
+ );
8036
+ const taskToGlobalMaps = this.readArrayPayload(
8037
+ inquiryResult,
8038
+ ["taskToGlobalMaps", "task_to_global_maps"]
8039
+ );
8040
+ const helperToGlobalMaps = this.readArrayPayload(
8041
+ inquiryResult,
8042
+ ["helperToGlobalMaps", "helper_to_global_maps"]
8043
+ );
6671
8044
  const serviceInstances = this.normalizeServiceInstancesFromSync(
6672
8045
  inquiryResult
6673
8046
  );
@@ -6701,6 +8074,8 @@ var ServiceRegistry = class _ServiceRegistry {
6701
8074
  serviceInstanceTransports: serviceInstanceTransports.length,
6702
8075
  serviceManifests: serviceManifests.length,
6703
8076
  tasks: tasks.length,
8077
+ helpers: helpers.length,
8078
+ globals: globals.length,
6704
8079
  signals: signals.length,
6705
8080
  intents: intents.length,
6706
8081
  actors: actors.length,
@@ -6726,6 +8101,8 @@ var ServiceRegistry = class _ServiceRegistry {
6726
8101
  serviceInstanceTransports,
6727
8102
  serviceManifests,
6728
8103
  tasks,
8104
+ helpers,
8105
+ globals,
6729
8106
  signals,
6730
8107
  intents,
6731
8108
  actors,
@@ -6733,6 +8110,10 @@ var ServiceRegistry = class _ServiceRegistry {
6733
8110
  directionalTaskMaps,
6734
8111
  actorTaskMaps,
6735
8112
  taskToRoutineMaps,
8113
+ taskToHelperMaps,
8114
+ helperToHelperMaps,
8115
+ taskToGlobalMaps,
8116
+ helperToGlobalMaps,
6736
8117
  __inquiryMeta: inquiryResult.__inquiryMeta
6737
8118
  };
6738
8119
  },
@@ -7352,29 +8733,51 @@ var ServiceRegistry = class _ServiceRegistry {
7352
8733
  this.runtimeStatusHeartbeatStarted = true;
7353
8734
  if (!this.runtimeMetricsSamplingStarted) {
7354
8735
  this.runtimeMetricsSamplingStarted = true;
8736
+ CadenzaService.emit(META_RUNTIME_METRICS_SAMPLE_TICK_SIGNAL, {});
7355
8737
  CadenzaService.interval(
7356
8738
  META_RUNTIME_METRICS_SAMPLE_TICK_SIGNAL,
7357
8739
  {},
7358
8740
  this.runtimeMetricsSampleIntervalMs,
7359
- true
8741
+ false,
8742
+ this.buildJitteredIntervalStartDate(
8743
+ this.runtimeMetricsSampleIntervalMs,
8744
+ "runtime-metrics-sample"
8745
+ )
7360
8746
  );
7361
8747
  }
8748
+ CadenzaService.emit(META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL, {
8749
+ reason: "heartbeat"
8750
+ });
7362
8751
  CadenzaService.interval(
7363
8752
  META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL,
7364
8753
  { reason: "heartbeat" },
7365
8754
  this.runtimeStatusHeartbeatIntervalMs,
7366
- true
8755
+ false,
8756
+ this.buildJitteredIntervalStartDate(
8757
+ this.runtimeStatusHeartbeatIntervalMs,
8758
+ "runtime-status-heartbeat"
8759
+ )
7367
8760
  );
7368
8761
  CadenzaService.interval(
7369
8762
  META_RUNTIME_STATUS_MONITOR_TICK_SIGNAL,
7370
8763
  {},
7371
- this.runtimeStatusHeartbeatIntervalMs
8764
+ this.runtimeStatusHeartbeatIntervalMs,
8765
+ false,
8766
+ this.buildJitteredIntervalStartDate(
8767
+ this.runtimeStatusHeartbeatIntervalMs,
8768
+ "runtime-status-monitor"
8769
+ )
7372
8770
  );
8771
+ CadenzaService.emit(META_RUNTIME_STATUS_REST_REFRESH_TICK_SIGNAL, {});
7373
8772
  CadenzaService.interval(
7374
8773
  META_RUNTIME_STATUS_REST_REFRESH_TICK_SIGNAL,
7375
8774
  {},
7376
8775
  this.runtimeStatusRestRefreshIntervalMs,
7377
- true
8776
+ false,
8777
+ this.buildJitteredIntervalStartDate(
8778
+ this.runtimeStatusRestRefreshIntervalMs,
8779
+ "runtime-status-rest-refresh"
8780
+ )
7378
8781
  );
7379
8782
  return true;
7380
8783
  },
@@ -8379,11 +9782,14 @@ var ServiceRegistry = class _ServiceRegistry {
8379
9782
  }
8380
9783
  collectBootstrapFullSyncPayload(ctx) {
8381
9784
  const serviceInstances = [];
9785
+ const serviceInstanceLeases = [];
8382
9786
  const serviceInstanceTransports = [];
8383
9787
  const manifestSnapshots = [];
8384
9788
  const signalToTaskMaps = [];
8385
9789
  const intentToTaskMaps = [];
8386
9790
  const tasks = [];
9791
+ const helpers = [];
9792
+ const globals = [];
8387
9793
  const signals = [];
8388
9794
  const intents = [];
8389
9795
  const actors = [];
@@ -8391,11 +9797,18 @@ var ServiceRegistry = class _ServiceRegistry {
8391
9797
  const directionalTaskMaps = [];
8392
9798
  const actorTaskMaps = [];
8393
9799
  const taskToRoutineMaps = [];
9800
+ const taskToHelperMaps = [];
9801
+ const helperToHelperMaps = [];
9802
+ const taskToGlobalMaps = [];
9803
+ const helperToGlobalMaps = [];
8394
9804
  const seenServiceInstances = /* @__PURE__ */ new Set();
9805
+ const seenServiceInstanceLeases = /* @__PURE__ */ new Set();
8395
9806
  const seenServiceInstanceTransports = /* @__PURE__ */ new Set();
8396
9807
  const seenSignalMaps = /* @__PURE__ */ new Set();
8397
9808
  const seenIntentMaps = /* @__PURE__ */ new Set();
8398
9809
  const seenTasks = /* @__PURE__ */ new Set();
9810
+ const seenHelpers = /* @__PURE__ */ new Set();
9811
+ const seenGlobals = /* @__PURE__ */ new Set();
8399
9812
  const seenSignals = /* @__PURE__ */ new Set();
8400
9813
  const seenIntents = /* @__PURE__ */ new Set();
8401
9814
  const seenActors = /* @__PURE__ */ new Set();
@@ -8403,6 +9816,10 @@ var ServiceRegistry = class _ServiceRegistry {
8403
9816
  const seenDirectionalTaskMaps = /* @__PURE__ */ new Set();
8404
9817
  const seenActorTaskMaps = /* @__PURE__ */ new Set();
8405
9818
  const seenTaskToRoutineMaps = /* @__PURE__ */ new Set();
9819
+ const seenTaskToHelperMaps = /* @__PURE__ */ new Set();
9820
+ const seenHelperToHelperMaps = /* @__PURE__ */ new Set();
9821
+ const seenTaskToGlobalMaps = /* @__PURE__ */ new Set();
9822
+ const seenHelperToGlobalMaps = /* @__PURE__ */ new Set();
8406
9823
  const contexts = Array.isArray(ctx.joinedContexts) ? [ctx, ...ctx.joinedContexts] : [ctx];
8407
9824
  const pushUnique = (rows, target, seen, keyResolver) => {
8408
9825
  for (const row of rows) {
@@ -8433,6 +9850,12 @@ var ServiceRegistry = class _ServiceRegistry {
8433
9850
  "serviceInstance",
8434
9851
  "service_instance"
8435
9852
  ]);
9853
+ const serviceInstanceLeaseRows = readDirectArrayPayload(candidate, [
9854
+ "serviceInstanceLeases",
9855
+ "service_instance_leases",
9856
+ "serviceInstanceLease",
9857
+ "service_instance_lease"
9858
+ ]);
8436
9859
  const serviceInstanceTransportRows = readDirectArrayPayload(candidate, [
8437
9860
  "serviceInstanceTransports",
8438
9861
  "service_instance_transports",
@@ -8463,6 +9886,12 @@ var ServiceRegistry = class _ServiceRegistry {
8463
9886
  seenServiceInstances,
8464
9887
  (row) => String(row.uuid ?? "").trim()
8465
9888
  );
9889
+ pushUnique(
9890
+ serviceInstanceLeaseRows,
9891
+ serviceInstanceLeases,
9892
+ seenServiceInstanceLeases,
9893
+ (row) => String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
9894
+ );
8466
9895
  pushUnique(
8467
9896
  serviceInstanceTransportRows,
8468
9897
  serviceInstanceTransports,
@@ -8483,6 +9912,8 @@ var ServiceRegistry = class _ServiceRegistry {
8483
9912
  seenSignalMaps,
8484
9913
  (row) => `${String(row.service_name ?? row.serviceName ?? "").trim()}|${String(
8485
9914
  row.signal_name ?? row.signalName ?? ""
9915
+ ).trim()}|${String(row.task_name ?? row.taskName ?? "").trim()}|${String(
9916
+ row.task_version ?? row.taskVersion ?? 1
8486
9917
  ).trim()}`
8487
9918
  );
8488
9919
  pushUnique(
@@ -8517,10 +9948,23 @@ var ServiceRegistry = class _ServiceRegistry {
8517
9948
  seenSignalMaps,
8518
9949
  (entry) => `${String(entry.service_name ?? entry.serviceName ?? "").trim()}|${String(
8519
9950
  entry.signal_name ?? entry.signalName ?? ""
9951
+ ).trim()}|${String(entry.task_name ?? entry.taskName ?? "").trim()}|${String(
9952
+ entry.task_version ?? entry.taskVersion ?? 1
8520
9953
  ).trim()}`
8521
9954
  );
8522
9955
  continue;
8523
9956
  }
9957
+ if (row.status !== void 0 && (row.service_instance_id !== void 0 || row.serviceInstanceId !== void 0)) {
9958
+ pushUnique(
9959
+ [row],
9960
+ serviceInstanceLeases,
9961
+ seenServiceInstanceLeases,
9962
+ (entry) => String(
9963
+ entry.service_instance_id ?? entry.serviceInstanceId ?? ""
9964
+ ).trim()
9965
+ );
9966
+ continue;
9967
+ }
8524
9968
  if (row.service_instance_id !== void 0 || row.serviceInstanceId !== void 0) {
8525
9969
  pushUnique(
8526
9970
  [row],
@@ -8549,9 +9993,40 @@ var ServiceRegistry = class _ServiceRegistry {
8549
9993
  }
8550
9994
  }
8551
9995
  }
8552
- const hasExplicitSignalRoutingRows = signalToTaskMaps.length > 0;
8553
- const hasExplicitIntentRoutingRows = intentToTaskMaps.length > 0;
8554
- const latestManifestSnapshots = selectLatestServiceManifestSnapshots(manifestSnapshots);
9996
+ const mergedServiceInstances = overlayServiceInstancesWithLeases(
9997
+ serviceInstances,
9998
+ serviceInstanceLeases
9999
+ );
10000
+ const activeServiceInstanceIds = new Set(
10001
+ mergedServiceInstances.filter((row) => row.is_active === true || row.isActive === true).map((row) => String(row.uuid ?? "").trim()).filter((uuid10) => uuid10.length > 0)
10002
+ );
10003
+ const filteredServiceInstances = activeServiceInstanceIds.size > 0 ? mergedServiceInstances.filter(
10004
+ (row) => activeServiceInstanceIds.has(String(row.uuid ?? "").trim())
10005
+ ) : mergedServiceInstances;
10006
+ const filteredServiceInstanceTransports = activeServiceInstanceIds.size > 0 ? serviceInstanceTransports.filter(
10007
+ (row) => activeServiceInstanceIds.has(
10008
+ String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
10009
+ )
10010
+ ) : serviceInstanceTransports;
10011
+ const filteredManifestSnapshots = activeServiceInstanceIds.size > 0 ? manifestSnapshots.filter(
10012
+ (snapshot) => activeServiceInstanceIds.has(snapshot.serviceInstanceId)
10013
+ ) : manifestSnapshots;
10014
+ const activeServiceNames = new Set(
10015
+ filteredServiceInstances.map((row) => String(row.service_name ?? row.serviceName ?? "").trim()).filter((serviceName) => serviceName.length > 0)
10016
+ );
10017
+ const filteredSignalToTaskMaps = activeServiceNames.size > 0 ? signalToTaskMaps.filter(
10018
+ (row) => activeServiceNames.has(
10019
+ String(row.service_name ?? row.serviceName ?? "").trim()
10020
+ )
10021
+ ) : signalToTaskMaps;
10022
+ const filteredIntentToTaskMaps = activeServiceNames.size > 0 ? intentToTaskMaps.filter(
10023
+ (row) => activeServiceNames.has(
10024
+ String(row.service_name ?? row.serviceName ?? "").trim()
10025
+ )
10026
+ ) : intentToTaskMaps;
10027
+ const hasExplicitSignalRoutingRows = filteredSignalToTaskMaps.length > 0;
10028
+ const hasExplicitIntentRoutingRows = filteredIntentToTaskMaps.length > 0;
10029
+ const latestManifestSnapshots = selectLatestServiceManifestSnapshots(filteredManifestSnapshots);
8555
10030
  const explodedManifest = explodeServiceManifestSnapshots(
8556
10031
  latestManifestSnapshots
8557
10032
  );
@@ -8571,6 +10046,22 @@ var ServiceRegistry = class _ServiceRegistry {
8571
10046
  row.version ?? 1
8572
10047
  ).trim()}`
8573
10048
  );
10049
+ pushUnique(
10050
+ explodedManifest.helpers,
10051
+ helpers,
10052
+ seenHelpers,
10053
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.name ?? "").trim()}|${String(
10054
+ row.version ?? 1
10055
+ ).trim()}`
10056
+ );
10057
+ pushUnique(
10058
+ explodedManifest.globals,
10059
+ globals,
10060
+ seenGlobals,
10061
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.name ?? "").trim()}|${String(
10062
+ row.version ?? 1
10063
+ ).trim()}`
10064
+ );
8574
10065
  pushUnique(
8575
10066
  explodedManifest.signals,
8576
10067
  signals,
@@ -8631,10 +10122,54 @@ var ServiceRegistry = class _ServiceRegistry {
8631
10122
  row.task_version ?? 1
8632
10123
  ).trim()}`
8633
10124
  );
10125
+ pushUnique(
10126
+ explodedManifest.taskToHelperMaps,
10127
+ taskToHelperMaps,
10128
+ seenTaskToHelperMaps,
10129
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.task_name ?? "").trim()}|${String(
10130
+ row.task_version ?? 1
10131
+ ).trim()}|${String(row.alias ?? "").trim()}|${String(
10132
+ row.helper_name ?? ""
10133
+ ).trim()}|${String(row.helper_version ?? 1).trim()}`
10134
+ );
10135
+ pushUnique(
10136
+ explodedManifest.helperToHelperMaps,
10137
+ helperToHelperMaps,
10138
+ seenHelperToHelperMaps,
10139
+ (row) => `${String(row.service_name ?? "").trim()}|${String(
10140
+ row.helper_name ?? ""
10141
+ ).trim()}|${String(row.helper_version ?? 1).trim()}|${String(
10142
+ row.alias ?? ""
10143
+ ).trim()}|${String(row.dependency_helper_name ?? "").trim()}|${String(
10144
+ row.dependency_helper_version ?? 1
10145
+ ).trim()}`
10146
+ );
10147
+ pushUnique(
10148
+ explodedManifest.taskToGlobalMaps,
10149
+ taskToGlobalMaps,
10150
+ seenTaskToGlobalMaps,
10151
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.task_name ?? "").trim()}|${String(
10152
+ row.task_version ?? 1
10153
+ ).trim()}|${String(row.alias ?? "").trim()}|${String(
10154
+ row.global_name ?? ""
10155
+ ).trim()}|${String(row.global_version ?? 1).trim()}`
10156
+ );
10157
+ pushUnique(
10158
+ explodedManifest.helperToGlobalMaps,
10159
+ helperToGlobalMaps,
10160
+ seenHelperToGlobalMaps,
10161
+ (row) => `${String(row.service_name ?? "").trim()}|${String(
10162
+ row.helper_name ?? ""
10163
+ ).trim()}|${String(row.helper_version ?? 1).trim()}|${String(
10164
+ row.alias ?? ""
10165
+ ).trim()}|${String(row.global_name ?? "").trim()}|${String(
10166
+ row.global_version ?? 1
10167
+ ).trim()}`
10168
+ );
8634
10169
  if (!hasExplicitSignalRoutingRows) {
8635
10170
  pushUnique(
8636
10171
  explodedManifest.signalToTaskMaps,
8637
- signalToTaskMaps,
10172
+ filteredSignalToTaskMaps,
8638
10173
  seenSignalMaps,
8639
10174
  (row) => `${String(row.signal_name ?? "").trim()}|${String(
8640
10175
  row.service_name ?? ""
@@ -8646,7 +10181,7 @@ var ServiceRegistry = class _ServiceRegistry {
8646
10181
  if (!hasExplicitIntentRoutingRows) {
8647
10182
  pushUnique(
8648
10183
  explodedManifest.intentToTaskMaps,
8649
- intentToTaskMaps,
10184
+ filteredIntentToTaskMaps,
8650
10185
  seenIntentMaps,
8651
10186
  (row) => `${String(row.intent_name ?? "").trim()}|${String(
8652
10187
  row.service_name ?? ""
@@ -8656,10 +10191,13 @@ var ServiceRegistry = class _ServiceRegistry {
8656
10191
  );
8657
10192
  }
8658
10193
  return {
8659
- serviceInstances,
8660
- serviceInstanceTransports,
10194
+ serviceInstances: filteredServiceInstances,
10195
+ serviceInstanceLeases,
10196
+ serviceInstanceTransports: filteredServiceInstanceTransports,
8661
10197
  serviceManifests,
8662
10198
  tasks,
10199
+ helpers,
10200
+ globals,
8663
10201
  signals,
8664
10202
  intents,
8665
10203
  actors,
@@ -8667,8 +10205,12 @@ var ServiceRegistry = class _ServiceRegistry {
8667
10205
  directionalTaskMaps,
8668
10206
  actorTaskMaps,
8669
10207
  taskToRoutineMaps,
8670
- signalToTaskMaps,
8671
- intentToTaskMaps
10208
+ taskToHelperMaps,
10209
+ helperToHelperMaps,
10210
+ taskToGlobalMaps,
10211
+ helperToGlobalMaps,
10212
+ signalToTaskMaps: filteredSignalToTaskMaps,
10213
+ intentToTaskMaps: filteredIntentToTaskMaps
8672
10214
  };
8673
10215
  }
8674
10216
  buildRemoteIntentDeputyKey(map) {
@@ -9097,29 +10639,32 @@ var ServiceRegistry = class _ServiceRegistry {
9097
10639
  const controller = typeof AbortController === "function" ? new AbortController() : null;
9098
10640
  const timeoutId = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
9099
10641
  try {
9100
- const requestBody = stripDelegationRequestSnapshot(
9101
- ensureDelegationContextMetadata(
9102
- attachDelegationRequestSnapshot({
9103
- ...context,
9104
- __remoteRoutineName: remoteRoutineName,
9105
- __serviceName: "CadenzaDB",
9106
- __localServiceName: this.serviceName,
9107
- __timeout: timeoutMs,
9108
- __syncing: true,
9109
- __transportOrigin: target.origin,
9110
- __transportProtocol: "rest",
9111
- __transportProtocols: ["rest"],
9112
- __routeKey: target.routeKey,
9113
- routeKey: target.routeKey,
9114
- __fetchId: target.fetchId,
9115
- fetchId: target.fetchId,
9116
- __metadata: {
9117
- ...context.__metadata && typeof context.__metadata === "object" ? context.__metadata : {},
10642
+ const sanitizedContext = sanitizeAuthorityBootstrapDelegationContext(context);
10643
+ const requestBody = compactAuthorityBootstrapRequestBody(
10644
+ stripDelegationRequestSnapshot(
10645
+ ensureDelegationContextMetadata(
10646
+ attachDelegationRequestSnapshot({
10647
+ ...sanitizedContext,
10648
+ __remoteRoutineName: remoteRoutineName,
10649
+ __serviceName: "CadenzaDB",
10650
+ __localServiceName: this.serviceName,
9118
10651
  __timeout: timeoutMs,
9119
10652
  __syncing: true,
9120
- __authorityBootstrapChannel: true
9121
- }
9122
- })
10653
+ __transportOrigin: target.origin,
10654
+ __transportProtocol: "rest",
10655
+ __transportProtocols: ["rest"],
10656
+ __routeKey: target.routeKey,
10657
+ routeKey: target.routeKey,
10658
+ __fetchId: target.fetchId,
10659
+ fetchId: target.fetchId,
10660
+ __metadata: {
10661
+ ...sanitizedContext.__metadata && typeof sanitizedContext.__metadata === "object" ? sanitizedContext.__metadata : {},
10662
+ __timeout: timeoutMs,
10663
+ __syncing: true,
10664
+ __authorityBootstrapChannel: true
10665
+ }
10666
+ })
10667
+ )
9123
10668
  )
9124
10669
  );
9125
10670
  const response = await globalThis.fetch(`${target.origin}/delegation`, {
@@ -9132,22 +10677,22 @@ var ServiceRegistry = class _ServiceRegistry {
9132
10677
  });
9133
10678
  if ("ok" in response && response.ok === false) {
9134
10679
  return {
9135
- ...context,
10680
+ ...sanitizedContext,
9136
10681
  __error: `Bootstrap authority delegation failed with HTTP ${response.status}`,
9137
10682
  errored: true
9138
10683
  };
9139
10684
  }
9140
10685
  const payload = typeof response.json === "function" ? await response.json() : response;
9141
10686
  return payload && typeof payload === "object" ? {
9142
- ...context,
10687
+ ...sanitizedContext,
9143
10688
  ...payload
9144
10689
  } : {
9145
- ...context,
10690
+ ...sanitizedContext,
9146
10691
  returnedValue: payload
9147
10692
  };
9148
10693
  } catch (error) {
9149
10694
  return {
9150
- ...context,
10695
+ ...sanitizeAuthorityBootstrapDelegationContext(context),
9151
10696
  __error: error instanceof Error ? error.message : String(error),
9152
10697
  errored: true
9153
10698
  };
@@ -9274,12 +10819,14 @@ var ServiceRegistry = class _ServiceRegistry {
9274
10819
  };
9275
10820
  const [
9276
10821
  serviceInstances,
10822
+ serviceInstanceLeases,
9277
10823
  serviceInstanceTransports,
9278
10824
  serviceManifests,
9279
10825
  signalToTaskMaps,
9280
10826
  intentToTaskMaps
9281
10827
  ] = await Promise.all([
9282
10828
  DatabaseController.instance.queryAuthorityTableRows("service_instance"),
10829
+ queryOptionalAuthorityRoutingRows("service_instance_lease"),
9283
10830
  DatabaseController.instance.queryAuthorityTableRows(
9284
10831
  "service_instance_transport"
9285
10832
  ),
@@ -9292,6 +10839,7 @@ var ServiceRegistry = class _ServiceRegistry {
9292
10839
  __syncing: true,
9293
10840
  ...this.collectBootstrapFullSyncPayload({
9294
10841
  serviceInstances,
10842
+ serviceInstanceLeases,
9295
10843
  serviceInstanceTransports,
9296
10844
  serviceManifests,
9297
10845
  signalToTaskMaps,
@@ -9324,9 +10872,14 @@ var ServiceRegistry = class _ServiceRegistry {
9324
10872
  return false;
9325
10873
  }
9326
10874
  const scheduleRetry = (reason, error) => {
9327
- const delayMs = SERVICE_COMMUNICATION_PERSIST_RETRY_DELAYS_MS[descriptor.retryAttempt];
10875
+ const baseDelayMs = SERVICE_COMMUNICATION_PERSIST_RETRY_DELAYS_MS[descriptor.retryAttempt];
9328
10876
  const nextAttempt = descriptor.retryAttempt + 1;
9329
- if (delayMs !== void 0) {
10877
+ if (baseDelayMs !== void 0) {
10878
+ const delayMs = buildDeterministicJitteredDelayMs(
10879
+ baseDelayMs,
10880
+ this.serviceCommunicationRetryJitterRatio,
10881
+ `${descriptor.serviceInstanceId}:${descriptor.communicationType}:${descriptor.retryAttempt}`
10882
+ );
9330
10883
  CadenzaService.schedule(
9331
10884
  retrySignal,
9332
10885
  buildServiceCommunicationRetryContext({
@@ -9474,6 +11027,31 @@ var ServiceRegistry = class _ServiceRegistry {
9474
11027
  })
9475
11028
  );
9476
11029
  }
11030
+ buildDeterministicInstanceJitterKey(scope) {
11031
+ const serviceName = String(this.serviceName ?? "").trim() || "unknown-service";
11032
+ const serviceInstanceId = String(this.serviceInstanceId ?? "").trim() || "pending-instance";
11033
+ return `${serviceName}:${serviceInstanceId}:${scope}`;
11034
+ }
11035
+ buildJitteredIntervalStartDate(intervalMs, scope) {
11036
+ const jitterOffsetMs = buildDeterministicJitterOffsetMs(
11037
+ intervalMs,
11038
+ this.runtimeStatusLoopJitterRatio,
11039
+ this.buildDeterministicInstanceJitterKey(scope)
11040
+ );
11041
+ if (jitterOffsetMs <= 0) {
11042
+ return void 0;
11043
+ }
11044
+ return new Date(Date.now() + intervalMs + jitterOffsetMs);
11045
+ }
11046
+ buildJitteredBootstrapRetryDelayMs(baseDelayMs, attempt) {
11047
+ return buildDeterministicJitteredDelayMs(
11048
+ baseDelayMs,
11049
+ this.bootstrapFullSyncRetryJitterRatio,
11050
+ this.buildDeterministicInstanceJitterKey(
11051
+ `bootstrap-full-sync-retry-${attempt}`
11052
+ )
11053
+ );
11054
+ }
9477
11055
  ensureAuthorityBootstrapSignalTransmissions() {
9478
11056
  if (this.serviceName !== "CadenzaDB") {
9479
11057
  return false;
@@ -9551,8 +11129,11 @@ var ServiceRegistry = class _ServiceRegistry {
9551
11129
  }
9552
11130
  const retryGeneration = this.bootstrapFullSyncRetryGeneration;
9553
11131
  const retryReason = this.bootstrapFullSyncRetryReason ?? "service_registry_bootstrap_retry";
9554
- const delayMs = EARLY_FULL_SYNC_DELAYS_MS[this.bootstrapFullSyncRetryIndex];
9555
11132
  const attempt = this.bootstrapFullSyncRetryIndex + 1;
11133
+ const delayMs = this.buildJitteredBootstrapRetryDelayMs(
11134
+ EARLY_FULL_SYNC_DELAYS_MS[this.bootstrapFullSyncRetryIndex],
11135
+ attempt
11136
+ );
9556
11137
  this.bootstrapFullSyncRetryIndex += 1;
9557
11138
  this.bootstrapFullSyncRetryTimer = setTimeout(() => {
9558
11139
  this.bootstrapFullSyncRetryTimer = null;
@@ -11455,6 +13036,18 @@ var ServiceRegistry = class _ServiceRegistry {
11455
13036
  isNonResponsive,
11456
13037
  isBlocked
11457
13038
  );
13039
+ const cpuUsage = this.readRuntimeStatusMetric(ctx, "cpuUsage", "cpu", "cpuLoad");
13040
+ const memoryUsage = this.readRuntimeStatusMetric(
13041
+ ctx,
13042
+ "memoryUsage",
13043
+ "memory",
13044
+ "memoryPressure"
13045
+ );
13046
+ const eventLoopLag = this.readRuntimeStatusMetric(
13047
+ ctx,
13048
+ "eventLoopLag",
13049
+ "eventLoopLagMs"
13050
+ );
11458
13051
  return {
11459
13052
  serviceName,
11460
13053
  serviceInstanceId,
@@ -11467,22 +13060,20 @@ var ServiceRegistry = class _ServiceRegistry {
11467
13060
  state: ctx.state === "healthy" || ctx.state === "degraded" || ctx.state === "overloaded" || ctx.state === "unavailable" ? ctx.state : resolved.state,
11468
13061
  acceptingWork: typeof ctx.acceptingWork === "boolean" ? ctx.acceptingWork : resolved.acceptingWork,
11469
13062
  numberOfRunningGraphs,
11470
- cpuUsage: this.readRuntimeStatusMetric(ctx, "cpuUsage", "cpu", "cpuLoad"),
11471
- memoryUsage: this.readRuntimeStatusMetric(
11472
- ctx,
11473
- "memoryUsage",
11474
- "memory",
11475
- "memoryPressure"
11476
- ),
11477
- eventLoopLag: this.readRuntimeStatusMetric(
11478
- ctx,
11479
- "eventLoopLag",
11480
- "eventLoopLagMs"
11481
- ),
13063
+ cpuUsage,
13064
+ memoryUsage,
13065
+ eventLoopLag,
11482
13066
  isActive,
11483
13067
  isNonResponsive,
11484
13068
  isBlocked,
11485
- health: ctx.health ?? ctx.__health ?? {}
13069
+ health: sanitizeAuthorityRuntimeStatusHealth(ctx.health ?? ctx.__health, {
13070
+ state: ctx.state === "healthy" || ctx.state === "degraded" || ctx.state === "overloaded" || ctx.state === "unavailable" ? ctx.state : resolved.state,
13071
+ acceptingWork: typeof ctx.acceptingWork === "boolean" ? ctx.acceptingWork : resolved.acceptingWork,
13072
+ reportedAt: ctx.reportedAt ?? (typeof ctx.__reportedAt === "string" ? ctx.__reportedAt : void 0) ?? (/* @__PURE__ */ new Date()).toISOString(),
13073
+ cpuUsage,
13074
+ memoryUsage,
13075
+ eventLoopLag
13076
+ })
11486
13077
  };
11487
13078
  }
11488
13079
  applyRuntimeStatusReport(report) {
@@ -11523,12 +13114,14 @@ var ServiceRegistry = class _ServiceRegistry {
11523
13114
  instance.isFrontend = report.isFrontend;
11524
13115
  }
11525
13116
  instance.numberOfRunningGraphs = report.numberOfRunningGraphs;
11526
- const runtimeMetricsHealth = {
13117
+ const runtimeStatusHealth = sanitizeAuthorityRuntimeStatusHealth(report.health, {
13118
+ state: report.state,
13119
+ acceptingWork: report.acceptingWork,
13120
+ reportedAt: report.reportedAt,
11527
13121
  cpuUsage: report.cpuUsage ?? null,
11528
13122
  memoryUsage: report.memoryUsage ?? null,
11529
- eventLoopLag: report.eventLoopLag ?? null,
11530
- runtimeMetrics: report.health?.runtimeMetrics && typeof report.health.runtimeMetrics === "object" ? report.health.runtimeMetrics : void 0
11531
- };
13123
+ eventLoopLag: report.eventLoopLag ?? null
13124
+ });
11532
13125
  instance.isActive = report.isActive;
11533
13126
  instance.isNonResponsive = report.isNonResponsive;
11534
13127
  instance.isBlocked = report.isBlocked;
@@ -11537,13 +13130,7 @@ var ServiceRegistry = class _ServiceRegistry {
11537
13130
  instance.reportedAt = report.reportedAt;
11538
13131
  instance.health = {
11539
13132
  ...instance.health ?? {},
11540
- ...report.health ?? {},
11541
- ...runtimeMetricsHealth,
11542
- runtimeStatus: {
11543
- state: report.state,
11544
- acceptingWork: report.acceptingWork,
11545
- reportedAt: report.reportedAt
11546
- }
13133
+ ...runtimeStatusHealth ?? {}
11547
13134
  };
11548
13135
  this.lastHeartbeatAtByInstance.set(report.serviceInstanceId, Date.now());
11549
13136
  this.missedHeartbeatsByInstance.set(report.serviceInstanceId, 0);
@@ -11715,15 +13302,20 @@ var ServiceRegistry = class _ServiceRegistry {
11715
13302
  isActive: snapshot.isActive,
11716
13303
  isNonResponsive: snapshot.isNonResponsive,
11717
13304
  isBlocked: snapshot.isBlocked,
11718
- health: {
11719
- ...localInstance.health ?? {},
11720
- ...this.buildRuntimeMetricsHealthPayload(runtimeMetricsSnapshot) ?? {},
11721
- runtimeStatus: {
13305
+ health: sanitizeAuthorityRuntimeStatusHealth(
13306
+ {
13307
+ ...localInstance.health ?? {},
13308
+ ...this.buildRuntimeMetricsHealthPayload(runtimeMetricsSnapshot) ?? {}
13309
+ },
13310
+ {
11722
13311
  state: snapshot.state,
11723
13312
  acceptingWork: snapshot.acceptingWork,
11724
- reportedAt
13313
+ reportedAt,
13314
+ cpuUsage: runtimeMetricsSnapshot?.cpuUsage ?? null,
13315
+ memoryUsage: runtimeMetricsSnapshot?.memoryUsage ?? null,
13316
+ eventLoopLag: runtimeMetricsSnapshot?.eventLoopLag ?? null
11725
13317
  }
11726
- }
13318
+ )
11727
13319
  };
11728
13320
  this.applyRuntimeStatusReport(report);
11729
13321
  return detailLevel === "full" ? report : this.stripRuntimeStatusReportForPeer(report);
@@ -12077,6 +13669,32 @@ var ServiceRegistry = class _ServiceRegistry {
12077
13669
  if (!instancePersisted) {
12078
13670
  return false;
12079
13671
  }
13672
+ await this.delegateAuthorityLifecycleUpdate(
13673
+ "Update service_instance_lease",
13674
+ {
13675
+ reason,
13676
+ graceful: true,
13677
+ data: {
13678
+ status: "inactive",
13679
+ is_ready: false,
13680
+ readiness_reason: "graceful_shutdown",
13681
+ lease_expires_at: reportedAt,
13682
+ last_lease_renewed_at: reportedAt,
13683
+ last_ready_at: null,
13684
+ last_observed_transport_at: reportedAt,
13685
+ shutdown_requested_at: reportedAt,
13686
+ deleted: false,
13687
+ modified: reportedAt
13688
+ },
13689
+ queryData: {
13690
+ filter: {
13691
+ service_instance_id: localInstance.uuid
13692
+ }
13693
+ },
13694
+ __serviceInstanceId: localInstance.uuid
13695
+ },
13696
+ Math.max(1e3, timeoutMs)
13697
+ );
12080
13698
  for (const transport of localInstance.transports) {
12081
13699
  if (!isPersistedUuid(transport.uuid)) {
12082
13700
  continue;
@@ -12228,6 +13846,7 @@ var ServiceRegistry = class _ServiceRegistry {
12228
13846
  };
12229
13847
  }
12230
13848
  reset() {
13849
+ this.clearBootstrapFullSyncRetryTimer();
12231
13850
  this.instances.clear();
12232
13851
  this.deputies.clear();
12233
13852
  this.remoteSignals.clear();
@@ -12251,6 +13870,23 @@ var ServiceRegistry = class _ServiceRegistry {
12251
13870
  this.lastRuntimeStatusSnapshot = null;
12252
13871
  this.isFrontend = false;
12253
13872
  this.localInstanceSeed = null;
13873
+ this.bootstrapFullSyncRetryIndex = 0;
13874
+ this.bootstrapFullSyncRetryGeneration = 0;
13875
+ this.bootstrapFullSyncSatisfied = false;
13876
+ this.bootstrapFullSyncRetryReason = null;
13877
+ this.knownGlobalSignalMaps.clear();
13878
+ this.authorityBootstrapRoute = {
13879
+ origin: null,
13880
+ role: "internal",
13881
+ routeKey: null,
13882
+ fetchId: null,
13883
+ serviceInstanceId: null,
13884
+ serviceTransportId: null,
13885
+ handshakeEstablished: false
13886
+ };
13887
+ this.authorityBootstrapHandshakeInFlight = false;
13888
+ this.authorityFullSyncResponderTask = null;
13889
+ this.authorityServiceCommunicationPersistenceTask = null;
12254
13890
  }
12255
13891
  };
12256
13892
 
@@ -12359,7 +13995,25 @@ var SignalTransmissionTask = class extends Task2 {
12359
13995
  ...ctx
12360
13996
  })
12361
13997
  );
12362
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
13998
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
13999
+ this,
14000
+ deputyContext,
14001
+ emit2,
14002
+ inquire,
14003
+ progressCallback
14004
+ ) : {
14005
+ helpers: {},
14006
+ globals: {}
14007
+ };
14008
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
14009
+ };
14010
+ return this.taskFunction(
14011
+ deputyContext,
14012
+ emit2,
14013
+ inquire,
14014
+ resolvedTools,
14015
+ resolvedProgressCallback
14016
+ );
12363
14017
  }
12364
14018
  };
12365
14019
 
@@ -12384,6 +14038,41 @@ var TRACED_INQUIRY_METADATA_SIGNALS = /* @__PURE__ */ new Set([
12384
14038
  "global.meta.graph_metadata.inquiry_updated"
12385
14039
  ]);
12386
14040
  var ACTOR_SESSION_TRACE_ENABLED3 = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
14041
+ function summarizeRequestBodyForLogging(body) {
14042
+ if (typeof body !== "string") {
14043
+ return body;
14044
+ }
14045
+ const summary = {
14046
+ bodyLength: body.length
14047
+ };
14048
+ try {
14049
+ const parsed = JSON.parse(body);
14050
+ const queryData = parsed.queryData && typeof parsed.queryData === "object" ? parsed.queryData : null;
14051
+ const queryDataData = queryData?.data && typeof queryData.data === "object" ? queryData.data : null;
14052
+ const data = parsed.data && typeof parsed.data === "object" ? parsed.data : null;
14053
+ summary.rootKeys = Object.keys(parsed).slice(0, 24);
14054
+ summary.remoteRoutineName = typeof parsed.__remoteRoutineName === "string" ? parsed.__remoteRoutineName : null;
14055
+ summary.serviceName = typeof parsed.__serviceName === "string" ? parsed.__serviceName : null;
14056
+ summary.authorityBootstrapChannel = parsed.__authorityBootstrapChannel === true || parsed.__metadata?.__authorityBootstrapChannel === true;
14057
+ summary.hasData = data !== null;
14058
+ summary.dataKeys = data ? Object.keys(data).slice(0, 24) : [];
14059
+ summary.hasQueryData = queryData !== null;
14060
+ summary.queryDataKeys = queryData ? Object.keys(queryData).slice(0, 24) : [];
14061
+ summary.queryDataDataKeys = queryDataData ? Object.keys(queryDataData).slice(0, 24) : [];
14062
+ } catch {
14063
+ summary.preview = body.slice(0, 240);
14064
+ }
14065
+ return summary;
14066
+ }
14067
+ function summarizeRequestInitForLogging(requestInit) {
14068
+ if (!requestInit || typeof requestInit !== "object") {
14069
+ return requestInit;
14070
+ }
14071
+ return {
14072
+ ...requestInit,
14073
+ body: summarizeRequestBodyForLogging(requestInit.body)
14074
+ };
14075
+ }
12387
14076
  var RestController = class _RestController {
12388
14077
  /**
12389
14078
  * Constructor for initializing the REST server and related configurations.
@@ -12417,16 +14106,17 @@ var RestController = class _RestController {
12417
14106
  const parsedResponse = await this.parseFetchResponse(response);
12418
14107
  return parsedResponse.data;
12419
14108
  } catch (error) {
14109
+ const loggedRequestInit = summarizeRequestInitForLogging(requestInit);
12420
14110
  if (error?.name === "AbortError") {
12421
14111
  CadenzaService.log(
12422
14112
  "Fetch request timed out.",
12423
- { error, URL: url, requestInit },
14113
+ { error, URL: url, requestInit: loggedRequestInit },
12424
14114
  "warning"
12425
14115
  );
12426
14116
  } else {
12427
14117
  CadenzaService.log(
12428
14118
  "Fetch request error.",
12429
- { error, URL: url, requestInit },
14119
+ { error, URL: url, requestInit: loggedRequestInit },
12430
14120
  "error"
12431
14121
  );
12432
14122
  }
@@ -12572,7 +14262,7 @@ var RestController = class _RestController {
12572
14262
  return { ...ctx, __app: app };
12573
14263
  },
12574
14264
  "Sets up the Express server according to the security profile"
12575
- ).attachSignal("meta.service_registry.instance_registration_requested").then(
14265
+ ).then(
12576
14266
  CadenzaService.createMetaTask(
12577
14267
  "Define RestServer",
12578
14268
  (ctx) => {
@@ -12652,16 +14342,16 @@ var RestController = class _RestController {
12652
14342
  };
12653
14343
  CadenzaService.createEphemeralMetaTask(
12654
14344
  "Resolve delegation",
12655
- (endCtx) => resolveDelegation(endCtx, "success"),
14345
+ (endCtx) => resolveDelegation(
14346
+ endCtx,
14347
+ endCtx?.errored || endCtx?.failed ? "error" : "success"
14348
+ ),
12656
14349
  "Resolves a delegation request",
12657
14350
  { register: false }
12658
- ).doOn(`meta.node.graph_completed:${deputyExecId}`).emits(`meta.rest.delegation_resolved:${deputyExecId}`);
12659
- CadenzaService.createEphemeralMetaTask(
12660
- "Resolve delegation target lookup failure",
12661
- (endCtx) => resolveDelegation(endCtx, "error"),
12662
- "Resolves delegation requests that cannot find a local task or routine",
12663
- { register: false }
12664
- ).doOn(targetNotFoundSignal);
14351
+ ).doOn(
14352
+ `meta.node.graph_completed:${deputyExecId}`,
14353
+ targetNotFoundSignal
14354
+ ).emits(`meta.rest.delegation_resolved:${deputyExecId}`);
12665
14355
  if (!CadenzaService.get(remoteRoutineName) && !CadenzaService.registry.routines.get(remoteRoutineName)) {
12666
14356
  CadenzaService.emit(targetNotFoundSignal, {
12667
14357
  ...ctx2,
@@ -12969,32 +14659,40 @@ var RestController = class _RestController {
12969
14659
  serviceName,
12970
14660
  URL2
12971
14661
  );
12972
- fetchDiagnostics.destroyed = false;
12973
- fetchDiagnostics.updatedAt = Date.now();
12974
14662
  if (CadenzaService.get(`Send Handshake to ${clientTaskSuffix}`)) {
12975
- console.error("Fetch client already exists", { URL: URL2, fetchId });
12976
- CadenzaService.schedule(
12977
- `meta.fetch.handshake_requested:${fetchId}`,
12978
- {
12979
- serviceInstanceId: ctx.serviceInstanceId,
12980
- serviceName,
12981
- communicationTypes: ctx.communicationTypes,
12982
- serviceTransportId: ctx.serviceTransportId,
12983
- serviceOrigin: URL2,
12984
- fetchId,
12985
- routeKey,
12986
- socketClientId: ctx.socketClientId ?? (routeKey ? buildTransportHandleKey(routeKey, "socket") : void 0),
12987
- transportProtocols: ctx.transportProtocols,
12988
- transportProtocol: "rest",
12989
- handshakeData: ctx.handshakeData
12990
- },
12991
- 0
12992
- );
14663
+ const shouldRetryHandshake = ctx.__forceHandshakeRecovery === true || fetchDiagnostics.destroyed === true || (fetchDiagnostics.connected !== true || typeof fetchDiagnostics.lastHandshakeError === "string") && fetchDiagnostics.handshakeInFlight !== true;
14664
+ if (shouldRetryHandshake) {
14665
+ fetchDiagnostics.destroyed = false;
14666
+ fetchDiagnostics.handshakeInFlight = true;
14667
+ fetchDiagnostics.updatedAt = Date.now();
14668
+ console.error("Fetch client already exists", { URL: URL2, fetchId });
14669
+ CadenzaService.debounce(
14670
+ `meta.fetch.handshake_requested:${fetchId}`,
14671
+ {
14672
+ serviceInstanceId: ctx.serviceInstanceId,
14673
+ serviceName,
14674
+ communicationTypes: ctx.communicationTypes,
14675
+ serviceTransportId: ctx.serviceTransportId,
14676
+ serviceOrigin: URL2,
14677
+ fetchId,
14678
+ routeKey,
14679
+ socketClientId: ctx.socketClientId ?? (routeKey ? buildTransportHandleKey(routeKey, "socket") : void 0),
14680
+ transportProtocols: ctx.transportProtocols,
14681
+ transportProtocol: "rest",
14682
+ handshakeData: ctx.handshakeData
14683
+ },
14684
+ 50
14685
+ );
14686
+ }
12993
14687
  return true;
12994
14688
  }
14689
+ fetchDiagnostics.destroyed = false;
14690
+ fetchDiagnostics.handshakeInFlight = false;
14691
+ fetchDiagnostics.updatedAt = Date.now();
12995
14692
  const handshakeTask = CadenzaService.createMetaTask(
12996
14693
  `Send Handshake to ${clientTaskSuffix}`,
12997
14694
  async (ctx2, emit2) => {
14695
+ fetchDiagnostics.handshakeInFlight = true;
12998
14696
  try {
12999
14697
  const response = await this.fetchDataWithTimeout(
13000
14698
  `${URL2}/handshake`,
@@ -13010,6 +14708,7 @@ var RestController = class _RestController {
13010
14708
  if (response.__status !== "success") {
13011
14709
  const error = response.__error ?? `Failed to connect to service ${serviceName} ${ctx2.serviceInstanceId}`;
13012
14710
  fetchDiagnostics.connected = false;
14711
+ fetchDiagnostics.handshakeInFlight = false;
13013
14712
  fetchDiagnostics.lastHandshakeError = error;
13014
14713
  fetchDiagnostics.updatedAt = Date.now();
13015
14714
  this.recordFetchClientError(fetchId, serviceName, URL2, error);
@@ -13029,6 +14728,7 @@ var RestController = class _RestController {
13029
14728
  ctx2.serviceInstanceId = response.__serviceInstanceId;
13030
14729
  fetchDiagnostics.connected = true;
13031
14730
  fetchDiagnostics.destroyed = false;
14731
+ fetchDiagnostics.handshakeInFlight = false;
13032
14732
  fetchDiagnostics.lastHandshakeAt = (/* @__PURE__ */ new Date()).toISOString();
13033
14733
  fetchDiagnostics.lastHandshakeError = null;
13034
14734
  fetchDiagnostics.updatedAt = Date.now();
@@ -13057,6 +14757,7 @@ var RestController = class _RestController {
13057
14757
  }
13058
14758
  } catch (e) {
13059
14759
  fetchDiagnostics.connected = false;
14760
+ fetchDiagnostics.handshakeInFlight = false;
13060
14761
  fetchDiagnostics.lastHandshakeError = this.getErrorMessage(e);
13061
14762
  fetchDiagnostics.updatedAt = Date.now();
13062
14763
  this.recordFetchClientError(fetchId, serviceName, URL2, e);
@@ -13089,8 +14790,8 @@ var RestController = class _RestController {
13089
14790
  }
13090
14791
  const routedDelegateCtx = stripTransportSelectionRoutingContext(ctx2);
13091
14792
  const delegateCtx = ensureDelegationContextMetadata(
13092
- attachDelegationRequestSnapshot(
13093
- stripDelegationRequestSnapshot(routedDelegateCtx)
14793
+ restoreDelegationRequestSnapshot(
14794
+ attachDelegationRequestSnapshot(routedDelegateCtx)
13094
14795
  )
13095
14796
  );
13096
14797
  const deputyExecId = delegateCtx.__metadata.__deputyExecId;
@@ -13150,13 +14851,11 @@ var RestController = class _RestController {
13150
14851
  fetchDiagnostics.delegationFailures++;
13151
14852
  fetchDiagnostics.updatedAt = Date.now();
13152
14853
  this.recordFetchClientError(fetchId, serviceName, URL2, e);
13153
- resultContext = {
13154
- __signalName: "meta.fetch.delegate_failed",
13155
- __error: `Error: ${e}`,
13156
- errored: true,
13157
- ...delegateCtx,
13158
- ...delegateCtx.__metadata
13159
- };
14854
+ resultContext = buildDelegationFailureContext(
14855
+ "meta.fetch.delegate_failed",
14856
+ delegateCtx,
14857
+ e
14858
+ );
13160
14859
  routeOutcome = "failure";
13161
14860
  emit2("meta.fetch.delegate_failed", resultContext);
13162
14861
  } finally {
@@ -13322,6 +15021,7 @@ var RestController = class _RestController {
13322
15021
  return false;
13323
15022
  }
13324
15023
  fetchDiagnostics.connected = false;
15024
+ fetchDiagnostics.handshakeInFlight = false;
13325
15025
  fetchDiagnostics.destroyed = true;
13326
15026
  fetchDiagnostics.updatedAt = Date.now();
13327
15027
  CadenzaService.log("Destroying fetch client", { URL: URL2, serviceName });
@@ -13361,7 +15061,15 @@ var RestController = class _RestController {
13361
15061
  const fetchId = String(
13362
15062
  ctx.fetchId ?? ctx.__fetchId ?? (routeKey ? buildTransportHandleKey(routeKey, "rest") : serviceTransportId ?? "")
13363
15063
  );
13364
- CadenzaService.schedule(`meta.fetch.handshake_requested:${fetchId}`, {
15064
+ const fetchDiagnostics = this.ensureFetchClientDiagnostics(
15065
+ fetchId,
15066
+ String(serviceName ?? ""),
15067
+ String(serviceOrigin ?? "")
15068
+ );
15069
+ if (fetchDiagnostics.handshakeInFlight !== true) {
15070
+ fetchDiagnostics.handshakeInFlight = true;
15071
+ }
15072
+ CadenzaService.debounce(`meta.fetch.handshake_requested:${fetchId}`, {
13365
15073
  serviceInstanceId,
13366
15074
  serviceName,
13367
15075
  communicationTypes,
@@ -13377,7 +15085,7 @@ var RestController = class _RestController {
13377
15085
  serviceName: CadenzaService.serviceRegistry.serviceName
13378
15086
  // JWT token...
13379
15087
  }
13380
- }, 0);
15088
+ }, 50);
13381
15089
  return true;
13382
15090
  },
13383
15091
  "Prepares handshake"
@@ -13431,6 +15139,7 @@ var RestController = class _RestController {
13431
15139
  serviceName,
13432
15140
  url,
13433
15141
  connected: false,
15142
+ handshakeInFlight: false,
13434
15143
  destroyed: false,
13435
15144
  lastHandshakeAt: null,
13436
15145
  lastHandshakeError: null,
@@ -14868,8 +16577,8 @@ var SocketController = class _SocketController {
14868
16577
  }
14869
16578
  const routedDelegateCtx = stripTransportSelectionRoutingContext(delegateCtx);
14870
16579
  const normalizedDelegateCtx = ensureDelegationContextMetadata(
14871
- attachDelegationRequestSnapshot(
14872
- stripDelegationRequestSnapshot(routedDelegateCtx)
16580
+ restoreDelegationRequestSnapshot(
16581
+ attachDelegationRequestSnapshot(routedDelegateCtx)
14873
16582
  )
14874
16583
  );
14875
16584
  delete normalizedDelegateCtx.__isSubMeta;
@@ -14942,13 +16651,11 @@ var SocketController = class _SocketController {
14942
16651
  return resolvedResultContext;
14943
16652
  } catch (error) {
14944
16653
  const message = error instanceof Error ? error.message : String(error);
14945
- const failedContext = {
14946
- __signalName: "meta.socket_client.delegate_failed",
14947
- errored: true,
14948
- __error: message,
14949
- ...normalizedDelegateCtx,
14950
- ...normalizedDelegateCtx.__metadata
14951
- };
16654
+ const failedContext = buildDelegationFailureContext(
16655
+ "meta.socket_client.delegate_failed",
16656
+ normalizedDelegateCtx,
16657
+ error
16658
+ );
14952
16659
  if (deputyExecId) {
14953
16660
  emitter(`meta.socket_client.delegated:${deputyExecId}`, {
14954
16661
  ...failedContext,
@@ -15635,7 +17342,7 @@ var SignalController = class _SignalController {
15635
17342
  }
15636
17343
  const traceContext = { ...ctx };
15637
17344
  delete traceContext.__traceCreatedBySignalBroker;
15638
- const sanitizedTraceContext = stripLocalRoutinePersistenceHints(traceContext);
17345
+ const sanitizedTraceContext = sanitizeExecutionPersistenceContext(traceContext);
15639
17346
  const routineMetadata = resolveRoutinePersistenceMetadata(traceContext);
15640
17347
  const { context: routineContext, metaContext: routineMetaContext } = splitRoutinePersistenceContext(traceContext);
15641
17348
  const traceCreatedBySignalBroker = ctx.__traceCreatedBySignalBroker === true || signalEmission.__traceCreatedBySignalBroker === true;
@@ -15957,6 +17664,51 @@ import { META_ACTOR_SESSION_STATE_PERSIST_INTENT } from "@cadenza.io/core";
15957
17664
  var ACTOR_SESSION_STATE_PERSIST_CONCURRENCY = 20;
15958
17665
  var META_ACTOR_SESSION_STATE_HYDRATE_INTENT = "meta-actor-session-state-hydrate";
15959
17666
  var ACTOR_SESSION_TRACE_ENABLED4 = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
17667
+ function findNestedContextValue(ctx, key) {
17668
+ if (!ctx || typeof ctx !== "object") {
17669
+ return void 0;
17670
+ }
17671
+ if (Object.prototype.hasOwnProperty.call(ctx, key) || ctx[key] !== void 0) {
17672
+ return ctx[key];
17673
+ }
17674
+ const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
17675
+ for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
17676
+ const nested = joinedContexts[index];
17677
+ if (!nested || typeof nested !== "object") {
17678
+ continue;
17679
+ }
17680
+ const nestedValue = findNestedContextValue(nested, key);
17681
+ if (nestedValue !== void 0) {
17682
+ return nestedValue;
17683
+ }
17684
+ }
17685
+ return void 0;
17686
+ }
17687
+ function resolveActorSessionStateRow(ctx) {
17688
+ const singular = findNestedContextValue(ctx, "actorSessionState");
17689
+ if (singular && typeof singular === "object" && !Array.isArray(singular)) {
17690
+ return singular;
17691
+ }
17692
+ const plural = findNestedContextValue(ctx, "actorSessionStates");
17693
+ if (Array.isArray(plural)) {
17694
+ const first = plural.find(
17695
+ (entry) => entry && typeof entry === "object" && !Array.isArray(entry)
17696
+ );
17697
+ if (first) {
17698
+ return first;
17699
+ }
17700
+ }
17701
+ const rows = findNestedContextValue(ctx, "rows");
17702
+ if (Array.isArray(rows)) {
17703
+ const first = rows.find(
17704
+ (entry) => entry && typeof entry === "object" && !Array.isArray(entry)
17705
+ );
17706
+ if (first) {
17707
+ return first;
17708
+ }
17709
+ }
17710
+ return null;
17711
+ }
15960
17712
  function shouldAssumeSuccessfulActorSessionRowCount(ctx) {
15961
17713
  return ctx.__success === true && ctx.rowCount === void 0 && ctx.__status === "success" && ctx.__serviceName === "CadenzaDB" && ctx.__localTaskName === "Insert actor_session_state in CadenzaDB";
15962
17714
  }
@@ -16029,7 +17781,7 @@ function registerActorSessionPersistenceTasks() {
16029
17781
  )
16030
17782
  );
16031
17783
  }
16032
- const row = ctx.actorSessionState && typeof ctx.actorSessionState === "object" && !Array.isArray(ctx.actorSessionState) ? ctx.actorSessionState : null;
17784
+ const row = resolveActorSessionStateRow(ctx);
16033
17785
  if (!row) {
16034
17786
  return {
16035
17787
  __success: true,
@@ -16274,6 +18026,16 @@ function buildActorRegistrationData(actor) {
16274
18026
  version: 1
16275
18027
  };
16276
18028
  }
18029
+ function sanitizePersistedTaskSourceFields(task, data) {
18030
+ if (!task.isMeta && !task.isDeputy) {
18031
+ return data;
18032
+ }
18033
+ return {
18034
+ ...data,
18035
+ function_string: "",
18036
+ tag_id_getter: null
18037
+ };
18038
+ }
16277
18039
  function resolveSyncServiceName(task) {
16278
18040
  const ownerServiceName = typeof task?.ownerServiceName === "string" ? task.ownerServiceName.trim() : "";
16279
18041
  const taskServiceName = typeof task?.serviceName === "string" ? task.serviceName.trim() : "";
@@ -16436,16 +18198,20 @@ function resolveSyncInsertTask(isCadenzaDBReady, tableName, queryData = {}, opti
16436
18198
  ctx,
16437
18199
  queryData
16438
18200
  );
16439
- 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) {
16440
- console.warn(
16441
- "[CADENZA_SYNC_EMPTY_INSERT]",
16442
- {
16443
- tableName,
16444
- queryData: originalQueryData,
16445
- ctx,
16446
- joinedContexts: Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : []
16447
- }
16448
- );
18201
+ const hasEmptyObjectData = originalQueryData.data && typeof originalQueryData.data === "object" && !Array.isArray(originalQueryData.data) && Object.keys(originalQueryData.data).length === 0;
18202
+ const hasMissingData = originalQueryData.data === void 0;
18203
+ if ((tableName === "task" || tableName === "signal_registry" || tableName === "directional_task_graph_map") && (hasEmptyObjectData || hasMissingData)) {
18204
+ console.warn("[CADENZA_SYNC_EMPTY_INSERT]", {
18205
+ tableName,
18206
+ hasMissingData,
18207
+ hasEmptyObjectData,
18208
+ taskName: typeof ctx.__taskName === "string" ? ctx.__taskName : void 0,
18209
+ reason: typeof ctx.__reason === "string" ? ctx.__reason : void 0,
18210
+ syncSourceServiceName: typeof ctx.__syncSourceServiceName === "string" ? ctx.__syncSourceServiceName : void 0,
18211
+ queryData: originalQueryData,
18212
+ ctx,
18213
+ joinedContexts: Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : []
18214
+ });
16449
18215
  }
16450
18216
  return buildSyncExecutionEnvelope(
16451
18217
  ctx,
@@ -16536,7 +18302,7 @@ function isBootstrapLocalOnlyActorName(actorName) {
16536
18302
  return BOOTSTRAP_LOCAL_ONLY_ACTOR_NAMES.has(actorName);
16537
18303
  }
16538
18304
  function isBootstrapLocalOnlySignal(signalName) {
16539
- 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);
18305
+ 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);
16540
18306
  }
16541
18307
  function hasNonZeroPending(summary) {
16542
18308
  return Object.values(summary).some((value) => Number(value) > 0);
@@ -16764,6 +18530,12 @@ function resolveLocalRoutineFromSyncContext(ctx) {
16764
18530
  );
16765
18531
  return routineName ? CadenzaService.getRoutine(routineName) : void 0;
16766
18532
  }
18533
+ function shouldTrackDirectionalTaskMapForBootstrap(predecessorTask, nextTask) {
18534
+ if (!predecessorTask || !nextTask) {
18535
+ return false;
18536
+ }
18537
+ return predecessorTask.isMeta !== true && predecessorTask.isSubMeta !== true && nextTask.isMeta !== true && nextTask.isSubMeta !== true;
18538
+ }
16767
18539
  function resolveSignalNameFromSyncContext(ctx) {
16768
18540
  const candidateSignalNames = [
16769
18541
  ctx.signalName,
@@ -17381,40 +19153,41 @@ var GraphSyncController = class _GraphSyncController {
17381
19153
  if (task.registered) continue;
17382
19154
  const { __functionString, __getTagCallback } = task.export();
17383
19155
  this.tasksSynced = false;
19156
+ const taskRegistrationData = sanitizePersistedTaskSourceFields(task, {
19157
+ name: task.name,
19158
+ version: task.version,
19159
+ description: task.description,
19160
+ function_string: __functionString,
19161
+ tag_id_getter: __getTagCallback,
19162
+ layer_index: task.layerIndex,
19163
+ concurrency: task.concurrency,
19164
+ timeout: task.timeout,
19165
+ is_unique: task.isUnique,
19166
+ is_signal: task.isSignal,
19167
+ is_throttled: task.isThrottled,
19168
+ is_debounce: task.isDebounce,
19169
+ is_ephemeral: task.isEphemeral,
19170
+ is_meta: task.isMeta,
19171
+ is_sub_meta: task.isSubMeta,
19172
+ is_hidden: task.isHidden,
19173
+ validate_input_context: task.validateInputContext,
19174
+ validate_output_context: task.validateOutputContext,
19175
+ retry_count: task.retryCount,
19176
+ retry_delay: task.retryDelay,
19177
+ retry_delay_max: task.retryDelayMax,
19178
+ retry_delay_factor: task.retryDelayFactor,
19179
+ service_name: serviceName2,
19180
+ signals: {
19181
+ emits: Array.from(task.emitsSignals),
19182
+ signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
19183
+ signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
19184
+ observed: Array.from(task.observedSignals)
19185
+ },
19186
+ intents: Array.from(task.handlesIntents)
19187
+ });
17384
19188
  yield {
17385
19189
  __syncing: ctx.__syncing,
17386
- data: {
17387
- name: task.name,
17388
- version: task.version,
17389
- description: task.description,
17390
- function_string: __functionString,
17391
- tag_id_getter: __getTagCallback,
17392
- layer_index: task.layerIndex,
17393
- concurrency: task.concurrency,
17394
- timeout: task.timeout,
17395
- is_unique: task.isUnique,
17396
- is_signal: task.isSignal,
17397
- is_throttled: task.isThrottled,
17398
- is_debounce: task.isDebounce,
17399
- is_ephemeral: task.isEphemeral,
17400
- is_meta: task.isMeta,
17401
- is_sub_meta: task.isSubMeta,
17402
- is_hidden: task.isHidden,
17403
- validate_input_context: task.validateInputContext,
17404
- validate_output_context: task.validateOutputContext,
17405
- retry_count: task.retryCount,
17406
- retry_delay: task.retryDelay,
17407
- retry_delay_max: task.retryDelayMax,
17408
- retry_delay_factor: task.retryDelayFactor,
17409
- service_name: serviceName2,
17410
- signals: {
17411
- emits: Array.from(task.emitsSignals),
17412
- signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
17413
- signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
17414
- observed: Array.from(task.observedSignals)
17415
- },
17416
- intents: Array.from(task.handlesIntents)
17417
- },
19190
+ data: taskRegistrationData,
17418
19191
  __taskName: task.name
17419
19192
  };
17420
19193
  }
@@ -17840,7 +19613,7 @@ var GraphSyncController = class _GraphSyncController {
17840
19613
  return;
17841
19614
  }
17842
19615
  for (const t of task.nextTasks) {
17843
- if (task.taskMapRegistration.has(t.name) || t.hidden || !t.register || !t.registered) {
19616
+ if (task.taskMapRegistration.has(t.name) || t.hidden || !t.register || !t.registered || !shouldTrackDirectionalTaskMapForBootstrap(task, t)) {
17844
19617
  continue;
17845
19618
  }
17846
19619
  const serviceName2 = resolveSyncServiceName(t);
@@ -17908,7 +19681,7 @@ var GraphSyncController = class _GraphSyncController {
17908
19681
  return false;
17909
19682
  }
17910
19683
  for (const nextTask of task.nextTasks) {
17911
- if (task.taskMapRegistration.has(nextTask.name) || nextTask.isHidden || !nextTask.register || !nextTask.registered) {
19684
+ if (task.taskMapRegistration.has(nextTask.name) || nextTask.isHidden || !nextTask.register || !nextTask.registered || !shouldTrackDirectionalTaskMapForBootstrap(task, nextTask)) {
17912
19685
  continue;
17913
19686
  }
17914
19687
  if (resolveSyncServiceName(nextTask)) {
@@ -18573,13 +20346,50 @@ var GraphSyncController = class _GraphSyncController {
18573
20346
  startActorPrimitiveSyncTask,
18574
20347
  startRoutinePrimitiveSyncTask
18575
20348
  );
18576
- const getAllTasksForSyncTask = CadenzaService.registry.getAllTasks.clone();
20349
+ const getAllTasksForSyncTask = CadenzaService.createMetaTask(
20350
+ "Get all tasks for sync",
20351
+ (ctx) => ({
20352
+ ...ctx,
20353
+ tasks: Array.from(CadenzaService.registry.tasks.values())
20354
+ }),
20355
+ "Collects local tasks for the primitive sync phase.",
20356
+ {
20357
+ register: false,
20358
+ isHidden: true
20359
+ }
20360
+ );
18577
20361
  startTaskPrimitiveSyncTask.then(
18578
20362
  getAllTasksForSyncTask,
18579
20363
  gatherTaskRegistrationTask
18580
20364
  );
18581
20365
  getAllTasksForSyncTask.then(this.splitTasksForRegistration);
18582
- const getSignalsForSyncTask = CadenzaService.signalBroker.getSignalsTask.clone();
20366
+ const getSignalsForSyncTask = CadenzaService.createMetaTask(
20367
+ "Get signals for sync",
20368
+ (ctx) => {
20369
+ const uniqueSignals = Array.from(
20370
+ /* @__PURE__ */ new Set([
20371
+ ...CadenzaService.signalBroker.signalObservers.keys(),
20372
+ ...CadenzaService.signalBroker.emittedSignalsRegistry
20373
+ ])
20374
+ ).filter((signal) => !signal.includes(":"));
20375
+ const processedSignals = uniqueSignals.map((signal) => ({
20376
+ signal,
20377
+ data: {
20378
+ registered: CadenzaService.signalBroker.signalObservers.get(signal)?.registered ?? false,
20379
+ metadata: CadenzaService.signalBroker.getSignalMetadata(signal) ?? null
20380
+ }
20381
+ }));
20382
+ return {
20383
+ ...ctx,
20384
+ signals: processedSignals
20385
+ };
20386
+ },
20387
+ "Collects local signals for the primitive sync phase.",
20388
+ {
20389
+ register: false,
20390
+ isHidden: true
20391
+ }
20392
+ );
18583
20393
  startSignalPrimitiveSyncTask.then(
18584
20394
  getSignalsForSyncTask,
18585
20395
  gatherSignalRegistrationTask
@@ -18621,40 +20431,110 @@ var GraphSyncController = class _GraphSyncController {
18621
20431
  gatherActorRegistrationTask
18622
20432
  );
18623
20433
  getAllActorsForSyncTask.then(this.splitActorsForRegistration);
18624
- const getAllRoutinesForSyncTask = CadenzaService.registry.getAllRoutines.clone();
20434
+ const getAllRoutinesForSyncTask = CadenzaService.createMetaTask(
20435
+ "Get all routines for sync",
20436
+ (ctx) => ({
20437
+ ...ctx,
20438
+ routines: Array.from(CadenzaService.registry.routines.values())
20439
+ }),
20440
+ "Collects local routines for the primitive sync phase.",
20441
+ {
20442
+ register: false,
20443
+ isHidden: true
20444
+ }
20445
+ );
18625
20446
  startRoutinePrimitiveSyncTask.then(
18626
20447
  getAllRoutinesForSyncTask,
18627
20448
  gatherRoutineRegistrationTask
18628
20449
  );
18629
20450
  getAllRoutinesForSyncTask.then(this.splitRoutinesTask);
18630
- const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20451
+ const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.createMetaTask(
20452
+ "Iterate tasks for directional task map sync",
20453
+ function* (ctx) {
20454
+ for (const task of CadenzaService.registry.tasks.values()) {
20455
+ yield { ...ctx, task };
20456
+ }
20457
+ },
20458
+ "Iterates local tasks for directional task-map sync.",
20459
+ {
20460
+ register: false,
20461
+ isHidden: true
20462
+ }
20463
+ );
18631
20464
  startDirectionalTaskMapSyncTask.then(
18632
20465
  iterateTasksForDirectionalTaskMapSyncTask,
18633
20466
  gatherDirectionalTaskMapRegistrationTask
18634
20467
  );
18635
20468
  iterateTasksForDirectionalTaskMapSyncTask.then(this.registerTaskMapTask);
18636
20469
  recordTaskMapRegistrationTask.then(gatherDirectionalTaskMapRegistrationTask);
18637
- const iterateTasksForSignalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20470
+ const iterateTasksForSignalTaskMapSyncTask = CadenzaService.createMetaTask(
20471
+ "Iterate tasks for signal task map sync",
20472
+ function* (ctx) {
20473
+ for (const task of CadenzaService.registry.tasks.values()) {
20474
+ yield { ...ctx, task };
20475
+ }
20476
+ },
20477
+ "Iterates local tasks for signal-to-task map sync.",
20478
+ {
20479
+ register: false,
20480
+ isHidden: true
20481
+ }
20482
+ );
18638
20483
  startSignalTaskMapSyncTask.then(
18639
20484
  iterateTasksForSignalTaskMapSyncTask,
18640
20485
  gatherSignalTaskMapRegistrationTask
18641
20486
  );
18642
20487
  iterateTasksForSignalTaskMapSyncTask.then(this.registerSignalToTaskMapTask);
18643
20488
  this.registerSignalToTaskMapTask.then(gatherSignalTaskMapRegistrationTask);
18644
- const iterateTasksForIntentTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20489
+ const iterateTasksForIntentTaskMapSyncTask = CadenzaService.createMetaTask(
20490
+ "Iterate tasks for intent task map sync",
20491
+ function* (ctx) {
20492
+ for (const task of CadenzaService.registry.tasks.values()) {
20493
+ yield { ...ctx, task };
20494
+ }
20495
+ },
20496
+ "Iterates local tasks for intent-to-task map sync.",
20497
+ {
20498
+ register: false,
20499
+ isHidden: true
20500
+ }
20501
+ );
18645
20502
  startIntentTaskMapSyncTask.then(
18646
20503
  iterateTasksForIntentTaskMapSyncTask,
18647
20504
  gatherIntentTaskMapRegistrationTask
18648
20505
  );
18649
20506
  iterateTasksForIntentTaskMapSyncTask.then(this.registerIntentToTaskMapTask);
18650
20507
  this.registerIntentToTaskMapTask.then(gatherIntentTaskMapRegistrationTask);
18651
- const iterateTasksForActorTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20508
+ const iterateTasksForActorTaskMapSyncTask = CadenzaService.createMetaTask(
20509
+ "Iterate tasks for actor task map sync",
20510
+ function* (ctx) {
20511
+ for (const task of CadenzaService.registry.tasks.values()) {
20512
+ yield { ...ctx, task };
20513
+ }
20514
+ },
20515
+ "Iterates local tasks for actor-to-task map sync.",
20516
+ {
20517
+ register: false,
20518
+ isHidden: true
20519
+ }
20520
+ );
18652
20521
  startActorTaskMapSyncTask.then(
18653
20522
  iterateTasksForActorTaskMapSyncTask,
18654
20523
  gatherActorTaskMapRegistrationTask
18655
20524
  );
18656
20525
  iterateTasksForActorTaskMapSyncTask.then(this.registerActorTaskMapTask);
18657
- const getAllRoutinesForTaskMapSyncTask = CadenzaService.registry.getAllRoutines.clone();
20526
+ const getAllRoutinesForTaskMapSyncTask = CadenzaService.createMetaTask(
20527
+ "Get all routines for task map sync",
20528
+ (ctx) => ({
20529
+ ...ctx,
20530
+ routines: Array.from(CadenzaService.registry.routines.values())
20531
+ }),
20532
+ "Collects local routines for routine-to-task map sync.",
20533
+ {
20534
+ register: false,
20535
+ isHidden: true
20536
+ }
20537
+ );
18658
20538
  startRoutineTaskMapSyncTask.then(
18659
20539
  getAllRoutinesForTaskMapSyncTask,
18660
20540
  gatherRoutineTaskMapRegistrationTask
@@ -18730,11 +20610,37 @@ function resolveTaskByName(name) {
18730
20610
  const taskName = String(name ?? "");
18731
20611
  return taskName ? CadenzaService.get(taskName) : void 0;
18732
20612
  }
20613
+ function resolveHelperFromMetadataContext(ctx) {
20614
+ const toolRuntime = CadenzaService;
20615
+ const helperName = String(
20616
+ ctx?.helperName ?? ctx?.data?.helperName ?? ctx?.data?.helper_name ?? ctx?.filter?.helperName ?? ctx?.filter?.helper_name ?? ""
20617
+ );
20618
+ return helperName ? toolRuntime.getHelper?.(helperName) : void 0;
20619
+ }
20620
+ function resolveGlobalFromMetadataContext(ctx) {
20621
+ const toolRuntime = CadenzaService;
20622
+ const globalName = String(
20623
+ ctx?.globalName ?? ctx?.data?.globalName ?? ctx?.data?.global_name ?? ctx?.filter?.globalName ?? ctx?.filter?.global_name ?? ""
20624
+ );
20625
+ return globalName ? toolRuntime.getGlobal?.(globalName) : void 0;
20626
+ }
18733
20627
  function resolvePredecessorTaskFromMetadataContext(ctx) {
18734
20628
  return resolveTaskByName(
18735
20629
  ctx?.predecessorTaskName ?? ctx?.data?.predecessorTaskName ?? ctx?.data?.predecessor_task_name ?? ctx?.filter?.predecessorTaskName ?? ctx?.filter?.predecessor_task_name
18736
20630
  );
18737
20631
  }
20632
+ function sanitizePersistedTaskSourceFields2(task, data) {
20633
+ if (!task?.isMeta && !task?.isDeputy) {
20634
+ return data;
20635
+ }
20636
+ return {
20637
+ ...data,
20638
+ functionString: "",
20639
+ function_string: "",
20640
+ tagIdGetter: null,
20641
+ tag_id_getter: null
20642
+ };
20643
+ }
18738
20644
  function shouldSkipDirectTaskMetadata(task) {
18739
20645
  return !task || !task.register || task.isHidden || task.isDeputy;
18740
20646
  }
@@ -18812,6 +20718,9 @@ function shouldPersistBusinessInquiryCompletion(ctx) {
18812
20718
  const inquiryName = String(ctx?.data?.metadata?.inquiryMeta?.inquiry ?? "");
18813
20719
  return inquiryName.length > 0 && !isMetaIntentName(inquiryName);
18814
20720
  }
20721
+ function shouldPersistExecutionTrace(ctx) {
20722
+ return ctx?.data?.isMeta !== true && ctx?.data?.is_meta !== true;
20723
+ }
18815
20724
  function shouldPersistRoutineExecution(ctx) {
18816
20725
  if (ctx?.data?.isMeta === true || ctx?.data?.is_meta === true) {
18817
20726
  return false;
@@ -18875,10 +20784,10 @@ var GraphMetadataController = class _GraphMetadataController {
18875
20784
  task.registrationRequested = true;
18876
20785
  }
18877
20786
  return buildDatabaseTriggerContext(
18878
- {
20787
+ sanitizePersistedTaskSourceFields2(task, {
18879
20788
  ...ctx.data,
18880
20789
  serviceName: CadenzaService.serviceRegistry.serviceName
18881
- },
20790
+ }),
18882
20791
  void 0,
18883
20792
  { onConflict },
18884
20793
  { onConflict }
@@ -18981,6 +20890,88 @@ var GraphMetadataController = class _GraphMetadataController {
18981
20890
  serviceName: CadenzaService.serviceRegistry.serviceName
18982
20891
  });
18983
20892
  }).doOn("meta.task.intent_associated").emits("global.meta.graph_metadata.task_intent_associated");
20893
+ const buildHelperMetadataContext = (ctx) => {
20894
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20895
+ return false;
20896
+ }
20897
+ const helper = resolveHelperFromMetadataContext(ctx);
20898
+ if (!helper) {
20899
+ return false;
20900
+ }
20901
+ return buildDatabaseTriggerContext({
20902
+ ...ctx.data,
20903
+ serviceName: CadenzaService.serviceRegistry.serviceName
20904
+ });
20905
+ };
20906
+ createLocalGraphMetadataTask("Handle helper creation", buildHelperMetadataContext).doOn("meta.helper.created").emits("global.meta.graph_metadata.helper_created");
20907
+ createLocalGraphMetadataTask("Handle helper update", buildHelperMetadataContext).doOn("meta.helper.updated").emits("global.meta.graph_metadata.helper_updated");
20908
+ const buildGlobalMetadataContext = (ctx) => {
20909
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20910
+ return false;
20911
+ }
20912
+ const globalDefinition = resolveGlobalFromMetadataContext(ctx);
20913
+ if (!globalDefinition) {
20914
+ return false;
20915
+ }
20916
+ return buildDatabaseTriggerContext({
20917
+ ...ctx.data,
20918
+ serviceName: CadenzaService.serviceRegistry.serviceName
20919
+ });
20920
+ };
20921
+ createLocalGraphMetadataTask("Handle global creation", buildGlobalMetadataContext).doOn("meta.global.created").emits("global.meta.graph_metadata.global_created");
20922
+ createLocalGraphMetadataTask("Handle global update", buildGlobalMetadataContext).doOn("meta.global.updated").emits("global.meta.graph_metadata.global_updated");
20923
+ createLocalGraphMetadataTask("Handle task helper association", (ctx) => {
20924
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20925
+ return false;
20926
+ }
20927
+ const task = resolveTaskFromMetadataContext(ctx);
20928
+ if (shouldSkipDirectTaskMetadata(task)) {
20929
+ return false;
20930
+ }
20931
+ return buildDatabaseTriggerContext({
20932
+ ...ctx.data,
20933
+ serviceName: CadenzaService.serviceRegistry.serviceName
20934
+ });
20935
+ }).doOn("meta.task.helper_associated").emits("global.meta.graph_metadata.task_helper_associated");
20936
+ createLocalGraphMetadataTask("Handle helper helper association", (ctx) => {
20937
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20938
+ return false;
20939
+ }
20940
+ const helper = resolveHelperFromMetadataContext(ctx);
20941
+ if (!helper) {
20942
+ return false;
20943
+ }
20944
+ return buildDatabaseTriggerContext({
20945
+ ...ctx.data,
20946
+ serviceName: CadenzaService.serviceRegistry.serviceName
20947
+ });
20948
+ }).doOn("meta.helper.helper_associated").emits("global.meta.graph_metadata.helper_helper_associated");
20949
+ createLocalGraphMetadataTask("Handle task global association", (ctx) => {
20950
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20951
+ return false;
20952
+ }
20953
+ const task = resolveTaskFromMetadataContext(ctx);
20954
+ if (shouldSkipDirectTaskMetadata(task)) {
20955
+ return false;
20956
+ }
20957
+ return buildDatabaseTriggerContext({
20958
+ ...ctx.data,
20959
+ serviceName: CadenzaService.serviceRegistry.serviceName
20960
+ });
20961
+ }).doOn("meta.task.global_associated").emits("global.meta.graph_metadata.task_global_associated");
20962
+ createLocalGraphMetadataTask("Handle helper global association", (ctx) => {
20963
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20964
+ return false;
20965
+ }
20966
+ const helper = resolveHelperFromMetadataContext(ctx);
20967
+ if (!helper) {
20968
+ return false;
20969
+ }
20970
+ return buildDatabaseTriggerContext({
20971
+ ...ctx.data,
20972
+ serviceName: CadenzaService.serviceRegistry.serviceName
20973
+ });
20974
+ }).doOn("meta.helper.global_associated").emits("global.meta.graph_metadata.helper_global_associated");
18984
20975
  createLocalGraphMetadataTask("Handle task unsubscribing signal", (ctx) => {
18985
20976
  if (!shouldEmitDirectPrimitiveMetadata()) {
18986
20977
  return false;
@@ -19048,6 +21039,9 @@ var GraphMetadataController = class _GraphMetadataController {
19048
21039
  });
19049
21040
  }).doOn("meta.routine.task_added").emits("global.meta.graph_metadata.task_added_to_routine");
19050
21041
  createLocalGraphMetadataTask("Handle new trace", (ctx) => {
21042
+ if (!shouldPersistExecutionTrace(ctx)) {
21043
+ return false;
21044
+ }
19051
21045
  return buildDatabaseTriggerContext({
19052
21046
  ...ctx.data,
19053
21047
  service_name: CadenzaService.serviceRegistry.serviceName,
@@ -19061,10 +21055,10 @@ var GraphMetadataController = class _GraphMetadataController {
19061
21055
  return false;
19062
21056
  }
19063
21057
  const routineData = ctx.data ?? {};
19064
- const sanitizedRoutineContext = stripLocalRoutinePersistenceHints(
21058
+ const sanitizedRoutineContext = sanitizeExecutionPersistenceContext(
19065
21059
  routineData.context ?? {}
19066
21060
  );
19067
- const sanitizedRoutineMetaContext = stripLocalRoutinePersistenceHints(
21061
+ const sanitizedRoutineMetaContext = sanitizeExecutionPersistenceContext(
19068
21062
  routineData.metaContext ?? {}
19069
21063
  );
19070
21064
  const routineExecutionRow = {
@@ -19199,12 +21193,13 @@ var GraphMetadataController = class _GraphMetadataController {
19199
21193
  createLocalGraphMetadataTask(
19200
21194
  "Handle routine execution ended",
19201
21195
  (ctx) => {
21196
+ const sanitizedData = sanitizeExecutionPersistenceResultPayload({
21197
+ ...ctx.data,
21198
+ serviceName: CadenzaService.serviceRegistry.serviceName,
21199
+ serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
21200
+ });
19202
21201
  return buildDatabaseTriggerContext(
19203
- {
19204
- ...ctx.data,
19205
- serviceName: CadenzaService.serviceRegistry.serviceName,
19206
- serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
19207
- },
21202
+ sanitizedData,
19208
21203
  ctx.filter ?? void 0
19209
21204
  );
19210
21205
  },
@@ -19218,10 +21213,10 @@ var GraphMetadataController = class _GraphMetadataController {
19218
21213
  return false;
19219
21214
  }
19220
21215
  const taskExecutionData = ctx.data ?? {};
19221
- const sanitizedTaskContext = stripLocalRoutinePersistenceHints(
21216
+ const sanitizedTaskContext = sanitizeExecutionPersistenceContext(
19222
21217
  taskExecutionData.context ?? {}
19223
21218
  );
19224
- const sanitizedTaskMetaContext = stripLocalRoutinePersistenceHints(
21219
+ const sanitizedTaskMetaContext = sanitizeExecutionPersistenceContext(
19225
21220
  taskExecutionData.metaContext ?? {}
19226
21221
  );
19227
21222
  const routineMetadata = resolveRoutinePersistenceMetadata(
@@ -19454,12 +21449,13 @@ var GraphMetadataController = class _GraphMetadataController {
19454
21449
  if (!shouldPersistTaskExecutionMetadata(ctx)) {
19455
21450
  return false;
19456
21451
  }
21452
+ const sanitizedData = sanitizeExecutionPersistenceResultPayload({
21453
+ ...ctx.data,
21454
+ serviceName: CadenzaService.serviceRegistry.serviceName,
21455
+ serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
21456
+ });
19457
21457
  return buildDatabaseTriggerContext(
19458
- {
19459
- ...ctx.data,
19460
- serviceName: CadenzaService.serviceRegistry.serviceName,
19461
- serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
19462
- },
21458
+ sanitizedData,
19463
21459
  ctx.filter ?? void 0
19464
21460
  );
19465
21461
  },
@@ -20206,6 +22202,15 @@ var DEFAULT_DEPUTY_TASK_CONCURRENCY = 50;
20206
22202
  var DEFAULT_DEPUTY_TASK_TIMEOUT_MS = 12e4;
20207
22203
  var DEFAULT_DATABASE_PROXY_TASK_CONCURRENCY = 50;
20208
22204
  var DEFAULT_DATABASE_PROXY_TASK_TIMEOUT_MS = 12e4;
22205
+ var SERVICE_MANIFEST_PUBLICATION_ORDER = [
22206
+ "routing_capability",
22207
+ "business_structural",
22208
+ "local_meta_structural"
22209
+ ];
22210
+ function getServiceManifestPublicationLayerRank(layer) {
22211
+ const index = SERVICE_MANIFEST_PUBLICATION_ORDER.indexOf(layer);
22212
+ return index >= 0 ? index : SERVICE_MANIFEST_PUBLICATION_ORDER.length - 1;
22213
+ }
20209
22214
  var CadenzaService = class {
20210
22215
  static unregisterGracefulShutdownHandlers() {
20211
22216
  for (const cleanup of this.shutdownHandlerCleanup) {
@@ -20332,7 +22337,15 @@ var CadenzaService = class {
20332
22337
  this.replayRegisteredTaskSignalObservations();
20333
22338
  this.replayRegisteredTaskIntentAssociations();
20334
22339
  }
20335
- static requestServiceManifestPublication(reason, immediate = false) {
22340
+ static normalizeServiceManifestPublicationLayer(value, fallback = "business_structural") {
22341
+ return value === "routing_capability" || value === "business_structural" || value === "local_meta_structural" ? value : fallback;
22342
+ }
22343
+ static mergeServiceManifestPublicationRequest(reason, targetLayer) {
22344
+ this.serviceManifestPublicationPendingReason = reason;
22345
+ const currentTargetLayer = this.serviceManifestPublicationPendingLayer ?? "routing_capability";
22346
+ this.serviceManifestPublicationPendingLayer = getServiceManifestPublicationLayerRank(targetLayer) >= getServiceManifestPublicationLayerRank(currentTargetLayer) ? targetLayer : currentTargetLayer;
22347
+ }
22348
+ static requestServiceManifestPublication(reason, immediate = false, targetLayer = "business_structural") {
20336
22349
  if (!this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
20337
22350
  return;
20338
22351
  }
@@ -20340,7 +22353,8 @@ var CadenzaService = class {
20340
22353
  const payload = {
20341
22354
  __reason: reason,
20342
22355
  __serviceName: this.serviceRegistry.serviceName,
20343
- __serviceInstanceId: this.serviceRegistry.serviceInstanceId
22356
+ __serviceInstanceId: this.serviceRegistry.serviceInstanceId,
22357
+ __publicationLayer: targetLayer
20344
22358
  };
20345
22359
  if (immediate) {
20346
22360
  this.emit(signalName, payload);
@@ -20348,32 +22362,53 @@ var CadenzaService = class {
20348
22362
  }
20349
22363
  this.debounce(signalName, payload, 100);
20350
22364
  }
20351
- static scheduleServiceManifestPublicationRetry(reason) {
22365
+ static scheduleServiceManifestPublicationRetry(reason, targetLayer = "business_structural") {
20352
22366
  if (!this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
20353
22367
  return;
20354
22368
  }
20355
22369
  setTimeout(() => {
20356
- this.requestServiceManifestPublication(reason, false);
22370
+ this.requestServiceManifestPublication(reason, false, targetLayer);
20357
22371
  }, 1e3);
20358
22372
  }
20359
- static async publishServiceManifestIfNeeded(reason) {
22373
+ static async publishServiceManifestIfNeeded(reason, targetLayer = "business_structural") {
20360
22374
  if (!this.serviceRegistry.connectsToCadenzaDB || !this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
20361
22375
  return false;
20362
22376
  }
20363
22377
  const publishReason = typeof reason === "string" && reason.trim().length > 0 ? reason.trim() : "service_manifest_publish";
22378
+ const publishTargetLayer = this.normalizeServiceManifestPublicationLayer(
22379
+ targetLayer
22380
+ );
20364
22381
  if (this.serviceManifestPublicationInFlight) {
20365
- this.serviceManifestPublicationPendingReason = publishReason;
22382
+ this.mergeServiceManifestPublicationRequest(
22383
+ publishReason,
22384
+ publishTargetLayer
22385
+ );
20366
22386
  return false;
20367
22387
  }
20368
- const snapshot = buildServiceManifestSnapshot({
20369
- serviceName: this.serviceRegistry.serviceName,
20370
- serviceInstanceId: this.serviceRegistry.serviceInstanceId,
20371
- revision: this.serviceManifestRevision + 1,
20372
- publishedAt: (/* @__PURE__ */ new Date()).toISOString()
22388
+ const publicationPlan = SERVICE_MANIFEST_PUBLICATION_ORDER.filter(
22389
+ (layer) => getServiceManifestPublicationLayerRank(layer) <= getServiceManifestPublicationLayerRank(publishTargetLayer)
22390
+ ).map((layer) => {
22391
+ const snapshot2 = buildServiceManifestSnapshot({
22392
+ serviceName: this.serviceRegistry.serviceName,
22393
+ serviceInstanceId: this.serviceRegistry.serviceInstanceId,
22394
+ revision: this.serviceManifestRevision + 1,
22395
+ publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
22396
+ publicationLayer: layer
22397
+ });
22398
+ return {
22399
+ layer,
22400
+ snapshot: snapshot2,
22401
+ changed: this.lastPublishedServiceManifestHashes[layer] !== snapshot2.manifestHash
22402
+ };
20373
22403
  });
20374
- if (this.lastPublishedServiceManifestHash && this.lastPublishedServiceManifestHash === snapshot.manifestHash) {
22404
+ const nextPublication = publicationPlan.find((entry) => entry.changed);
22405
+ if (!nextPublication) {
20375
22406
  return false;
20376
22407
  }
22408
+ const { layer: publicationLayer, snapshot } = nextPublication;
22409
+ const hasPendingFollowupLayer = publicationPlan.some(
22410
+ (entry) => entry.changed && getServiceManifestPublicationLayerRank(entry.layer) > getServiceManifestPublicationLayerRank(publicationLayer)
22411
+ );
20377
22412
  this.serviceManifestPublicationInFlight = true;
20378
22413
  try {
20379
22414
  this.serviceRegistry.ensureBootstrapAuthorityControlPlaneForInquiry(
@@ -20381,7 +22416,10 @@ var CadenzaService = class {
20381
22416
  snapshot
20382
22417
  );
20383
22418
  if (!this.serviceRegistry.hasAuthorityBootstrapHandshakeEstablished()) {
20384
- this.scheduleServiceManifestPublicationRetry(publishReason);
22419
+ this.scheduleServiceManifestPublicationRetry(
22420
+ publishReason,
22421
+ publishTargetLayer
22422
+ );
20385
22423
  return false;
20386
22424
  }
20387
22425
  await this.inquire(AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT, snapshot, {
@@ -20389,32 +22427,48 @@ var CadenzaService = class {
20389
22427
  requireComplete: true
20390
22428
  });
20391
22429
  this.serviceManifestRevision = snapshot.revision;
20392
- this.lastPublishedServiceManifestHash = snapshot.manifestHash;
22430
+ this.lastPublishedServiceManifestHashes[publicationLayer] = snapshot.manifestHash;
22431
+ if (hasPendingFollowupLayer) {
22432
+ this.mergeServiceManifestPublicationRequest(
22433
+ publishReason,
22434
+ publishTargetLayer
22435
+ );
22436
+ }
20393
22437
  return {
20394
22438
  serviceManifest: snapshot,
20395
- published: true
22439
+ published: true,
22440
+ publicationLayer
20396
22441
  };
20397
22442
  } catch (error) {
20398
22443
  this.log("Service manifest publication failed. Scheduling retry.", {
20399
22444
  serviceName: this.serviceRegistry.serviceName,
20400
22445
  serviceInstanceId: this.serviceRegistry.serviceInstanceId,
20401
22446
  reason: publishReason,
22447
+ publicationLayer,
20402
22448
  error: resolveInquiryFailureError(
20403
22449
  AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT,
20404
22450
  error
20405
22451
  ),
20406
22452
  inquiryMeta: error && typeof error === "object" && "__inquiryMeta" in error ? error.__inquiryMeta : null
20407
22453
  });
20408
- this.scheduleServiceManifestPublicationRetry(publishReason);
22454
+ this.scheduleServiceManifestPublicationRetry(
22455
+ publishReason,
22456
+ publishTargetLayer
22457
+ );
20409
22458
  return false;
20410
22459
  } finally {
20411
22460
  this.serviceManifestPublicationInFlight = false;
20412
- if (this.serviceManifestPublicationPendingReason) {
22461
+ if (this.serviceManifestPublicationPendingReason && this.serviceManifestPublicationPendingLayer) {
20413
22462
  const pendingReason = this.serviceManifestPublicationPendingReason;
22463
+ const pendingLayer = this.serviceManifestPublicationPendingLayer;
20414
22464
  this.serviceManifestPublicationPendingReason = null;
22465
+ this.serviceManifestPublicationPendingLayer = null;
20415
22466
  this.debounce(
20416
22467
  "meta.service_manifest.publish_requested",
20417
- { __reason: pendingReason },
22468
+ {
22469
+ __reason: pendingReason,
22470
+ __publicationLayer: pendingLayer
22471
+ },
20418
22472
  100
20419
22473
  );
20420
22474
  }
@@ -20427,9 +22481,13 @@ var CadenzaService = class {
20427
22481
  this.createMetaTask(
20428
22482
  "Publish service manifest",
20429
22483
  async (ctx) => this.publishServiceManifestIfNeeded(
20430
- typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0 ? ctx.__reason.trim() : "service_manifest_publish"
22484
+ typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0 ? ctx.__reason.trim() : "service_manifest_publish",
22485
+ this.normalizeServiceManifestPublicationLayer(
22486
+ ctx.__publicationLayer,
22487
+ "business_structural"
22488
+ )
20431
22489
  ),
20432
- "Publishes a full static manifest snapshot to authority when the manifest hash changes.",
22490
+ "Publishes staged static manifest snapshots to authority when the manifest hash changes.",
20433
22491
  {
20434
22492
  register: false,
20435
22493
  isHidden: true
@@ -20439,13 +22497,18 @@ var CadenzaService = class {
20439
22497
  "Request manifest publication after structural change",
20440
22498
  (ctx) => {
20441
22499
  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";
22500
+ const targetLayer = reason === "meta.service_registry.instance_inserted" ? "business_structural" : this.normalizeServiceManifestPublicationLayer(
22501
+ ctx.__publicationLayer,
22502
+ "business_structural"
22503
+ );
20442
22504
  this.requestServiceManifestPublication(
20443
22505
  reason,
20444
- reason === "meta.service_registry.instance_inserted"
22506
+ reason === "meta.service_registry.instance_inserted",
22507
+ targetLayer
20445
22508
  );
20446
22509
  return true;
20447
22510
  },
20448
- "Requests a manifest publication when a static service primitive changes.",
22511
+ "Requests staged manifest publication when a static service primitive changes.",
20449
22512
  {
20450
22513
  register: false,
20451
22514
  isHidden: true
@@ -20457,9 +22520,17 @@ var CadenzaService = class {
20457
22520
  "meta.task.relationship_added",
20458
22521
  "meta.task.relationship_removed",
20459
22522
  "meta.task.intent_associated",
22523
+ "meta.task.helper_associated",
22524
+ "meta.task.global_associated",
20460
22525
  "meta.task.observed_signal",
20461
22526
  "meta.task.attached_signal",
20462
22527
  "meta.task.detached_signal",
22528
+ "meta.helper.created",
22529
+ "meta.helper.updated",
22530
+ "meta.global.created",
22531
+ "meta.global.updated",
22532
+ "meta.helper.helper_associated",
22533
+ "meta.helper.global_associated",
20463
22534
  "meta.actor.created",
20464
22535
  "meta.actor.task_associated",
20465
22536
  "meta.fetch.handshake_complete",
@@ -21700,10 +23771,28 @@ var CadenzaService = class {
21700
23771
  __isFrontend: isFrontend,
21701
23772
  __declaredTransports: declaredTransports
21702
23773
  };
23774
+ let bootstrapServiceCreationRequested = false;
21703
23775
  if (options.cadenzaDB?.connect) {
21704
- this.createEphemeralMetaTask("Create service", async (context, emit2) => {
21705
- emit2("meta.create_service_requested", initContext);
21706
- }).doOn("meta.fetch.handshake_complete");
23776
+ this.createMetaTask(
23777
+ "Create service",
23778
+ async (context, emit2) => {
23779
+ const handshakeServiceName = String(context?.serviceName ?? "").trim();
23780
+ if (handshakeServiceName !== "CadenzaDB") {
23781
+ return false;
23782
+ }
23783
+ if (bootstrapServiceCreationRequested) {
23784
+ return false;
23785
+ }
23786
+ bootstrapServiceCreationRequested = true;
23787
+ emit2("meta.create_service_requested", initContext);
23788
+ return true;
23789
+ },
23790
+ "Requests local service creation only once after the initial authority bootstrap handshake completes.",
23791
+ {
23792
+ register: false,
23793
+ isHidden: true
23794
+ }
23795
+ ).doOn("meta.fetch.handshake_complete");
21707
23796
  } else {
21708
23797
  this.emit("meta.create_service_requested", initContext);
21709
23798
  this.createMetaTask("Create signal transmission for sync", (ctx, emit2) => {
@@ -21716,10 +23805,33 @@ var CadenzaService = class {
21716
23805
  );
21717
23806
  }).doOn("meta.rest.handshake", "meta.socket.handshake");
21718
23807
  }
23808
+ let serviceSetupCompletedHandled = false;
21719
23809
  this.createMetaTask("Handle service setup completion", (ctx, emit2) => {
23810
+ if (serviceSetupCompletedHandled) {
23811
+ return false;
23812
+ }
23813
+ const insertedServiceInstanceId = String(
23814
+ ctx?.serviceInstanceId ?? ctx?.service_instance_id ?? ctx?.serviceInstance?.uuid ?? ctx?.serviceInstance?.serviceInstanceId ?? ""
23815
+ ).trim();
23816
+ const insertedServiceName = String(
23817
+ ctx?.serviceName ?? ctx?.service_name ?? ctx?.serviceInstance?.serviceName ?? ctx?.serviceInstance?.service_name ?? ""
23818
+ ).trim();
23819
+ if (!insertedServiceInstanceId && !insertedServiceName) {
23820
+ return false;
23821
+ }
23822
+ if (insertedServiceInstanceId && insertedServiceInstanceId !== serviceId) {
23823
+ return false;
23824
+ }
23825
+ if (!insertedServiceInstanceId && insertedServiceName && insertedServiceName !== serviceName) {
23826
+ return false;
23827
+ }
23828
+ serviceSetupCompletedHandled = true;
21720
23829
  if (options.cadenzaDB?.connect) {
21721
23830
  this.serviceRegistry.bootstrapFullSync(emit2, ctx, "service_setup_completed");
21722
- void this.publishServiceManifestIfNeeded("service_setup_completed");
23831
+ void this.publishServiceManifestIfNeeded(
23832
+ "service_setup_completed",
23833
+ "business_structural"
23834
+ );
21723
23835
  }
21724
23836
  if (isFrontend) {
21725
23837
  registerActorSessionPersistenceTasks();
@@ -21774,7 +23886,11 @@ var CadenzaService = class {
21774
23886
  );
21775
23887
  }
21776
23888
  this.serviceCreated = true;
21777
- this.requestServiceManifestPublication("service_created", true);
23889
+ this.requestServiceManifestPublication(
23890
+ "service_created",
23891
+ true,
23892
+ "routing_capability"
23893
+ );
21778
23894
  }
21779
23895
  /**
21780
23896
  * Creates a Cadenza metadata service with the specified name, description, and options.
@@ -22530,6 +24646,11 @@ var CadenzaService = class {
22530
24646
  this.warnedInvalidMetaIntentResponderKeys = /* @__PURE__ */ new Set();
22531
24647
  this.hydratedInquiryResults = /* @__PURE__ */ new Map();
22532
24648
  this.frontendSyncScheduled = false;
24649
+ this.serviceManifestRevision = 0;
24650
+ this.lastPublishedServiceManifestHashes = {};
24651
+ this.serviceManifestPublicationInFlight = false;
24652
+ this.serviceManifestPublicationPendingReason = null;
24653
+ this.serviceManifestPublicationPendingLayer = null;
22533
24654
  resetBrowserRuntimeActorHandles();
22534
24655
  }
22535
24656
  };
@@ -22543,9 +24664,10 @@ CadenzaService.warnedInvalidMetaIntentResponderKeys = /* @__PURE__ */ new Set();
22543
24664
  CadenzaService.hydratedInquiryResults = /* @__PURE__ */ new Map();
22544
24665
  CadenzaService.frontendSyncScheduled = false;
22545
24666
  CadenzaService.serviceManifestRevision = 0;
22546
- CadenzaService.lastPublishedServiceManifestHash = null;
24667
+ CadenzaService.lastPublishedServiceManifestHashes = {};
22547
24668
  CadenzaService.serviceManifestPublicationInFlight = false;
22548
24669
  CadenzaService.serviceManifestPublicationPendingReason = null;
24670
+ CadenzaService.serviceManifestPublicationPendingLayer = null;
22549
24671
  CadenzaService.shutdownHandlersRegistered = false;
22550
24672
  CadenzaService.shutdownInFlight = false;
22551
24673
  CadenzaService.shutdownHandlerCleanup = [];
@@ -22579,6 +24701,17 @@ function normalizeArrayResponse(value, keys) {
22579
24701
  if (Array.isArray(value?.data)) {
22580
24702
  return value.data;
22581
24703
  }
24704
+ const joinedContexts = Array.isArray(value?.joinedContexts) ? value.joinedContexts : [];
24705
+ for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
24706
+ const nested = joinedContexts[index];
24707
+ if (!nested || typeof nested !== "object") {
24708
+ continue;
24709
+ }
24710
+ const rows = normalizeArrayResponse(nested, keys);
24711
+ if (rows.length > 0) {
24712
+ return rows;
24713
+ }
24714
+ }
22582
24715
  return [];
22583
24716
  }
22584
24717
  function buildQueryResponseKeys(tableName) {