@cadenza.io/service 2.19.1 → 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.
package/dist/index.js CHANGED
@@ -39,15 +39,15 @@ __export(src_exports, {
39
39
  AUTHORITY_SERVICE_INSTANCE_TRANSPORT_REGISTER_TASK_NAME: () => AUTHORITY_SERVICE_INSTANCE_TRANSPORT_REGISTER_TASK_NAME,
40
40
  AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT: () => AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT,
41
41
  AUTHORITY_SERVICE_MANIFEST_UPDATED_SIGNAL: () => AUTHORITY_SERVICE_MANIFEST_UPDATED_SIGNAL,
42
- Actor: () => import_core6.Actor,
42
+ Actor: () => import_core7.Actor,
43
43
  DatabaseController: () => DatabaseController,
44
44
  DatabaseTask: () => DatabaseTask,
45
- DebounceTask: () => import_core6.DebounceTask,
45
+ DebounceTask: () => import_core7.DebounceTask,
46
46
  DeputyTask: () => DeputyTask,
47
47
  EXECUTION_PERSISTENCE_BUNDLE_SIGNAL: () => EXECUTION_PERSISTENCE_BUNDLE_SIGNAL,
48
- EphemeralTask: () => import_core6.EphemeralTask,
48
+ EphemeralTask: () => import_core7.EphemeralTask,
49
49
  GraphMetadataController: () => GraphMetadataController,
50
- GraphRoutine: () => import_core6.GraphRoutine,
50
+ GraphRoutine: () => import_core7.GraphRoutine,
51
51
  RUNTIME_STATUS_AUTHORITY_SYNC_REQUESTED_SIGNAL: () => RUNTIME_STATUS_AUTHORITY_SYNC_REQUESTED_SIGNAL,
52
52
  RUNTIME_VALIDATION_INTENTS: () => RUNTIME_VALIDATION_INTENTS,
53
53
  RUNTIME_VALIDATION_SIGNALS: () => RUNTIME_VALIDATION_SIGNALS,
@@ -56,7 +56,7 @@ __export(src_exports, {
56
56
  SignalController: () => SignalController,
57
57
  SignalTransmissionTask: () => SignalTransmissionTask,
58
58
  SocketController: () => SocketController,
59
- Task: () => import_core6.Task,
59
+ Task: () => import_core7.Task,
60
60
  buildAuthorityRuntimeStatusSignature: () => buildAuthorityRuntimeStatusSignature,
61
61
  buildExecutionPersistenceDependency: () => buildExecutionPersistenceDependency,
62
62
  buildExecutionPersistenceEnsureEvent: () => buildExecutionPersistenceEnsureEvent,
@@ -87,7 +87,7 @@ __export(src_exports, {
87
87
  module.exports = __toCommonJS(src_exports);
88
88
 
89
89
  // src/Cadenza.ts
90
- var import_core5 = __toESM(require("@cadenza.io/core"));
90
+ var import_core6 = __toESM(require("@cadenza.io/core"));
91
91
 
92
92
  // src/graph/definition/DeputyTask.ts
93
93
  var import_uuid2 = require("uuid");
@@ -163,14 +163,55 @@ var ROOT_METADATA_PASSTHROUGH_KEYS = [
163
163
  "__inquirySourceRoutineExecutionId"
164
164
  ];
165
165
  var DELEGATION_REQUEST_SNAPSHOT_KEY = "__delegationRequestContext";
166
+ var DELEGATION_FAILURE_CONTEXT_KEYS = [
167
+ "__remoteRoutineName",
168
+ "__serviceName",
169
+ "__timeout",
170
+ "__localTaskName",
171
+ "__localTaskVersion",
172
+ "__localServiceName",
173
+ "__localRoutineExecId",
174
+ "__previousTaskExecutionId",
175
+ "__fetchId",
176
+ "fetchId",
177
+ "__routeKey",
178
+ "routeKey",
179
+ "__instance",
180
+ "__transportId",
181
+ "__transportOrigin",
182
+ "__transportProtocols",
183
+ "__transportProtocol",
184
+ "__retries",
185
+ "__triedInstances",
186
+ "__delegationRequestContext",
187
+ "__metadata",
188
+ "serviceName",
189
+ "serviceInstanceId",
190
+ "serviceTransportId",
191
+ "serviceOrigin",
192
+ "transportProtocols",
193
+ "transportProtocol"
194
+ ];
195
+ function isPlainObject(value) {
196
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
197
+ return false;
198
+ }
199
+ const prototype = Object.getPrototypeOf(value);
200
+ return prototype === Object.prototype || prototype === null;
201
+ }
166
202
  function cloneDelegationValue(value) {
203
+ if (value instanceof Date) {
204
+ return new Date(value.getTime());
205
+ }
167
206
  if (Array.isArray(value)) {
168
- return value.map(
169
- (item) => item && typeof item === "object" ? { ...item } : item
170
- );
207
+ return value.map((item) => cloneDelegationValue(item));
171
208
  }
172
- if (value && typeof value === "object") {
173
- return { ...value };
209
+ if (isPlainObject(value)) {
210
+ const clone = {};
211
+ for (const [key, nestedValue] of Object.entries(value)) {
212
+ clone[key] = cloneDelegationValue(nestedValue);
213
+ }
214
+ return clone;
174
215
  }
175
216
  return value;
176
217
  }
@@ -206,9 +247,9 @@ function attachDelegationRequestSnapshot(input) {
206
247
  function restoreDelegationRequestSnapshot(input) {
207
248
  const context = input && typeof input === "object" ? { ...input } : {};
208
249
  const mutableContext = context;
209
- const snapshotCandidate = mutableContext[DELEGATION_REQUEST_SNAPSHOT_KEY];
250
+ const snapshotCandidate = mutableContext[DELEGATION_REQUEST_SNAPSHOT_KEY] ?? (mutableContext.__metadata && typeof mutableContext.__metadata === "object" ? mutableContext.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY] : void 0);
210
251
  const snapshot = snapshotCandidate && typeof snapshotCandidate === "object" ? snapshotCandidate : null;
211
- const looksLikeDelegationResult = mutableContext.__status !== void 0 || mutableContext.__success !== void 0 || mutableContext.rowCount !== void 0 || mutableContext.__nextNodes !== void 0 || mutableContext.__isDeputy === true;
252
+ const looksLikeDelegationResult = mutableContext.__status !== void 0 || mutableContext.__success !== void 0 || mutableContext.rowCount !== void 0 || mutableContext.__nextNodes !== void 0 || mutableContext.__isDeputy === true || mutableContext.errored === true || mutableContext.failed === true || mutableContext.timedOut === true || mutableContext.__error !== void 0 || mutableContext.error !== void 0 || mutableContext.__inquiryMeta !== void 0;
212
253
  if (!snapshot || !looksLikeDelegationResult) {
213
254
  return context;
214
255
  }
@@ -229,6 +270,26 @@ function stripDelegationRequestSnapshot(input) {
229
270
  delete context[DELEGATION_REQUEST_SNAPSHOT_KEY];
230
271
  return context;
231
272
  }
273
+ function buildDelegationFailureContext(signalName, input, error) {
274
+ const source = input && typeof input === "object" ? { ...input } : {};
275
+ const slimContext = {};
276
+ for (const key of DELEGATION_FAILURE_CONTEXT_KEYS) {
277
+ if (source[key] !== void 0) {
278
+ slimContext[key] = cloneDelegationValue(source[key]);
279
+ }
280
+ }
281
+ if (slimContext[DELEGATION_REQUEST_SNAPSHOT_KEY] === void 0 && source.__metadata && typeof source.__metadata === "object" && source.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY] !== void 0) {
282
+ slimContext[DELEGATION_REQUEST_SNAPSHOT_KEY] = cloneDelegationValue(
283
+ source.__metadata[DELEGATION_REQUEST_SNAPSHOT_KEY]
284
+ );
285
+ }
286
+ return {
287
+ __signalName: signalName,
288
+ __error: error instanceof Error ? error.message : String(error ?? "Unknown error"),
289
+ errored: true,
290
+ ...slimContext
291
+ };
292
+ }
232
293
  function stripTransportSelectionRoutingContext(input) {
233
294
  const context = stripLocalRoutinePersistenceHints(
234
295
  input && typeof input === "object" ? { ...input } : {}
@@ -448,6 +509,8 @@ var DeputyTask = class extends import_core.Task {
448
509
 
449
510
  // src/graph/definition/DatabaseTask.ts
450
511
  var ACTOR_SESSION_TRACE_ENABLED = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
512
+ var actorSessionEmptyDelegationLogCount = 0;
513
+ var ACTOR_SESSION_EMPTY_DELEGATION_LOG_LIMIT = 40;
451
514
  var INSTANCE_TRACE_ENABLED = process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true";
452
515
  var EXECUTION_OBSERVABILITY_INSERT_ROUTINES = /* @__PURE__ */ new Set([
453
516
  "Insert execution_trace",
@@ -549,15 +612,16 @@ var DatabaseTask = class extends DeputyTask {
549
612
  }
550
613
  delete ctx.__metadata;
551
614
  const isResolverExecution = typeof ctx.__resolverRequestId === "string" && ctx.__resolverRequestId.length > 0;
552
- const dynamicQueryData = isResolverExecution ? {} : ctx.__resolverQueryData && typeof ctx.__resolverQueryData === "object" ? ctx.__resolverQueryData : ctx.queryData ?? {};
615
+ const resolverQueryData = ctx.__resolverQueryData && typeof ctx.__resolverQueryData === "object" ? ctx.__resolverQueryData : null;
616
+ const dynamicQueryData = resolverQueryData ?? (ctx.queryData && typeof ctx.queryData === "object" ? ctx.queryData : {});
553
617
  delete ctx.queryData;
554
618
  const nextQueryData = {
555
619
  ...this.queryData,
556
- data: {
557
- ...ctx.data
558
- },
559
620
  ...dynamicQueryData
560
621
  };
622
+ if (dynamicQueryData.data === void 0 && ctx.data !== void 0) {
623
+ nextQueryData.data = ctx.data && typeof ctx.data === "object" && !Array.isArray(ctx.data) ? { ...ctx.data } : ctx.data;
624
+ }
561
625
  const deputyContext = attachDelegationRequestSnapshot(
562
626
  stripDelegationRequestSnapshot(
563
627
  hoistDelegationMetadataFields({
@@ -617,6 +681,22 @@ var DatabaseTask = class extends DeputyTask {
617
681
  rootKeys: Object.keys(rawContext)
618
682
  });
619
683
  }
684
+ if (this.remoteRoutineName === "Insert actor_session_state" && deputyContext.data === void 0 && deputyContext.queryData === void 0 && actorSessionEmptyDelegationLogCount < ACTOR_SESSION_EMPTY_DELEGATION_LOG_LIMIT) {
685
+ actorSessionEmptyDelegationLogCount += 1;
686
+ console.warn("[CADENZA_ACTOR_SESSION_EMPTY_DELEGATION]", {
687
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
688
+ localTaskName: this.name,
689
+ remoteRoutineName: this.remoteRoutineName,
690
+ hadSnapshotBeforeRestore: initialFullContext.__delegationRequestContext !== void 0 || initialFullContext.__metadata?.__delegationRequestContext !== void 0,
691
+ restoredRootKeys: Object.keys(rawContext),
692
+ deputyRootKeys: Object.keys(deputyContext),
693
+ signalName: rawContext.__signalName ?? rawContext.__metadata?.__signalName ?? null,
694
+ inquiryName: rawContext.__inquiryName ?? rawContext.__metadata?.__inquiryName ?? null,
695
+ sourceServiceName: rawContext.__localServiceName ?? rawContext.__metadata?.__localServiceName ?? null,
696
+ sourceRoutineName: rawContext.__routineName ?? rawContext.__metadata?.__routineName ?? null,
697
+ sourceTaskName: rawContext.__localTaskName ?? rawContext.__metadata?.__localTaskName ?? null
698
+ });
699
+ }
620
700
  return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
621
701
  }
622
702
  };
@@ -662,6 +742,26 @@ var AUTHORITY_SYNC_DEBUG_TASK_NAMES = /* @__PURE__ */ new Set([
662
742
  ]);
663
743
  var AUTHORITY_SYNC_DEBUG_ROUTINE_NAMES = /* @__PURE__ */ new Set(["Sync services"]);
664
744
  var INTENT_MAP_DEBUG_ENABLED = process.env.CADENZA_INTENT_MAP_DEBUG === "1" || process.env.CADENZA_INTENT_MAP_DEBUG === "true";
745
+ function normalizeQueryResultValue(value) {
746
+ if (value instanceof Date) {
747
+ return value.toISOString();
748
+ }
749
+ if (Array.isArray(value)) {
750
+ return value.map((entry) => normalizeQueryResultValue(entry));
751
+ }
752
+ if (value && typeof value === "object") {
753
+ const prototype = Object.getPrototypeOf(value);
754
+ if (prototype === Object.prototype || prototype === null) {
755
+ return Object.fromEntries(
756
+ Object.entries(value).map(([key, nestedValue]) => [
757
+ key,
758
+ normalizeQueryResultValue(nestedValue)
759
+ ])
760
+ );
761
+ }
762
+ }
763
+ return value;
764
+ }
665
765
  var POSTGRES_SETUP_DEBUG_ENABLED = process.env.CADENZA_POSTGRES_SETUP_DEBUG === "1" || process.env.CADENZA_POSTGRES_SETUP_DEBUG === "true";
666
766
  var ACTOR_SESSION_TRACE_ENABLED2 = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
667
767
  var ACTOR_SESSION_TRACE_LIMIT = 20;
@@ -959,14 +1059,14 @@ function errorMessage(error) {
959
1059
  }
960
1060
  return String(error);
961
1061
  }
962
- function isPlainObject(value) {
1062
+ function isPlainObject2(value) {
963
1063
  return typeof value === "object" && value !== null && !Array.isArray(value);
964
1064
  }
965
1065
  function stableStringify(value) {
966
1066
  if (Array.isArray(value)) {
967
1067
  return `[${value.map((item) => stableStringify(item)).join(",")}]`;
968
1068
  }
969
- if (isPlainObject(value)) {
1069
+ if (isPlainObject2(value)) {
970
1070
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
971
1071
  }
972
1072
  return JSON.stringify(value);
@@ -1082,7 +1182,23 @@ function resolveGeneratedTaskTag(tableName, actorToken, context, operation) {
1082
1182
  if (operation === "insert") {
1083
1183
  return `insert:${actorToken}:${tableName}`;
1084
1184
  }
1085
- return context?.__metadata?.__executionTraceId ?? context?.__executionTraceId ?? "default";
1185
+ 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;
1186
+ if (typeof traceScopedTag === "string" && traceScopedTag.length > 0) {
1187
+ return traceScopedTag;
1188
+ }
1189
+ const queryScope = {
1190
+ queryData: context?.queryData,
1191
+ filter: context?.filter,
1192
+ fields: context?.fields,
1193
+ joins: context?.joins,
1194
+ sort: context?.sort,
1195
+ limit: context?.limit,
1196
+ offset: context?.offset,
1197
+ queryMode: context?.queryMode,
1198
+ aggregates: context?.aggregates,
1199
+ groupBy: context?.groupBy
1200
+ };
1201
+ return `read:${actorToken}:${tableName}:${stableStringify(queryScope)}`;
1086
1202
  }
1087
1203
  function resolveExecutionObservabilitySafetyPolicyForTable(basePolicy, tableName) {
1088
1204
  if (!EXECUTION_OBSERVABILITY_TABLES.has(tableName)) {
@@ -1164,6 +1280,44 @@ function mergeTriggerQueryData(context, triggerQueryData) {
1164
1280
  ...triggerQueryData
1165
1281
  };
1166
1282
  }
1283
+ function isNonEmptyPlainObject(value) {
1284
+ return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0;
1285
+ }
1286
+ function isMissingInsertData(data) {
1287
+ return !data || Array.isArray(data) && data.length === 0 || typeof data === "object" && !Array.isArray(data) && Object.keys(data).length === 0;
1288
+ }
1289
+ function resolveActorSessionDelegationSnapshot(context) {
1290
+ const direct = context.__delegationRequestContext && typeof context.__delegationRequestContext === "object" ? context.__delegationRequestContext : null;
1291
+ if (direct) {
1292
+ return direct;
1293
+ }
1294
+ const metadata = context.__metadata && typeof context.__metadata === "object" ? context.__metadata : null;
1295
+ const nested = metadata?.__delegationRequestContext && typeof metadata.__delegationRequestContext === "object" ? metadata.__delegationRequestContext : null;
1296
+ return nested;
1297
+ }
1298
+ function recoverActorSessionInsertPayload(context, payload) {
1299
+ if (!isMissingInsertData(payload.data)) {
1300
+ return payload;
1301
+ }
1302
+ const snapshot = resolveActorSessionDelegationSnapshot(context);
1303
+ if (!snapshot) {
1304
+ return payload;
1305
+ }
1306
+ const snapshotQueryData = snapshot.queryData && typeof snapshot.queryData === "object" ? { ...snapshot.queryData } : {};
1307
+ const snapshotData = isNonEmptyPlainObject(snapshotQueryData.data) ? snapshotQueryData.data : isNonEmptyPlainObject(snapshot.data) ? snapshot.data : null;
1308
+ if (!snapshotData) {
1309
+ return payload;
1310
+ }
1311
+ const recoveredPayload = {
1312
+ ...snapshotQueryData,
1313
+ ...payload,
1314
+ data: snapshotData
1315
+ };
1316
+ if (recoveredPayload.onConflict === void 0 && snapshotQueryData.onConflict) {
1317
+ recoveredPayload.onConflict = snapshotQueryData.onConflict;
1318
+ }
1319
+ return recoveredPayload;
1320
+ }
1167
1321
  function resolveOperationPayload(context) {
1168
1322
  const queryData = typeof context.queryData === "object" && context.queryData ? context.queryData : {};
1169
1323
  return mergeTriggerQueryData(context, queryData);
@@ -1891,6 +2045,23 @@ var DatabaseController = class _DatabaseController {
1891
2045
  async insertFunction(registration, tableName, context) {
1892
2046
  const { data, transaction = true, fields = [], onConflict } = context;
1893
2047
  if (!data || Array.isArray(data) && data.length === 0) {
2048
+ if (tableName === "actor_session_state") {
2049
+ const rawContext = context;
2050
+ const rawMetadata = rawContext.__metadata && typeof rawContext.__metadata === "object" ? rawContext.__metadata : void 0;
2051
+ console.warn("[CADENZA_ACTOR_SESSION_EMPTY_INSERT]", {
2052
+ tableName,
2053
+ contextKeys: Object.keys(context ?? {}),
2054
+ queryDataKeys: [],
2055
+ hasDelegationSnapshot: rawContext.__delegationRequestContext !== void 0 || rawMetadata?.__delegationRequestContext !== void 0,
2056
+ localTaskName: typeof rawContext.__localTaskName === "string" ? rawContext.__localTaskName : void 0,
2057
+ remoteRoutineName: typeof rawContext.__remoteRoutineName === "string" ? rawContext.__remoteRoutineName : void 0,
2058
+ serviceName: typeof rawContext.__serviceName === "string" ? rawContext.__serviceName : void 0,
2059
+ actorName: typeof rawContext.actor_name === "string" ? rawContext.actor_name : void 0,
2060
+ actorKey: typeof rawContext.actor_key === "string" ? rawContext.actor_key : void 0,
2061
+ durableVersion: rawContext.durable_version,
2062
+ metadata: rawMetadata
2063
+ });
2064
+ }
1894
2065
  return {
1895
2066
  rowCount: 0,
1896
2067
  errored: true,
@@ -2960,9 +3131,18 @@ var DatabaseController = class _DatabaseController {
2960
3131
  }
2961
3132
  }
2962
3133
  }
2963
- const operationPayload = resolveOperationPayload(context);
3134
+ const initialOperationPayload = resolveOperationPayload(context);
3135
+ let operationPayload = initialOperationPayload;
3136
+ if (tableName === "actor_session_state" && op === "insert") {
3137
+ operationPayload = recoverActorSessionInsertPayload(
3138
+ context,
3139
+ operationPayload
3140
+ );
3141
+ }
2964
3142
  const actorSessionInsertData = operationPayload.data;
2965
- const actorSessionInsertMissingData = !actorSessionInsertData || Array.isArray(actorSessionInsertData) && actorSessionInsertData.length === 0 || typeof actorSessionInsertData === "object" && !Array.isArray(actorSessionInsertData) && Object.keys(actorSessionInsertData).length === 0;
3143
+ const actorSessionInsertMissingData = isMissingInsertData(
3144
+ actorSessionInsertData
3145
+ );
2966
3146
  if (tableName === "actor_session_state" && op === "insert" && actorSessionInsertMissingData) {
2967
3147
  logActorSessionTrace("empty_insert_payload", {
2968
3148
  taskName,
@@ -2978,7 +3158,10 @@ var DatabaseController = class _DatabaseController {
2978
3158
  payloadDataType: actorSessionInsertData === null ? "null" : Array.isArray(actorSessionInsertData) ? "array" : typeof actorSessionInsertData,
2979
3159
  payloadDataKeys: actorSessionInsertData && typeof actorSessionInsertData === "object" && !Array.isArray(actorSessionInsertData) ? Object.keys(actorSessionInsertData) : [],
2980
3160
  queryDataKeys: context.queryData && typeof context.queryData === "object" && !Array.isArray(context.queryData) ? Object.keys(context.queryData) : [],
2981
- rootKeys: Object.keys(context ?? {}).slice(0, 24)
3161
+ rootKeys: Object.keys(context ?? {}).slice(0, 24),
3162
+ initialPayloadMissingData: isMissingInsertData(
3163
+ initialOperationPayload.data
3164
+ )
2982
3165
  });
2983
3166
  }
2984
3167
  const shouldDebugAuthoritySync = shouldDebugAuthoritySyncPayload(
@@ -3273,7 +3456,7 @@ var DatabaseController = class _DatabaseController {
3273
3456
  return rows.map((row) => {
3274
3457
  const camelCasedRow = {};
3275
3458
  for (const [key, value] of Object.entries(row)) {
3276
- camelCasedRow[(0, import_lodash_es.camelCase)(key)] = value;
3459
+ camelCasedRow[(0, import_lodash_es.camelCase)(key)] = normalizeQueryResultValue(value);
3277
3460
  }
3278
3461
  return camelCasedRow;
3279
3462
  });
@@ -3708,14 +3891,14 @@ var META_INTENT_PREFIX = "meta-";
3708
3891
  var META_RUNTIME_TRANSPORT_DIAGNOSTICS_INTENT = "meta-runtime-transport-diagnostics";
3709
3892
  var META_RUNTIME_STATUS_INTENT = "meta-runtime-status";
3710
3893
  var META_READINESS_INTENT = "meta-readiness";
3711
- function isPlainObject2(value) {
3894
+ function isPlainObject3(value) {
3712
3895
  return typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
3713
3896
  }
3714
3897
  function deepMergeDeterministic(left, right) {
3715
3898
  if (Array.isArray(left) && Array.isArray(right)) {
3716
3899
  return [...left, ...right];
3717
3900
  }
3718
- if (isPlainObject2(left) && isPlainObject2(right)) {
3901
+ if (isPlainObject3(left) && isPlainObject3(right)) {
3719
3902
  const merged = { ...left };
3720
3903
  const keys = Array.from(/* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])).sort();
3721
3904
  for (const key of keys) {
@@ -4537,6 +4720,7 @@ function normalizeServiceManifestSnapshot(input) {
4537
4720
  revision,
4538
4721
  manifestHash,
4539
4722
  publishedAt,
4723
+ publicationLayer: record.publicationLayer === "routing_capability" || record.publicationLayer === "business_structural" || record.publicationLayer === "local_meta_structural" ? record.publicationLayer : "business_structural",
4540
4724
  tasks: normalizeArray(record.tasks),
4541
4725
  signals: normalizeArray(record.signals),
4542
4726
  intents: normalizeArray(record.intents),
@@ -4666,6 +4850,7 @@ function decomposeSignalName(signalName) {
4666
4850
  }
4667
4851
 
4668
4852
  // src/registry/serviceManifest.ts
4853
+ var import_core2 = __toESM(require("@cadenza.io/core"));
4669
4854
  var ACTOR_TASK_METADATA = /* @__PURE__ */ Symbol.for("@cadenza.io/core/actor-task-meta");
4670
4855
  function getActorTaskRuntimeMetadata(taskFunction) {
4671
4856
  if (typeof taskFunction !== "function") {
@@ -4810,14 +4995,48 @@ function buildRoutineDefinition(routine, serviceName) {
4810
4995
  };
4811
4996
  }
4812
4997
  function shouldExportTask(task) {
4813
- return !task.isDeputy && !task.isEphemeral;
4998
+ return task.register !== false && task.isHidden !== true && !task.isDeputy && !task.isEphemeral;
4814
4999
  }
4815
5000
  function shouldExportRoutine(routine) {
4816
5001
  return Boolean(String(routine?.name ?? "").trim());
4817
5002
  }
5003
+ function buildTaskKey(task) {
5004
+ return `${task.service_name}|${task.name}|${task.version}`;
5005
+ }
5006
+ function buildActorKey(actor) {
5007
+ return `${actor.service_name}|${actor.name}|${actor.version}`;
5008
+ }
5009
+ function buildRoutineKey(routine) {
5010
+ return `${routine.service_name}|${routine.name}|${routine.version}`;
5011
+ }
5012
+ function listManifestTasks() {
5013
+ const registryTasks = Array.from(CadenzaService.registry.tasks.values()).filter(
5014
+ (task) => Boolean(task)
5015
+ );
5016
+ const cachedTasks = Array.from(
5017
+ import_core2.default.taskCache?.values?.() ?? []
5018
+ ).filter((task) => Boolean(task));
5019
+ return Array.from(
5020
+ new Map(
5021
+ [...registryTasks, ...cachedTasks].map((task) => [task.name, task])
5022
+ ).values()
5023
+ );
5024
+ }
5025
+ function isRoutingCriticalMetaSignal(_signal) {
5026
+ return false;
5027
+ }
5028
+ function isRoutingCriticalMetaIntent(_intent) {
5029
+ return false;
5030
+ }
4818
5031
  function buildServiceManifestSnapshot(params) {
4819
- const { serviceName, serviceInstanceId, revision, publishedAt } = params;
4820
- const tasks = Array.from(CadenzaService.registry.tasks.values()).filter((task) => Boolean(task)).filter(shouldExportTask);
5032
+ const {
5033
+ serviceName,
5034
+ serviceInstanceId,
5035
+ revision,
5036
+ publishedAt,
5037
+ publicationLayer = "business_structural"
5038
+ } = params;
5039
+ const tasks = listManifestTasks().filter(shouldExportTask);
4821
5040
  const routines = Array.from(CadenzaService.registry.routines.values()).filter((routine) => Boolean(routine)).filter(shouldExportRoutine);
4822
5041
  const actors = CadenzaService.getAllActors();
4823
5042
  const taskDefinitions = tasks.map((task) => buildTaskDefinition(task, serviceName)).sort(
@@ -4965,41 +5184,385 @@ function buildServiceManifestSnapshot(params) {
4965
5184
  }
4966
5185
  }
4967
5186
  }
4968
- const manifestBody = {
4969
- serviceName,
4970
- serviceInstanceId,
4971
- tasks: taskDefinitions,
4972
- signals: Array.from(signalDefinitions.values()).sort(
4973
- (left, right) => left.name.localeCompare(right.name)
4974
- ),
4975
- intents: intentDefinitions,
4976
- actors: actorDefinitions,
4977
- routines: routineDefinitions,
4978
- directionalTaskMaps: Array.from(directionalTaskMaps.values()).sort(
4979
- (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
4980
- `${right.predecessor_task_name}:${right.task_name}`
4981
- )
4982
- ),
4983
- signalToTaskMaps: Array.from(signalTaskMaps.values()).sort(
4984
- (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
4985
- `${right.signal_name}:${right.task_name}`
4986
- )
4987
- ),
4988
- intentToTaskMaps: Array.from(intentTaskMaps.values()).sort(
4989
- (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
4990
- `${right.intent_name}:${right.task_name}`
5187
+ const taskDefinitionsByKey = new Map(
5188
+ taskDefinitions.map((task) => [buildTaskKey(task), task])
5189
+ );
5190
+ const signalDefinitionsByName = new Map(
5191
+ Array.from(signalDefinitions.values()).map((signal) => [signal.name, signal])
5192
+ );
5193
+ const intentDefinitionsByName = new Map(
5194
+ intentDefinitions.map((intent) => [intent.name, intent])
5195
+ );
5196
+ const actorDefinitionsByKey = new Map(
5197
+ actorDefinitions.map((actor) => [buildActorKey(actor), actor])
5198
+ );
5199
+ const routineDefinitionsByKey = new Map(
5200
+ routineDefinitions.map((routine) => [buildRoutineKey(routine), routine])
5201
+ );
5202
+ const routingTaskKeys = /* @__PURE__ */ new Set();
5203
+ const routingSignalNames = /* @__PURE__ */ new Set();
5204
+ const routingIntentNames = /* @__PURE__ */ new Set();
5205
+ const publishedSignalTaskMaps = Array.from(signalTaskMaps.values()).filter((map) => {
5206
+ const signal = signalDefinitionsByName.get(map.signal_name);
5207
+ return signal?.is_meta !== true || (signal ? isRoutingCriticalMetaSignal(signal) : false);
5208
+ }).sort(
5209
+ (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
5210
+ `${right.signal_name}:${right.task_name}`
5211
+ )
5212
+ );
5213
+ const publishedIntentTaskMaps = Array.from(intentTaskMaps.values()).filter((map) => {
5214
+ const intent = intentDefinitionsByName.get(map.intent_name);
5215
+ return intent?.is_meta !== true || (intent ? isRoutingCriticalMetaIntent(intent) : false);
5216
+ }).sort(
5217
+ (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
5218
+ `${right.intent_name}:${right.task_name}`
5219
+ )
5220
+ );
5221
+ const localMetaSignalTaskMaps = Array.from(signalTaskMaps.values()).filter((map) => !publishedSignalTaskMaps.includes(map)).sort(
5222
+ (left, right) => `${left.signal_name}:${left.task_name}`.localeCompare(
5223
+ `${right.signal_name}:${right.task_name}`
5224
+ )
5225
+ );
5226
+ const localMetaIntentTaskMaps = Array.from(intentTaskMaps.values()).filter((map) => !publishedIntentTaskMaps.includes(map)).sort(
5227
+ (left, right) => `${left.intent_name}:${left.task_name}`.localeCompare(
5228
+ `${right.intent_name}:${right.task_name}`
5229
+ )
5230
+ );
5231
+ for (const map of publishedSignalTaskMaps) {
5232
+ routingTaskKeys.add(
5233
+ buildTaskKey({
5234
+ service_name: map.service_name,
5235
+ name: map.task_name,
5236
+ version: map.task_version
5237
+ })
5238
+ );
5239
+ routingSignalNames.add(map.signal_name);
5240
+ }
5241
+ for (const map of publishedIntentTaskMaps) {
5242
+ routingTaskKeys.add(
5243
+ buildTaskKey({
5244
+ service_name: map.service_name,
5245
+ name: map.task_name,
5246
+ version: map.task_version
5247
+ })
5248
+ );
5249
+ routingIntentNames.add(map.intent_name);
5250
+ }
5251
+ const routingTasks = Array.from(routingTaskKeys).map((key) => taskDefinitionsByKey.get(key) ?? null).filter((task) => task !== null).sort(
5252
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5253
+ );
5254
+ const routingSignals = Array.from(routingSignalNames).map((name) => signalDefinitionsByName.get(name) ?? null).filter((signal) => signal !== null).sort((left, right) => left.name.localeCompare(right.name));
5255
+ const routingIntents = Array.from(routingIntentNames).map((name) => intentDefinitionsByName.get(name) ?? null).filter((intent) => intent !== null).sort((left, right) => left.name.localeCompare(right.name));
5256
+ const businessTasks = taskDefinitions.filter((task) => task.is_meta !== true && task.is_sub_meta !== true).sort(
5257
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5258
+ );
5259
+ const businessSignals = Array.from(signalDefinitions.values()).filter((signal) => signal.is_meta !== true).sort((left, right) => left.name.localeCompare(right.name));
5260
+ const businessIntents = intentDefinitions.filter((intent) => intent.is_meta !== true).sort((left, right) => left.name.localeCompare(right.name));
5261
+ const businessActors = actorDefinitions.filter((actor) => actor.is_meta !== true).sort(
5262
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5263
+ );
5264
+ const businessRoutines = routineDefinitions.filter((routine) => routine.is_meta !== true).sort(
5265
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5266
+ );
5267
+ const businessDirectionalTaskMaps = Array.from(directionalTaskMaps.values()).filter((map) => {
5268
+ const predecessor = taskDefinitionsByKey.get(
5269
+ buildTaskKey({
5270
+ service_name: map.predecessor_service_name,
5271
+ name: map.predecessor_task_name,
5272
+ version: map.predecessor_task_version
5273
+ })
5274
+ );
5275
+ const task = taskDefinitionsByKey.get(
5276
+ buildTaskKey({
5277
+ service_name: map.service_name,
5278
+ name: map.task_name,
5279
+ version: map.task_version
5280
+ })
5281
+ );
5282
+ return predecessor?.is_meta !== true && predecessor?.is_sub_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
5283
+ }).sort(
5284
+ (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
5285
+ `${right.predecessor_task_name}:${right.task_name}`
5286
+ )
5287
+ );
5288
+ const businessActorTaskMaps = Array.from(actorTaskMaps.values()).filter((map) => {
5289
+ const actor = actorDefinitionsByKey.get(
5290
+ buildActorKey({
5291
+ service_name: map.service_name,
5292
+ name: map.actor_name,
5293
+ version: map.actor_version
5294
+ })
5295
+ );
5296
+ const task = taskDefinitionsByKey.get(
5297
+ buildTaskKey({
5298
+ service_name: map.service_name,
5299
+ name: map.task_name,
5300
+ version: map.task_version
5301
+ })
5302
+ );
5303
+ return actor?.is_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
5304
+ }).sort(
5305
+ (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
5306
+ `${right.actor_name}:${right.task_name}`
5307
+ )
5308
+ );
5309
+ const businessTaskToRoutineMaps = Array.from(taskToRoutineMaps.values()).filter((map) => {
5310
+ const routine = routineDefinitionsByKey.get(
5311
+ buildRoutineKey({
5312
+ service_name: map.service_name,
5313
+ name: map.routine_name,
5314
+ version: map.routine_version
5315
+ })
5316
+ );
5317
+ const task = taskDefinitionsByKey.get(
5318
+ buildTaskKey({
5319
+ service_name: map.service_name,
5320
+ name: map.task_name,
5321
+ version: map.task_version
5322
+ })
5323
+ );
5324
+ return routine?.is_meta !== true && task?.is_meta !== true && task?.is_sub_meta !== true;
5325
+ }).sort(
5326
+ (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
5327
+ `${right.routine_name}:${right.task_name}`
5328
+ )
5329
+ );
5330
+ const localMetaTasks = taskDefinitions.filter((task) => task.is_meta === true || task.is_sub_meta === true).sort(
5331
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5332
+ );
5333
+ const localMetaSignals = Array.from(signalDefinitions.values()).filter((signal) => signal.is_meta === true).sort((left, right) => left.name.localeCompare(right.name));
5334
+ const localMetaIntents = intentDefinitions.filter((intent) => intent.is_meta === true).sort((left, right) => left.name.localeCompare(right.name));
5335
+ const localMetaActors = actorDefinitions.filter((actor) => actor.is_meta === true).sort(
5336
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5337
+ );
5338
+ const localMetaRoutines = routineDefinitions.filter((routine) => routine.is_meta === true).sort(
5339
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5340
+ );
5341
+ const localMetaDirectionalTaskMaps = Array.from(directionalTaskMaps.values()).filter((map) => !businessDirectionalTaskMaps.includes(map)).sort(
5342
+ (left, right) => `${left.predecessor_task_name}:${left.task_name}`.localeCompare(
5343
+ `${right.predecessor_task_name}:${right.task_name}`
5344
+ )
5345
+ );
5346
+ const localMetaActorTaskMaps = Array.from(actorTaskMaps.values()).filter((map) => !businessActorTaskMaps.includes(map)).sort(
5347
+ (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
5348
+ `${right.actor_name}:${right.task_name}`
5349
+ )
5350
+ );
5351
+ const localMetaTaskToRoutineMaps = Array.from(taskToRoutineMaps.values()).filter((map) => !businessTaskToRoutineMaps.includes(map)).sort(
5352
+ (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
5353
+ `${right.routine_name}:${right.task_name}`
5354
+ )
5355
+ );
5356
+ const businessLocalMetaTaskKeys = /* @__PURE__ */ new Set();
5357
+ const businessLocalMetaSignalNames = /* @__PURE__ */ new Set();
5358
+ const businessLocalMetaIntentNames = /* @__PURE__ */ new Set();
5359
+ const businessLocalMetaActorKeys = /* @__PURE__ */ new Set();
5360
+ const businessLocalMetaRoutineKeys = /* @__PURE__ */ new Set();
5361
+ for (const map of localMetaSignalTaskMaps) {
5362
+ businessLocalMetaSignalNames.add(map.signal_name);
5363
+ businessLocalMetaTaskKeys.add(
5364
+ buildTaskKey({
5365
+ service_name: map.service_name,
5366
+ name: map.task_name,
5367
+ version: map.task_version
5368
+ })
5369
+ );
5370
+ }
5371
+ for (const map of localMetaIntentTaskMaps) {
5372
+ businessLocalMetaIntentNames.add(map.intent_name);
5373
+ businessLocalMetaTaskKeys.add(
5374
+ buildTaskKey({
5375
+ service_name: map.service_name,
5376
+ name: map.task_name,
5377
+ version: map.task_version
5378
+ })
5379
+ );
5380
+ }
5381
+ for (const map of localMetaActorTaskMaps) {
5382
+ businessLocalMetaActorKeys.add(
5383
+ buildActorKey({
5384
+ service_name: map.service_name,
5385
+ name: map.actor_name,
5386
+ version: map.actor_version
5387
+ })
5388
+ );
5389
+ businessLocalMetaTaskKeys.add(
5390
+ buildTaskKey({
5391
+ service_name: map.service_name,
5392
+ name: map.task_name,
5393
+ version: map.task_version
5394
+ })
5395
+ );
5396
+ }
5397
+ for (const map of localMetaTaskToRoutineMaps) {
5398
+ businessLocalMetaRoutineKeys.add(
5399
+ buildRoutineKey({
5400
+ service_name: map.service_name,
5401
+ name: map.routine_name,
5402
+ version: map.routine_version
5403
+ })
5404
+ );
5405
+ businessLocalMetaTaskKeys.add(
5406
+ buildTaskKey({
5407
+ service_name: map.service_name,
5408
+ name: map.task_name,
5409
+ version: map.task_version
5410
+ })
5411
+ );
5412
+ }
5413
+ const businessLocalMetaTasks = Array.from(businessLocalMetaTaskKeys).map((key) => taskDefinitionsByKey.get(key) ?? null).filter(
5414
+ (task) => task !== null && (task.is_meta === true || task.is_sub_meta === true)
5415
+ ).sort(
5416
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5417
+ );
5418
+ const businessLocalMetaSignals = Array.from(businessLocalMetaSignalNames).map((name) => signalDefinitionsByName.get(name) ?? null).filter(
5419
+ (signal) => signal !== null && signal.is_meta === true
5420
+ ).sort((left, right) => left.name.localeCompare(right.name));
5421
+ const businessLocalMetaIntents = Array.from(businessLocalMetaIntentNames).map((name) => intentDefinitionsByName.get(name) ?? null).filter(
5422
+ (intent) => intent !== null && intent.is_meta === true
5423
+ ).sort((left, right) => left.name.localeCompare(right.name));
5424
+ const businessLocalMetaActors = Array.from(businessLocalMetaActorKeys).map((key) => actorDefinitionsByKey.get(key) ?? null).filter(
5425
+ (actor) => actor !== null && actor.is_meta === true
5426
+ ).sort(
5427
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5428
+ );
5429
+ const businessLocalMetaRoutines = Array.from(businessLocalMetaRoutineKeys).map((key) => routineDefinitionsByKey.get(key) ?? null).filter(
5430
+ (routine) => routine !== null && routine.is_meta === true
5431
+ ).sort(
5432
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5433
+ );
5434
+ const cumulativeTasks = publicationLayer === "routing_capability" ? routingTasks : publicationLayer === "business_structural" ? Array.from(
5435
+ new Map(
5436
+ [...routingTasks, ...businessTasks, ...businessLocalMetaTasks].map((task) => [
5437
+ buildTaskKey(task),
5438
+ task
5439
+ ])
5440
+ ).values()
5441
+ ).sort(
5442
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5443
+ ) : Array.from(
5444
+ new Map(
5445
+ [...routingTasks, ...businessTasks, ...localMetaTasks].map((task) => [
5446
+ buildTaskKey(task),
5447
+ task
5448
+ ])
5449
+ ).values()
5450
+ ).sort(
5451
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5452
+ );
5453
+ const cumulativeSignals = publicationLayer === "routing_capability" ? routingSignals : publicationLayer === "business_structural" ? Array.from(
5454
+ new Map(
5455
+ [...routingSignals, ...businessSignals, ...businessLocalMetaSignals].map(
5456
+ (signal) => [signal.name, signal]
4991
5457
  )
4992
- ),
4993
- actorTaskMaps: Array.from(actorTaskMaps.values()).sort(
4994
- (left, right) => `${left.actor_name}:${left.task_name}`.localeCompare(
4995
- `${right.actor_name}:${right.task_name}`
5458
+ ).values()
5459
+ ).sort((left, right) => left.name.localeCompare(right.name)) : Array.from(
5460
+ new Map(
5461
+ [...routingSignals, ...businessSignals, ...localMetaSignals].map((signal) => [
5462
+ signal.name,
5463
+ signal
5464
+ ])
5465
+ ).values()
5466
+ ).sort((left, right) => left.name.localeCompare(right.name));
5467
+ const cumulativeIntents = publicationLayer === "routing_capability" ? routingIntents : publicationLayer === "business_structural" ? Array.from(
5468
+ new Map(
5469
+ [...routingIntents, ...businessIntents, ...businessLocalMetaIntents].map(
5470
+ (intent) => [intent.name, intent]
4996
5471
  )
4997
- ),
4998
- taskToRoutineMaps: Array.from(taskToRoutineMaps.values()).sort(
4999
- (left, right) => `${left.routine_name}:${left.task_name}`.localeCompare(
5000
- `${right.routine_name}:${right.task_name}`
5472
+ ).values()
5473
+ ).sort((left, right) => left.name.localeCompare(right.name)) : Array.from(
5474
+ new Map(
5475
+ [...routingIntents, ...businessIntents, ...localMetaIntents].map((intent) => [
5476
+ intent.name,
5477
+ intent
5478
+ ])
5479
+ ).values()
5480
+ ).sort((left, right) => left.name.localeCompare(right.name));
5481
+ const cumulativeActors = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
5482
+ new Map(
5483
+ [...businessActors, ...businessLocalMetaActors].map((actor) => [
5484
+ buildActorKey(actor),
5485
+ actor
5486
+ ])
5487
+ ).values()
5488
+ ).sort(
5489
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5490
+ ) : Array.from(
5491
+ new Map(
5492
+ [...businessActors, ...localMetaActors].map((actor) => [
5493
+ buildActorKey(actor),
5494
+ actor
5495
+ ])
5496
+ ).values()
5497
+ ).sort(
5498
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5499
+ );
5500
+ const cumulativeRoutines = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
5501
+ new Map(
5502
+ [...businessRoutines, ...businessLocalMetaRoutines].map((routine) => [
5503
+ buildRoutineKey(routine),
5504
+ routine
5505
+ ])
5506
+ ).values()
5507
+ ).sort(
5508
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5509
+ ) : Array.from(
5510
+ new Map(
5511
+ [...businessRoutines, ...localMetaRoutines].map((routine) => [
5512
+ buildRoutineKey(routine),
5513
+ routine
5514
+ ])
5515
+ ).values()
5516
+ ).sort(
5517
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5518
+ );
5519
+ const cumulativeDirectionalTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessDirectionalTaskMaps : Array.from(
5520
+ new Map(
5521
+ [...businessDirectionalTaskMaps, ...localMetaDirectionalTaskMaps].map(
5522
+ (map) => [
5523
+ `${map.predecessor_service_name}|${map.predecessor_task_name}|${map.predecessor_task_version}|${map.service_name}|${map.task_name}|${map.task_version}`,
5524
+ map
5525
+ ]
5001
5526
  )
5002
- )
5527
+ ).values()
5528
+ );
5529
+ const cumulativeActorTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? Array.from(
5530
+ new Map(
5531
+ [...businessActorTaskMaps, ...localMetaActorTaskMaps].map((map) => [
5532
+ `${map.service_name}|${map.actor_name}|${map.actor_version}|${map.task_name}|${map.task_version}|${map.mode}`,
5533
+ map
5534
+ ])
5535
+ ).values()
5536
+ ) : Array.from(
5537
+ new Map(
5538
+ [...businessActorTaskMaps, ...localMetaActorTaskMaps].map((map) => [
5539
+ `${map.service_name}|${map.actor_name}|${map.actor_version}|${map.task_name}|${map.task_version}|${map.mode}`,
5540
+ map
5541
+ ])
5542
+ ).values()
5543
+ );
5544
+ const cumulativeTaskToRoutineMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToRoutineMaps : Array.from(
5545
+ new Map(
5546
+ [...businessTaskToRoutineMaps, ...localMetaTaskToRoutineMaps].map((map) => [
5547
+ `${map.service_name}|${map.task_name}|${map.task_version}|${map.routine_name}|${map.routine_version}`,
5548
+ map
5549
+ ])
5550
+ ).values()
5551
+ );
5552
+ const manifestBody = {
5553
+ serviceName,
5554
+ serviceInstanceId,
5555
+ publicationLayer,
5556
+ tasks: cumulativeTasks,
5557
+ signals: cumulativeSignals,
5558
+ intents: cumulativeIntents,
5559
+ actors: cumulativeActors,
5560
+ routines: cumulativeRoutines,
5561
+ directionalTaskMaps: cumulativeDirectionalTaskMaps,
5562
+ signalToTaskMaps: publicationLayer === "routing_capability" ? publishedSignalTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps] : [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps],
5563
+ intentToTaskMaps: publicationLayer === "routing_capability" ? publishedIntentTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps] : [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps],
5564
+ actorTaskMaps: cumulativeActorTaskMaps,
5565
+ taskToRoutineMaps: cumulativeTaskToRoutineMaps
5003
5566
  };
5004
5567
  return {
5005
5568
  ...manifestBody,
@@ -5137,7 +5700,7 @@ var SERVICE_REGISTRY_TRACE_SERVICE2 = (process.env.CADENZA_SERVICE_REGISTRY_TRAC
5137
5700
  function shouldTraceServiceRegistry(serviceName) {
5138
5701
  return SERVICE_REGISTRY_TRACE_SERVICE2.length > 0 && serviceName === SERVICE_REGISTRY_TRACE_SERVICE2;
5139
5702
  }
5140
- function buildServiceRegistryInsertQueryData(ctx, queryData) {
5703
+ function buildServiceRegistryInsertQueryData(tableName, ctx, queryData) {
5141
5704
  const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
5142
5705
  const getJoinedValue = (key) => {
5143
5706
  for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
@@ -5155,7 +5718,8 @@ function buildServiceRegistryInsertQueryData(ctx, queryData) {
5155
5718
  if (!Object.prototype.hasOwnProperty.call(queryData, "onConflict")) {
5156
5719
  delete nextQueryData.onConflict;
5157
5720
  }
5158
- const resolvedData = Object.prototype.hasOwnProperty.call(ctx, "data") || ctx.data !== void 0 ? ctx.data : getJoinedValue("data");
5721
+ const preferRegistrationData = tableName === "service" || tableName === "service_instance" || tableName === "service_instance_transport";
5722
+ const resolvedData = preferRegistrationData ? registrationData ?? (Object.prototype.hasOwnProperty.call(ctx, "data") || ctx.data !== void 0 ? ctx.data : getJoinedValue("data")) : Object.prototype.hasOwnProperty.call(ctx, "data") || ctx.data !== void 0 ? ctx.data : getJoinedValue("data");
5159
5723
  const resolvedBatch = Object.prototype.hasOwnProperty.call(ctx, "batch") || ctx.batch !== void 0 ? ctx.batch : getJoinedValue("batch");
5160
5724
  const nextData = resolvedData !== void 0 ? resolvedData && typeof resolvedData === "object" ? { ...resolvedData } : resolvedData : registrationData && typeof registrationData === "object" && !Array.isArray(registrationData) ? { ...registrationData } : registrationData;
5161
5725
  if (nextData !== void 0) {
@@ -5182,8 +5746,114 @@ function sanitizeServiceRegistryInsertExecutionContext(ctx) {
5182
5746
  delete sanitized.returnedValue;
5183
5747
  delete sanitized.queryData;
5184
5748
  delete sanitized.onConflict;
5749
+ delete sanitized.task;
5750
+ delete sanitized.routine;
5751
+ delete sanitized.httpServer;
5752
+ delete sanitized.service;
5753
+ delete sanitized.serviceInstance;
5754
+ delete sanitized.joinedContexts;
5755
+ delete sanitized.__declaredTransports;
5756
+ delete sanitized.__resolverOriginalContext;
5757
+ delete sanitized.__resolverQueryData;
5185
5758
  return sanitized;
5186
5759
  }
5760
+ function sanitizeAuthorityBootstrapDelegationContext(ctx) {
5761
+ const sanitized = stripDelegationRequestSnapshot({
5762
+ ...ctx
5763
+ });
5764
+ delete sanitized.__resolverOriginalContext;
5765
+ delete sanitized.__resolverQueryData;
5766
+ delete sanitized.joinedContexts;
5767
+ delete sanitized.httpServer;
5768
+ delete sanitized.service;
5769
+ delete sanitized.serviceInstance;
5770
+ delete sanitized.task;
5771
+ delete sanitized.routine;
5772
+ delete sanitized.__declaredTransports;
5773
+ const queryData = sanitized.queryData && typeof sanitized.queryData === "object" ? { ...sanitized.queryData } : null;
5774
+ if (queryData) {
5775
+ delete queryData.joinedContexts;
5776
+ sanitized.queryData = queryData;
5777
+ }
5778
+ return sanitized;
5779
+ }
5780
+ function cloneServiceRegistryContextValue(value) {
5781
+ if (value instanceof Date) {
5782
+ return new Date(value.getTime());
5783
+ }
5784
+ if (Array.isArray(value)) {
5785
+ return value.map(
5786
+ (entry) => cloneServiceRegistryContextValue(entry)
5787
+ );
5788
+ }
5789
+ if (value && typeof value === "object") {
5790
+ const clone = {};
5791
+ for (const [key, nestedValue] of Object.entries(value)) {
5792
+ clone[key] = cloneServiceRegistryContextValue(nestedValue);
5793
+ }
5794
+ return clone;
5795
+ }
5796
+ return value;
5797
+ }
5798
+ function buildServiceRegistryResolverOriginalContext(tableName, ctx, queryData) {
5799
+ const originalContext = {};
5800
+ for (const key of [
5801
+ "__serviceName",
5802
+ "serviceName",
5803
+ "__serviceInstanceId",
5804
+ "serviceInstanceId",
5805
+ "__registrationData",
5806
+ "__reason",
5807
+ "__syncing",
5808
+ "__syncSourceServiceName",
5809
+ "__preferredTransportProtocol",
5810
+ "__networkMode",
5811
+ "__securityProfile",
5812
+ "__loadBalance",
5813
+ "__cadenzaDBConnect",
5814
+ "__isFrontend",
5815
+ "__isDatabase",
5816
+ "__retryCount",
5817
+ "__retries",
5818
+ "__triedInstances"
5819
+ ]) {
5820
+ if (ctx[key] !== void 0) {
5821
+ originalContext[key] = cloneServiceRegistryContextValue(ctx[key]);
5822
+ }
5823
+ }
5824
+ if (queryData.data !== void 0) {
5825
+ originalContext.data = cloneServiceRegistryContextValue(queryData.data);
5826
+ }
5827
+ if (queryData.batch !== void 0) {
5828
+ originalContext.batch = cloneServiceRegistryContextValue(queryData.batch);
5829
+ }
5830
+ if (Object.prototype.hasOwnProperty.call(queryData, "onConflict")) {
5831
+ originalContext.queryData = {
5832
+ data: queryData.data !== void 0 ? cloneServiceRegistryContextValue(queryData.data) : void 0,
5833
+ batch: queryData.batch !== void 0 ? cloneServiceRegistryContextValue(queryData.batch) : void 0,
5834
+ onConflict: cloneServiceRegistryContextValue(queryData.onConflict)
5835
+ };
5836
+ } else if (queryData.data !== void 0 || queryData.batch !== void 0) {
5837
+ originalContext.queryData = {
5838
+ data: queryData.data !== void 0 ? cloneServiceRegistryContextValue(queryData.data) : void 0,
5839
+ batch: queryData.batch !== void 0 ? cloneServiceRegistryContextValue(queryData.batch) : void 0
5840
+ };
5841
+ }
5842
+ if (tableName === "service_instance") {
5843
+ for (const key of [
5844
+ "__transportData",
5845
+ "transportData",
5846
+ "__useSocket",
5847
+ "__retryCount",
5848
+ "__isFrontend"
5849
+ ]) {
5850
+ if (ctx[key] !== void 0) {
5851
+ originalContext[key] = cloneServiceRegistryContextValue(ctx[key]);
5852
+ }
5853
+ }
5854
+ }
5855
+ return originalContext;
5856
+ }
5187
5857
  function clearTransientRoutingErrorState(context) {
5188
5858
  delete context.errored;
5189
5859
  delete context.failed;
@@ -5239,7 +5909,8 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
5239
5909
  delete result.__resolverOriginalContext;
5240
5910
  delete result.__resolverQueryData;
5241
5911
  const normalizedQueryData = result.queryData && typeof result.queryData === "object" ? { ...result.queryData } : { ...queryData };
5242
- const resolvedData = result.data ?? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData;
5912
+ const preferRequestedData = tableName === "service" || tableName === "service_instance" || tableName === "service_instance_transport";
5913
+ const resolvedData = preferRequestedData ? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData ?? result.data : result.data ?? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData;
5243
5914
  if (resolvedData !== void 0 && result.data === void 0) {
5244
5915
  result.data = resolvedData;
5245
5916
  }
@@ -5269,6 +5940,7 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
5269
5940
  ).trim();
5270
5941
  if (resolvedServiceName) {
5271
5942
  result.__serviceName = resolvedServiceName;
5943
+ result.serviceName = resolvedServiceName;
5272
5944
  }
5273
5945
  }
5274
5946
  const resolvedLocalServiceInstanceId = String(
@@ -5277,6 +5949,18 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
5277
5949
  if (resolvedLocalServiceInstanceId) {
5278
5950
  result.__serviceInstanceId = resolvedLocalServiceInstanceId;
5279
5951
  }
5952
+ if (tableName === "service_instance") {
5953
+ const resolvedServiceName = String(
5954
+ ctx.__serviceName ?? resolveServiceNameFromContext(ctx) ?? resolvedData?.service_name ?? resolvedData?.serviceName ?? ""
5955
+ ).trim();
5956
+ if (resolvedServiceName) {
5957
+ result.__serviceName = resolvedServiceName;
5958
+ result.serviceName = resolvedServiceName;
5959
+ }
5960
+ if (resolvedLocalServiceInstanceId) {
5961
+ result.serviceInstanceId = resolvedLocalServiceInstanceId;
5962
+ }
5963
+ }
5280
5964
  if (tableName === "service_instance" || tableName === "service_instance_transport") {
5281
5965
  const resolvedUuid = String(
5282
5966
  result.uuid ?? resolvedData?.uuid ?? ctx.__serviceInstanceId ?? ""
@@ -5376,9 +6060,15 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5376
6060
  ctx
5377
6061
  );
5378
6062
  const nextQueryData = buildServiceRegistryInsertQueryData(
6063
+ tableName,
5379
6064
  sanitizedContext,
5380
6065
  queryData
5381
6066
  );
6067
+ const resolverOriginalContext = buildServiceRegistryResolverOriginalContext(
6068
+ tableName,
6069
+ sanitizedContext,
6070
+ nextQueryData
6071
+ );
5382
6072
  const delegationContext = ensureDelegationContextMetadata({
5383
6073
  ...sanitizedContext,
5384
6074
  data: nextQueryData.data !== void 0 ? nextQueryData.data : sanitizedContext.data,
@@ -5391,9 +6081,7 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5391
6081
  delegationContext.__metadata.__blockRemoteExecution = delegationContext.__metadata.__blockRemoteExecution ?? delegationContext.__blockRemoteExecution ?? false;
5392
6082
  const nextContext = {
5393
6083
  ...delegationContext,
5394
- __resolverOriginalContext: {
5395
- ...sanitizedContext
5396
- },
6084
+ __resolverOriginalContext: resolverOriginalContext,
5397
6085
  __resolverQueryData: nextQueryData
5398
6086
  };
5399
6087
  if (tableName === "service_instance_transport" && shouldTraceServiceRegistry(
@@ -5565,6 +6253,7 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
5565
6253
  if (bootstrapAuthorityInsertSpec) {
5566
6254
  const sanitizedContext = sanitizeServiceRegistryInsertExecutionContext(ctx);
5567
6255
  const nextQueryData = buildServiceRegistryInsertQueryData(
6256
+ tableName,
5568
6257
  sanitizedContext,
5569
6258
  queryData
5570
6259
  );
@@ -5999,6 +6688,9 @@ var ServiceRegistry = class _ServiceRegistry {
5999
6688
  ctx.deleted ?? ctx.serviceInstance?.deleted ?? ctx.data?.deleted
6000
6689
  );
6001
6690
  if (uuid10 === this.serviceInstanceId) return;
6691
+ if (serviceName === this.serviceName) {
6692
+ return false;
6693
+ }
6002
6694
  if (deleted) {
6003
6695
  const existingInstance = this.instances.get(serviceName)?.find((instance) => instance.uuid === uuid10);
6004
6696
  const indexToDelete = this.instances.get(serviceName)?.findIndex((i) => i.uuid === uuid10) ?? -1;
@@ -6085,9 +6777,6 @@ var ServiceRegistry = class _ServiceRegistry {
6085
6777
  emit2
6086
6778
  );
6087
6779
  }
6088
- if (this.serviceName === serviceName) {
6089
- return false;
6090
- }
6091
6780
  if (trackedInstance?.isFrontend) {
6092
6781
  return true;
6093
6782
  }
@@ -6141,6 +6830,9 @@ var ServiceRegistry = class _ServiceRegistry {
6141
6830
  if (!ownerInstance) {
6142
6831
  return false;
6143
6832
  }
6833
+ if (ownerInstance.serviceName === this.serviceName && ownerInstance.uuid !== this.serviceInstanceId) {
6834
+ return false;
6835
+ }
6144
6836
  if (transport.deleted) {
6145
6837
  this.clearTransportFailureState(ownerInstance.uuid, transport.uuid);
6146
6838
  const transportKey = this.buildTransportRouteKey(
@@ -8567,6 +9259,8 @@ var ServiceRegistry = class _ServiceRegistry {
8567
9259
  seenSignalMaps,
8568
9260
  (row) => `${String(row.service_name ?? row.serviceName ?? "").trim()}|${String(
8569
9261
  row.signal_name ?? row.signalName ?? ""
9262
+ ).trim()}|${String(row.task_name ?? row.taskName ?? "").trim()}|${String(
9263
+ row.task_version ?? row.taskVersion ?? 1
8570
9264
  ).trim()}`
8571
9265
  );
8572
9266
  pushUnique(
@@ -8601,6 +9295,8 @@ var ServiceRegistry = class _ServiceRegistry {
8601
9295
  seenSignalMaps,
8602
9296
  (entry) => `${String(entry.service_name ?? entry.serviceName ?? "").trim()}|${String(
8603
9297
  entry.signal_name ?? entry.signalName ?? ""
9298
+ ).trim()}|${String(entry.task_name ?? entry.taskName ?? "").trim()}|${String(
9299
+ entry.task_version ?? entry.taskVersion ?? 1
8604
9300
  ).trim()}`
8605
9301
  );
8606
9302
  continue;
@@ -8633,7 +9329,36 @@ var ServiceRegistry = class _ServiceRegistry {
8633
9329
  }
8634
9330
  }
8635
9331
  }
8636
- const latestManifestSnapshots = selectLatestServiceManifestSnapshots(manifestSnapshots);
9332
+ const activeServiceInstanceIds = new Set(
9333
+ serviceInstances.filter((row) => row.is_active === true || row.isActive === true).map((row) => String(row.uuid ?? "").trim()).filter((uuid10) => uuid10.length > 0)
9334
+ );
9335
+ const filteredServiceInstances = activeServiceInstanceIds.size > 0 ? serviceInstances.filter(
9336
+ (row) => activeServiceInstanceIds.has(String(row.uuid ?? "").trim())
9337
+ ) : serviceInstances;
9338
+ const filteredServiceInstanceTransports = activeServiceInstanceIds.size > 0 ? serviceInstanceTransports.filter(
9339
+ (row) => activeServiceInstanceIds.has(
9340
+ String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
9341
+ )
9342
+ ) : serviceInstanceTransports;
9343
+ const filteredManifestSnapshots = activeServiceInstanceIds.size > 0 ? manifestSnapshots.filter(
9344
+ (snapshot) => activeServiceInstanceIds.has(snapshot.serviceInstanceId)
9345
+ ) : manifestSnapshots;
9346
+ const activeServiceNames = new Set(
9347
+ filteredServiceInstances.map((row) => String(row.service_name ?? row.serviceName ?? "").trim()).filter((serviceName) => serviceName.length > 0)
9348
+ );
9349
+ const filteredSignalToTaskMaps = activeServiceNames.size > 0 ? signalToTaskMaps.filter(
9350
+ (row) => activeServiceNames.has(
9351
+ String(row.service_name ?? row.serviceName ?? "").trim()
9352
+ )
9353
+ ) : signalToTaskMaps;
9354
+ const filteredIntentToTaskMaps = activeServiceNames.size > 0 ? intentToTaskMaps.filter(
9355
+ (row) => activeServiceNames.has(
9356
+ String(row.service_name ?? row.serviceName ?? "").trim()
9357
+ )
9358
+ ) : intentToTaskMaps;
9359
+ const hasExplicitSignalRoutingRows = filteredSignalToTaskMaps.length > 0;
9360
+ const hasExplicitIntentRoutingRows = filteredIntentToTaskMaps.length > 0;
9361
+ const latestManifestSnapshots = selectLatestServiceManifestSnapshots(filteredManifestSnapshots);
8637
9362
  const explodedManifest = explodeServiceManifestSnapshots(
8638
9363
  latestManifestSnapshots
8639
9364
  );
@@ -8705,37 +9430,41 @@ var ServiceRegistry = class _ServiceRegistry {
8705
9430
  );
8706
9431
  pushUnique(
8707
9432
  explodedManifest.taskToRoutineMaps,
8708
- taskToRoutineMaps,
8709
- seenTaskToRoutineMaps,
8710
- (row) => `${String(row.routine_name ?? "").trim()}|${String(row.routine_version ?? 1).trim()}|${String(
8711
- row.service_name ?? ""
8712
- ).trim()}|${String(row.task_name ?? "").trim()}|${String(
8713
- row.task_version ?? 1
8714
- ).trim()}`
8715
- );
8716
- pushUnique(
8717
- explodedManifest.signalToTaskMaps,
8718
- signalToTaskMaps,
8719
- seenSignalMaps,
8720
- (row) => `${String(row.signal_name ?? "").trim()}|${String(
8721
- row.service_name ?? ""
8722
- ).trim()}|${String(row.task_name ?? "").trim()}|${String(
8723
- row.task_version ?? 1
8724
- ).trim()}`
8725
- );
8726
- pushUnique(
8727
- explodedManifest.intentToTaskMaps,
8728
- intentToTaskMaps,
8729
- seenIntentMaps,
8730
- (row) => `${String(row.intent_name ?? "").trim()}|${String(
9433
+ taskToRoutineMaps,
9434
+ seenTaskToRoutineMaps,
9435
+ (row) => `${String(row.routine_name ?? "").trim()}|${String(row.routine_version ?? 1).trim()}|${String(
8731
9436
  row.service_name ?? ""
8732
9437
  ).trim()}|${String(row.task_name ?? "").trim()}|${String(
8733
9438
  row.task_version ?? 1
8734
9439
  ).trim()}`
8735
9440
  );
9441
+ if (!hasExplicitSignalRoutingRows) {
9442
+ pushUnique(
9443
+ explodedManifest.signalToTaskMaps,
9444
+ filteredSignalToTaskMaps,
9445
+ seenSignalMaps,
9446
+ (row) => `${String(row.signal_name ?? "").trim()}|${String(
9447
+ row.service_name ?? ""
9448
+ ).trim()}|${String(row.task_name ?? "").trim()}|${String(
9449
+ row.task_version ?? 1
9450
+ ).trim()}`
9451
+ );
9452
+ }
9453
+ if (!hasExplicitIntentRoutingRows) {
9454
+ pushUnique(
9455
+ explodedManifest.intentToTaskMaps,
9456
+ filteredIntentToTaskMaps,
9457
+ seenIntentMaps,
9458
+ (row) => `${String(row.intent_name ?? "").trim()}|${String(
9459
+ row.service_name ?? ""
9460
+ ).trim()}|${String(row.task_name ?? "").trim()}|${String(
9461
+ row.task_version ?? 1
9462
+ ).trim()}`
9463
+ );
9464
+ }
8736
9465
  return {
8737
- serviceInstances,
8738
- serviceInstanceTransports,
9466
+ serviceInstances: filteredServiceInstances,
9467
+ serviceInstanceTransports: filteredServiceInstanceTransports,
8739
9468
  serviceManifests,
8740
9469
  tasks,
8741
9470
  signals,
@@ -8745,8 +9474,8 @@ var ServiceRegistry = class _ServiceRegistry {
8745
9474
  directionalTaskMaps,
8746
9475
  actorTaskMaps,
8747
9476
  taskToRoutineMaps,
8748
- signalToTaskMaps,
8749
- intentToTaskMaps
9477
+ signalToTaskMaps: filteredSignalToTaskMaps,
9478
+ intentToTaskMaps: filteredIntentToTaskMaps
8750
9479
  };
8751
9480
  }
8752
9481
  buildRemoteIntentDeputyKey(map) {
@@ -9175,10 +9904,11 @@ var ServiceRegistry = class _ServiceRegistry {
9175
9904
  const controller = typeof AbortController === "function" ? new AbortController() : null;
9176
9905
  const timeoutId = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
9177
9906
  try {
9907
+ const sanitizedContext = sanitizeAuthorityBootstrapDelegationContext(context);
9178
9908
  const requestBody = stripDelegationRequestSnapshot(
9179
9909
  ensureDelegationContextMetadata(
9180
9910
  attachDelegationRequestSnapshot({
9181
- ...context,
9911
+ ...sanitizedContext,
9182
9912
  __remoteRoutineName: remoteRoutineName,
9183
9913
  __serviceName: "CadenzaDB",
9184
9914
  __localServiceName: this.serviceName,
@@ -9192,7 +9922,7 @@ var ServiceRegistry = class _ServiceRegistry {
9192
9922
  __fetchId: target.fetchId,
9193
9923
  fetchId: target.fetchId,
9194
9924
  __metadata: {
9195
- ...context.__metadata && typeof context.__metadata === "object" ? context.__metadata : {},
9925
+ ...sanitizedContext.__metadata && typeof sanitizedContext.__metadata === "object" ? sanitizedContext.__metadata : {},
9196
9926
  __timeout: timeoutMs,
9197
9927
  __syncing: true,
9198
9928
  __authorityBootstrapChannel: true
@@ -9210,22 +9940,22 @@ var ServiceRegistry = class _ServiceRegistry {
9210
9940
  });
9211
9941
  if ("ok" in response && response.ok === false) {
9212
9942
  return {
9213
- ...context,
9943
+ ...sanitizedContext,
9214
9944
  __error: `Bootstrap authority delegation failed with HTTP ${response.status}`,
9215
9945
  errored: true
9216
9946
  };
9217
9947
  }
9218
9948
  const payload = typeof response.json === "function" ? await response.json() : response;
9219
9949
  return payload && typeof payload === "object" ? {
9220
- ...context,
9950
+ ...sanitizedContext,
9221
9951
  ...payload
9222
9952
  } : {
9223
- ...context,
9953
+ ...sanitizedContext,
9224
9954
  returnedValue: payload
9225
9955
  };
9226
9956
  } catch (error) {
9227
9957
  return {
9228
- ...context,
9958
+ ...sanitizeAuthorityBootstrapDelegationContext(context),
9229
9959
  __error: error instanceof Error ? error.message : String(error),
9230
9960
  errored: true
9231
9961
  };
@@ -9335,16 +10065,35 @@ var ServiceRegistry = class _ServiceRegistry {
9335
10065
  const authorityFullSyncResponderTask = CadenzaService.createMetaTask(
9336
10066
  BOOTSTRAP_FULL_SYNC_RESPONDER_TASK_NAME,
9337
10067
  async (ctx) => {
10068
+ const queryOptionalAuthorityRoutingRows = async (tableName) => {
10069
+ try {
10070
+ return await DatabaseController.instance.queryAuthorityTableRows(
10071
+ tableName
10072
+ );
10073
+ } catch (error) {
10074
+ const message = error instanceof Error ? error.message : String(error);
10075
+ if (message.includes(
10076
+ `Table '${tableName}' is not registered on the CadenzaDB PostgresActor`
10077
+ )) {
10078
+ return [];
10079
+ }
10080
+ throw error;
10081
+ }
10082
+ };
9338
10083
  const [
9339
10084
  serviceInstances,
9340
10085
  serviceInstanceTransports,
9341
- serviceManifests
10086
+ serviceManifests,
10087
+ signalToTaskMaps,
10088
+ intentToTaskMaps
9342
10089
  ] = await Promise.all([
9343
10090
  DatabaseController.instance.queryAuthorityTableRows("service_instance"),
9344
10091
  DatabaseController.instance.queryAuthorityTableRows(
9345
10092
  "service_instance_transport"
9346
10093
  ),
9347
- DatabaseController.instance.queryAuthorityTableRows("service_manifest")
10094
+ DatabaseController.instance.queryAuthorityTableRows("service_manifest"),
10095
+ queryOptionalAuthorityRoutingRows("signal_to_task_map"),
10096
+ queryOptionalAuthorityRoutingRows("intent_to_task_map")
9348
10097
  ]);
9349
10098
  return {
9350
10099
  ...ctx,
@@ -9352,7 +10101,9 @@ var ServiceRegistry = class _ServiceRegistry {
9352
10101
  ...this.collectBootstrapFullSyncPayload({
9353
10102
  serviceInstances,
9354
10103
  serviceInstanceTransports,
9355
- serviceManifests
10104
+ serviceManifests,
10105
+ signalToTaskMaps,
10106
+ intentToTaskMaps
9356
10107
  })
9357
10108
  };
9358
10109
  },
@@ -12312,9 +13063,9 @@ var ServiceRegistry = class _ServiceRegistry {
12312
13063
  };
12313
13064
 
12314
13065
  // src/graph/definition/SignalTransmissionTask.ts
12315
- var import_core2 = require("@cadenza.io/core");
13066
+ var import_core3 = require("@cadenza.io/core");
12316
13067
  var import_uuid4 = require("uuid");
12317
- var SignalTransmissionTask = class extends import_core2.Task {
13068
+ var SignalTransmissionTask = class extends import_core3.Task {
12318
13069
  /**
12319
13070
  * Constructs a new instance of the class and initializes it with the provided parameters.
12320
13071
  *
@@ -12441,6 +13192,41 @@ var TRACED_INQUIRY_METADATA_SIGNALS = /* @__PURE__ */ new Set([
12441
13192
  "global.meta.graph_metadata.inquiry_updated"
12442
13193
  ]);
12443
13194
  var ACTOR_SESSION_TRACE_ENABLED3 = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
13195
+ function summarizeRequestBodyForLogging(body) {
13196
+ if (typeof body !== "string") {
13197
+ return body;
13198
+ }
13199
+ const summary = {
13200
+ bodyLength: body.length
13201
+ };
13202
+ try {
13203
+ const parsed = JSON.parse(body);
13204
+ const queryData = parsed.queryData && typeof parsed.queryData === "object" ? parsed.queryData : null;
13205
+ const queryDataData = queryData?.data && typeof queryData.data === "object" ? queryData.data : null;
13206
+ const data = parsed.data && typeof parsed.data === "object" ? parsed.data : null;
13207
+ summary.rootKeys = Object.keys(parsed).slice(0, 24);
13208
+ summary.remoteRoutineName = typeof parsed.__remoteRoutineName === "string" ? parsed.__remoteRoutineName : null;
13209
+ summary.serviceName = typeof parsed.__serviceName === "string" ? parsed.__serviceName : null;
13210
+ summary.authorityBootstrapChannel = parsed.__authorityBootstrapChannel === true || parsed.__metadata?.__authorityBootstrapChannel === true;
13211
+ summary.hasData = data !== null;
13212
+ summary.dataKeys = data ? Object.keys(data).slice(0, 24) : [];
13213
+ summary.hasQueryData = queryData !== null;
13214
+ summary.queryDataKeys = queryData ? Object.keys(queryData).slice(0, 24) : [];
13215
+ summary.queryDataDataKeys = queryDataData ? Object.keys(queryDataData).slice(0, 24) : [];
13216
+ } catch {
13217
+ summary.preview = body.slice(0, 240);
13218
+ }
13219
+ return summary;
13220
+ }
13221
+ function summarizeRequestInitForLogging(requestInit) {
13222
+ if (!requestInit || typeof requestInit !== "object") {
13223
+ return requestInit;
13224
+ }
13225
+ return {
13226
+ ...requestInit,
13227
+ body: summarizeRequestBodyForLogging(requestInit.body)
13228
+ };
13229
+ }
12444
13230
  var RestController = class _RestController {
12445
13231
  /**
12446
13232
  * Constructor for initializing the REST server and related configurations.
@@ -12474,16 +13260,17 @@ var RestController = class _RestController {
12474
13260
  const parsedResponse = await this.parseFetchResponse(response);
12475
13261
  return parsedResponse.data;
12476
13262
  } catch (error) {
13263
+ const loggedRequestInit = summarizeRequestInitForLogging(requestInit);
12477
13264
  if (error?.name === "AbortError") {
12478
13265
  CadenzaService.log(
12479
13266
  "Fetch request timed out.",
12480
- { error, URL: url, requestInit },
13267
+ { error, URL: url, requestInit: loggedRequestInit },
12481
13268
  "warning"
12482
13269
  );
12483
13270
  } else {
12484
13271
  CadenzaService.log(
12485
13272
  "Fetch request error.",
12486
- { error, URL: url, requestInit },
13273
+ { error, URL: url, requestInit: loggedRequestInit },
12487
13274
  "error"
12488
13275
  );
12489
13276
  }
@@ -12629,7 +13416,7 @@ var RestController = class _RestController {
12629
13416
  return { ...ctx, __app: app };
12630
13417
  },
12631
13418
  "Sets up the Express server according to the security profile"
12632
- ).attachSignal("meta.service_registry.instance_registration_requested").then(
13419
+ ).then(
12633
13420
  CadenzaService.createMetaTask(
12634
13421
  "Define RestServer",
12635
13422
  (ctx) => {
@@ -13026,32 +13813,40 @@ var RestController = class _RestController {
13026
13813
  serviceName,
13027
13814
  URL2
13028
13815
  );
13029
- fetchDiagnostics.destroyed = false;
13030
- fetchDiagnostics.updatedAt = Date.now();
13031
13816
  if (CadenzaService.get(`Send Handshake to ${clientTaskSuffix}`)) {
13032
- console.error("Fetch client already exists", { URL: URL2, fetchId });
13033
- CadenzaService.schedule(
13034
- `meta.fetch.handshake_requested:${fetchId}`,
13035
- {
13036
- serviceInstanceId: ctx.serviceInstanceId,
13037
- serviceName,
13038
- communicationTypes: ctx.communicationTypes,
13039
- serviceTransportId: ctx.serviceTransportId,
13040
- serviceOrigin: URL2,
13041
- fetchId,
13042
- routeKey,
13043
- socketClientId: ctx.socketClientId ?? (routeKey ? buildTransportHandleKey(routeKey, "socket") : void 0),
13044
- transportProtocols: ctx.transportProtocols,
13045
- transportProtocol: "rest",
13046
- handshakeData: ctx.handshakeData
13047
- },
13048
- 0
13049
- );
13817
+ const shouldRetryHandshake = ctx.__forceHandshakeRecovery === true || fetchDiagnostics.destroyed === true || (fetchDiagnostics.connected !== true || typeof fetchDiagnostics.lastHandshakeError === "string") && fetchDiagnostics.handshakeInFlight !== true;
13818
+ if (shouldRetryHandshake) {
13819
+ fetchDiagnostics.destroyed = false;
13820
+ fetchDiagnostics.handshakeInFlight = true;
13821
+ fetchDiagnostics.updatedAt = Date.now();
13822
+ console.error("Fetch client already exists", { URL: URL2, fetchId });
13823
+ CadenzaService.debounce(
13824
+ `meta.fetch.handshake_requested:${fetchId}`,
13825
+ {
13826
+ serviceInstanceId: ctx.serviceInstanceId,
13827
+ serviceName,
13828
+ communicationTypes: ctx.communicationTypes,
13829
+ serviceTransportId: ctx.serviceTransportId,
13830
+ serviceOrigin: URL2,
13831
+ fetchId,
13832
+ routeKey,
13833
+ socketClientId: ctx.socketClientId ?? (routeKey ? buildTransportHandleKey(routeKey, "socket") : void 0),
13834
+ transportProtocols: ctx.transportProtocols,
13835
+ transportProtocol: "rest",
13836
+ handshakeData: ctx.handshakeData
13837
+ },
13838
+ 50
13839
+ );
13840
+ }
13050
13841
  return true;
13051
13842
  }
13843
+ fetchDiagnostics.destroyed = false;
13844
+ fetchDiagnostics.handshakeInFlight = false;
13845
+ fetchDiagnostics.updatedAt = Date.now();
13052
13846
  const handshakeTask = CadenzaService.createMetaTask(
13053
13847
  `Send Handshake to ${clientTaskSuffix}`,
13054
13848
  async (ctx2, emit2) => {
13849
+ fetchDiagnostics.handshakeInFlight = true;
13055
13850
  try {
13056
13851
  const response = await this.fetchDataWithTimeout(
13057
13852
  `${URL2}/handshake`,
@@ -13067,6 +13862,7 @@ var RestController = class _RestController {
13067
13862
  if (response.__status !== "success") {
13068
13863
  const error = response.__error ?? `Failed to connect to service ${serviceName} ${ctx2.serviceInstanceId}`;
13069
13864
  fetchDiagnostics.connected = false;
13865
+ fetchDiagnostics.handshakeInFlight = false;
13070
13866
  fetchDiagnostics.lastHandshakeError = error;
13071
13867
  fetchDiagnostics.updatedAt = Date.now();
13072
13868
  this.recordFetchClientError(fetchId, serviceName, URL2, error);
@@ -13086,6 +13882,7 @@ var RestController = class _RestController {
13086
13882
  ctx2.serviceInstanceId = response.__serviceInstanceId;
13087
13883
  fetchDiagnostics.connected = true;
13088
13884
  fetchDiagnostics.destroyed = false;
13885
+ fetchDiagnostics.handshakeInFlight = false;
13089
13886
  fetchDiagnostics.lastHandshakeAt = (/* @__PURE__ */ new Date()).toISOString();
13090
13887
  fetchDiagnostics.lastHandshakeError = null;
13091
13888
  fetchDiagnostics.updatedAt = Date.now();
@@ -13114,6 +13911,7 @@ var RestController = class _RestController {
13114
13911
  }
13115
13912
  } catch (e) {
13116
13913
  fetchDiagnostics.connected = false;
13914
+ fetchDiagnostics.handshakeInFlight = false;
13117
13915
  fetchDiagnostics.lastHandshakeError = this.getErrorMessage(e);
13118
13916
  fetchDiagnostics.updatedAt = Date.now();
13119
13917
  this.recordFetchClientError(fetchId, serviceName, URL2, e);
@@ -13146,8 +13944,8 @@ var RestController = class _RestController {
13146
13944
  }
13147
13945
  const routedDelegateCtx = stripTransportSelectionRoutingContext(ctx2);
13148
13946
  const delegateCtx = ensureDelegationContextMetadata(
13149
- attachDelegationRequestSnapshot(
13150
- stripDelegationRequestSnapshot(routedDelegateCtx)
13947
+ restoreDelegationRequestSnapshot(
13948
+ attachDelegationRequestSnapshot(routedDelegateCtx)
13151
13949
  )
13152
13950
  );
13153
13951
  const deputyExecId = delegateCtx.__metadata.__deputyExecId;
@@ -13207,13 +14005,11 @@ var RestController = class _RestController {
13207
14005
  fetchDiagnostics.delegationFailures++;
13208
14006
  fetchDiagnostics.updatedAt = Date.now();
13209
14007
  this.recordFetchClientError(fetchId, serviceName, URL2, e);
13210
- resultContext = {
13211
- __signalName: "meta.fetch.delegate_failed",
13212
- __error: `Error: ${e}`,
13213
- errored: true,
13214
- ...delegateCtx,
13215
- ...delegateCtx.__metadata
13216
- };
14008
+ resultContext = buildDelegationFailureContext(
14009
+ "meta.fetch.delegate_failed",
14010
+ delegateCtx,
14011
+ e
14012
+ );
13217
14013
  routeOutcome = "failure";
13218
14014
  emit2("meta.fetch.delegate_failed", resultContext);
13219
14015
  } finally {
@@ -13379,6 +14175,7 @@ var RestController = class _RestController {
13379
14175
  return false;
13380
14176
  }
13381
14177
  fetchDiagnostics.connected = false;
14178
+ fetchDiagnostics.handshakeInFlight = false;
13382
14179
  fetchDiagnostics.destroyed = true;
13383
14180
  fetchDiagnostics.updatedAt = Date.now();
13384
14181
  CadenzaService.log("Destroying fetch client", { URL: URL2, serviceName });
@@ -13418,7 +14215,15 @@ var RestController = class _RestController {
13418
14215
  const fetchId = String(
13419
14216
  ctx.fetchId ?? ctx.__fetchId ?? (routeKey ? buildTransportHandleKey(routeKey, "rest") : serviceTransportId ?? "")
13420
14217
  );
13421
- CadenzaService.schedule(`meta.fetch.handshake_requested:${fetchId}`, {
14218
+ const fetchDiagnostics = this.ensureFetchClientDiagnostics(
14219
+ fetchId,
14220
+ String(serviceName ?? ""),
14221
+ String(serviceOrigin ?? "")
14222
+ );
14223
+ if (fetchDiagnostics.handshakeInFlight !== true) {
14224
+ fetchDiagnostics.handshakeInFlight = true;
14225
+ }
14226
+ CadenzaService.debounce(`meta.fetch.handshake_requested:${fetchId}`, {
13422
14227
  serviceInstanceId,
13423
14228
  serviceName,
13424
14229
  communicationTypes,
@@ -13434,7 +14239,7 @@ var RestController = class _RestController {
13434
14239
  serviceName: CadenzaService.serviceRegistry.serviceName
13435
14240
  // JWT token...
13436
14241
  }
13437
- }, 0);
14242
+ }, 50);
13438
14243
  return true;
13439
14244
  },
13440
14245
  "Prepares handshake"
@@ -13488,6 +14293,7 @@ var RestController = class _RestController {
13488
14293
  serviceName,
13489
14294
  url,
13490
14295
  connected: false,
14296
+ handshakeInFlight: false,
13491
14297
  destroyed: false,
13492
14298
  lastHandshakeAt: null,
13493
14299
  lastHandshakeError: null,
@@ -14925,8 +15731,8 @@ var SocketController = class _SocketController {
14925
15731
  }
14926
15732
  const routedDelegateCtx = stripTransportSelectionRoutingContext(delegateCtx);
14927
15733
  const normalizedDelegateCtx = ensureDelegationContextMetadata(
14928
- attachDelegationRequestSnapshot(
14929
- stripDelegationRequestSnapshot(routedDelegateCtx)
15734
+ restoreDelegationRequestSnapshot(
15735
+ attachDelegationRequestSnapshot(routedDelegateCtx)
14930
15736
  )
14931
15737
  );
14932
15738
  delete normalizedDelegateCtx.__isSubMeta;
@@ -14999,13 +15805,11 @@ var SocketController = class _SocketController {
14999
15805
  return resolvedResultContext;
15000
15806
  } catch (error) {
15001
15807
  const message = error instanceof Error ? error.message : String(error);
15002
- const failedContext = {
15003
- __signalName: "meta.socket_client.delegate_failed",
15004
- errored: true,
15005
- __error: message,
15006
- ...normalizedDelegateCtx,
15007
- ...normalizedDelegateCtx.__metadata
15008
- };
15808
+ const failedContext = buildDelegationFailureContext(
15809
+ "meta.socket_client.delegate_failed",
15810
+ normalizedDelegateCtx,
15811
+ error
15812
+ );
15009
15813
  if (deputyExecId) {
15010
15814
  emitter(`meta.socket_client.delegated:${deputyExecId}`, {
15011
15815
  ...failedContext,
@@ -16010,14 +16814,60 @@ var RuntimeValidationController = class _RuntimeValidationController {
16010
16814
  };
16011
16815
 
16012
16816
  // src/graph/controllers/registerActorSessionPersistence.ts
16013
- var import_core3 = require("@cadenza.io/core");
16817
+ var import_core4 = require("@cadenza.io/core");
16014
16818
  var ACTOR_SESSION_STATE_PERSIST_CONCURRENCY = 20;
16819
+ var META_ACTOR_SESSION_STATE_HYDRATE_INTENT = "meta-actor-session-state-hydrate";
16015
16820
  var ACTOR_SESSION_TRACE_ENABLED4 = process.env.CADENZA_ACTOR_SESSION_TRACE === "1" || process.env.CADENZA_ACTOR_SESSION_TRACE === "true";
16821
+ function findNestedContextValue(ctx, key) {
16822
+ if (!ctx || typeof ctx !== "object") {
16823
+ return void 0;
16824
+ }
16825
+ if (Object.prototype.hasOwnProperty.call(ctx, key) || ctx[key] !== void 0) {
16826
+ return ctx[key];
16827
+ }
16828
+ const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
16829
+ for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
16830
+ const nested = joinedContexts[index];
16831
+ if (!nested || typeof nested !== "object") {
16832
+ continue;
16833
+ }
16834
+ const nestedValue = findNestedContextValue(nested, key);
16835
+ if (nestedValue !== void 0) {
16836
+ return nestedValue;
16837
+ }
16838
+ }
16839
+ return void 0;
16840
+ }
16841
+ function resolveActorSessionStateRow(ctx) {
16842
+ const singular = findNestedContextValue(ctx, "actorSessionState");
16843
+ if (singular && typeof singular === "object" && !Array.isArray(singular)) {
16844
+ return singular;
16845
+ }
16846
+ const plural = findNestedContextValue(ctx, "actorSessionStates");
16847
+ if (Array.isArray(plural)) {
16848
+ const first = plural.find(
16849
+ (entry) => entry && typeof entry === "object" && !Array.isArray(entry)
16850
+ );
16851
+ if (first) {
16852
+ return first;
16853
+ }
16854
+ }
16855
+ const rows = findNestedContextValue(ctx, "rows");
16856
+ if (Array.isArray(rows)) {
16857
+ const first = rows.find(
16858
+ (entry) => entry && typeof entry === "object" && !Array.isArray(entry)
16859
+ );
16860
+ if (first) {
16861
+ return first;
16862
+ }
16863
+ }
16864
+ return null;
16865
+ }
16016
16866
  function shouldAssumeSuccessfulActorSessionRowCount(ctx) {
16017
16867
  return ctx.__success === true && ctx.rowCount === void 0 && ctx.__status === "success" && ctx.__serviceName === "CadenzaDB" && ctx.__localTaskName === "Insert actor_session_state in CadenzaDB";
16018
16868
  }
16019
16869
  function registerActorSessionPersistenceTasks() {
16020
- if (CadenzaService.get("Persist actor session state")) {
16870
+ if (CadenzaService.get("Persist actor session state") && CadenzaService.get("Hydrate actor session state")) {
16021
16871
  return;
16022
16872
  }
16023
16873
  const localActorSessionTaskOptions = {
@@ -16034,6 +16884,14 @@ function registerActorSessionPersistenceTasks() {
16034
16884
  isSubMeta: true
16035
16885
  }
16036
16886
  );
16887
+ const actorSessionStateQueryTask = CadenzaService.getLocalCadenzaDBQueryTask("actor_session_state") ?? CadenzaService.get("dbQueryActorSessionState") ?? CadenzaService.get("Query actor_session_state in CadenzaDB") ?? CadenzaService.createCadenzaDBQueryTask(
16888
+ "actor_session_state",
16889
+ {},
16890
+ {
16891
+ concurrency: ACTOR_SESSION_STATE_PERSIST_CONCURRENCY,
16892
+ isSubMeta: true
16893
+ }
16894
+ );
16037
16895
  const validateActorSessionStatePersistenceTask = CadenzaService.createMetaTask(
16038
16896
  "Validate actor session state persistence",
16039
16897
  (ctx) => {
@@ -16067,6 +16925,103 @@ function registerActorSessionPersistenceTasks() {
16067
16925
  const insertAndValidateActorSessionStateTask = actorSessionStateInsertTask.then(
16068
16926
  validateActorSessionStatePersistenceTask
16069
16927
  );
16928
+ const validateActorSessionStateHydrationTask = CadenzaService.createMetaTask(
16929
+ "Validate actor session state hydration",
16930
+ (ctx) => {
16931
+ if (ctx.errored || ctx.failed || ctx.__success !== true) {
16932
+ throw new Error(
16933
+ String(
16934
+ ctx.__error ?? ctx.error ?? "actor_session_state hydration query failed"
16935
+ )
16936
+ );
16937
+ }
16938
+ const row = resolveActorSessionStateRow(ctx);
16939
+ if (!row) {
16940
+ return {
16941
+ __success: true,
16942
+ hydrated: false
16943
+ };
16944
+ }
16945
+ const expiresAt = typeof row.expiresAt === "string" ? row.expiresAt : typeof row.expires_at === "string" ? row.expires_at : null;
16946
+ const expiresAtMs = expiresAt ? Date.parse(expiresAt) : Number.NaN;
16947
+ if (Number.isFinite(expiresAtMs) && expiresAtMs <= Date.now()) {
16948
+ return {
16949
+ __success: true,
16950
+ hydrated: false
16951
+ };
16952
+ }
16953
+ const durableState = row.durableState ?? row.durable_state ?? null;
16954
+ const durableVersion = Number(
16955
+ row.durableVersion ?? row.durable_version ?? Number.NaN
16956
+ );
16957
+ if (typeof durableState !== "object" || durableState === null || Array.isArray(durableState)) {
16958
+ throw new Error("actor_session_state durable_state must be a non-null object");
16959
+ }
16960
+ if (!Number.isInteger(durableVersion) || durableVersion < 0) {
16961
+ throw new Error(
16962
+ "actor_session_state durable_version must be a non-negative integer"
16963
+ );
16964
+ }
16965
+ return {
16966
+ __success: true,
16967
+ hydrated: true,
16968
+ actor_name: row.actorName ?? row.actor_name,
16969
+ actor_version: row.actorVersion ?? row.actor_version,
16970
+ actor_key: row.actorKey ?? row.actor_key,
16971
+ service_name: row.serviceName ?? row.service_name,
16972
+ durable_state: durableState,
16973
+ durable_version: durableVersion
16974
+ };
16975
+ },
16976
+ "Validates and normalizes hydrated actor_session_state rows.",
16977
+ localActorSessionTaskOptions
16978
+ );
16979
+ const queryAndValidateActorSessionStateTask = actorSessionStateQueryTask.then(
16980
+ validateActorSessionStateHydrationTask
16981
+ );
16982
+ CadenzaService.createMetaTask(
16983
+ "Hydrate actor session state",
16984
+ (ctx) => {
16985
+ const actorName = typeof ctx.actor_name === "string" ? ctx.actor_name.trim() : "";
16986
+ const actorKey = typeof ctx.actor_key === "string" ? ctx.actor_key.trim() : "";
16987
+ const actorVersion = Number(ctx.actor_version ?? 1);
16988
+ const serviceName = CadenzaService.serviceRegistry.serviceName;
16989
+ if (!actorName) {
16990
+ throw new Error("actor_name is required for actor session hydration");
16991
+ }
16992
+ if (!actorKey) {
16993
+ throw new Error("actor_key is required for actor session hydration");
16994
+ }
16995
+ if (!Number.isInteger(actorVersion) || actorVersion < 1) {
16996
+ throw new Error("actor_version must be a positive integer");
16997
+ }
16998
+ if (!serviceName) {
16999
+ throw new Error("service_name is not available for actor session hydration");
17000
+ }
17001
+ return {
17002
+ ...ctx,
17003
+ actor_name: actorName,
17004
+ actor_key: actorKey,
17005
+ actor_version: actorVersion,
17006
+ service_name: serviceName,
17007
+ queryData: {
17008
+ filter: {
17009
+ actor_name: actorName,
17010
+ actor_version: actorVersion,
17011
+ actor_key: actorKey,
17012
+ service_name: serviceName,
17013
+ deleted: false
17014
+ },
17015
+ queryMode: "one",
17016
+ sort: {
17017
+ updated: "desc"
17018
+ }
17019
+ }
17020
+ };
17021
+ },
17022
+ "Builds a one-row actor_session_state lookup for lazy actor hydration.",
17023
+ localActorSessionTaskOptions
17024
+ ).then(queryAndValidateActorSessionStateTask).respondsTo(META_ACTOR_SESSION_STATE_HYDRATE_INTENT);
16070
17025
  CadenzaService.createMetaTask(
16071
17026
  "Persist actor session state",
16072
17027
  (ctx) => {
@@ -16158,11 +17113,11 @@ function registerActorSessionPersistenceTasks() {
16158
17113
  },
16159
17114
  "Validates and prepares actor_session_state payload for strict write-through persistence.",
16160
17115
  localActorSessionTaskOptions
16161
- ).then(insertAndValidateActorSessionStateTask).respondsTo(import_core3.META_ACTOR_SESSION_STATE_PERSIST_INTENT);
17116
+ ).then(insertAndValidateActorSessionStateTask).respondsTo(import_core4.META_ACTOR_SESSION_STATE_PERSIST_INTENT);
16162
17117
  }
16163
17118
 
16164
17119
  // src/graph/controllers/GraphSyncController.ts
16165
- var import_core4 = require("@cadenza.io/core");
17120
+ var import_core5 = require("@cadenza.io/core");
16166
17121
  var import_uuid7 = require("uuid");
16167
17122
  var ACTOR_TASK_METADATA2 = /* @__PURE__ */ Symbol.for("@cadenza.io/core/actor-task-meta");
16168
17123
  function getActorTaskRuntimeMetadata2(taskFunction) {
@@ -16246,7 +17201,7 @@ function buildIntentRegistryData(intent) {
16246
17201
  };
16247
17202
  }
16248
17203
  function isLocalOnlySyncIntent(intentName) {
16249
- return intentName === import_core4.META_ACTOR_SESSION_STATE_PERSIST_INTENT;
17204
+ return intentName === import_core5.META_ACTOR_SESSION_STATE_PERSIST_INTENT;
16250
17205
  }
16251
17206
  function getJoinedContextValue(ctx, key) {
16252
17207
  const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
@@ -16385,16 +17340,20 @@ function resolveSyncInsertTask(isCadenzaDBReady, tableName, queryData = {}, opti
16385
17340
  ctx,
16386
17341
  queryData
16387
17342
  );
16388
- 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) {
16389
- console.warn(
16390
- "[CADENZA_SYNC_EMPTY_INSERT]",
16391
- {
16392
- tableName,
16393
- queryData: originalQueryData,
16394
- ctx,
16395
- joinedContexts: Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : []
16396
- }
16397
- );
17343
+ const hasEmptyObjectData = originalQueryData.data && typeof originalQueryData.data === "object" && !Array.isArray(originalQueryData.data) && Object.keys(originalQueryData.data).length === 0;
17344
+ const hasMissingData = originalQueryData.data === void 0;
17345
+ if ((tableName === "task" || tableName === "signal_registry" || tableName === "directional_task_graph_map") && (hasEmptyObjectData || hasMissingData)) {
17346
+ console.warn("[CADENZA_SYNC_EMPTY_INSERT]", {
17347
+ tableName,
17348
+ hasMissingData,
17349
+ hasEmptyObjectData,
17350
+ taskName: typeof ctx.__taskName === "string" ? ctx.__taskName : void 0,
17351
+ reason: typeof ctx.__reason === "string" ? ctx.__reason : void 0,
17352
+ syncSourceServiceName: typeof ctx.__syncSourceServiceName === "string" ? ctx.__syncSourceServiceName : void 0,
17353
+ queryData: originalQueryData,
17354
+ ctx,
17355
+ joinedContexts: Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : []
17356
+ });
16398
17357
  }
16399
17358
  return buildSyncExecutionEnvelope(
16400
17359
  ctx,
@@ -16485,7 +17444,7 @@ function isBootstrapLocalOnlyActorName(actorName) {
16485
17444
  return BOOTSTRAP_LOCAL_ONLY_ACTOR_NAMES.has(actorName);
16486
17445
  }
16487
17446
  function isBootstrapLocalOnlySignal(signalName) {
16488
- 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);
17447
+ 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);
16489
17448
  }
16490
17449
  function hasNonZeroPending(summary) {
16491
17450
  return Object.values(summary).some((value) => Number(value) > 0);
@@ -16713,6 +17672,12 @@ function resolveLocalRoutineFromSyncContext(ctx) {
16713
17672
  );
16714
17673
  return routineName ? CadenzaService.getRoutine(routineName) : void 0;
16715
17674
  }
17675
+ function shouldTrackDirectionalTaskMapForBootstrap(predecessorTask, nextTask) {
17676
+ if (!predecessorTask || !nextTask) {
17677
+ return false;
17678
+ }
17679
+ return predecessorTask.isMeta !== true && predecessorTask.isSubMeta !== true && nextTask.isMeta !== true && nextTask.isSubMeta !== true;
17680
+ }
16716
17681
  function resolveSignalNameFromSyncContext(ctx) {
16717
17682
  const candidateSignalNames = [
16718
17683
  ctx.signalName,
@@ -17789,7 +18754,7 @@ var GraphSyncController = class _GraphSyncController {
17789
18754
  return;
17790
18755
  }
17791
18756
  for (const t of task.nextTasks) {
17792
- if (task.taskMapRegistration.has(t.name) || t.hidden || !t.register || !t.registered) {
18757
+ if (task.taskMapRegistration.has(t.name) || t.hidden || !t.register || !t.registered || !shouldTrackDirectionalTaskMapForBootstrap(task, t)) {
17793
18758
  continue;
17794
18759
  }
17795
18760
  const serviceName2 = resolveSyncServiceName(t);
@@ -17857,7 +18822,7 @@ var GraphSyncController = class _GraphSyncController {
17857
18822
  return false;
17858
18823
  }
17859
18824
  for (const nextTask of task.nextTasks) {
17860
- if (task.taskMapRegistration.has(nextTask.name) || nextTask.isHidden || !nextTask.register || !nextTask.registered) {
18825
+ if (task.taskMapRegistration.has(nextTask.name) || nextTask.isHidden || !nextTask.register || !nextTask.registered || !shouldTrackDirectionalTaskMapForBootstrap(task, nextTask)) {
17861
18826
  continue;
17862
18827
  }
17863
18828
  if (resolveSyncServiceName(nextTask)) {
@@ -20167,10 +21132,23 @@ function resolveInquiryFailureError(inquiry, value, depth = 3, seen = /* @__PURE
20167
21132
  }
20168
21133
  return `Inquiry '${inquiry}' did not complete successfully`;
20169
21134
  }
21135
+ function normalizePositiveInteger2(value, fallback) {
21136
+ const normalized = Number(value);
21137
+ return Number.isInteger(normalized) && normalized > 0 ? normalized : fallback;
21138
+ }
20170
21139
  var DEFAULT_DEPUTY_TASK_CONCURRENCY = 50;
20171
21140
  var DEFAULT_DEPUTY_TASK_TIMEOUT_MS = 12e4;
20172
21141
  var DEFAULT_DATABASE_PROXY_TASK_CONCURRENCY = 50;
20173
21142
  var DEFAULT_DATABASE_PROXY_TASK_TIMEOUT_MS = 12e4;
21143
+ var SERVICE_MANIFEST_PUBLICATION_ORDER = [
21144
+ "routing_capability",
21145
+ "business_structural",
21146
+ "local_meta_structural"
21147
+ ];
21148
+ function getServiceManifestPublicationLayerRank(layer) {
21149
+ const index = SERVICE_MANIFEST_PUBLICATION_ORDER.indexOf(layer);
21150
+ return index >= 0 ? index : SERVICE_MANIFEST_PUBLICATION_ORDER.length - 1;
21151
+ }
20174
21152
  var CadenzaService = class {
20175
21153
  static unregisterGracefulShutdownHandlers() {
20176
21154
  for (const cleanup of this.shutdownHandlerCleanup) {
@@ -20297,7 +21275,15 @@ var CadenzaService = class {
20297
21275
  this.replayRegisteredTaskSignalObservations();
20298
21276
  this.replayRegisteredTaskIntentAssociations();
20299
21277
  }
20300
- static requestServiceManifestPublication(reason, immediate = false) {
21278
+ static normalizeServiceManifestPublicationLayer(value, fallback = "business_structural") {
21279
+ return value === "routing_capability" || value === "business_structural" || value === "local_meta_structural" ? value : fallback;
21280
+ }
21281
+ static mergeServiceManifestPublicationRequest(reason, targetLayer) {
21282
+ this.serviceManifestPublicationPendingReason = reason;
21283
+ const currentTargetLayer = this.serviceManifestPublicationPendingLayer ?? "routing_capability";
21284
+ this.serviceManifestPublicationPendingLayer = getServiceManifestPublicationLayerRank(targetLayer) >= getServiceManifestPublicationLayerRank(currentTargetLayer) ? targetLayer : currentTargetLayer;
21285
+ }
21286
+ static requestServiceManifestPublication(reason, immediate = false, targetLayer = "business_structural") {
20301
21287
  if (!this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
20302
21288
  return;
20303
21289
  }
@@ -20305,7 +21291,8 @@ var CadenzaService = class {
20305
21291
  const payload = {
20306
21292
  __reason: reason,
20307
21293
  __serviceName: this.serviceRegistry.serviceName,
20308
- __serviceInstanceId: this.serviceRegistry.serviceInstanceId
21294
+ __serviceInstanceId: this.serviceRegistry.serviceInstanceId,
21295
+ __publicationLayer: targetLayer
20309
21296
  };
20310
21297
  if (immediate) {
20311
21298
  this.emit(signalName, payload);
@@ -20313,32 +21300,53 @@ var CadenzaService = class {
20313
21300
  }
20314
21301
  this.debounce(signalName, payload, 100);
20315
21302
  }
20316
- static scheduleServiceManifestPublicationRetry(reason) {
21303
+ static scheduleServiceManifestPublicationRetry(reason, targetLayer = "business_structural") {
20317
21304
  if (!this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
20318
21305
  return;
20319
21306
  }
20320
21307
  setTimeout(() => {
20321
- this.requestServiceManifestPublication(reason, false);
21308
+ this.requestServiceManifestPublication(reason, false, targetLayer);
20322
21309
  }, 1e3);
20323
21310
  }
20324
- static async publishServiceManifestIfNeeded(reason) {
21311
+ static async publishServiceManifestIfNeeded(reason, targetLayer = "business_structural") {
20325
21312
  if (!this.serviceRegistry.connectsToCadenzaDB || !this.serviceRegistry.serviceName || !this.serviceRegistry.serviceInstanceId) {
20326
21313
  return false;
20327
21314
  }
20328
21315
  const publishReason = typeof reason === "string" && reason.trim().length > 0 ? reason.trim() : "service_manifest_publish";
21316
+ const publishTargetLayer = this.normalizeServiceManifestPublicationLayer(
21317
+ targetLayer
21318
+ );
20329
21319
  if (this.serviceManifestPublicationInFlight) {
20330
- this.serviceManifestPublicationPendingReason = publishReason;
21320
+ this.mergeServiceManifestPublicationRequest(
21321
+ publishReason,
21322
+ publishTargetLayer
21323
+ );
20331
21324
  return false;
20332
21325
  }
20333
- const snapshot = buildServiceManifestSnapshot({
20334
- serviceName: this.serviceRegistry.serviceName,
20335
- serviceInstanceId: this.serviceRegistry.serviceInstanceId,
20336
- revision: this.serviceManifestRevision + 1,
20337
- publishedAt: (/* @__PURE__ */ new Date()).toISOString()
21326
+ const publicationPlan = SERVICE_MANIFEST_PUBLICATION_ORDER.filter(
21327
+ (layer) => getServiceManifestPublicationLayerRank(layer) <= getServiceManifestPublicationLayerRank(publishTargetLayer)
21328
+ ).map((layer) => {
21329
+ const snapshot2 = buildServiceManifestSnapshot({
21330
+ serviceName: this.serviceRegistry.serviceName,
21331
+ serviceInstanceId: this.serviceRegistry.serviceInstanceId,
21332
+ revision: this.serviceManifestRevision + 1,
21333
+ publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
21334
+ publicationLayer: layer
21335
+ });
21336
+ return {
21337
+ layer,
21338
+ snapshot: snapshot2,
21339
+ changed: this.lastPublishedServiceManifestHashes[layer] !== snapshot2.manifestHash
21340
+ };
20338
21341
  });
20339
- if (this.lastPublishedServiceManifestHash && this.lastPublishedServiceManifestHash === snapshot.manifestHash) {
21342
+ const nextPublication = publicationPlan.find((entry) => entry.changed);
21343
+ if (!nextPublication) {
20340
21344
  return false;
20341
21345
  }
21346
+ const { layer: publicationLayer, snapshot } = nextPublication;
21347
+ const hasPendingFollowupLayer = publicationPlan.some(
21348
+ (entry) => entry.changed && getServiceManifestPublicationLayerRank(entry.layer) > getServiceManifestPublicationLayerRank(publicationLayer)
21349
+ );
20342
21350
  this.serviceManifestPublicationInFlight = true;
20343
21351
  try {
20344
21352
  this.serviceRegistry.ensureBootstrapAuthorityControlPlaneForInquiry(
@@ -20346,7 +21354,10 @@ var CadenzaService = class {
20346
21354
  snapshot
20347
21355
  );
20348
21356
  if (!this.serviceRegistry.hasAuthorityBootstrapHandshakeEstablished()) {
20349
- this.scheduleServiceManifestPublicationRetry(publishReason);
21357
+ this.scheduleServiceManifestPublicationRetry(
21358
+ publishReason,
21359
+ publishTargetLayer
21360
+ );
20350
21361
  return false;
20351
21362
  }
20352
21363
  await this.inquire(AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT, snapshot, {
@@ -20354,32 +21365,48 @@ var CadenzaService = class {
20354
21365
  requireComplete: true
20355
21366
  });
20356
21367
  this.serviceManifestRevision = snapshot.revision;
20357
- this.lastPublishedServiceManifestHash = snapshot.manifestHash;
21368
+ this.lastPublishedServiceManifestHashes[publicationLayer] = snapshot.manifestHash;
21369
+ if (hasPendingFollowupLayer) {
21370
+ this.mergeServiceManifestPublicationRequest(
21371
+ publishReason,
21372
+ publishTargetLayer
21373
+ );
21374
+ }
20358
21375
  return {
20359
21376
  serviceManifest: snapshot,
20360
- published: true
21377
+ published: true,
21378
+ publicationLayer
20361
21379
  };
20362
21380
  } catch (error) {
20363
21381
  this.log("Service manifest publication failed. Scheduling retry.", {
20364
21382
  serviceName: this.serviceRegistry.serviceName,
20365
21383
  serviceInstanceId: this.serviceRegistry.serviceInstanceId,
20366
21384
  reason: publishReason,
21385
+ publicationLayer,
20367
21386
  error: resolveInquiryFailureError(
20368
21387
  AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT,
20369
21388
  error
20370
21389
  ),
20371
21390
  inquiryMeta: error && typeof error === "object" && "__inquiryMeta" in error ? error.__inquiryMeta : null
20372
21391
  });
20373
- this.scheduleServiceManifestPublicationRetry(publishReason);
21392
+ this.scheduleServiceManifestPublicationRetry(
21393
+ publishReason,
21394
+ publishTargetLayer
21395
+ );
20374
21396
  return false;
20375
21397
  } finally {
20376
21398
  this.serviceManifestPublicationInFlight = false;
20377
- if (this.serviceManifestPublicationPendingReason) {
21399
+ if (this.serviceManifestPublicationPendingReason && this.serviceManifestPublicationPendingLayer) {
20378
21400
  const pendingReason = this.serviceManifestPublicationPendingReason;
21401
+ const pendingLayer = this.serviceManifestPublicationPendingLayer;
20379
21402
  this.serviceManifestPublicationPendingReason = null;
21403
+ this.serviceManifestPublicationPendingLayer = null;
20380
21404
  this.debounce(
20381
21405
  "meta.service_manifest.publish_requested",
20382
- { __reason: pendingReason },
21406
+ {
21407
+ __reason: pendingReason,
21408
+ __publicationLayer: pendingLayer
21409
+ },
20383
21410
  100
20384
21411
  );
20385
21412
  }
@@ -20392,9 +21419,13 @@ var CadenzaService = class {
20392
21419
  this.createMetaTask(
20393
21420
  "Publish service manifest",
20394
21421
  async (ctx) => this.publishServiceManifestIfNeeded(
20395
- typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0 ? ctx.__reason.trim() : "service_manifest_publish"
21422
+ typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0 ? ctx.__reason.trim() : "service_manifest_publish",
21423
+ this.normalizeServiceManifestPublicationLayer(
21424
+ ctx.__publicationLayer,
21425
+ "business_structural"
21426
+ )
20396
21427
  ),
20397
- "Publishes a full static manifest snapshot to authority when the manifest hash changes.",
21428
+ "Publishes staged static manifest snapshots to authority when the manifest hash changes.",
20398
21429
  {
20399
21430
  register: false,
20400
21431
  isHidden: true
@@ -20404,13 +21435,18 @@ var CadenzaService = class {
20404
21435
  "Request manifest publication after structural change",
20405
21436
  (ctx) => {
20406
21437
  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";
21438
+ const targetLayer = reason === "meta.service_registry.instance_inserted" ? "business_structural" : this.normalizeServiceManifestPublicationLayer(
21439
+ ctx.__publicationLayer,
21440
+ "business_structural"
21441
+ );
20407
21442
  this.requestServiceManifestPublication(
20408
21443
  reason,
20409
- reason === "meta.service_registry.instance_inserted"
21444
+ reason === "meta.service_registry.instance_inserted",
21445
+ targetLayer
20410
21446
  );
20411
21447
  return true;
20412
21448
  },
20413
- "Requests a manifest publication when a static service primitive changes.",
21449
+ "Requests staged manifest publication when a static service primitive changes.",
20414
21450
  {
20415
21451
  register: false,
20416
21452
  isHidden: true
@@ -20453,19 +21489,19 @@ var CadenzaService = class {
20453
21489
  static bootstrap() {
20454
21490
  if (this.isBootstrapped) return;
20455
21491
  this.isBootstrapped = true;
20456
- import_core5.default.bootstrap();
20457
- import_core5.default.setRuntimeInquiryDelegate(
21492
+ import_core6.default.bootstrap();
21493
+ import_core6.default.setRuntimeInquiryDelegate(
20458
21494
  (inquiry, context, options) => this.inquire(
20459
21495
  inquiry,
20460
21496
  context,
20461
21497
  options ?? {}
20462
21498
  )
20463
21499
  );
20464
- this.signalBroker = import_core5.default.signalBroker;
20465
- this.inquiryBroker = import_core5.default.inquiryBroker;
20466
- this.runner = import_core5.default.runner;
20467
- this.metaRunner = import_core5.default.metaRunner;
20468
- this.registry = import_core5.default.registry;
21500
+ this.signalBroker = import_core6.default.signalBroker;
21501
+ this.inquiryBroker = import_core6.default.inquiryBroker;
21502
+ this.runner = import_core6.default.runner;
21503
+ this.metaRunner = import_core6.default.metaRunner;
21504
+ this.registry = import_core6.default.registry;
20469
21505
  this.serviceRegistry = ServiceRegistry.instance;
20470
21506
  RestController.instance;
20471
21507
  SocketController.instance;
@@ -20499,8 +21535,8 @@ var CadenzaService = class {
20499
21535
  return;
20500
21536
  }
20501
21537
  this.frontendSyncScheduled = true;
20502
- import_core5.default.interval("meta.sync_requested", { __syncing: false }, 18e4);
20503
- import_core5.default.schedule("meta.sync_requested", { __syncing: false }, 250);
21538
+ import_core6.default.interval("meta.sync_requested", { __syncing: false }, 18e4);
21539
+ import_core6.default.schedule("meta.sync_requested", { __syncing: false }, 250);
20504
21540
  }
20505
21541
  static normalizeDeclaredTransports(transports, serviceId, useSocket) {
20506
21542
  return (transports ?? []).map((transport) => normalizeServiceTransportConfig(transport)).filter(
@@ -20558,7 +21594,7 @@ var CadenzaService = class {
20558
21594
  * @return {void} Does not return any value.
20559
21595
  */
20560
21596
  static validateName(name) {
20561
- import_core5.default.validateName(name);
21597
+ import_core6.default.validateName(name);
20562
21598
  }
20563
21599
  /**
20564
21600
  * Gets the current run strategy from the Cadenza configuration.
@@ -20566,7 +21602,7 @@ var CadenzaService = class {
20566
21602
  * @return {Function} The run strategy function defined in the Cadenza configuration.
20567
21603
  */
20568
21604
  static get runStrategy() {
20569
- return import_core5.default.runStrategy;
21605
+ return import_core6.default.runStrategy;
20570
21606
  }
20571
21607
  /**
20572
21608
  * Sets the mode for the Cadenza application.
@@ -20575,7 +21611,7 @@ var CadenzaService = class {
20575
21611
  * @return {void} This method does not return a value.
20576
21612
  */
20577
21613
  static setMode(mode) {
20578
- import_core5.default.setMode(mode);
21614
+ import_core6.default.setMode(mode);
20579
21615
  }
20580
21616
  static hasCompletedBootstrapSync() {
20581
21617
  return !this.serviceCreated || this.bootstrapSyncCompleted;
@@ -20618,16 +21654,16 @@ var CadenzaService = class {
20618
21654
  * ```
20619
21655
  */
20620
21656
  static emit(signal, data = {}, options = {}) {
20621
- import_core5.default.emit(signal, data, options);
21657
+ import_core6.default.emit(signal, data, options);
20622
21658
  }
20623
21659
  static debounce(signal, context = {}, delayMs = 500) {
20624
- import_core5.default.debounce(signal, context, delayMs);
21660
+ import_core6.default.debounce(signal, context, delayMs);
20625
21661
  }
20626
21662
  static schedule(signal, context, timeoutMs, exactDateTime) {
20627
- import_core5.default.schedule(signal, context, timeoutMs, exactDateTime);
21663
+ import_core6.default.schedule(signal, context, timeoutMs, exactDateTime);
20628
21664
  }
20629
21665
  static interval(signal, context, intervalMs, leading = false, startDateTime) {
20630
- import_core5.default.interval(signal, context, intervalMs, leading, startDateTime);
21666
+ import_core6.default.interval(signal, context, intervalMs, leading, startDateTime);
20631
21667
  }
20632
21668
  static defineIntent(intent) {
20633
21669
  this.inquiryBroker?.addIntent(intent);
@@ -20635,35 +21671,35 @@ var CadenzaService = class {
20635
21671
  }
20636
21672
  static getRuntimeValidationPolicy() {
20637
21673
  this.bootstrap();
20638
- return import_core5.default.getRuntimeValidationPolicy();
21674
+ return import_core6.default.getRuntimeValidationPolicy();
20639
21675
  }
20640
21676
  static setRuntimeValidationPolicy(policy = {}) {
20641
21677
  this.bootstrap();
20642
- return import_core5.default.setRuntimeValidationPolicy(policy);
21678
+ return import_core6.default.setRuntimeValidationPolicy(policy);
20643
21679
  }
20644
21680
  static replaceRuntimeValidationPolicy(policy = {}) {
20645
21681
  this.bootstrap();
20646
- return import_core5.default.replaceRuntimeValidationPolicy(policy);
21682
+ return import_core6.default.replaceRuntimeValidationPolicy(policy);
20647
21683
  }
20648
21684
  static clearRuntimeValidationPolicy() {
20649
21685
  this.bootstrap();
20650
- import_core5.default.clearRuntimeValidationPolicy();
21686
+ import_core6.default.clearRuntimeValidationPolicy();
20651
21687
  }
20652
21688
  static getRuntimeValidationScopes() {
20653
21689
  this.bootstrap();
20654
- return import_core5.default.getRuntimeValidationScopes();
21690
+ return import_core6.default.getRuntimeValidationScopes();
20655
21691
  }
20656
21692
  static upsertRuntimeValidationScope(scope) {
20657
21693
  this.bootstrap();
20658
- return import_core5.default.upsertRuntimeValidationScope(scope);
21694
+ return import_core6.default.upsertRuntimeValidationScope(scope);
20659
21695
  }
20660
21696
  static removeRuntimeValidationScope(id) {
20661
21697
  this.bootstrap();
20662
- import_core5.default.removeRuntimeValidationScope(id);
21698
+ import_core6.default.removeRuntimeValidationScope(id);
20663
21699
  }
20664
21700
  static clearRuntimeValidationScopes() {
20665
21701
  this.bootstrap();
20666
- import_core5.default.clearRuntimeValidationScopes();
21702
+ import_core6.default.clearRuntimeValidationScopes();
20667
21703
  }
20668
21704
  static getInquiryResponderDescriptor(task) {
20669
21705
  return this.serviceRegistry.getInquiryResponderDescriptor(task);
@@ -21025,7 +22061,7 @@ var CadenzaService = class {
21025
22061
  });
21026
22062
  }
21027
22063
  static get(taskName) {
21028
- return import_core5.default.get(taskName);
22064
+ return import_core6.default.get(taskName);
21029
22065
  }
21030
22066
  static getLocalCadenzaDBTask(tableName, operation) {
21031
22067
  const generatedTaskName = this.buildGeneratedLocalCadenzaDBTaskName(
@@ -21036,7 +22072,7 @@ var CadenzaService = class {
21036
22072
  tableName,
21037
22073
  operation
21038
22074
  );
21039
- return import_core5.default.get(generatedTaskName) ?? import_core5.default.get(legacyTaskName);
22075
+ return import_core6.default.get(generatedTaskName) ?? import_core6.default.get(legacyTaskName);
21040
22076
  }
21041
22077
  static getLocalCadenzaDBInsertTask(tableName) {
21042
22078
  return this.getLocalCadenzaDBTask(tableName, "insert");
@@ -21045,15 +22081,15 @@ var CadenzaService = class {
21045
22081
  return this.getLocalCadenzaDBTask(tableName, "query");
21046
22082
  }
21047
22083
  static getActor(actorName) {
21048
- const cadenzaWithActors = import_core5.default;
22084
+ const cadenzaWithActors = import_core6.default;
21049
22085
  return cadenzaWithActors.getActor?.(actorName);
21050
22086
  }
21051
22087
  static getAllActors() {
21052
- const cadenzaWithActors = import_core5.default;
22088
+ const cadenzaWithActors = import_core6.default;
21053
22089
  return cadenzaWithActors.getAllActors?.() ?? [];
21054
22090
  }
21055
22091
  static getRoutine(routineName) {
21056
- return import_core5.default.getRoutine(routineName);
22092
+ return import_core6.default.getRoutine(routineName);
21057
22093
  }
21058
22094
  /**
21059
22095
  * Creates a new DeputyTask instance based on the provided routine name, service name, and options.
@@ -21665,10 +22701,28 @@ var CadenzaService = class {
21665
22701
  __isFrontend: isFrontend,
21666
22702
  __declaredTransports: declaredTransports
21667
22703
  };
22704
+ let bootstrapServiceCreationRequested = false;
21668
22705
  if (options.cadenzaDB?.connect) {
21669
- this.createEphemeralMetaTask("Create service", async (context, emit2) => {
21670
- emit2("meta.create_service_requested", initContext);
21671
- }).doOn("meta.fetch.handshake_complete");
22706
+ this.createMetaTask(
22707
+ "Create service",
22708
+ async (context, emit2) => {
22709
+ const handshakeServiceName = String(context?.serviceName ?? "").trim();
22710
+ if (handshakeServiceName !== "CadenzaDB") {
22711
+ return false;
22712
+ }
22713
+ if (bootstrapServiceCreationRequested) {
22714
+ return false;
22715
+ }
22716
+ bootstrapServiceCreationRequested = true;
22717
+ emit2("meta.create_service_requested", initContext);
22718
+ return true;
22719
+ },
22720
+ "Requests local service creation only once after the initial authority bootstrap handshake completes.",
22721
+ {
22722
+ register: false,
22723
+ isHidden: true
22724
+ }
22725
+ ).doOn("meta.fetch.handshake_complete");
21672
22726
  } else {
21673
22727
  this.emit("meta.create_service_requested", initContext);
21674
22728
  this.createMetaTask("Create signal transmission for sync", (ctx, emit2) => {
@@ -21681,10 +22735,33 @@ var CadenzaService = class {
21681
22735
  );
21682
22736
  }).doOn("meta.rest.handshake", "meta.socket.handshake");
21683
22737
  }
22738
+ let serviceSetupCompletedHandled = false;
21684
22739
  this.createMetaTask("Handle service setup completion", (ctx, emit2) => {
22740
+ if (serviceSetupCompletedHandled) {
22741
+ return false;
22742
+ }
22743
+ const insertedServiceInstanceId = String(
22744
+ ctx?.serviceInstanceId ?? ctx?.service_instance_id ?? ctx?.serviceInstance?.uuid ?? ctx?.serviceInstance?.serviceInstanceId ?? ""
22745
+ ).trim();
22746
+ const insertedServiceName = String(
22747
+ ctx?.serviceName ?? ctx?.service_name ?? ctx?.serviceInstance?.serviceName ?? ctx?.serviceInstance?.service_name ?? ""
22748
+ ).trim();
22749
+ if (!insertedServiceInstanceId && !insertedServiceName) {
22750
+ return false;
22751
+ }
22752
+ if (insertedServiceInstanceId && insertedServiceInstanceId !== serviceId) {
22753
+ return false;
22754
+ }
22755
+ if (!insertedServiceInstanceId && insertedServiceName && insertedServiceName !== serviceName) {
22756
+ return false;
22757
+ }
22758
+ serviceSetupCompletedHandled = true;
21685
22759
  if (options.cadenzaDB?.connect) {
21686
22760
  this.serviceRegistry.bootstrapFullSync(emit2, ctx, "service_setup_completed");
21687
- void this.publishServiceManifestIfNeeded("service_setup_completed");
22761
+ void this.publishServiceManifestIfNeeded(
22762
+ "service_setup_completed",
22763
+ "business_structural"
22764
+ );
21688
22765
  }
21689
22766
  if (isFrontend) {
21690
22767
  registerActorSessionPersistenceTasks();
@@ -21694,7 +22771,7 @@ var CadenzaService = class {
21694
22771
  return true;
21695
22772
  }).doOn("meta.service_registry.instance_inserted");
21696
22773
  if (!options.cadenzaDB?.connect) {
21697
- import_core5.default.schedule(
22774
+ import_core6.default.schedule(
21698
22775
  "meta.service_registry.instance_registration_requested",
21699
22776
  {
21700
22777
  data: {
@@ -21739,7 +22816,11 @@ var CadenzaService = class {
21739
22816
  );
21740
22817
  }
21741
22818
  this.serviceCreated = true;
21742
- this.requestServiceManifestPublication("service_created", true);
22819
+ this.requestServiceManifestPublication(
22820
+ "service_created",
22821
+ true,
22822
+ "routing_capability"
22823
+ );
21743
22824
  }
21744
22825
  /**
21745
22826
  * Creates a Cadenza metadata service with the specified name, description, and options.
@@ -22000,11 +23081,84 @@ var CadenzaService = class {
22000
23081
  }
22001
23082
  static createActor(spec, options = {}) {
22002
23083
  this.bootstrap();
22003
- return import_core5.default.createActor(spec, options);
23084
+ return import_core6.default.createActor(
23085
+ spec,
23086
+ this.withActorSessionHydration(
23087
+ spec,
23088
+ options
23089
+ )
23090
+ );
22004
23091
  }
22005
23092
  static createActorFromDefinition(definition, options = {}) {
22006
23093
  this.bootstrap();
22007
- return import_core5.default.createActorFromDefinition(definition, options);
23094
+ return import_core6.default.createActorFromDefinition(
23095
+ definition,
23096
+ this.withActorSessionHydration(
23097
+ {
23098
+ name: definition.name,
23099
+ description: definition.description,
23100
+ defaultKey: definition.defaultKey,
23101
+ kind: definition.kind,
23102
+ loadPolicy: definition.loadPolicy,
23103
+ writeContract: definition.writeContract,
23104
+ consistencyProfile: definition.consistencyProfile,
23105
+ retry: definition.retry,
23106
+ idempotency: definition.idempotency,
23107
+ session: definition.session,
23108
+ runtimeReadGuard: definition.runtimeReadGuard,
23109
+ key: definition.key,
23110
+ state: definition.state,
23111
+ taskBindings: definition.tasks,
23112
+ initState: definition.state?.durable?.initState ?? definition.state?.durable?.initialState
23113
+ },
23114
+ options
23115
+ )
23116
+ );
23117
+ }
23118
+ static withActorSessionHydration(spec, options) {
23119
+ if (options.hydrateDurableState || spec.session?.persistDurableState !== true) {
23120
+ return options;
23121
+ }
23122
+ const actorName = String(spec.name ?? "").trim();
23123
+ const actorVersion = 1;
23124
+ const timeoutMs = normalizePositiveInteger2(
23125
+ spec.session?.persistenceTimeoutMs,
23126
+ 5e3
23127
+ );
23128
+ return {
23129
+ ...options,
23130
+ hydrateDurableState: async (actorKey) => {
23131
+ registerActorSessionPersistenceTasks();
23132
+ const response = await import_core6.default.inquire(
23133
+ META_ACTOR_SESSION_STATE_HYDRATE_INTENT,
23134
+ {
23135
+ actor_name: actorName,
23136
+ actor_version: actorVersion,
23137
+ actor_key: actorKey
23138
+ },
23139
+ {
23140
+ timeout: timeoutMs,
23141
+ requireComplete: true,
23142
+ rejectOnTimeout: true
23143
+ }
23144
+ );
23145
+ if (!response || typeof response !== "object" || response.__success !== true) {
23146
+ throw new Error(
23147
+ resolveInquiryFailureError(
23148
+ META_ACTOR_SESSION_STATE_HYDRATE_INTENT,
23149
+ response
23150
+ )
23151
+ );
23152
+ }
23153
+ if (response.hydrated !== true) {
23154
+ return null;
23155
+ }
23156
+ return {
23157
+ durableState: response.durable_state,
23158
+ durableVersion: Number(response.durable_version)
23159
+ };
23160
+ }
23161
+ };
22008
23162
  }
22009
23163
  /**
22010
23164
  * Creates and registers a new task with the provided name, function, and optional details.
@@ -22078,7 +23232,7 @@ var CadenzaService = class {
22078
23232
  */
22079
23233
  static createTask(name, func, description, options = {}) {
22080
23234
  this.bootstrap();
22081
- return import_core5.default.createTask(name, func, description, options);
23235
+ return import_core6.default.createTask(name, func, description, options);
22082
23236
  }
22083
23237
  /**
22084
23238
  * Creates a meta task with the specified name, functionality, description, and options.
@@ -22094,7 +23248,7 @@ var CadenzaService = class {
22094
23248
  */
22095
23249
  static createMetaTask(name, func, description, options = {}) {
22096
23250
  this.bootstrap();
22097
- return import_core5.default.createMetaTask(name, func, description, options);
23251
+ return import_core6.default.createMetaTask(name, func, description, options);
22098
23252
  }
22099
23253
  /**
22100
23254
  * Creates a unique task by wrapping the provided task function with a uniqueness constraint.
@@ -22144,7 +23298,7 @@ var CadenzaService = class {
22144
23298
  */
22145
23299
  static createUniqueTask(name, func, description, options = {}) {
22146
23300
  this.bootstrap();
22147
- return import_core5.default.createUniqueTask(name, func, description, options);
23301
+ return import_core6.default.createUniqueTask(name, func, description, options);
22148
23302
  }
22149
23303
  /**
22150
23304
  * Creates a unique meta task with the specified name, function, description, and options.
@@ -22158,7 +23312,7 @@ var CadenzaService = class {
22158
23312
  */
22159
23313
  static createUniqueMetaTask(name, func, description, options = {}) {
22160
23314
  this.bootstrap();
22161
- return import_core5.default.createUniqueMetaTask(name, func, description, options);
23315
+ return import_core6.default.createUniqueMetaTask(name, func, description, options);
22162
23316
  }
22163
23317
  /**
22164
23318
  * Creates a throttled task with a concurrency limit of 1, ensuring that only one instance of the task can run at a time for a specific throttle tag.
@@ -22191,7 +23345,7 @@ var CadenzaService = class {
22191
23345
  */
22192
23346
  static createThrottledTask(name, func, throttledIdGetter = () => "default", description, options = {}) {
22193
23347
  this.bootstrap();
22194
- return import_core5.default.createThrottledTask(
23348
+ return import_core6.default.createThrottledTask(
22195
23349
  name,
22196
23350
  func,
22197
23351
  throttledIdGetter,
@@ -22212,7 +23366,7 @@ var CadenzaService = class {
22212
23366
  */
22213
23367
  static createThrottledMetaTask(name, func, throttledIdGetter = () => "default", description, options = {}) {
22214
23368
  this.bootstrap();
22215
- return import_core5.default.createThrottledMetaTask(
23369
+ return import_core6.default.createThrottledMetaTask(
22216
23370
  name,
22217
23371
  func,
22218
23372
  throttledIdGetter,
@@ -22255,7 +23409,7 @@ var CadenzaService = class {
22255
23409
  */
22256
23410
  static createDebounceTask(name, func, description, debounceTime = 1e3, options = {}) {
22257
23411
  this.bootstrap();
22258
- return import_core5.default.createDebounceTask(
23412
+ return import_core6.default.createDebounceTask(
22259
23413
  name,
22260
23414
  func,
22261
23415
  description,
@@ -22276,7 +23430,7 @@ var CadenzaService = class {
22276
23430
  */
22277
23431
  static createDebounceMetaTask(name, func, description, debounceTime = 1e3, options = {}) {
22278
23432
  this.bootstrap();
22279
- return import_core5.default.createDebounceMetaTask(
23433
+ return import_core6.default.createDebounceMetaTask(
22280
23434
  name,
22281
23435
  func,
22282
23436
  description,
@@ -22346,7 +23500,7 @@ var CadenzaService = class {
22346
23500
  */
22347
23501
  static createEphemeralTask(name, func, description, options = {}) {
22348
23502
  this.bootstrap();
22349
- return import_core5.default.createEphemeralTask(name, func, description, options);
23503
+ return import_core6.default.createEphemeralTask(name, func, description, options);
22350
23504
  }
22351
23505
  /**
22352
23506
  * Creates an ephemeral meta-task with the specified name, function, description, and options.
@@ -22360,7 +23514,7 @@ var CadenzaService = class {
22360
23514
  */
22361
23515
  static createEphemeralMetaTask(name, func, description, options = {}) {
22362
23516
  this.bootstrap();
22363
- return import_core5.default.createEphemeralMetaTask(name, func, description, options);
23517
+ return import_core6.default.createEphemeralMetaTask(name, func, description, options);
22364
23518
  }
22365
23519
  /**
22366
23520
  * Creates a new routine with the specified name, tasks, and an optional description.
@@ -22392,7 +23546,7 @@ var CadenzaService = class {
22392
23546
  */
22393
23547
  static createRoutine(name, tasks, description = "") {
22394
23548
  this.bootstrap();
22395
- return import_core5.default.createRoutine(name, tasks, description);
23549
+ return import_core6.default.createRoutine(name, tasks, description);
22396
23550
  }
22397
23551
  /**
22398
23552
  * Creates a meta routine with a given name, tasks, and optional description.
@@ -22407,10 +23561,10 @@ var CadenzaService = class {
22407
23561
  */
22408
23562
  static createMetaRoutine(name, tasks, description = "") {
22409
23563
  this.bootstrap();
22410
- return import_core5.default.createMetaRoutine(name, tasks, description);
23564
+ return import_core6.default.createMetaRoutine(name, tasks, description);
22411
23565
  }
22412
23566
  static reset() {
22413
- import_core5.default.reset();
23567
+ import_core6.default.reset();
22414
23568
  this.serviceRegistry?.reset();
22415
23569
  this.unregisterGracefulShutdownHandlers();
22416
23570
  this.isBootstrapped = false;
@@ -22422,6 +23576,11 @@ var CadenzaService = class {
22422
23576
  this.warnedInvalidMetaIntentResponderKeys = /* @__PURE__ */ new Set();
22423
23577
  this.hydratedInquiryResults = /* @__PURE__ */ new Map();
22424
23578
  this.frontendSyncScheduled = false;
23579
+ this.serviceManifestRevision = 0;
23580
+ this.lastPublishedServiceManifestHashes = {};
23581
+ this.serviceManifestPublicationInFlight = false;
23582
+ this.serviceManifestPublicationPendingReason = null;
23583
+ this.serviceManifestPublicationPendingLayer = null;
22425
23584
  resetBrowserRuntimeActorHandles();
22426
23585
  }
22427
23586
  };
@@ -22435,15 +23594,16 @@ CadenzaService.warnedInvalidMetaIntentResponderKeys = /* @__PURE__ */ new Set();
22435
23594
  CadenzaService.hydratedInquiryResults = /* @__PURE__ */ new Map();
22436
23595
  CadenzaService.frontendSyncScheduled = false;
22437
23596
  CadenzaService.serviceManifestRevision = 0;
22438
- CadenzaService.lastPublishedServiceManifestHash = null;
23597
+ CadenzaService.lastPublishedServiceManifestHashes = {};
22439
23598
  CadenzaService.serviceManifestPublicationInFlight = false;
22440
23599
  CadenzaService.serviceManifestPublicationPendingReason = null;
23600
+ CadenzaService.serviceManifestPublicationPendingLayer = null;
22441
23601
  CadenzaService.shutdownHandlersRegistered = false;
22442
23602
  CadenzaService.shutdownInFlight = false;
22443
23603
  CadenzaService.shutdownHandlerCleanup = [];
22444
23604
 
22445
23605
  // src/index.ts
22446
- var import_core6 = require("@cadenza.io/core");
23606
+ var import_core7 = require("@cadenza.io/core");
22447
23607
 
22448
23608
  // src/ssr/createSSRInquiryBridge.ts
22449
23609
  var import_uuid9 = require("uuid");
@@ -22465,6 +23625,17 @@ function normalizeArrayResponse(value, keys) {
22465
23625
  if (Array.isArray(value?.data)) {
22466
23626
  return value.data;
22467
23627
  }
23628
+ const joinedContexts = Array.isArray(value?.joinedContexts) ? value.joinedContexts : [];
23629
+ for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
23630
+ const nested = joinedContexts[index];
23631
+ if (!nested || typeof nested !== "object") {
23632
+ continue;
23633
+ }
23634
+ const rows = normalizeArrayResponse(nested, keys);
23635
+ if (rows.length > 0) {
23636
+ return rows;
23637
+ }
23638
+ }
22468
23639
  return [];
22469
23640
  }
22470
23641
  function buildQueryResponseKeys(tableName) {