@cadenza.io/service 2.20.0 → 2.20.1

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.
@@ -79,14 +79,55 @@ var ROOT_METADATA_PASSTHROUGH_KEYS = [
79
79
  "__inquirySourceRoutineExecutionId"
80
80
  ];
81
81
  var DELEGATION_REQUEST_SNAPSHOT_KEY = "__delegationRequestContext";
82
+ var DELEGATION_FAILURE_CONTEXT_KEYS = [
83
+ "__remoteRoutineName",
84
+ "__serviceName",
85
+ "__timeout",
86
+ "__localTaskName",
87
+ "__localTaskVersion",
88
+ "__localServiceName",
89
+ "__localRoutineExecId",
90
+ "__previousTaskExecutionId",
91
+ "__fetchId",
92
+ "fetchId",
93
+ "__routeKey",
94
+ "routeKey",
95
+ "__instance",
96
+ "__transportId",
97
+ "__transportOrigin",
98
+ "__transportProtocols",
99
+ "__transportProtocol",
100
+ "__retries",
101
+ "__triedInstances",
102
+ "__delegationRequestContext",
103
+ "__metadata",
104
+ "serviceName",
105
+ "serviceInstanceId",
106
+ "serviceTransportId",
107
+ "serviceOrigin",
108
+ "transportProtocols",
109
+ "transportProtocol"
110
+ ];
111
+ function isPlainObject(value) {
112
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
113
+ return false;
114
+ }
115
+ const prototype = Object.getPrototypeOf(value);
116
+ return prototype === Object.prototype || prototype === null;
117
+ }
82
118
  function cloneDelegationValue(value) {
119
+ if (value instanceof Date) {
120
+ return new Date(value.getTime());
121
+ }
83
122
  if (Array.isArray(value)) {
84
- return value.map(
85
- (item) => item && typeof item === "object" ? { ...item } : item
86
- );
123
+ return value.map((item) => cloneDelegationValue(item));
87
124
  }
88
- if (value && typeof value === "object") {
89
- return { ...value };
125
+ if (isPlainObject(value)) {
126
+ const clone = {};
127
+ for (const [key, nestedValue] of Object.entries(value)) {
128
+ clone[key] = cloneDelegationValue(nestedValue);
129
+ }
130
+ return clone;
90
131
  }
91
132
  return value;
92
133
  }
@@ -122,9 +163,9 @@ function attachDelegationRequestSnapshot(input) {
122
163
  function restoreDelegationRequestSnapshot(input) {
123
164
  const context = input && typeof input === "object" ? { ...input } : {};
124
165
  const mutableContext = context;
125
- const snapshotCandidate = mutableContext[DELEGATION_REQUEST_SNAPSHOT_KEY];
166
+ const snapshotCandidate = mutableContext[DELEGATION_REQUEST_SNAPSHOT_KEY] ?? (mutableContext.__metadata && typeof mutableContext.__metadata === "object" ? mutableContext.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY] : void 0);
126
167
  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;
168
+ 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
169
  if (!snapshot || !looksLikeDelegationResult) {
129
170
  return context;
130
171
  }
@@ -145,6 +186,26 @@ function stripDelegationRequestSnapshot(input) {
145
186
  delete context[DELEGATION_REQUEST_SNAPSHOT_KEY];
146
187
  return context;
147
188
  }
189
+ function buildDelegationFailureContext(signalName, input, error) {
190
+ const source = input && typeof input === "object" ? { ...input } : {};
191
+ const slimContext = {};
192
+ for (const key of DELEGATION_FAILURE_CONTEXT_KEYS) {
193
+ if (source[key] !== void 0) {
194
+ slimContext[key] = cloneDelegationValue(source[key]);
195
+ }
196
+ }
197
+ if (slimContext[DELEGATION_REQUEST_SNAPSHOT_KEY] === void 0 && source.__metadata && typeof source.__metadata === "object" && source.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY] !== void 0) {
198
+ slimContext[DELEGATION_REQUEST_SNAPSHOT_KEY] = cloneDelegationValue(
199
+ source.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY]
200
+ );
201
+ }
202
+ return {
203
+ __signalName: signalName,
204
+ __error: error instanceof Error ? error.message : String(error ?? "Unknown error"),
205
+ errored: true,
206
+ ...slimContext
207
+ };
208
+ }
148
209
  function stripTransportSelectionRoutingContext(input) {
149
210
  const context = stripLocalRoutinePersistenceHints(
150
211
  input && typeof input === "object" ? { ...input } : {}
@@ -364,6 +425,8 @@ var DeputyTask = class extends Task {
364
425
 
365
426
  // src/graph/definition/DatabaseTask.ts
366
427
  var ACTOR_SESSION_TRACE_ENABLED = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
428
+ var actorSessionEmptyDelegationLogCount = 0;
429
+ var ACTOR_SESSION_EMPTY_DELEGATION_LOG_LIMIT = 40;
367
430
  var INSTANCE_TRACE_ENABLED = process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true";
368
431
  var EXECUTION_OBSERVABILITY_INSERT_ROUTINES = /* @__PURE__ */ new Set([
369
432
  "Insert execution_trace",
@@ -465,15 +528,16 @@ var DatabaseTask = class extends DeputyTask {
465
528
  }
466
529
  delete ctx.__metadata;
467
530
  const isResolverExecution = typeof ctx.__resolverRequestId === "string" && ctx.__resolverRequestId.length > 0;
468
- const dynamicQueryData = isResolverExecution ? {} : ctx.__resolverQueryData && typeof ctx.__resolverQueryData === "object" ? ctx.__resolverQueryData : ctx.queryData ?? {};
531
+ const resolverQueryData = ctx.__resolverQueryData && typeof ctx.__resolverQueryData === "object" ? ctx.__resolverQueryData : null;
532
+ const dynamicQueryData = resolverQueryData ?? (ctx.queryData && typeof ctx.queryData === "object" ? ctx.queryData : {});
469
533
  delete ctx.queryData;
470
534
  const nextQueryData = {
471
535
  ...this.queryData,
472
- data: {
473
- ...ctx.data
474
- },
475
536
  ...dynamicQueryData
476
537
  };
538
+ if (dynamicQueryData.data === void 0 && ctx.data !== void 0) {
539
+ nextQueryData.data = ctx.data && typeof ctx.data === "object" && !Array.isArray(ctx.data) ? { ...ctx.data } : ctx.data;
540
+ }
477
541
  const deputyContext = attachDelegationRequestSnapshot(
478
542
  stripDelegationRequestSnapshot(
479
543
  hoistDelegationMetadataFields({
@@ -533,6 +597,22 @@ var DatabaseTask = class extends DeputyTask {
533
597
  rootKeys: Object.keys(rawContext)
534
598
  });
535
599
  }
600
+ if (this.remoteRoutineName === "Insert actor_session_state" && deputyContext.data === void 0 && deputyContext.queryData === void 0 && actorSessionEmptyDelegationLogCount < ACTOR_SESSION_EMPTY_DELEGATION_LOG_LIMIT) {
601
+ actorSessionEmptyDelegationLogCount += 1;
602
+ console.warn("[CADENZA_ACTOR_SESSION_EMPTY_DELEGATION]", {
603
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
604
+ localTaskName: this.name,
605
+ remoteRoutineName: this.remoteRoutineName,
606
+ hadSnapshotBeforeRestore: initialFullContext.__delegationRequestContext !== void 0 || initialFullContext.__metadata?.__delegationRequestContext !== void 0,
607
+ restoredRootKeys: Object.keys(rawContext),
608
+ deputyRootKeys: Object.keys(deputyContext),
609
+ signalName: rawContext.__signalName ?? rawContext.__metadata?.__signalName ?? null,
610
+ inquiryName: rawContext.__inquiryName ?? rawContext.__metadata?.__inquiryName ?? null,
611
+ sourceServiceName: rawContext.__localServiceName ?? rawContext.__metadata?.__localServiceName ?? null,
612
+ sourceRoutineName: rawContext.__routineName ?? rawContext.__metadata?.__routineName ?? null,
613
+ sourceTaskName: rawContext.__localTaskName ?? rawContext.__metadata?.__localTaskName ?? null
614
+ });
615
+ }
536
616
  return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
537
617
  }
538
618
  };
@@ -572,14 +652,14 @@ var META_INTENT_PREFIX = "meta-";
572
652
  var META_RUNTIME_TRANSPORT_DIAGNOSTICS_INTENT = "meta-runtime-transport-diagnostics";
573
653
  var META_RUNTIME_STATUS_INTENT = "meta-runtime-status";
574
654
  var META_READINESS_INTENT = "meta-readiness";
575
- function isPlainObject(value) {
655
+ function isPlainObject2(value) {
576
656
  return typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
577
657
  }
578
658
  function deepMergeDeterministic(left, right) {
579
659
  if (Array.isArray(left) && Array.isArray(right)) {
580
660
  return [...left, ...right];
581
661
  }
582
- if (isPlainObject(left) && isPlainObject(right)) {
662
+ if (isPlainObject2(left) && isPlainObject2(right)) {
583
663
  const merged = { ...left };
584
664
  const keys = Array.from(/* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])).sort();
585
665
  for (const key of keys) {
@@ -1401,6 +1481,7 @@ function normalizeServiceManifestSnapshot(input) {
1401
1481
  revision,
1402
1482
  manifestHash,
1403
1483
  publishedAt,
1484
+ publicationLayer: record.publicationLayer === "routing_capability" || record.publicationLayer === "business_structural" || record.publicationLayer === "local_meta_structural" ? record.publicationLayer : "business_structural",
1404
1485
  tasks: normalizeArray(record.tasks),
1405
1486
  signals: normalizeArray(record.signals),
1406
1487
  intents: normalizeArray(record.intents),
@@ -1530,6 +1611,7 @@ function decomposeSignalName(signalName) {
1530
1611
  }
1531
1612
 
1532
1613
  // src/registry/serviceManifest.ts
1614
+ import CoreCadenza from "@cadenza.io/core";
1533
1615
  var ACTOR_TASK_METADATA = /* @__PURE__ */ Symbol.for("@cadenza.io/core/actor-task-meta");
1534
1616
  function getActorTaskRuntimeMetadata(taskFunction) {
1535
1617
  if (typeof taskFunction !== "function") {
@@ -1674,14 +1756,48 @@ function buildRoutineDefinition(routine, serviceName) {
1674
1756
  };
1675
1757
  }
1676
1758
  function shouldExportTask(task) {
1677
- return !task.isDeputy && !task.isEphemeral;
1759
+ return task.register !== false && task.isHidden !== true && !task.isDeputy && !task.isEphemeral;
1678
1760
  }
1679
1761
  function shouldExportRoutine(routine) {
1680
1762
  return Boolean(String(routine?.name ?? "").trim());
1681
1763
  }
1764
+ function buildTaskKey(task) {
1765
+ return `${task.service_name}|${task.name}|${task.version}`;
1766
+ }
1767
+ function buildActorKey(actor) {
1768
+ return `${actor.service_name}|${actor.name}|${actor.version}`;
1769
+ }
1770
+ function buildRoutineKey(routine) {
1771
+ return `${routine.service_name}|${routine.name}|${routine.version}`;
1772
+ }
1773
+ function listManifestTasks() {
1774
+ const registryTasks = Array.from(CadenzaService.registry.tasks.values()).filter(
1775
+ (task) => Boolean(task)
1776
+ );
1777
+ const cachedTasks = Array.from(
1778
+ CoreCadenza.taskCache?.values?.() ?? []
1779
+ ).filter((task) => Boolean(task));
1780
+ return Array.from(
1781
+ new Map(
1782
+ [...registryTasks, ...cachedTasks].map((task) => [task.name, task])
1783
+ ).values()
1784
+ );
1785
+ }
1786
+ function isRoutingCriticalMetaSignal(_signal) {
1787
+ return false;
1788
+ }
1789
+ function isRoutingCriticalMetaIntent(_intent) {
1790
+ return false;
1791
+ }
1682
1792
  function buildServiceManifestSnapshot(params) {
1683
- const { serviceName, serviceInstanceId, revision, publishedAt } = params;
1684
- const tasks = Array.from(CadenzaService.registry.tasks.values()).filter((task) => Boolean(task)).filter(shouldExportTask);
1793
+ const {
1794
+ serviceName,
1795
+ serviceInstanceId,
1796
+ revision,
1797
+ publishedAt,
1798
+ publicationLayer = "business_structural"
1799
+ } = params;
1800
+ const tasks = listManifestTasks().filter(shouldExportTask);
1685
1801
  const routines = Array.from(CadenzaService.registry.routines.values()).filter((routine) => Boolean(routine)).filter(shouldExportRoutine);
1686
1802
  const actors = CadenzaService.getAllActors();
1687
1803
  const taskDefinitions = tasks.map((task) => buildTaskDefinition(task, serviceName)).sort(
@@ -1829,41 +1945,385 @@ function buildServiceManifestSnapshot(params) {
1829
1945
  }
1830
1946
  }
1831
1947
  }
1832
- const manifestBody = {
1833
- serviceName,
1834
- serviceInstanceId,
1835
- tasks: taskDefinitions,
1836
- signals: Array.from(signalDefinitions.values()).sort(
1837
- (left, right) => left.name.localeCompare(right.name)
1838
- ),
1839
- intents: intentDefinitions,
1840
- actors: actorDefinitions,
1841
- routines: routineDefinitions,
1842
- directionalTaskMaps: Array.from(directionalTaskMaps.values()).sort(
1843
- (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
1844
- `${right.predecessor_task_name}:${right.task_name}`
1845
- )
1846
- ),
1847
- signalToTaskMaps: Array.from(signalTaskMaps.values()).sort(
1848
- (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
1849
- `${right.signal_name}:${right.task_name}`
1850
- )
1851
- ),
1852
- intentToTaskMaps: Array.from(intentTaskMaps.values()).sort(
1853
- (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
1854
- `${right.intent_name}:${right.task_name}`
1948
+ const taskDefinitionsByKey = new Map(
1949
+ taskDefinitions.map((task) => [buildTaskKey(task), task])
1950
+ );
1951
+ const signalDefinitionsByName = new Map(
1952
+ Array.from(signalDefinitions.values()).map((signal) => [signal.name, signal])
1953
+ );
1954
+ const intentDefinitionsByName = new Map(
1955
+ intentDefinitions.map((intent) => [intent.name, intent])
1956
+ );
1957
+ const actorDefinitionsByKey = new Map(
1958
+ actorDefinitions.map((actor) => [buildActorKey(actor), actor])
1959
+ );
1960
+ const routineDefinitionsByKey = new Map(
1961
+ routineDefinitions.map((routine) => [buildRoutineKey(routine), routine])
1962
+ );
1963
+ const routingTaskKeys = /* @__PURE__ */ new Set();
1964
+ const routingSignalNames = /* @__PURE__ */ new Set();
1965
+ const routingIntentNames = /* @__PURE__ */ new Set();
1966
+ const publishedSignalTaskMaps = Array.from(signalTaskMaps.values()).filter((map) => {
1967
+ const signal = signalDefinitionsByName.get(map.signal_name);
1968
+ return signal?.is_meta !== true || (signal ? isRoutingCriticalMetaSignal(signal) : false);
1969
+ }).sort(
1970
+ (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
1971
+ `${right.signal_name}:${right.task_name}`
1972
+ )
1973
+ );
1974
+ const publishedIntentTaskMaps = Array.from(intentTaskMaps.values()).filter((map) => {
1975
+ const intent = intentDefinitionsByName.get(map.intent_name);
1976
+ return intent?.is_meta !== true || (intent ? isRoutingCriticalMetaIntent(intent) : false);
1977
+ }).sort(
1978
+ (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
1979
+ `${right.intent_name}:${right.task_name}`
1980
+ )
1981
+ );
1982
+ const localMetaSignalTaskMaps = Array.from(signalTaskMaps.values()).filter((map) => !publishedSignalTaskMaps.includes(map)).sort(
1983
+ (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
1984
+ `${right.signal_name}:${right.task_name}`
1985
+ )
1986
+ );
1987
+ const localMetaIntentTaskMaps = Array.from(intentTaskMaps.values()).filter((map) => !publishedIntentTaskMaps.includes(map)).sort(
1988
+ (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
1989
+ `${right.intent_name}:${right.task_name}`
1990
+ )
1991
+ );
1992
+ for (const map of publishedSignalTaskMaps) {
1993
+ routingTaskKeys.add(
1994
+ buildTaskKey({
1995
+ service_name: map.service_name,
1996
+ name: map.task_name,
1997
+ version: map.task_version
1998
+ })
1999
+ );
2000
+ routingSignalNames.add(map.signal_name);
2001
+ }
2002
+ for (const map of publishedIntentTaskMaps) {
2003
+ routingTaskKeys.add(
2004
+ buildTaskKey({
2005
+ service_name: map.service_name,
2006
+ name: map.task_name,
2007
+ version: map.task_version
2008
+ })
2009
+ );
2010
+ routingIntentNames.add(map.intent_name);
2011
+ }
2012
+ const routingTasks = Array.from(routingTaskKeys).map((key) => taskDefinitionsByKey.get(key) ?? null).filter((task) => task !== null).sort(
2013
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2014
+ );
2015
+ const routingSignals = Array.from(routingSignalNames).map((name) => signalDefinitionsByName.get(name) ?? null).filter((signal) => signal !== null).sort((left, right) => left.name.localeCompare(right.name));
2016
+ const routingIntents = Array.from(routingIntentNames).map((name) => intentDefinitionsByName.get(name) ?? null).filter((intent) => intent !== null).sort((left, right) => left.name.localeCompare(right.name));
2017
+ const businessTasks = taskDefinitions.filter((task) => task.is_meta !== true && task.is_sub_meta !== true).sort(
2018
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2019
+ );
2020
+ const businessSignals = Array.from(signalDefinitions.values()).filter((signal) => signal.is_meta !== true).sort((left, right) => left.name.localeCompare(right.name));
2021
+ const businessIntents = intentDefinitions.filter((intent) => intent.is_meta !== true).sort((left, right) => left.name.localeCompare(right.name));
2022
+ const businessActors = actorDefinitions.filter((actor) => actor.is_meta !== true).sort(
2023
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2024
+ );
2025
+ const businessRoutines = routineDefinitions.filter((routine) => routine.is_meta !== true).sort(
2026
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2027
+ );
2028
+ const businessDirectionalTaskMaps = Array.from(directionalTaskMaps.values()).filter((map) => {
2029
+ const predecessor = taskDefinitionsByKey.get(
2030
+ buildTaskKey({
2031
+ service_name: map.predecessor_service_name,
2032
+ name: map.predecessor_task_name,
2033
+ version: map.predecessor_task_version
2034
+ })
2035
+ );
2036
+ const task = taskDefinitionsByKey.get(
2037
+ buildTaskKey({
2038
+ service_name: map.service_name,
2039
+ name: map.task_name,
2040
+ version: map.task_version
2041
+ })
2042
+ );
2043
+ return predecessor?.is_meta !== true && predecessor?.is_sub_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
2044
+ }).sort(
2045
+ (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
2046
+ `${right.predecessor_task_name}:${right.task_name}`
2047
+ )
2048
+ );
2049
+ const businessActorTaskMaps = Array.from(actorTaskMaps.values()).filter((map) => {
2050
+ const actor = actorDefinitionsByKey.get(
2051
+ buildActorKey({
2052
+ service_name: map.service_name,
2053
+ name: map.actor_name,
2054
+ version: map.actor_version
2055
+ })
2056
+ );
2057
+ const task = taskDefinitionsByKey.get(
2058
+ buildTaskKey({
2059
+ service_name: map.service_name,
2060
+ name: map.task_name,
2061
+ version: map.task_version
2062
+ })
2063
+ );
2064
+ return actor?.is_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
2065
+ }).sort(
2066
+ (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
2067
+ `${right.actor_name}:${right.task_name}`
2068
+ )
2069
+ );
2070
+ const businessTaskToRoutineMaps = Array.from(taskToRoutineMaps.values()).filter((map) => {
2071
+ const routine = routineDefinitionsByKey.get(
2072
+ buildRoutineKey({
2073
+ service_name: map.service_name,
2074
+ name: map.routine_name,
2075
+ version: map.routine_version
2076
+ })
2077
+ );
2078
+ const task = taskDefinitionsByKey.get(
2079
+ buildTaskKey({
2080
+ service_name: map.service_name,
2081
+ name: map.task_name,
2082
+ version: map.task_version
2083
+ })
2084
+ );
2085
+ return routine?.is_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
2086
+ }).sort(
2087
+ (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
2088
+ `${right.routine_name}:${right.task_name}`
2089
+ )
2090
+ );
2091
+ const localMetaTasks = taskDefinitions.filter((task) => task.is_meta === true || task.is_sub_meta === true).sort(
2092
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2093
+ );
2094
+ const localMetaSignals = Array.from(signalDefinitions.values()).filter((signal) => signal.is_meta === true).sort((left, right) => left.name.localeCompare(right.name));
2095
+ const localMetaIntents = intentDefinitions.filter((intent) => intent.is_meta === true).sort((left, right) => left.name.localeCompare(right.name));
2096
+ const localMetaActors = actorDefinitions.filter((actor) => actor.is_meta === true).sort(
2097
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2098
+ );
2099
+ const localMetaRoutines = routineDefinitions.filter((routine) => routine.is_meta === true).sort(
2100
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2101
+ );
2102
+ const localMetaDirectionalTaskMaps = Array.from(directionalTaskMaps.values()).filter((map) => !businessDirectionalTaskMaps.includes(map)).sort(
2103
+ (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
2104
+ `${right.predecessor_task_name}:${right.task_name}`
2105
+ )
2106
+ );
2107
+ const localMetaActorTaskMaps = Array.from(actorTaskMaps.values()).filter((map) => !businessActorTaskMaps.includes(map)).sort(
2108
+ (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
2109
+ `${right.actor_name}:${right.task_name}`
2110
+ )
2111
+ );
2112
+ const localMetaTaskToRoutineMaps = Array.from(taskToRoutineMaps.values()).filter((map) => !businessTaskToRoutineMaps.includes(map)).sort(
2113
+ (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
2114
+ `${right.routine_name}:${right.task_name}`
2115
+ )
2116
+ );
2117
+ const businessLocalMetaTaskKeys = /* @__PURE__ */ new Set();
2118
+ const businessLocalMetaSignalNames = /* @__PURE__ */ new Set();
2119
+ const businessLocalMetaIntentNames = /* @__PURE__ */ new Set();
2120
+ const businessLocalMetaActorKeys = /* @__PURE__ */ new Set();
2121
+ const businessLocalMetaRoutineKeys = /* @__PURE__ */ new Set();
2122
+ for (const map of localMetaSignalTaskMaps) {
2123
+ businessLocalMetaSignalNames.add(map.signal_name);
2124
+ businessLocalMetaTaskKeys.add(
2125
+ buildTaskKey({
2126
+ service_name: map.service_name,
2127
+ name: map.task_name,
2128
+ version: map.task_version
2129
+ })
2130
+ );
2131
+ }
2132
+ for (const map of localMetaIntentTaskMaps) {
2133
+ businessLocalMetaIntentNames.add(map.intent_name);
2134
+ businessLocalMetaTaskKeys.add(
2135
+ buildTaskKey({
2136
+ service_name: map.service_name,
2137
+ name: map.task_name,
2138
+ version: map.task_version
2139
+ })
2140
+ );
2141
+ }
2142
+ for (const map of localMetaActorTaskMaps) {
2143
+ businessLocalMetaActorKeys.add(
2144
+ buildActorKey({
2145
+ service_name: map.service_name,
2146
+ name: map.actor_name,
2147
+ version: map.actor_version
2148
+ })
2149
+ );
2150
+ businessLocalMetaTaskKeys.add(
2151
+ buildTaskKey({
2152
+ service_name: map.service_name,
2153
+ name: map.task_name,
2154
+ version: map.task_version
2155
+ })
2156
+ );
2157
+ }
2158
+ for (const map of localMetaTaskToRoutineMaps) {
2159
+ businessLocalMetaRoutineKeys.add(
2160
+ buildRoutineKey({
2161
+ service_name: map.service_name,
2162
+ name: map.routine_name,
2163
+ version: map.routine_version
2164
+ })
2165
+ );
2166
+ businessLocalMetaTaskKeys.add(
2167
+ buildTaskKey({
2168
+ service_name: map.service_name,
2169
+ name: map.task_name,
2170
+ version: map.task_version
2171
+ })
2172
+ );
2173
+ }
2174
+ const businessLocalMetaTasks = Array.from(businessLocalMetaTaskKeys).map((key) => taskDefinitionsByKey.get(key) ?? null).filter(
2175
+ (task) => task !== null && (task.is_meta === true || task.is_sub_meta === true)
2176
+ ).sort(
2177
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2178
+ );
2179
+ const businessLocalMetaSignals = Array.from(businessLocalMetaSignalNames).map((name) => signalDefinitionsByName.get(name) ?? null).filter(
2180
+ (signal) => signal !== null && signal.is_meta === true
2181
+ ).sort((left, right) => left.name.localeCompare(right.name));
2182
+ const businessLocalMetaIntents = Array.from(businessLocalMetaIntentNames).map((name) => intentDefinitionsByName.get(name) ?? null).filter(
2183
+ (intent) => intent !== null && intent.is_meta === true
2184
+ ).sort((left, right) => left.name.localeCompare(right.name));
2185
+ const businessLocalMetaActors = Array.from(businessLocalMetaActorKeys).map((key) => actorDefinitionsByKey.get(key) ?? null).filter(
2186
+ (actor) => actor !== null && actor.is_meta === true
2187
+ ).sort(
2188
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2189
+ );
2190
+ const businessLocalMetaRoutines = Array.from(businessLocalMetaRoutineKeys).map((key) => routineDefinitionsByKey.get(key) ?? null).filter(
2191
+ (routine) => routine !== null && routine.is_meta === true
2192
+ ).sort(
2193
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2194
+ );
2195
+ const cumulativeTasks = publicationLayer === "routing_capability" ? routingTasks : publicationLayer === "business_structural" ? Array.from(
2196
+ new Map(
2197
+ [...routingTasks, ...businessTasks, ...businessLocalMetaTasks].map((task) => [
2198
+ buildTaskKey(task),
2199
+ task
2200
+ ])
2201
+ ).values()
2202
+ ).sort(
2203
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2204
+ ) : Array.from(
2205
+ new Map(
2206
+ [...routingTasks, ...businessTasks, ...localMetaTasks].map((task) => [
2207
+ buildTaskKey(task),
2208
+ task
2209
+ ])
2210
+ ).values()
2211
+ ).sort(
2212
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2213
+ );
2214
+ const cumulativeSignals = publicationLayer === "routing_capability" ? routingSignals : publicationLayer === "business_structural" ? Array.from(
2215
+ new Map(
2216
+ [...routingSignals, ...businessSignals, ...businessLocalMetaSignals].map(
2217
+ (signal) => [signal.name, signal]
1855
2218
  )
1856
- ),
1857
- actorTaskMaps: Array.from(actorTaskMaps.values()).sort(
1858
- (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
1859
- `${right.actor_name}:${right.task_name}`
2219
+ ).values()
2220
+ ).sort((left, right) => left.name.localeCompare(right.name)) : Array.from(
2221
+ new Map(
2222
+ [...routingSignals, ...businessSignals, ...localMetaSignals].map((signal) => [
2223
+ signal.name,
2224
+ signal
2225
+ ])
2226
+ ).values()
2227
+ ).sort((left, right) => left.name.localeCompare(right.name));
2228
+ const cumulativeIntents = publicationLayer === "routing_capability" ? routingIntents : publicationLayer === "business_structural" ? Array.from(
2229
+ new Map(
2230
+ [...routingIntents, ...businessIntents, ...businessLocalMetaIntents].map(
2231
+ (intent) => [intent.name, intent]
1860
2232
  )
1861
- ),
1862
- taskToRoutineMaps: Array.from(taskToRoutineMaps.values()).sort(
1863
- (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
1864
- `${right.routine_name}:${right.task_name}`
2233
+ ).values()
2234
+ ).sort((left, right) => left.name.localeCompare(right.name)) : Array.from(
2235
+ new Map(
2236
+ [...routingIntents, ...businessIntents, ...localMetaIntents].map((intent) => [
2237
+ intent.name,
2238
+ intent
2239
+ ])
2240
+ ).values()
2241
+ ).sort((left, right) => left.name.localeCompare(right.name));
2242
+ const cumulativeActors = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
2243
+ new Map(
2244
+ [...businessActors, ...businessLocalMetaActors].map((actor) => [
2245
+ buildActorKey(actor),
2246
+ actor
2247
+ ])
2248
+ ).values()
2249
+ ).sort(
2250
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2251
+ ) : Array.from(
2252
+ new Map(
2253
+ [...businessActors, ...localMetaActors].map((actor) => [
2254
+ buildActorKey(actor),
2255
+ actor
2256
+ ])
2257
+ ).values()
2258
+ ).sort(
2259
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2260
+ );
2261
+ const cumulativeRoutines = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
2262
+ new Map(
2263
+ [...businessRoutines, ...businessLocalMetaRoutines].map((routine) => [
2264
+ buildRoutineKey(routine),
2265
+ routine
2266
+ ])
2267
+ ).values()
2268
+ ).sort(
2269
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2270
+ ) : Array.from(
2271
+ new Map(
2272
+ [...businessRoutines, ...localMetaRoutines].map((routine) => [
2273
+ buildRoutineKey(routine),
2274
+ routine
2275
+ ])
2276
+ ).values()
2277
+ ).sort(
2278
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2279
+ );
2280
+ const cumulativeDirectionalTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessDirectionalTaskMaps : Array.from(
2281
+ new Map(
2282
+ [...businessDirectionalTaskMaps, ...localMetaDirectionalTaskMaps].map(
2283
+ (map) => [
2284
+ `${map.predecessor_service_name}|${map.predecessor_task_name}|${map.predecessor_task_version}|${map.service_name}|${map.task_name}|${map.task_version}`,
2285
+ map
2286
+ ]
1865
2287
  )
1866
- )
2288
+ ).values()
2289
+ );
2290
+ const cumulativeActorTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
2291
+ new Map(
2292
+ [...businessActorTaskMaps, ...localMetaActorTaskMaps].map((map) => [
2293
+ `${map.service_name}|${map.actor_name}|${map.actor_version}|${map.task_name}|${map.task_version}|${map.mode}`,
2294
+ map
2295
+ ])
2296
+ ).values()
2297
+ ) : Array.from(
2298
+ new Map(
2299
+ [...businessActorTaskMaps, ...localMetaActorTaskMaps].map((map) => [
2300
+ `${map.service_name}|${map.actor_name}|${map.actor_version}|${map.task_name}|${map.task_version}|${map.mode}`,
2301
+ map
2302
+ ])
2303
+ ).values()
2304
+ );
2305
+ const cumulativeTaskToRoutineMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToRoutineMaps : Array.from(
2306
+ new Map(
2307
+ [...businessTaskToRoutineMaps, ...localMetaTaskToRoutineMaps].map((map) => [
2308
+ `${map.service_name}|${map.task_name}|${map.task_version}|${map.routine_name}|${map.routine_version}`,
2309
+ map
2310
+ ])
2311
+ ).values()
2312
+ );
2313
+ const manifestBody = {
2314
+ serviceName,
2315
+ serviceInstanceId,
2316
+ publicationLayer,
2317
+ tasks: cumulativeTasks,
2318
+ signals: cumulativeSignals,
2319
+ intents: cumulativeIntents,
2320
+ actors: cumulativeActors,
2321
+ routines: cumulativeRoutines,
2322
+ directionalTaskMaps: cumulativeDirectionalTaskMaps,
2323
+ signalToTaskMaps: publicationLayer === "routing_capability" ? publishedSignalTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps] : [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps],
2324
+ intentToTaskMaps: publicationLayer === "routing_capability" ? publishedIntentTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps] : [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps],
2325
+ actorTaskMaps: cumulativeActorTaskMaps,
2326
+ taskToRoutineMaps: cumulativeTaskToRoutineMaps
1867
2327
  };
1868
2328
  return {
1869
2329
  ...manifestBody,
@@ -2001,7 +2461,7 @@ var SERVICE_REGISTRY_TRACE_SERVICE2 = (process.env.CADENZA_SERVICE_REGISTRY_TRAC
2001
2461
  function shouldTraceServiceRegistry(serviceName) {
2002
2462
  return SERVICE_REGISTRY_TRACE_SERVICE2.length > 0 && serviceName === SERVICE_REGISTRY_TRACE_SERVICE2;
2003
2463
  }
2004
- function buildServiceRegistryInsertQueryData(ctx, queryData) {
2464
+ function buildServiceRegistryInsertQueryData(tableName, ctx, queryData) {
2005
2465
  const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
2006
2466
  const getJoinedValue = (key) => {
2007
2467
  for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
@@ -2019,7 +2479,8 @@ function buildServiceRegistryInsertQueryData(ctx, queryData) {
2019
2479
  if (!Object.prototype.hasOwnProperty.call(queryData, "onConflict")) {
2020
2480
  delete nextQueryData.onConflict;
2021
2481
  }
2022
- const resolvedData = Object.prototype.hasOwnProperty.call(ctx, "data") || ctx.data !== void 0 ? ctx.data : getJoinedValue("data");
2482
+ const preferRegistrationData = tableName === "service" || tableName === "service_instance" || tableName === "service_instance_transport";
2483
+ 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");
2023
2484
  const resolvedBatch = Object.prototype.hasOwnProperty.call(ctx, "batch") || ctx.batch !== void 0 ? ctx.batch : getJoinedValue("batch");
2024
2485
  const nextData = resolvedData !== void 0 ? resolvedData && typeof resolvedData === "object" ? { ...resolvedData } : resolvedData : registrationData && typeof registrationData === "object" && !Array.isArray(registrationData) ? { ...registrationData } : registrationData;
2025
2486
  if (nextData !== void 0) {
@@ -2046,8 +2507,114 @@ function sanitizeServiceRegistryInsertExecutionContext(ctx) {
2046
2507
  delete sanitized.returnedValue;
2047
2508
  delete sanitized.queryData;
2048
2509
  delete sanitized.onConflict;
2510
+ delete sanitized.task;
2511
+ delete sanitized.routine;
2512
+ delete sanitized.httpServer;
2513
+ delete sanitized.service;
2514
+ delete sanitized.serviceInstance;
2515
+ delete sanitized.joinedContexts;
2516
+ delete sanitized.__declaredTransports;
2517
+ delete sanitized.__resolverOriginalContext;
2518
+ delete sanitized.__resolverQueryData;
2519
+ return sanitized;
2520
+ }
2521
+ function sanitizeAuthorityBootstrapDelegationContext(ctx) {
2522
+ const sanitized = stripDelegationRequestSnapshot({
2523
+ ...ctx
2524
+ });
2525
+ delete sanitized.__resolverOriginalContext;
2526
+ delete sanitized.__resolverQueryData;
2527
+ delete sanitized.joinedContexts;
2528
+ delete sanitized.httpServer;
2529
+ delete sanitized.service;
2530
+ delete sanitized.serviceInstance;
2531
+ delete sanitized.task;
2532
+ delete sanitized.routine;
2533
+ delete sanitized.__declaredTransports;
2534
+ const queryData = sanitized.queryData && typeof sanitized.queryData === "object" ? { ...sanitized.queryData } : null;
2535
+ if (queryData) {
2536
+ delete queryData.joinedContexts;
2537
+ sanitized.queryData = queryData;
2538
+ }
2049
2539
  return sanitized;
2050
2540
  }
2541
+ function cloneServiceRegistryContextValue(value) {
2542
+ if (value instanceof Date) {
2543
+ return new Date(value.getTime());
2544
+ }
2545
+ if (Array.isArray(value)) {
2546
+ return value.map(
2547
+ (entry) => cloneServiceRegistryContextValue(entry)
2548
+ );
2549
+ }
2550
+ if (value && typeof value === "object") {
2551
+ const clone = {};
2552
+ for (const [key, nestedValue] of Object.entries(value)) {
2553
+ clone[key] = cloneServiceRegistryContextValue(nestedValue);
2554
+ }
2555
+ return clone;
2556
+ }
2557
+ return value;
2558
+ }
2559
+ function buildServiceRegistryResolverOriginalContext(tableName, ctx, queryData) {
2560
+ const originalContext = {};
2561
+ for (const key of [
2562
+ "__serviceName",
2563
+ "serviceName",
2564
+ "__serviceInstanceId",
2565
+ "serviceInstanceId",
2566
+ "__registrationData",
2567
+ "__reason",
2568
+ "__syncing",
2569
+ "__syncSourceServiceName",
2570
+ "__preferredTransportProtocol",
2571
+ "__networkMode",
2572
+ "__securityProfile",
2573
+ "__loadBalance",
2574
+ "__cadenzaDBConnect",
2575
+ "__isFrontend",
2576
+ "__isDatabase",
2577
+ "__retryCount",
2578
+ "__retries",
2579
+ "__triedInstances"
2580
+ ]) {
2581
+ if (ctx[key] !== void 0) {
2582
+ originalContext[key] = cloneServiceRegistryContextValue(ctx[key]);
2583
+ }
2584
+ }
2585
+ if (queryData.data !== void 0) {
2586
+ originalContext.data = cloneServiceRegistryContextValue(queryData.data);
2587
+ }
2588
+ if (queryData.batch !== void 0) {
2589
+ originalContext.batch = cloneServiceRegistryContextValue(queryData.batch);
2590
+ }
2591
+ if (Object.prototype.hasOwnProperty.call(queryData, "onConflict")) {
2592
+ originalContext.queryData = {
2593
+ data: queryData.data !== void 0 ? cloneServiceRegistryContextValue(queryData.data) : void 0,
2594
+ batch: queryData.batch !== void 0 ? cloneServiceRegistryContextValue(queryData.batch) : void 0,
2595
+ onConflict: cloneServiceRegistryContextValue(queryData.onConflict)
2596
+ };
2597
+ } else if (queryData.data !== void 0 || queryData.batch !== void 0) {
2598
+ originalContext.queryData = {
2599
+ data: queryData.data !== void 0 ? cloneServiceRegistryContextValue(queryData.data) : void 0,
2600
+ batch: queryData.batch !== void 0 ? cloneServiceRegistryContextValue(queryData.batch) : void 0
2601
+ };
2602
+ }
2603
+ if (tableName === "service_instance") {
2604
+ for (const key of [
2605
+ "__transportData",
2606
+ "transportData",
2607
+ "__useSocket",
2608
+ "__retryCount",
2609
+ "__isFrontend"
2610
+ ]) {
2611
+ if (ctx[key] !== void 0) {
2612
+ originalContext[key] = cloneServiceRegistryContextValue(ctx[key]);
2613
+ }
2614
+ }
2615
+ }
2616
+ return originalContext;
2617
+ }
2051
2618
  function clearTransientRoutingErrorState(context) {
2052
2619
  delete context.errored;
2053
2620
  delete context.failed;
@@ -2103,7 +2670,8 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
2103
2670
  delete result.__resolverOriginalContext;
2104
2671
  delete result.__resolverQueryData;
2105
2672
  const normalizedQueryData = result.queryData && typeof result.queryData === "object" ? { ...result.queryData } : { ...queryData };
2106
- const resolvedData = result.data ?? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData;
2673
+ const preferRequestedData = tableName === "service" || tableName === "service_instance" || tableName === "service_instance_transport";
2674
+ const resolvedData = preferRequestedData ? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData ?? result.data : result.data ?? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData;
2107
2675
  if (resolvedData !== void 0 && result.data === void 0) {
2108
2676
  result.data = resolvedData;
2109
2677
  }
@@ -2133,6 +2701,7 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
2133
2701
  ).trim();
2134
2702
  if (resolvedServiceName) {
2135
2703
  result.__serviceName = resolvedServiceName;
2704
+ result.serviceName = resolvedServiceName;
2136
2705
  }
2137
2706
  }
2138
2707
  const resolvedLocalServiceInstanceId = String(
@@ -2141,6 +2710,18 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
2141
2710
  if (resolvedLocalServiceInstanceId) {
2142
2711
  result.__serviceInstanceId = resolvedLocalServiceInstanceId;
2143
2712
  }
2713
+ if (tableName === "service_instance") {
2714
+ const resolvedServiceName = String(
2715
+ ctx.__serviceName ?? resolveServiceNameFromContext(ctx) ?? resolvedData?.service_name ?? resolvedData?.serviceName ?? ""
2716
+ ).trim();
2717
+ if (resolvedServiceName) {
2718
+ result.__serviceName = resolvedServiceName;
2719
+ result.serviceName = resolvedServiceName;
2720
+ }
2721
+ if (resolvedLocalServiceInstanceId) {
2722
+ result.serviceInstanceId = resolvedLocalServiceInstanceId;
2723
+ }
2724
+ }
2144
2725
  if (tableName === "service_instance" || tableName === "service_instance_transport") {
2145
2726
  const resolvedUuid = String(
2146
2727
  result.uuid ?? resolvedData?.uuid ?? ctx.__serviceInstanceId ?? ""
@@ -2240,9 +2821,15 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
2240
2821
  ctx
2241
2822
  );
2242
2823
  const nextQueryData = buildServiceRegistryInsertQueryData(
2824
+ tableName,
2243
2825
  sanitizedContext,
2244
2826
  queryData
2245
2827
  );
2828
+ const resolverOriginalContext = buildServiceRegistryResolverOriginalContext(
2829
+ tableName,
2830
+ sanitizedContext,
2831
+ nextQueryData
2832
+ );
2246
2833
  const delegationContext = ensureDelegationContextMetadata({
2247
2834
  ...sanitizedContext,
2248
2835
  data: nextQueryData.data !== void 0 ? nextQueryData.data : sanitizedContext.data,
@@ -2255,9 +2842,7 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
2255
2842
  delegationContext.__metadata.__blockRemoteExecution = delegationContext.__metadata.__blockRemoteExecution ?? delegationContext.__blockRemoteExecution ?? false;
2256
2843
  const nextContext = {
2257
2844
  ...delegationContext,
2258
- __resolverOriginalContext: {
2259
- ...sanitizedContext
2260
- },
2845
+ __resolverOriginalContext: resolverOriginalContext,
2261
2846
  __resolverQueryData: nextQueryData
2262
2847
  };
2263
2848
  if (tableName === "service_instance_transport" && shouldTraceServiceRegistry(
@@ -2429,6 +3014,7 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
2429
3014
  if (bootstrapAuthorityInsertSpec) {
2430
3015
  const sanitizedContext = sanitizeServiceRegistryInsertExecutionContext(ctx);
2431
3016
  const nextQueryData = buildServiceRegistryInsertQueryData(
3017
+ tableName,
2432
3018
  sanitizedContext,
2433
3019
  queryData
2434
3020
  );
@@ -2863,6 +3449,9 @@ var ServiceRegistry = class _ServiceRegistry {
2863
3449
  ctx.deleted ?? ctx.serviceInstance?.deleted ?? ctx.data?.deleted
2864
3450
  );
2865
3451
  if (uuid9 === this.serviceInstanceId) return;
3452
+ if (serviceName === this.serviceName) {
3453
+ return false;
3454
+ }
2866
3455
  if (deleted) {
2867
3456
  const existingInstance = this.instances.get(serviceName)?.find((instance) => instance.uuid === uuid9);
2868
3457
  const indexToDelete = this.instances.get(serviceName)?.findIndex((i) => i.uuid === uuid9) ?? -1;
@@ -2949,9 +3538,6 @@ var ServiceRegistry = class _ServiceRegistry {
2949
3538
  emit2
2950
3539
  );
2951
3540
  }
2952
- if (this.serviceName === serviceName) {
2953
- return false;
2954
- }
2955
3541
  if (trackedInstance?.isFrontend) {
2956
3542
  return true;
2957
3543
  }
@@ -3005,6 +3591,9 @@ var ServiceRegistry = class _ServiceRegistry {
3005
3591
  if (!ownerInstance) {
3006
3592
  return false;
3007
3593
  }
3594
+ if (ownerInstance.serviceName === this.serviceName && ownerInstance.uuid !== this.serviceInstanceId) {
3595
+ return false;
3596
+ }
3008
3597
  if (transport.deleted) {
3009
3598
  this.clearTransportFailureState(ownerInstance.uuid, transport.uuid);
3010
3599
  const transportKey = this.buildTransportRouteKey(
@@ -5431,6 +6020,8 @@ var ServiceRegistry = class _ServiceRegistry {
5431
6020
  seenSignalMaps,
5432
6021
  (row) => `${String(row.service_name ?? row.serviceName ?? "").trim()}|${String(
5433
6022
  row.signal_name ?? row.signalName ?? ""
6023
+ ).trim()}|${String(row.task_name ?? row.taskName ?? "").trim()}|${String(
6024
+ row.task_version ?? row.taskVersion ?? 1
5434
6025
  ).trim()}`
5435
6026
  );
5436
6027
  pushUnique(
@@ -5465,6 +6056,8 @@ var ServiceRegistry = class _ServiceRegistry {
5465
6056
  seenSignalMaps,
5466
6057
  (entry) => `${String(entry.service_name ?? entry.serviceName ?? "").trim()}|${String(
5467
6058
  entry.signal_name ?? entry.signalName ?? ""
6059
+ ).trim()}|${String(entry.task_name ?? entry.taskName ?? "").trim()}|${String(
6060
+ entry.task_version ?? entry.taskVersion ?? 1
5468
6061
  ).trim()}`
5469
6062
  );
5470
6063
  continue;
@@ -5497,9 +6090,36 @@ var ServiceRegistry = class _ServiceRegistry {
5497
6090
  }
5498
6091
  }
5499
6092
  }
5500
- const hasExplicitSignalRoutingRows = signalToTaskMaps.length > 0;
5501
- const hasExplicitIntentRoutingRows = intentToTaskMaps.length > 0;
5502
- const latestManifestSnapshots = selectLatestServiceManifestSnapshots(manifestSnapshots);
6093
+ const activeServiceInstanceIds = new Set(
6094
+ serviceInstances.filter((row) => row.is_active === true || row.isActive === true).map((row) => String(row.uuid ?? "").trim()).filter((uuid9) => uuid9.length > 0)
6095
+ );
6096
+ const filteredServiceInstances = activeServiceInstanceIds.size > 0 ? serviceInstances.filter(
6097
+ (row) => activeServiceInstanceIds.has(String(row.uuid ?? "").trim())
6098
+ ) : serviceInstances;
6099
+ const filteredServiceInstanceTransports = activeServiceInstanceIds.size > 0 ? serviceInstanceTransports.filter(
6100
+ (row) => activeServiceInstanceIds.has(
6101
+ String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
6102
+ )
6103
+ ) : serviceInstanceTransports;
6104
+ const filteredManifestSnapshots = activeServiceInstanceIds.size > 0 ? manifestSnapshots.filter(
6105
+ (snapshot) => activeServiceInstanceIds.has(snapshot.serviceInstanceId)
6106
+ ) : manifestSnapshots;
6107
+ const activeServiceNames = new Set(
6108
+ filteredServiceInstances.map((row) => String(row.service_name ?? row.serviceName ?? "").trim()).filter((serviceName) => serviceName.length > 0)
6109
+ );
6110
+ const filteredSignalToTaskMaps = activeServiceNames.size > 0 ? signalToTaskMaps.filter(
6111
+ (row) => activeServiceNames.has(
6112
+ String(row.service_name ?? row.serviceName ?? "").trim()
6113
+ )
6114
+ ) : signalToTaskMaps;
6115
+ const filteredIntentToTaskMaps = activeServiceNames.size > 0 ? intentToTaskMaps.filter(
6116
+ (row) => activeServiceNames.has(
6117
+ String(row.service_name ?? row.serviceName ?? "").trim()
6118
+ )
6119
+ ) : intentToTaskMaps;
6120
+ const hasExplicitSignalRoutingRows = filteredSignalToTaskMaps.length > 0;
6121
+ const hasExplicitIntentRoutingRows = filteredIntentToTaskMaps.length > 0;
6122
+ const latestManifestSnapshots = selectLatestServiceManifestSnapshots(filteredManifestSnapshots);
5503
6123
  const explodedManifest = explodeServiceManifestSnapshots(
5504
6124
  latestManifestSnapshots
5505
6125
  );
@@ -5582,7 +6202,7 @@ var ServiceRegistry = class _ServiceRegistry {
5582
6202
  if (!hasExplicitSignalRoutingRows) {
5583
6203
  pushUnique(
5584
6204
  explodedManifest.signalToTaskMaps,
5585
- signalToTaskMaps,
6205
+ filteredSignalToTaskMaps,
5586
6206
  seenSignalMaps,
5587
6207
  (row) => `${String(row.signal_name ?? "").trim()}|${String(
5588
6208
  row.service_name ?? ""
@@ -5594,7 +6214,7 @@ var ServiceRegistry = class _ServiceRegistry {
5594
6214
  if (!hasExplicitIntentRoutingRows) {
5595
6215
  pushUnique(
5596
6216
  explodedManifest.intentToTaskMaps,
5597
- intentToTaskMaps,
6217
+ filteredIntentToTaskMaps,
5598
6218
  seenIntentMaps,
5599
6219
  (row) => `${String(row.intent_name ?? "").trim()}|${String(
5600
6220
  row.service_name ?? ""
@@ -5604,8 +6224,8 @@ var ServiceRegistry = class _ServiceRegistry {
5604
6224
  );
5605
6225
  }
5606
6226
  return {
5607
- serviceInstances,
5608
- serviceInstanceTransports,
6227
+ serviceInstances: filteredServiceInstances,
6228
+ serviceInstanceTransports: filteredServiceInstanceTransports,
5609
6229
  serviceManifests,
5610
6230
  tasks,
5611
6231
  signals,
@@ -5615,8 +6235,8 @@ var ServiceRegistry = class _ServiceRegistry {
5615
6235
  directionalTaskMaps,
5616
6236
  actorTaskMaps,
5617
6237
  taskToRoutineMaps,
5618
- signalToTaskMaps,
5619
- intentToTaskMaps
6238
+ signalToTaskMaps: filteredSignalToTaskMaps,
6239
+ intentToTaskMaps: filteredIntentToTaskMaps
5620
6240
  };
5621
6241
  }
5622
6242
  buildRemoteIntentDeputyKey(map) {
@@ -6045,10 +6665,11 @@ var ServiceRegistry = class _ServiceRegistry {
6045
6665
  const controller = typeof AbortController === "function" ? new AbortController() : null;
6046
6666
  const timeoutId = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
6047
6667
  try {
6668
+ const sanitizedContext = sanitizeAuthorityBootstrapDelegationContext(context);
6048
6669
  const requestBody = stripDelegationRequestSnapshot(
6049
6670
  ensureDelegationContextMetadata(
6050
6671
  attachDelegationRequestSnapshot({
6051
- ...context,
6672
+ ...sanitizedContext,
6052
6673
  __remoteRoutineName: remoteRoutineName,
6053
6674
  __serviceName: "CadenzaDB",
6054
6675
  __localServiceName: this.serviceName,
@@ -6062,7 +6683,7 @@ var ServiceRegistry = class _ServiceRegistry {
6062
6683
  __fetchId: target.fetchId,
6063
6684
  fetchId: target.fetchId,
6064
6685
  __metadata: {
6065
- ...context.__metadata && typeof context.__metadata === "object" ? context.__metadata : {},
6686
+ ...sanitizedContext.__metadata && typeof sanitizedContext.__metadata === "object" ? sanitizedContext.__metadata : {},
6066
6687
  __timeout: timeoutMs,
6067
6688
  __syncing: true,
6068
6689
  __authorityBootstrapChannel: true
@@ -6080,22 +6701,22 @@ var ServiceRegistry = class _ServiceRegistry {
6080
6701
  });
6081
6702
  if ("ok" in response && response.ok === false) {
6082
6703
  return {
6083
- ...context,
6704
+ ...sanitizedContext,
6084
6705
  __error: `Bootstrap authority delegation failed with HTTP ${response.status}`,
6085
6706
  errored: true
6086
6707
  };
6087
6708
  }
6088
6709
  const payload = typeof response.json === "function" ? await response.json() : response;
6089
6710
  return payload && typeof payload === "object" ? {
6090
- ...context,
6711
+ ...sanitizedContext,
6091
6712
  ...payload
6092
6713
  } : {
6093
- ...context,
6714
+ ...sanitizedContext,
6094
6715
  returnedValue: payload
6095
6716
  };
6096
6717
  } catch (error) {
6097
6718
  return {
6098
- ...context,
6719
+ ...sanitizeAuthorityBootstrapDelegationContext(context),
6099
6720
  __error: error instanceof Error ? error.message : String(error),
6100
6721
  errored: true
6101
6722
  };
@@ -11113,8 +11734,8 @@ var SocketController = class _SocketController {
11113
11734
  }
11114
11735
  const routedDelegateCtx = stripTransportSelectionRoutingContext(delegateCtx);
11115
11736
  const normalizedDelegateCtx = ensureDelegationContextMetadata(
11116
- attachDelegationRequestSnapshot(
11117
- stripDelegationRequestSnapshot(routedDelegateCtx)
11737
+ restoreDelegationRequestSnapshot(
11738
+ attachDelegationRequestSnapshot(routedDelegateCtx)
11118
11739
  )
11119
11740
  );
11120
11741
  delete normalizedDelegateCtx.__isSubMeta;
@@ -11187,13 +11808,11 @@ var SocketController = class _SocketController {
11187
11808
  return resolvedResultContext;
11188
11809
  } catch (error) {
11189
11810
  const message = error instanceof Error ? error.message : String(error);
11190
- const failedContext = {
11191
- __signalName: "meta.socket_client.delegate_failed",
11192
- errored: true,
11193
- __error: message,
11194
- ...normalizedDelegateCtx,
11195
- ...normalizedDelegateCtx.__metadata
11196
- };
11811
+ const failedContext = buildDelegationFailureContext(
11812
+ "meta.socket_client.delegate_failed",
11813
+ normalizedDelegateCtx,
11814
+ error
11815
+ );
11197
11816
  if (deputyExecId) {
11198
11817
  emitter(`meta.socket_client.delegated:${deputyExecId}`, {
11199
11818
  ...failedContext,
@@ -12202,6 +12821,51 @@ import { META_ACTOR_SESSION_STATE_PERSIST_INTENT } from "@cadenza.io/core";
12202
12821
  var ACTOR_SESSION_STATE_PERSIST_CONCURRENCY = 20;
12203
12822
  var META_ACTOR_SESSION_STATE_HYDRATE_INTENT = "meta-actor-session-state-hydrate";
12204
12823
  var ACTOR_SESSION_TRACE_ENABLED2 = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
12824
+ function findNestedContextValue(ctx, key) {
12825
+ if (!ctx || typeof ctx !== "object") {
12826
+ return void 0;
12827
+ }
12828
+ if (Object.prototype.hasOwnProperty.call(ctx, key) || ctx[key] !== void 0) {
12829
+ return ctx[key];
12830
+ }
12831
+ const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
12832
+ for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
12833
+ const nested = joinedContexts[index];
12834
+ if (!nested || typeof nested !== "object") {
12835
+ continue;
12836
+ }
12837
+ const nestedValue = findNestedContextValue(nested, key);
12838
+ if (nestedValue !== void 0) {
12839
+ return nestedValue;
12840
+ }
12841
+ }
12842
+ return void 0;
12843
+ }
12844
+ function resolveActorSessionStateRow(ctx) {
12845
+ const singular = findNestedContextValue(ctx, "actorSessionState");
12846
+ if (singular && typeof singular === "object" && !Array.isArray(singular)) {
12847
+ return singular;
12848
+ }
12849
+ const plural = findNestedContextValue(ctx, "actorSessionStates");
12850
+ if (Array.isArray(plural)) {
12851
+ const first = plural.find(
12852
+ (entry) => entry && typeof entry === "object" && !Array.isArray(entry)
12853
+ );
12854
+ if (first) {
12855
+ return first;
12856
+ }
12857
+ }
12858
+ const rows = findNestedContextValue(ctx, "rows");
12859
+ if (Array.isArray(rows)) {
12860
+ const first = rows.find(
12861
+ (entry) => entry && typeof entry === "object" && !Array.isArray(entry)
12862
+ );
12863
+ if (first) {
12864
+ return first;
12865
+ }
12866
+ }
12867
+ return null;
12868
+ }
12205
12869
  function shouldAssumeSuccessfulActorSessionRowCount(ctx) {
12206
12870
  return ctx.__success === true && ctx.rowCount === void 0 && ctx.__status === "success" && ctx.__serviceName === "CadenzaDB" && ctx.__localTaskName === "Insert actor_session_state in CadenzaDB";
12207
12871
  }
@@ -12274,7 +12938,7 @@ function registerActorSessionPersistenceTasks() {
12274
12938
  )
12275
12939
  );
12276
12940
  }
12277
- const row = ctx.actorSessionState && typeof ctx.actorSessionState === "object" && !Array.isArray(ctx.actorSessionState) ? ctx.actorSessionState : null;
12941
+ const row = resolveActorSessionStateRow(ctx);
12278
12942
  if (!row) {
12279
12943
  return {
12280
12944
  __success: true,
@@ -12681,16 +13345,20 @@ function resolveSyncInsertTask(isCadenzaDBReady, tableName, queryData = {}, opti
12681
13345
  ctx,
12682
13346
  queryData
12683
13347
  );
12684
- 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) {
12685
- console.warn(
12686
- "[CADENZA_SYNC_EMPTY_INSERT]",
12687
- {
12688
- tableName,
12689
- queryData: originalQueryData,
12690
- ctx,
12691
- joinedContexts: Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : []
12692
- }
12693
- );
13348
+ const hasEmptyObjectData = originalQueryData.data && typeof originalQueryData.data === "object" && !Array.isArray(originalQueryData.data) && Object.keys(originalQueryData.data).length === 0;
13349
+ const hasMissingData = originalQueryData.data === void 0;
13350
+ if ((tableName === "task" || tableName === "signal_registry" || tableName === "directional_task_graph_map") && (hasEmptyObjectData || hasMissingData)) {
13351
+ console.warn("[CADENZA_SYNC_EMPTY_INSERT]", {
13352
+ tableName,
13353
+ hasMissingData,
13354
+ hasEmptyObjectData,
13355
+ taskName: typeof ctx.__taskName === "string" ? ctx.__taskName : void 0,
13356
+ reason: typeof ctx.__reason === "string" ? ctx.__reason : void 0,
13357
+ syncSourceServiceName: typeof ctx.__syncSourceServiceName === "string" ? ctx.__syncSourceServiceName : void 0,
13358
+ queryData: originalQueryData,
13359
+ ctx,
13360
+ joinedContexts: Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : []
13361
+ });
12694
13362
  }
12695
13363
  return buildSyncExecutionEnvelope(
12696
13364
  ctx,
@@ -12781,7 +13449,7 @@ function isBootstrapLocalOnlyActorName(actorName) {
12781
13449
  return BOOTSTRAP_LOCAL_ONLY_ACTOR_NAMES.has(actorName);
12782
13450
  }
12783
13451
  function isBootstrapLocalOnlySignal(signalName) {
12784
- 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);
13452
+ 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);
12785
13453
  }
12786
13454
  function hasNonZeroPending(summary) {
12787
13455
  return Object.values(summary).some((value) => Number(value) > 0);
@@ -13009,6 +13677,12 @@ function resolveLocalRoutineFromSyncContext(ctx) {
13009
13677
  );
13010
13678
  return routineName ? CadenzaService.getRoutine(routineName) : void 0;
13011
13679
  }
13680
+ function shouldTrackDirectionalTaskMapForBootstrap(predecessorTask, nextTask) {
13681
+ if (!predecessorTask || !nextTask) {
13682
+ return false;
13683
+ }
13684
+ return predecessorTask.isMeta !== true && predecessorTask.isSubMeta !== true && nextTask.isMeta !== true && nextTask.isSubMeta !== true;
13685
+ }
13012
13686
  function resolveSignalNameFromSyncContext(ctx) {
13013
13687
  const candidateSignalNames = [
13014
13688
  ctx.signalName,
@@ -14085,7 +14759,7 @@ var GraphSyncController = class _GraphSyncController {
14085
14759
  return;
14086
14760
  }
14087
14761
  for (const t of task.nextTasks) {
14088
- if (task.taskMapRegistration.has(t.name) || t.hidden || !t.register || !t.registered) {
14762
+ if (task.taskMapRegistration.has(t.name) || t.hidden || !t.register || !t.registered || !shouldTrackDirectionalTaskMapForBootstrap(task, t)) {
14089
14763
  continue;
14090
14764
  }
14091
14765
  const serviceName2 = resolveSyncServiceName(t);
@@ -14153,7 +14827,7 @@ var GraphSyncController = class _GraphSyncController {
14153
14827
  return false;
14154
14828
  }
14155
14829
  for (const nextTask of task.nextTasks) {
14156
- if (task.taskMapRegistration.has(nextTask.name) || nextTask.isHidden || !nextTask.register || !nextTask.registered) {
14830
+ if (task.taskMapRegistration.has(nextTask.name) || nextTask.isHidden || !nextTask.register || !nextTask.registered || !shouldTrackDirectionalTaskMapForBootstrap(task, nextTask)) {
14157
14831
  continue;
14158
14832
  }
14159
14833
  if (resolveSyncServiceName(nextTask)) {
@@ -16451,6 +17125,15 @@ var DEFAULT_DEPUTY_TASK_CONCURRENCY = 50;
16451
17125
  var DEFAULT_DEPUTY_TASK_TIMEOUT_MS = 12e4;
16452
17126
  var DEFAULT_DATABASE_PROXY_TASK_CONCURRENCY = 50;
16453
17127
  var DEFAULT_DATABASE_PROXY_TASK_TIMEOUT_MS = 12e4;
17128
+ var SERVICE_MANIFEST_PUBLICATION_ORDER = [
17129
+ "routing_capability",
17130
+ "business_structural",
17131
+ "local_meta_structural"
17132
+ ];
17133
+ function getServiceManifestPublicationLayerRank(layer) {
17134
+ const index = SERVICE_MANIFEST_PUBLICATION_ORDER.indexOf(layer);
17135
+ return index >= 0 ? index : SERVICE_MANIFEST_PUBLICATION_ORDER.length - 1;
17136
+ }
16454
17137
  var CadenzaService = class {
16455
17138
  static unregisterGracefulShutdownHandlers() {
16456
17139
  for (const cleanup of this.shutdownHandlerCleanup) {
@@ -16577,7 +17260,15 @@ var CadenzaService = class {
16577
17260
  this.replayRegisteredTaskSignalObservations();
16578
17261
  this.replayRegisteredTaskIntentAssociations();
16579
17262
  }
16580
- static requestServiceManifestPublication(reason, immediate = false) {
17263
+ static normalizeServiceManifestPublicationLayer(value, fallback = "business_structural") {
17264
+ return value === "routing_capability" || value === "business_structural" || value === "local_meta_structural" ? value : fallback;
17265
+ }
17266
+ static mergeServiceManifestPublicationRequest(reason, targetLayer) {
17267
+ this.serviceManifestPublicationPendingReason = reason;
17268
+ const currentTargetLayer = this.serviceManifestPublicationPendingLayer ?? "routing_capability";
17269
+ this.serviceManifestPublicationPendingLayer = getServiceManifestPublicationLayerRank(targetLayer) >= getServiceManifestPublicationLayerRank(currentTargetLayer) ? targetLayer : currentTargetLayer;
17270
+ }
17271
+ static requestServiceManifestPublication(reason, immediate = false, targetLayer = "business_structural") {
16581
17272
  if (!this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
16582
17273
  return;
16583
17274
  }
@@ -16585,7 +17276,8 @@ var CadenzaService = class {
16585
17276
  const payload = {
16586
17277
  __reason: reason,
16587
17278
  __serviceName: this.serviceRegistry.serviceName,
16588
- __serviceInstanceId: this.serviceRegistry.serviceInstanceId
17279
+ __serviceInstanceId: this.serviceRegistry.serviceInstanceId,
17280
+ __publicationLayer: targetLayer
16589
17281
  };
16590
17282
  if (immediate) {
16591
17283
  this.emit(signalName, payload);
@@ -16593,32 +17285,53 @@ var CadenzaService = class {
16593
17285
  }
16594
17286
  this.debounce(signalName, payload, 100);
16595
17287
  }
16596
- static scheduleServiceManifestPublicationRetry(reason) {
17288
+ static scheduleServiceManifestPublicationRetry(reason, targetLayer = "business_structural") {
16597
17289
  if (!this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
16598
17290
  return;
16599
17291
  }
16600
17292
  setTimeout(() => {
16601
- this.requestServiceManifestPublication(reason, false);
17293
+ this.requestServiceManifestPublication(reason, false, targetLayer);
16602
17294
  }, 1e3);
16603
17295
  }
16604
- static async publishServiceManifestIfNeeded(reason) {
17296
+ static async publishServiceManifestIfNeeded(reason, targetLayer = "business_structural") {
16605
17297
  if (!this.serviceRegistry.connectsToCadenzaDB || !this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
16606
17298
  return false;
16607
17299
  }
16608
17300
  const publishReason = typeof reason === "string" && reason.trim().length > 0 ? reason.trim() : "service_manifest_publish";
17301
+ const publishTargetLayer = this.normalizeServiceManifestPublicationLayer(
17302
+ targetLayer
17303
+ );
16609
17304
  if (this.serviceManifestPublicationInFlight) {
16610
- this.serviceManifestPublicationPendingReason = publishReason;
17305
+ this.mergeServiceManifestPublicationRequest(
17306
+ publishReason,
17307
+ publishTargetLayer
17308
+ );
16611
17309
  return false;
16612
17310
  }
16613
- const snapshot = buildServiceManifestSnapshot({
16614
- serviceName: this.serviceRegistry.serviceName,
16615
- serviceInstanceId: this.serviceRegistry.serviceInstanceId,
16616
- revision: this.serviceManifestRevision + 1,
16617
- publishedAt: (/* @__PURE__ */ new Date()).toISOString()
17311
+ const publicationPlan = SERVICE_MANIFEST_PUBLICATION_ORDER.filter(
17312
+ (layer) => getServiceManifestPublicationLayerRank(layer) <= getServiceManifestPublicationLayerRank(publishTargetLayer)
17313
+ ).map((layer) => {
17314
+ const snapshot2 = buildServiceManifestSnapshot({
17315
+ serviceName: this.serviceRegistry.serviceName,
17316
+ serviceInstanceId: this.serviceRegistry.serviceInstanceId,
17317
+ revision: this.serviceManifestRevision + 1,
17318
+ publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
17319
+ publicationLayer: layer
17320
+ });
17321
+ return {
17322
+ layer,
17323
+ snapshot: snapshot2,
17324
+ changed: this.lastPublishedServiceManifestHashes[layer] !== snapshot2.manifestHash
17325
+ };
16618
17326
  });
16619
- if (this.lastPublishedServiceManifestHash && this.lastPublishedServiceManifestHash === snapshot.manifestHash) {
17327
+ const nextPublication = publicationPlan.find((entry) => entry.changed);
17328
+ if (!nextPublication) {
16620
17329
  return false;
16621
17330
  }
17331
+ const { layer: publicationLayer, snapshot } = nextPublication;
17332
+ const hasPendingFollowupLayer = publicationPlan.some(
17333
+ (entry) => entry.changed && getServiceManifestPublicationLayerRank(entry.layer) > getServiceManifestPublicationLayerRank(publicationLayer)
17334
+ );
16622
17335
  this.serviceManifestPublicationInFlight = true;
16623
17336
  try {
16624
17337
  this.serviceRegistry.ensureBootstrapAuthorityControlPlaneForInquiry(
@@ -16626,7 +17339,10 @@ var CadenzaService = class {
16626
17339
  snapshot
16627
17340
  );
16628
17341
  if (!this.serviceRegistry.hasAuthorityBootstrapHandshakeEstablished()) {
16629
- this.scheduleServiceManifestPublicationRetry(publishReason);
17342
+ this.scheduleServiceManifestPublicationRetry(
17343
+ publishReason,
17344
+ publishTargetLayer
17345
+ );
16630
17346
  return false;
16631
17347
  }
16632
17348
  await this.inquire(AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT, snapshot, {
@@ -16634,32 +17350,48 @@ var CadenzaService = class {
16634
17350
  requireComplete: true
16635
17351
  });
16636
17352
  this.serviceManifestRevision = snapshot.revision;
16637
- this.lastPublishedServiceManifestHash = snapshot.manifestHash;
17353
+ this.lastPublishedServiceManifestHashes[publicationLayer] = snapshot.manifestHash;
17354
+ if (hasPendingFollowupLayer) {
17355
+ this.mergeServiceManifestPublicationRequest(
17356
+ publishReason,
17357
+ publishTargetLayer
17358
+ );
17359
+ }
16638
17360
  return {
16639
17361
  serviceManifest: snapshot,
16640
- published: true
17362
+ published: true,
17363
+ publicationLayer
16641
17364
  };
16642
17365
  } catch (error) {
16643
17366
  this.log("Service manifest publication failed. Scheduling retry.", {
16644
17367
  serviceName: this.serviceRegistry.serviceName,
16645
17368
  serviceInstanceId: this.serviceRegistry.serviceInstanceId,
16646
17369
  reason: publishReason,
17370
+ publicationLayer,
16647
17371
  error: resolveInquiryFailureError(
16648
17372
  AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT,
16649
17373
  error
16650
17374
  ),
16651
17375
  inquiryMeta: error && typeof error === "object" && "__inquiryMeta" in error ? error.__inquiryMeta : null
16652
17376
  });
16653
- this.scheduleServiceManifestPublicationRetry(publishReason);
17377
+ this.scheduleServiceManifestPublicationRetry(
17378
+ publishReason,
17379
+ publishTargetLayer
17380
+ );
16654
17381
  return false;
16655
17382
  } finally {
16656
17383
  this.serviceManifestPublicationInFlight = false;
16657
- if (this.serviceManifestPublicationPendingReason) {
17384
+ if (this.serviceManifestPublicationPendingReason && this.serviceManifestPublicationPendingLayer) {
16658
17385
  const pendingReason = this.serviceManifestPublicationPendingReason;
17386
+ const pendingLayer = this.serviceManifestPublicationPendingLayer;
16659
17387
  this.serviceManifestPublicationPendingReason = null;
17388
+ this.serviceManifestPublicationPendingLayer = null;
16660
17389
  this.debounce(
16661
17390
  "meta.service_manifest.publish_requested",
16662
- { __reason: pendingReason },
17391
+ {
17392
+ __reason: pendingReason,
17393
+ __publicationLayer: pendingLayer
17394
+ },
16663
17395
  100
16664
17396
  );
16665
17397
  }
@@ -16672,9 +17404,13 @@ var CadenzaService = class {
16672
17404
  this.createMetaTask(
16673
17405
  "Publish service manifest",
16674
17406
  async (ctx) => this.publishServiceManifestIfNeeded(
16675
- typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0 ? ctx.__reason.trim() : "service_manifest_publish"
17407
+ typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0 ? ctx.__reason.trim() : "service_manifest_publish",
17408
+ this.normalizeServiceManifestPublicationLayer(
17409
+ ctx.__publicationLayer,
17410
+ "business_structural"
17411
+ )
16676
17412
  ),
16677
- "Publishes a full static manifest snapshot to authority when the manifest hash changes.",
17413
+ "Publishes staged static manifest snapshots to authority when the manifest hash changes.",
16678
17414
  {
16679
17415
  register: false,
16680
17416
  isHidden: true
@@ -16684,13 +17420,18 @@ var CadenzaService = class {
16684
17420
  "Request manifest publication after structural change",
16685
17421
  (ctx) => {
16686
17422
  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";
17423
+ const targetLayer = reason === "meta.service_registry.instance_inserted" ? "business_structural" : this.normalizeServiceManifestPublicationLayer(
17424
+ ctx.__publicationLayer,
17425
+ "business_structural"
17426
+ );
16687
17427
  this.requestServiceManifestPublication(
16688
17428
  reason,
16689
- reason === "meta.service_registry.instance_inserted"
17429
+ reason === "meta.service_registry.instance_inserted",
17430
+ targetLayer
16690
17431
  );
16691
17432
  return true;
16692
17433
  },
16693
- "Requests a manifest publication when a static service primitive changes.",
17434
+ "Requests staged manifest publication when a static service primitive changes.",
16694
17435
  {
16695
17436
  register: false,
16696
17437
  isHidden: true
@@ -17945,10 +18686,28 @@ var CadenzaService = class {
17945
18686
  __isFrontend: isFrontend,
17946
18687
  __declaredTransports: declaredTransports
17947
18688
  };
18689
+ let bootstrapServiceCreationRequested = false;
17948
18690
  if (options.cadenzaDB?.connect) {
17949
- this.createEphemeralMetaTask("Create service", async (context, emit2) => {
17950
- emit2("meta.create_service_requested", initContext);
17951
- }).doOn("meta.fetch.handshake_complete");
18691
+ this.createMetaTask(
18692
+ "Create service",
18693
+ async (context, emit2) => {
18694
+ const handshakeServiceName = String(context?.serviceName ?? "").trim();
18695
+ if (handshakeServiceName !== "CadenzaDB") {
18696
+ return false;
18697
+ }
18698
+ if (bootstrapServiceCreationRequested) {
18699
+ return false;
18700
+ }
18701
+ bootstrapServiceCreationRequested = true;
18702
+ emit2("meta.create_service_requested", initContext);
18703
+ return true;
18704
+ },
18705
+ "Requests local service creation only once after the initial authority bootstrap handshake completes.",
18706
+ {
18707
+ register: false,
18708
+ isHidden: true
18709
+ }
18710
+ ).doOn("meta.fetch.handshake_complete");
17952
18711
  } else {
17953
18712
  this.emit("meta.create_service_requested", initContext);
17954
18713
  this.createMetaTask("Create signal transmission for sync", (ctx, emit2) => {
@@ -17961,10 +18720,33 @@ var CadenzaService = class {
17961
18720
  );
17962
18721
  }).doOn("meta.rest.handshake", "meta.socket.handshake");
17963
18722
  }
18723
+ let serviceSetupCompletedHandled = false;
17964
18724
  this.createMetaTask("Handle service setup completion", (ctx, emit2) => {
18725
+ if (serviceSetupCompletedHandled) {
18726
+ return false;
18727
+ }
18728
+ const insertedServiceInstanceId = String(
18729
+ ctx?.serviceInstanceId ?? ctx?.service_instance_id ?? ctx?.serviceInstance?.uuid ?? ctx?.serviceInstance?.serviceInstanceId ?? ""
18730
+ ).trim();
18731
+ const insertedServiceName = String(
18732
+ ctx?.serviceName ?? ctx?.service_name ?? ctx?.serviceInstance?.serviceName ?? ctx?.serviceInstance?.service_name ?? ""
18733
+ ).trim();
18734
+ if (!insertedServiceInstanceId && !insertedServiceName) {
18735
+ return false;
18736
+ }
18737
+ if (insertedServiceInstanceId && insertedServiceInstanceId !== serviceId) {
18738
+ return false;
18739
+ }
18740
+ if (!insertedServiceInstanceId && insertedServiceName && insertedServiceName !== serviceName) {
18741
+ return false;
18742
+ }
18743
+ serviceSetupCompletedHandled = true;
17965
18744
  if (options.cadenzaDB?.connect) {
17966
18745
  this.serviceRegistry.bootstrapFullSync(emit2, ctx, "service_setup_completed");
17967
- void this.publishServiceManifestIfNeeded("service_setup_completed");
18746
+ void this.publishServiceManifestIfNeeded(
18747
+ "service_setup_completed",
18748
+ "business_structural"
18749
+ );
17968
18750
  }
17969
18751
  if (isFrontend) {
17970
18752
  registerActorSessionPersistenceTasks();
@@ -18019,7 +18801,11 @@ var CadenzaService = class {
18019
18801
  );
18020
18802
  }
18021
18803
  this.serviceCreated = true;
18022
- this.requestServiceManifestPublication("service_created", true);
18804
+ this.requestServiceManifestPublication(
18805
+ "service_created",
18806
+ true,
18807
+ "routing_capability"
18808
+ );
18023
18809
  }
18024
18810
  /**
18025
18811
  * Creates a Cadenza metadata service with the specified name, description, and options.
@@ -18775,6 +19561,11 @@ var CadenzaService = class {
18775
19561
  this.warnedInvalidMetaIntentResponderKeys = /* @__PURE__ */ new Set();
18776
19562
  this.hydratedInquiryResults = /* @__PURE__ */ new Map();
18777
19563
  this.frontendSyncScheduled = false;
19564
+ this.serviceManifestRevision = 0;
19565
+ this.lastPublishedServiceManifestHashes = {};
19566
+ this.serviceManifestPublicationInFlight = false;
19567
+ this.serviceManifestPublicationPendingReason = null;
19568
+ this.serviceManifestPublicationPendingLayer = null;
18778
19569
  resetBrowserRuntimeActorHandles();
18779
19570
  }
18780
19571
  };
@@ -18788,9 +19579,10 @@ CadenzaService.warnedInvalidMetaIntentResponderKeys = /* @__PURE__ */ new Set();
18788
19579
  CadenzaService.hydratedInquiryResults = /* @__PURE__ */ new Map();
18789
19580
  CadenzaService.frontendSyncScheduled = false;
18790
19581
  CadenzaService.serviceManifestRevision = 0;
18791
- CadenzaService.lastPublishedServiceManifestHash = null;
19582
+ CadenzaService.lastPublishedServiceManifestHashes = {};
18792
19583
  CadenzaService.serviceManifestPublicationInFlight = false;
18793
19584
  CadenzaService.serviceManifestPublicationPendingReason = null;
19585
+ CadenzaService.serviceManifestPublicationPendingLayer = null;
18794
19586
  CadenzaService.shutdownHandlersRegistered = false;
18795
19587
  CadenzaService.shutdownInFlight = false;
18796
19588
  CadenzaService.shutdownHandlerCleanup = [];
@@ -18824,6 +19616,17 @@ function normalizeArrayResponse(value, keys) {
18824
19616
  if (Array.isArray(value?.data)) {
18825
19617
  return value.data;
18826
19618
  }
19619
+ const joinedContexts = Array.isArray(value?.joinedContexts) ? value.joinedContexts : [];
19620
+ for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
19621
+ const nested = joinedContexts[index];
19622
+ if (!nested || typeof nested !== "object") {
19623
+ continue;
19624
+ }
19625
+ const rows = normalizeArrayResponse(nested, keys);
19626
+ if (rows.length > 0) {
19627
+ return rows;
19628
+ }
19629
+ }
18827
19630
  return [];
18828
19631
  }
18829
19632
  function buildQueryResponseKeys(tableName) {