@cadenza.io/service 2.18.1 → 2.18.2

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
@@ -739,6 +739,21 @@ var CADENZA_DB_GATHERED_SYNC_SIGNAL = "global.meta.cadenza_db.gathered_sync_data
739
739
  var META_GATHERED_SYNC_TRANSMISSION_RECONCILE_SIGNAL = "meta.service_registry.gathered_sync_transmission_reconcile_requested";
740
740
  var META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL = "meta.service_registry.runtime_status.heartbeat_tick";
741
741
  var META_RUNTIME_STATUS_MONITOR_TICK_SIGNAL = "meta.service_registry.runtime_status.monitor_tick";
742
+ var EARLY_FULL_SYNC_DELAYS_MS = [
743
+ 100,
744
+ 1500,
745
+ 5e3,
746
+ 12e3,
747
+ 25e3,
748
+ 45e3,
749
+ 7e4
750
+ ];
751
+ var BOOTSTRAP_FULL_SYNC_RESPONDER_TASKS = [
752
+ "Query service_instance",
753
+ "Query service_instance_transport",
754
+ "Query signal_to_task_map",
755
+ "Query intent_to_task_map"
756
+ ];
742
757
  var INTERNAL_RUNTIME_STATUS_TASK_NAMES = /* @__PURE__ */ new Set([
743
758
  "Track local routine start",
744
759
  "Track local routine end",
@@ -880,6 +895,18 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
880
895
  ctx.__resolverQueryData ?? ctx.queryData ?? {},
881
896
  ctx
882
897
  );
898
+ if (tableName === "service_instance" && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
899
+ console.log("[CADENZA_INSTANCE_DEBUG] finalize_service_registry_insert", {
900
+ tableName,
901
+ hasNormalized: !!normalized,
902
+ normalizedKeys: normalized && typeof normalized === "object" ? Object.keys(normalized) : [],
903
+ uuid: normalized && typeof normalized === "object" ? normalized.uuid ?? normalized.data?.uuid ?? normalized.queryData?.data?.uuid ?? null : null,
904
+ serviceName: normalized && typeof normalized === "object" ? normalized.__serviceName ?? normalized.data?.service_name ?? normalized.queryData?.data?.service_name ?? null : null,
905
+ errored: normalized && typeof normalized === "object" ? normalized.errored === true : false,
906
+ error: normalized && typeof normalized === "object" ? normalized.__error ?? null : null,
907
+ inquiryMeta: normalized && typeof normalized === "object" ? normalized.__inquiryMeta ?? null : null
908
+ });
909
+ }
883
910
  if (!normalized || typeof normalized !== "object") {
884
911
  return normalized;
885
912
  }
@@ -924,6 +951,18 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
924
951
  ).doOn(executionResolvedSignal, executionFailedSignal);
925
952
  const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
926
953
  const executionSignal = localInsertTask ? localExecutionRequestedSignal : remoteExecutionRequestedSignal;
954
+ if (tableName === "service_instance" && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
955
+ console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert", {
956
+ tableName,
957
+ executionSignal,
958
+ hasLocalInsertTask: !!localInsertTask,
959
+ serviceName: ctx.__serviceName ?? ctx.data?.service_name ?? null,
960
+ serviceInstanceId: ctx.__serviceInstanceId ?? ctx.data?.uuid ?? null,
961
+ hasData: !!ctx.data,
962
+ dataKeys: ctx.data && typeof ctx.data === "object" ? Object.keys(ctx.data) : [],
963
+ registrationKeys: ctx.__registrationData && typeof ctx.__registrationData === "object" ? Object.keys(ctx.__registrationData) : []
964
+ });
965
+ }
927
966
  if (localInsertTask && !wiredLocalTaskNames.has(localInsertTask.name)) {
928
967
  wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
929
968
  wiredLocalTaskNames.add(localInsertTask.name);
@@ -1006,6 +1045,7 @@ var ServiceRegistry = class _ServiceRegistry {
1006
1045
  this.useSocket = false;
1007
1046
  this.retryCount = 3;
1008
1047
  this.isFrontend = false;
1048
+ this.connectsToCadenzaDB = false;
1009
1049
  CadenzaService.defineIntent({
1010
1050
  name: META_RUNTIME_TRANSPORT_DIAGNOSTICS_INTENT,
1011
1051
  description: "Gather transport diagnostics across all services and communication clients.",
@@ -1380,7 +1420,10 @@ var ServiceRegistry = class _ServiceRegistry {
1380
1420
  return true;
1381
1421
  },
1382
1422
  "Handles registration of remote signals"
1383
- ).emits("meta.service_registry.registered_global_signals").doOn("global.meta.cadenza_db.gathered_sync_data");
1423
+ ).emits("meta.service_registry.registered_global_signals").doOn(
1424
+ "global.meta.cadenza_db.gathered_sync_data",
1425
+ "global.meta.graph_metadata.task_signal_observed"
1426
+ );
1384
1427
  this.reconcileGatheredSyncTransmissionsTask = CadenzaService.createMetaTask(
1385
1428
  "Reconcile gathered sync signal transmissions",
1386
1429
  (ctx, emit) => this.reconcileGatheredSyncTransmissions(ctx, emit),
@@ -1534,7 +1577,7 @@ var ServiceRegistry = class _ServiceRegistry {
1534
1577
  );
1535
1578
  this.handleSocketStatusUpdateTask = CadenzaService.createMetaTask(
1536
1579
  "Handle Socket Status Update",
1537
- (ctx) => {
1580
+ (ctx, emit) => {
1538
1581
  const report = this.normalizeRuntimeStatusReport(ctx);
1539
1582
  if (!report) {
1540
1583
  return false;
@@ -1577,6 +1620,13 @@ var ServiceRegistry = class _ServiceRegistry {
1577
1620
  if (!applied) {
1578
1621
  return false;
1579
1622
  }
1623
+ const updatedInstance = this.getInstance(
1624
+ report.serviceName,
1625
+ report.serviceInstanceId
1626
+ );
1627
+ if (updatedInstance && !updatedInstance.isFrontend && (this.deputies.has(report.serviceName) || this.remoteIntents.has(report.serviceName) || this.remoteSignals.has(report.serviceName))) {
1628
+ this.ensureDependeeClientForInstance(updatedInstance, emit, ctx);
1629
+ }
1580
1630
  this.registerDependee(report.serviceName, report.serviceInstanceId);
1581
1631
  this.lastHeartbeatAtByInstance.set(report.serviceInstanceId, Date.now());
1582
1632
  this.missedHeartbeatsByInstance.set(report.serviceInstanceId, 0);
@@ -1587,9 +1637,23 @@ var ServiceRegistry = class _ServiceRegistry {
1587
1637
  },
1588
1638
  "Handles status update from socket broadcast"
1589
1639
  ).doOn("meta.socket_client.status_received");
1640
+ CadenzaService.createMetaTask(
1641
+ "Request full sync after CadenzaDB fetch handshake",
1642
+ (ctx) => {
1643
+ const serviceName = typeof ctx.serviceName === "string" ? ctx.serviceName.trim() : typeof ctx.__serviceName === "string" ? ctx.__serviceName.trim() : "";
1644
+ if (serviceName !== "CadenzaDB") {
1645
+ return false;
1646
+ }
1647
+ return this.scheduleEarlyFullSyncRequests("cadenza_db_fetch_handshake");
1648
+ },
1649
+ "Schedules a few early service-registry full-sync retries after the authority fetch transport comes up."
1650
+ ).doOn("meta.fetch.handshake_complete");
1590
1651
  this.fullSyncTask = CadenzaService.createMetaTask(
1591
1652
  "Full sync",
1592
1653
  async (ctx) => {
1654
+ if (this.connectsToCadenzaDB && this.serviceName !== "CadenzaDB" && !this.hasBootstrapFullSyncDeputies()) {
1655
+ return false;
1656
+ }
1593
1657
  const inquiryResult = await CadenzaService.inquire(
1594
1658
  META_SERVICE_REGISTRY_FULL_SYNC_INTENT,
1595
1659
  {
@@ -1646,7 +1710,7 @@ var ServiceRegistry = class _ServiceRegistry {
1646
1710
  );
1647
1711
  this.handleDeputyRegistrationTask = CadenzaService.createMetaTask(
1648
1712
  "Handle Deputy Registration",
1649
- (ctx) => {
1713
+ (ctx, emit) => {
1650
1714
  const { serviceName } = ctx;
1651
1715
  if (!this.deputies.has(serviceName)) this.deputies.set(serviceName, []);
1652
1716
  this.deputies.get(serviceName).push({
@@ -1656,6 +1720,7 @@ var ServiceRegistry = class _ServiceRegistry {
1656
1720
  localTaskName: ctx.localTaskName,
1657
1721
  communicationType: ctx.communicationType
1658
1722
  });
1723
+ this.ensureDependeeClientsForService(serviceName, emit, ctx);
1659
1724
  }
1660
1725
  ).doOn("meta.deputy.created");
1661
1726
  this.getAllInstances = CadenzaService.createMetaTask(
@@ -2208,9 +2273,29 @@ var ServiceRegistry = class _ServiceRegistry {
2208
2273
  retryDelayFactor: 1.3
2209
2274
  }
2210
2275
  ).emits("meta.service_registry.service_inserted").emitsOnFail("meta.service_registry.service_insertion_failed");
2211
- this.insertServiceInstanceTask = resolveServiceRegistryInsertTask(
2276
+ const insertServiceInstanceResolverTask = resolveServiceRegistryInsertTask(
2212
2277
  "service_instance",
2213
- {},
2278
+ {
2279
+ onConflict: {
2280
+ target: ["uuid"],
2281
+ action: {
2282
+ do: "update",
2283
+ set: {
2284
+ process_pid: "excluded",
2285
+ is_primary: "excluded",
2286
+ service_name: "excluded",
2287
+ is_database: "excluded",
2288
+ is_frontend: "excluded",
2289
+ is_blocked: "excluded",
2290
+ is_non_responsive: "excluded",
2291
+ is_active: "excluded",
2292
+ last_active: "excluded",
2293
+ health: "excluded",
2294
+ deleted: "false"
2295
+ }
2296
+ }
2297
+ }
2298
+ },
2214
2299
  {
2215
2300
  inputSchema: {
2216
2301
  type: "object",
@@ -2266,7 +2351,8 @@ var ServiceRegistry = class _ServiceRegistry {
2266
2351
  retryCount: 5,
2267
2352
  retryDelay: 1e3
2268
2353
  }
2269
- ).then(
2354
+ ).emitsOnFail("meta.service_registry.instance_insertion_failed");
2355
+ this.insertServiceInstanceTask = insertServiceInstanceResolverTask.then(
2270
2356
  CadenzaService.createMetaTask(
2271
2357
  "Setup service",
2272
2358
  (ctx) => {
@@ -2283,6 +2369,21 @@ var ServiceRegistry = class _ServiceRegistry {
2283
2369
  transports: ctx.__transportData ?? ctx.transportData ?? []
2284
2370
  });
2285
2371
  if (!normalizedLocalInstance?.uuid || !normalizedLocalInstance.serviceName) {
2372
+ if (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") {
2373
+ console.log("[CADENZA_INSTANCE_DEBUG] setup_service_rejected_instance", {
2374
+ hasServiceInstance: !!serviceInstance,
2375
+ hasData: !!data,
2376
+ hasQueryDataData: !!queryData?.data,
2377
+ serviceInstanceKeys: serviceInstance && typeof serviceInstance === "object" ? Object.keys(serviceInstance) : [],
2378
+ dataKeys: data && typeof data === "object" ? Object.keys(data) : [],
2379
+ queryDataDataKeys: queryData?.data && typeof queryData.data === "object" ? Object.keys(queryData.data) : [],
2380
+ normalizedLocalInstance,
2381
+ transportCount: Array.isArray(ctx.__transportData) ? ctx.__transportData.length : Array.isArray(ctx.transportData) ? ctx.transportData.length : 0,
2382
+ errored: ctx.errored === true,
2383
+ error: ctx.__error ?? null,
2384
+ inquiryMeta: ctx.__inquiryMeta ?? null
2385
+ });
2386
+ }
2286
2387
  return false;
2287
2388
  }
2288
2389
  this.serviceInstanceId = normalizedLocalInstance.uuid;
@@ -2334,9 +2435,41 @@ var ServiceRegistry = class _ServiceRegistry {
2334
2435
  ).attachSignal("meta.service_registry.transport_registration_requested")
2335
2436
  )
2336
2437
  );
2438
+ CadenzaService.createMetaTask(
2439
+ "Retry local service instance registration after failed insert",
2440
+ (ctx) => {
2441
+ const serviceName = String(
2442
+ ctx.__serviceName ?? ctx.data?.service_name ?? this.serviceName ?? ""
2443
+ ).trim();
2444
+ if (!serviceName || serviceName !== this.serviceName) {
2445
+ return false;
2446
+ }
2447
+ CadenzaService.schedule(
2448
+ "meta.service_registry.instance_registration_requested",
2449
+ { ...ctx },
2450
+ 5e3
2451
+ );
2452
+ return true;
2453
+ },
2454
+ "Retries local service instance registration only after the previous insert attempt has failed.",
2455
+ {
2456
+ register: false,
2457
+ isHidden: true
2458
+ }
2459
+ ).doOn("meta.service_registry.instance_insertion_failed");
2337
2460
  CadenzaService.createMetaTask(
2338
2461
  "Prepare service instance registration",
2339
2462
  (ctx) => {
2463
+ if (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") {
2464
+ console.log("[CADENZA_INSTANCE_DEBUG] prepare_service_instance_registration", {
2465
+ serviceName: ctx.data?.service_name ?? ctx.__serviceName ?? this.serviceName ?? null,
2466
+ serviceInstanceId: ctx.data?.uuid ?? ctx.__serviceInstanceId ?? this.serviceInstanceId ?? null,
2467
+ hasData: !!ctx.data,
2468
+ dataKeys: ctx.data && typeof ctx.data === "object" ? Object.keys(ctx.data) : [],
2469
+ transportCount: Array.isArray(ctx.__transportData) ? ctx.__transportData.length : Array.isArray(ctx.transportData) ? ctx.transportData.length : 0,
2470
+ skipRemoteExecution: ctx.__skipRemoteExecution === true
2471
+ });
2472
+ }
2340
2473
  const serviceName = String(
2341
2474
  ctx.data?.service_name ?? ctx.__serviceName ?? this.serviceName ?? ""
2342
2475
  ).trim();
@@ -2529,21 +2662,40 @@ var ServiceRegistry = class _ServiceRegistry {
2529
2662
  return [];
2530
2663
  }
2531
2664
  normalizeSignalMaps(ctx) {
2532
- return this.readArrayPayload(ctx, [
2665
+ const arrayPayload = this.readArrayPayload(ctx, [
2533
2666
  "signalToTaskMaps",
2534
2667
  "signal_to_task_maps",
2535
2668
  "signalToTaskMap",
2536
2669
  "signal_to_task_map"
2537
- ]).map((map) => ({
2538
- signalName: String(
2539
- map.signalName ?? map.signal_name ?? ""
2540
- ).trim(),
2541
- serviceName: String(
2542
- map.serviceName ?? map.service_name ?? ""
2543
- ).trim(),
2544
- isGlobal: Boolean(map.isGlobal ?? map.is_global ?? false),
2545
- deleted: Boolean(map.deleted)
2546
- })).filter((map) => map.signalName && map.serviceName);
2670
+ ]);
2671
+ if (arrayPayload.length > 0) {
2672
+ return arrayPayload.map((map) => ({
2673
+ signalName: String(
2674
+ map.signalName ?? map.signal_name ?? ""
2675
+ ).trim(),
2676
+ serviceName: String(
2677
+ map.serviceName ?? map.service_name ?? ""
2678
+ ).trim(),
2679
+ isGlobal: Boolean(map.isGlobal ?? map.is_global ?? false),
2680
+ deleted: Boolean(map.deleted)
2681
+ })).filter((map) => map.signalName && map.serviceName);
2682
+ }
2683
+ const single = ctx.signalToTaskMap ?? ctx.signal_to_task_map ?? ctx.data ?? (ctx.signalName ?? ctx.signal_name ? ctx : void 0);
2684
+ if (!single || typeof single !== "object") {
2685
+ return [];
2686
+ }
2687
+ return [
2688
+ {
2689
+ signalName: String(
2690
+ single.signalName ?? single.signal_name ?? ""
2691
+ ).trim(),
2692
+ serviceName: String(
2693
+ single.serviceName ?? single.service_name ?? ""
2694
+ ).trim(),
2695
+ isGlobal: Boolean(single.isGlobal ?? single.is_global ?? false),
2696
+ deleted: Boolean(single.deleted)
2697
+ }
2698
+ ].filter((map) => map.signalName && map.serviceName);
2547
2699
  }
2548
2700
  normalizeIntentMaps(ctx) {
2549
2701
  const arrayPayload = this.readArrayPayload(ctx, [
@@ -2658,7 +2810,7 @@ var ServiceRegistry = class _ServiceRegistry {
2658
2810
  )?.destroy();
2659
2811
  this.gatheredSyncTransmissionServices.delete(serviceName);
2660
2812
  }
2661
- if (createdRecipients.length > 0 && ctx.__signalName === CADENZA_DB_GATHERED_SYNC_SIGNAL) {
2813
+ if (createdRecipients.length > 0) {
2662
2814
  emit("meta.cadenza_db.sync_tick", {
2663
2815
  __syncing: true,
2664
2816
  __reason: "gathered_sync_transmissions_reconciled"
@@ -2733,6 +2885,56 @@ var ServiceRegistry = class _ServiceRegistry {
2733
2885
  }
2734
2886
  }
2735
2887
  }
2888
+ registerBootstrapFullSyncDeputies(emit, ctx) {
2889
+ if (!this.serviceName || this.serviceName === "CadenzaDB") {
2890
+ return false;
2891
+ }
2892
+ CadenzaService.inquiryBroker.addIntent({
2893
+ name: META_SERVICE_REGISTRY_FULL_SYNC_INTENT
2894
+ });
2895
+ for (const taskName of BOOTSTRAP_FULL_SYNC_RESPONDER_TASKS) {
2896
+ this.registerRemoteIntentDeputy({
2897
+ intentName: META_SERVICE_REGISTRY_FULL_SYNC_INTENT,
2898
+ serviceName: "CadenzaDB",
2899
+ taskName,
2900
+ taskVersion: 1
2901
+ });
2902
+ }
2903
+ this.ensureDependeeClientsForService("CadenzaDB", emit, ctx);
2904
+ return true;
2905
+ }
2906
+ hasBootstrapFullSyncDeputies() {
2907
+ if (!this.serviceName || this.serviceName === "CadenzaDB") {
2908
+ return true;
2909
+ }
2910
+ return BOOTSTRAP_FULL_SYNC_RESPONDER_TASKS.every(
2911
+ (taskName) => this.remoteIntentDeputiesByKey.has(
2912
+ this.buildRemoteIntentDeputyKey({
2913
+ intentName: META_SERVICE_REGISTRY_FULL_SYNC_INTENT,
2914
+ serviceName: "CadenzaDB",
2915
+ taskName,
2916
+ taskVersion: 1
2917
+ })
2918
+ )
2919
+ );
2920
+ }
2921
+ scheduleEarlyFullSyncRequests(reason) {
2922
+ for (const delayMs of EARLY_FULL_SYNC_DELAYS_MS) {
2923
+ CadenzaService.schedule(
2924
+ "meta.sync_requested",
2925
+ {
2926
+ __syncing: false,
2927
+ __reason: reason
2928
+ },
2929
+ delayMs
2930
+ );
2931
+ }
2932
+ return true;
2933
+ }
2934
+ bootstrapFullSync(emit, ctx, reason = "local_instance_inserted") {
2935
+ this.registerBootstrapFullSyncDeputies(emit, ctx);
2936
+ return this.scheduleEarlyFullSyncRequests(reason);
2937
+ }
2736
2938
  getInquiryResponderDescriptor(task) {
2737
2939
  const remote = this.remoteIntentDeputiesByTask.get(task);
2738
2940
  if (remote) {
@@ -2761,6 +2963,9 @@ var ServiceRegistry = class _ServiceRegistry {
2761
2963
  }
2762
2964
  return this.getInstance(this.serviceName, this.serviceInstanceId);
2763
2965
  }
2966
+ hasLocalInstanceRegistered() {
2967
+ return Boolean(this.getLocalInstance());
2968
+ }
2764
2969
  summarizeTransportForDebug(transport) {
2765
2970
  if (!transport) {
2766
2971
  return void 0;
@@ -3758,6 +3963,7 @@ var import_node_fs = __toESM(require("fs"));
3758
3963
  var import_node_https = __toESM(require("https"));
3759
3964
  var import_node_fetch = __toESM(require("node-fetch"));
3760
3965
  var import_uuid5 = require("uuid");
3966
+ var FETCH_HANDSHAKE_TIMEOUT_MS = 5e3;
3761
3967
  var RestController = class _RestController {
3762
3968
  /**
3763
3969
  * Constructor for initializing the REST server and related configurations.
@@ -3849,7 +4055,15 @@ var RestController = class _RestController {
3849
4055
  is_blocked: false,
3850
4056
  health: {}
3851
4057
  },
3852
- __transportData: []
4058
+ __transportData: Array.isArray(ctx.__declaredTransports) ? ctx.__declaredTransports.map((transport) => ({
4059
+ uuid: transport.uuid,
4060
+ service_instance_id: ctx.__serviceInstanceId,
4061
+ role: transport.role,
4062
+ origin: transport.origin,
4063
+ protocols: transport.protocols ?? ["rest", "socket"],
4064
+ ...transport.securityProfile ? { security_profile: transport.securityProfile } : {},
4065
+ ...transport.authStrategy ? { auth_strategy: transport.authStrategy } : {}
4066
+ })) : []
3853
4067
  });
3854
4068
  return;
3855
4069
  }
@@ -4181,6 +4395,19 @@ var RestController = class _RestController {
4181
4395
  ...ctx.data
4182
4396
  };
4183
4397
  ctx.__transportData = transportData;
4398
+ if (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") {
4399
+ console.log("[CADENZA_INSTANCE_DEBUG] configure_network_emit", {
4400
+ serviceName: ctx.__serviceName,
4401
+ serviceInstanceId: ctx.__serviceInstanceId,
4402
+ isDatabase: ctx.__isDatabase === true,
4403
+ transportCount: transportData.length,
4404
+ transports: transportData.map((transport) => ({
4405
+ role: transport.role,
4406
+ origin: transport.origin,
4407
+ protocols: transport.protocols
4408
+ }))
4409
+ });
4410
+ }
4184
4411
  delete ctx.__app;
4185
4412
  CadenzaService.emit(
4186
4413
  "meta.service_registry.instance_registration_requested",
@@ -4241,6 +4468,7 @@ var RestController = class _RestController {
4241
4468
  if (!serviceName || !URL2 || !fetchId) {
4242
4469
  return false;
4243
4470
  }
4471
+ const clientTaskSuffix = `${URL2} (${fetchId})`;
4244
4472
  const fetchDiagnostics = this.ensureFetchClientDiagnostics(
4245
4473
  fetchId,
4246
4474
  serviceName,
@@ -4248,12 +4476,12 @@ var RestController = class _RestController {
4248
4476
  );
4249
4477
  fetchDiagnostics.destroyed = false;
4250
4478
  fetchDiagnostics.updatedAt = Date.now();
4251
- if (CadenzaService.get(`Send Handshake to ${URL2}`)) {
4252
- console.error("Fetch client already exists", URL2);
4479
+ if (CadenzaService.get(`Send Handshake to ${clientTaskSuffix}`)) {
4480
+ console.error("Fetch client already exists", { URL: URL2, fetchId });
4253
4481
  return;
4254
4482
  }
4255
4483
  const handshakeTask = CadenzaService.createMetaTask(
4256
- `Send Handshake to ${URL2}`,
4484
+ `Send Handshake to ${clientTaskSuffix}`,
4257
4485
  async (ctx2, emit) => {
4258
4486
  try {
4259
4487
  const response = await this.fetchDataWithTimeout(
@@ -4265,7 +4493,7 @@ var RestController = class _RestController {
4265
4493
  method: "POST",
4266
4494
  body: JSON.stringify(ctx2.handshakeData)
4267
4495
  },
4268
- 1e3
4496
+ FETCH_HANDSHAKE_TIMEOUT_MS
4269
4497
  );
4270
4498
  if (response.__status !== "success") {
4271
4499
  const error = response.__error ?? `Failed to connect to service ${serviceName} ${ctx2.serviceInstanceId}`;
@@ -4322,7 +4550,7 @@ var RestController = class _RestController {
4322
4550
  "global.meta.fetch.service_communication_established"
4323
4551
  );
4324
4552
  const delegateTask = CadenzaService.createMetaTask(
4325
- `Delegate flow to REST server ${URL2}`,
4553
+ `Delegate flow to REST server ${clientTaskSuffix}`,
4326
4554
  async (ctx2, emit) => {
4327
4555
  if (ctx2.__remoteRoutineName === void 0) {
4328
4556
  return;
@@ -4376,7 +4604,7 @@ var RestController = class _RestController {
4376
4604
  `meta.service_registry.socket_failed:${fetchId}`
4377
4605
  ).emitsOnFail("meta.fetch.delegate_failed").attachSignal("meta.fetch.delegated");
4378
4606
  const transmitTask = CadenzaService.createMetaTask(
4379
- `Transmit signal to server ${URL2}`,
4607
+ `Transmit signal to server ${clientTaskSuffix}`,
4380
4608
  async (ctx2, emit) => {
4381
4609
  if (ctx2.__signalName === void 0) {
4382
4610
  return;
@@ -4429,7 +4657,7 @@ var RestController = class _RestController {
4429
4657
  "meta.signal_controller.wildcard_signal_registered"
4430
4658
  ).emitsOnFail("meta.fetch.signal_transmission_failed").attachSignal("meta.fetch.transmitted");
4431
4659
  const statusTask = CadenzaService.createMetaTask(
4432
- `Request status from ${URL2}`,
4660
+ `Request status from ${clientTaskSuffix}`,
4433
4661
  async (ctx2) => {
4434
4662
  fetchDiagnostics.statusChecks++;
4435
4663
  fetchDiagnostics.updatedAt = Date.now();
@@ -4466,7 +4694,7 @@ var RestController = class _RestController {
4466
4694
  },
4467
4695
  "Requests status"
4468
4696
  ).doOn("meta.fetch.status_check_requested").emits("meta.fetch.status_checked").emitsOnFail("meta.fetch.status_check_failed");
4469
- CadenzaService.createEphemeralMetaTask("Destroy fetch client", () => {
4697
+ CadenzaService.createEphemeralMetaTask(`Destroy fetch client ${fetchId}`, () => {
4470
4698
  fetchDiagnostics.connected = false;
4471
4699
  fetchDiagnostics.destroyed = true;
4472
4700
  fetchDiagnostics.updatedAt = Date.now();
@@ -6784,6 +7012,12 @@ var GraphMetadataController = class _GraphMetadataController {
6784
7012
  }
6785
7013
  );
6786
7014
  }).doOn("meta.task.attached_signal").emits("global.meta.graph_metadata.task_attached_signal");
7015
+ CadenzaService.createMetaTask("Handle task intent association", (ctx) => {
7016
+ return buildDatabaseTriggerContext({
7017
+ ...ctx.data,
7018
+ serviceName: CadenzaService.serviceRegistry.serviceName
7019
+ });
7020
+ }).doOn("meta.task.intent_associated").emits("global.meta.graph_metadata.task_intent_associated");
6787
7021
  CadenzaService.createMetaTask("Handle task unsubscribing signal", (ctx) => {
6788
7022
  return buildDatabaseTriggerContext(
6789
7023
  {
@@ -7001,6 +7235,7 @@ var AUTHORITY_SYNC_DEBUG_TASK_NAMES = /* @__PURE__ */ new Set([
7001
7235
  "Prepare for signal sync"
7002
7236
  ]);
7003
7237
  var AUTHORITY_SYNC_DEBUG_ROUTINE_NAMES = /* @__PURE__ */ new Set(["Sync services"]);
7238
+ var INTENT_MAP_DEBUG_ENABLED = process.env.CADENZA_INTENT_MAP_DEBUG === "1" || process.env.CADENZA_INTENT_MAP_DEBUG === "true";
7004
7239
  function logAuthoritySyncDebug(event, payload) {
7005
7240
  if (!AUTHORITY_SYNC_DEBUG_ENABLED) {
7006
7241
  return;
@@ -7040,6 +7275,12 @@ function shouldDebugAuthoritySyncPayload(tableName, payload) {
7040
7275
  }
7041
7276
  return false;
7042
7277
  }
7278
+ function logIntentMapSetupDebug(event, payload) {
7279
+ if (!INTENT_MAP_DEBUG_ENABLED) {
7280
+ return;
7281
+ }
7282
+ console.log("[CADENZA_INTENT_MAP_DEBUG]", event, payload);
7283
+ }
7043
7284
  function buildAuthoritySyncDebugSummary(payload, context) {
7044
7285
  const data = payload.data && typeof payload.data === "object" && !Array.isArray(payload.data) ? payload.data : {};
7045
7286
  return {
@@ -7524,6 +7765,18 @@ var DatabaseController = class _DatabaseController {
7524
7765
  if (!registration.tasksGenerated) {
7525
7766
  this.generateDatabaseTasks(registration);
7526
7767
  registration.tasksGenerated = true;
7768
+ const localTasks = Array.from(CadenzaService.registry.tasks.values());
7769
+ logIntentMapSetupDebug("generated_database_tasks", {
7770
+ actorName: registration.actorName,
7771
+ ownerServiceName: registration.ownerServiceName,
7772
+ totalLocalTasks: localTasks.length,
7773
+ generatedTaskNames: localTasks.map((task) => task.name).filter(
7774
+ (taskName) => /(Query|Insert|Update|Delete|COUNT|EXISTS|ONE|AGGREGATE|UPSERT) /.test(
7775
+ taskName
7776
+ )
7777
+ ).slice(0, 24)
7778
+ });
7779
+ CadenzaService.schedule("meta.sync_requested", { __syncing: true }, 250);
7527
7780
  }
7528
7781
  const nowIso = (/* @__PURE__ */ new Date()).toISOString();
7529
7782
  setRuntimeState({
@@ -9246,34 +9499,7 @@ function buildSyncInsertQueryData(ctx, queryData = {}) {
9246
9499
  }
9247
9500
  return nextQueryData;
9248
9501
  }
9249
- function buildSyncQueryQueryData(ctx, queryData = {}) {
9250
- const joinedQueryData = getJoinedContextValue(ctx, "queryData");
9251
- const existingQueryData = ctx.queryData && typeof ctx.queryData === "object" ? ctx.queryData : joinedQueryData && typeof joinedQueryData === "object" ? joinedQueryData : {};
9252
- const nextQueryData = {};
9253
- const allowedKeys = [
9254
- "transaction",
9255
- "filter",
9256
- "fields",
9257
- "joins",
9258
- "sort",
9259
- "limit",
9260
- "offset",
9261
- "queryMode",
9262
- "aggregates",
9263
- "groupBy"
9264
- ];
9265
- for (const key of allowedKeys) {
9266
- if (Object.prototype.hasOwnProperty.call(existingQueryData, key)) {
9267
- nextQueryData[key] = existingQueryData[key];
9268
- }
9269
- }
9270
- return {
9271
- ...nextQueryData,
9272
- ...queryData
9273
- };
9274
- }
9275
9502
  var REMOTE_AUTHORITY_SYNC_INSERT_CONCURRENCY = 5;
9276
- var REMOTE_AUTHORITY_SYNC_QUERY_CONCURRENCY = 3;
9277
9503
  function wireSyncTaskGraph(predecessorTask, graph, ...completionTasks) {
9278
9504
  if (!graph) {
9279
9505
  return void 0;
@@ -9286,11 +9512,27 @@ function wireSyncTaskGraph(predecessorTask, graph, ...completionTasks) {
9286
9512
  }
9287
9513
  function buildSyncExecutionEnvelope(ctx, queryData) {
9288
9514
  const originalContext = { ...ctx };
9515
+ const syncSourceServiceName = typeof ctx.__syncSourceServiceName === "string" && ctx.__syncSourceServiceName.trim().length > 0 ? ctx.__syncSourceServiceName : typeof ctx.__serviceName === "string" && ctx.__serviceName.trim().length > 0 ? ctx.__serviceName : resolveSyncServiceName();
9516
+ const rootDbOperationFields = {};
9517
+ for (const key of [
9518
+ "data",
9519
+ "batch",
9520
+ "transaction",
9521
+ "onConflict",
9522
+ "filter",
9523
+ "fields"
9524
+ ]) {
9525
+ if (Object.prototype.hasOwnProperty.call(queryData, key)) {
9526
+ rootDbOperationFields[key] = queryData[key];
9527
+ }
9528
+ }
9289
9529
  const nextContext = {
9290
9530
  __syncing: ctx.__syncing === true || ctx.__metadata?.__syncing === true || false,
9531
+ __syncSourceServiceName: syncSourceServiceName,
9291
9532
  __preferredTransportProtocol: "rest",
9292
9533
  __resolverOriginalContext: originalContext,
9293
9534
  __resolverQueryData: queryData,
9535
+ ...rootDbOperationFields,
9294
9536
  queryData
9295
9537
  };
9296
9538
  if (typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0) {
@@ -9298,9 +9540,26 @@ function buildSyncExecutionEnvelope(ctx, queryData) {
9298
9540
  }
9299
9541
  return nextContext;
9300
9542
  }
9543
+ function markCompletedSyncCycle(completedCycles, cycleId, limit = 32) {
9544
+ if (!cycleId) {
9545
+ return false;
9546
+ }
9547
+ if (completedCycles.has(cycleId)) {
9548
+ return false;
9549
+ }
9550
+ completedCycles.add(cycleId);
9551
+ while (completedCycles.size > limit) {
9552
+ const oldestCycleId = completedCycles.values().next().value;
9553
+ if (!oldestCycleId) {
9554
+ break;
9555
+ }
9556
+ completedCycles.delete(oldestCycleId);
9557
+ }
9558
+ return true;
9559
+ }
9301
9560
  function resolveSyncInsertTask(isCadenzaDBReady, tableName, queryData = {}, options = {}) {
9302
9561
  const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
9303
- if (!localInsertTask && !isCadenzaDBReady) {
9562
+ if (isCadenzaDBReady && !localInsertTask) {
9304
9563
  return void 0;
9305
9564
  }
9306
9565
  const targetTask = localInsertTask ?? CadenzaService.createCadenzaDBInsertTask(tableName, queryData, {
@@ -9351,6 +9610,11 @@ function resolveSyncInsertTask(isCadenzaDBReady, tableName, queryData = {}, opti
9351
9610
  ...ctx,
9352
9611
  queryData: ctx.queryData && typeof ctx.queryData === "object" ? ctx.queryData : originalQueryData
9353
9612
  };
9613
+ if (originalContext.__syncing === true && !didSyncInsertSucceed(normalizedContext)) {
9614
+ CadenzaService.debounce("meta.sync_requested", {
9615
+ delayMs: 1e3
9616
+ });
9617
+ }
9354
9618
  return normalizedContext;
9355
9619
  },
9356
9620
  `Finalizes ${tableName} graph-sync insert execution after the authority task finishes.`,
@@ -9378,63 +9642,16 @@ var CADENZA_DB_REQUIRED_LOCAL_SYNC_INSERT_TABLES = [
9378
9642
  "intent_to_task_map",
9379
9643
  "directional_task_graph_map"
9380
9644
  ];
9381
- var AUTHORITY_QUERY_RESULT_KEYS = {
9382
- task: "tasks",
9383
- routine: "routines",
9384
- signal_registry: "signalRegistrys",
9385
- intent_registry: "intentRegistrys"
9386
- };
9387
- var EARLY_SYNC_REQUEST_DELAYS_MS = [2e3, 1e4, 3e4];
9388
- function resolveSyncQueryRows(ctx, tableName) {
9389
- const resultKey = AUTHORITY_QUERY_RESULT_KEYS[tableName];
9390
- const rows = ctx?.[resultKey];
9391
- return Array.isArray(rows) ? rows : [];
9392
- }
9393
- function resolveSyncQueryTask(isCadenzaDBReady, tableName, queryData = {}, options = {}) {
9394
- const localQueryTask = CadenzaService.getLocalCadenzaDBQueryTask(tableName);
9395
- if (!localQueryTask && !isCadenzaDBReady) {
9396
- return void 0;
9397
- }
9398
- const targetTask = localQueryTask ?? CadenzaService.createCadenzaDBQueryTask(tableName, queryData, {
9399
- ...options,
9400
- concurrency: Number(options.concurrency) > 0 ? Math.min(
9401
- Number(options.concurrency),
9402
- REMOTE_AUTHORITY_SYNC_QUERY_CONCURRENCY
9403
- ) : REMOTE_AUTHORITY_SYNC_QUERY_CONCURRENCY,
9404
- register: false,
9405
- isHidden: true
9406
- });
9407
- const prepareQueryTask = CadenzaService.createMetaTask(
9408
- `Prepare graph sync query for ${tableName}`,
9409
- (ctx) => buildSyncExecutionEnvelope(
9410
- ctx,
9411
- buildSyncQueryQueryData(ctx, queryData)
9412
- ),
9413
- `Prepares ${tableName} graph-sync query payloads.`,
9414
- {
9415
- register: false,
9416
- isHidden: true
9417
- }
9418
- );
9419
- const finalizeQueryTask = CadenzaService.createMetaTask(
9420
- `Finalize graph sync query for ${tableName}`,
9421
- (ctx) => ctx,
9422
- `Finalizes ${tableName} graph-sync query payloads after authority lookup.`,
9423
- {
9424
- register: false,
9425
- isHidden: true
9426
- }
9427
- );
9428
- prepareQueryTask.then(targetTask);
9429
- targetTask.then(finalizeQueryTask);
9430
- return {
9431
- entryTask: prepareQueryTask,
9432
- completionTask: finalizeQueryTask
9433
- };
9434
- }
9645
+ var BOOTSTRAP_SYNC_STALE_CYCLE_MS = 15e3;
9646
+ var EARLY_SYNC_TICK_DELAYS_MS = [
9647
+ 400,
9648
+ BOOTSTRAP_SYNC_STALE_CYCLE_MS + 1e3,
9649
+ BOOTSTRAP_SYNC_STALE_CYCLE_MS * 2 + 2e3,
9650
+ BOOTSTRAP_SYNC_STALE_CYCLE_MS * 3 + 3e3
9651
+ ];
9435
9652
  function getRegistrableTasks() {
9436
9653
  return Array.from(CadenzaService.registry.tasks.values()).filter(
9437
- (task) => task.register && !task.isHidden
9654
+ (task) => task.register && !task.isHidden && !task.isDeputy
9438
9655
  );
9439
9656
  }
9440
9657
  function getRegistrableRoutines() {
@@ -9499,10 +9716,23 @@ var GraphSyncController = class _GraphSyncController {
9499
9716
  this.signalsSynced = false;
9500
9717
  this.intentsSynced = false;
9501
9718
  this.routinesSynced = false;
9719
+ this.directionalTaskMapsSynced = false;
9720
+ this.signalTaskMapsSynced = false;
9721
+ this.intentTaskMapsSynced = false;
9722
+ this.actorTaskMapsSynced = false;
9723
+ this.routineTaskMapsSynced = false;
9502
9724
  this.isCadenzaDBReady = false;
9503
9725
  this.initialized = false;
9504
9726
  this.initRetryScheduled = false;
9505
9727
  this.lastMissingLocalCadenzaDBInsertTablesKey = "";
9728
+ this.syncCycleCounter = 0;
9729
+ this.primitivePhaseCompletedCycles = /* @__PURE__ */ new Set();
9730
+ this.mapPhaseCompletedCycles = /* @__PURE__ */ new Set();
9731
+ this.activeSyncCycleId = null;
9732
+ this.activeSyncCycleStartedAt = 0;
9733
+ this.pendingBootstrapSyncRerun = false;
9734
+ this.localServiceInserted = false;
9735
+ this.localServiceInstanceInserted = false;
9506
9736
  }
9507
9737
  static get instance() {
9508
9738
  if (!this._instance) this._instance = new _GraphSyncController();
@@ -9576,45 +9806,9 @@ var GraphSyncController = class _GraphSyncController {
9576
9806
  },
9577
9807
  { concurrency: 30 }
9578
9808
  );
9579
- const ensureIntentRegistryBeforeIntentMapTask = resolveSyncInsertTask(
9580
- this.isCadenzaDBReady,
9581
- "intent_registry",
9582
- {
9583
- onConflict: {
9584
- target: ["name"],
9585
- action: {
9586
- do: "nothing"
9587
- }
9588
- }
9589
- },
9590
- { concurrency: 30 }
9591
- );
9592
- const authoritativeTaskQueryGraph = resolveSyncQueryTask(
9593
- this.isCadenzaDBReady,
9594
- "task",
9595
- {},
9596
- { concurrency: 10 }
9597
- );
9598
- const authoritativeRoutineQueryGraph = resolveSyncQueryTask(
9599
- this.isCadenzaDBReady,
9600
- "routine",
9601
- {},
9602
- { concurrency: 10 }
9603
- );
9604
- const authoritativeSignalQueryGraph = resolveSyncQueryTask(
9605
- this.isCadenzaDBReady,
9606
- "signal_registry",
9607
- {},
9608
- { concurrency: 10 }
9609
- );
9610
- const authoritativeIntentQueryGraph = resolveSyncQueryTask(
9611
- this.isCadenzaDBReady,
9612
- "intent_registry",
9613
- {},
9614
- { concurrency: 10 }
9615
- );
9616
9809
  const finalizeTaskSync = (emit, ctx) => {
9617
9810
  const pendingTasks = getRegistrableTasks().filter((task) => !task.registered);
9811
+ const serviceName2 = typeof ctx.__serviceName === "string" ? ctx.__serviceName : resolveSyncServiceName();
9618
9812
  if (pendingTasks.length > 0) {
9619
9813
  this.tasksSynced = false;
9620
9814
  return false;
@@ -9633,6 +9827,7 @@ var GraphSyncController = class _GraphSyncController {
9633
9827
  const pendingRoutines = getRegistrableRoutines().filter(
9634
9828
  (routine) => !routine.registered
9635
9829
  );
9830
+ const serviceName2 = typeof ctx.__serviceName === "string" ? ctx.__serviceName : resolveSyncServiceName();
9636
9831
  if (pendingRoutines.length > 0) {
9637
9832
  this.routinesSynced = false;
9638
9833
  return false;
@@ -9651,6 +9846,7 @@ var GraphSyncController = class _GraphSyncController {
9651
9846
  const pendingSignals = getRegistrableSignalObservers().filter(
9652
9847
  (observer) => observer.registered !== true
9653
9848
  );
9849
+ const serviceName2 = typeof ctx.__serviceName === "string" ? ctx.__serviceName : resolveSyncServiceName();
9654
9850
  if (pendingSignals.length > 0) {
9655
9851
  this.signalsSynced = false;
9656
9852
  return false;
@@ -9669,6 +9865,7 @@ var GraphSyncController = class _GraphSyncController {
9669
9865
  const pendingIntentNames = getRegistrableIntentNames().filter(
9670
9866
  (intentName) => !this.registeredIntentDefinitions.has(intentName)
9671
9867
  );
9868
+ const serviceName2 = typeof ctx.__serviceName === "string" ? ctx.__serviceName : resolveSyncServiceName();
9672
9869
  if (pendingIntentNames.length > 0) {
9673
9870
  this.intentsSynced = false;
9674
9871
  return false;
@@ -9934,14 +10131,15 @@ var GraphSyncController = class _GraphSyncController {
9934
10131
  );
9935
10132
  const processSignalRegistrationTask = CadenzaService.createMetaTask(
9936
10133
  "Process signal registration",
9937
- (ctx) => {
9938
- if (!didSyncInsertSucceed(ctx)) {
10134
+ (ctx, emit) => {
10135
+ const insertSucceeded = didSyncInsertSucceed(ctx);
10136
+ const signalName = resolveSignalNameFromSyncContext(ctx);
10137
+ if (!insertSucceeded) {
9939
10138
  return;
9940
10139
  }
9941
10140
  CadenzaService.debounce("meta.sync_controller.synced_resource", {
9942
10141
  delayMs: 3e3
9943
10142
  });
9944
- const signalName = resolveSignalNameFromSyncContext(ctx);
9945
10143
  if (!signalName) {
9946
10144
  return false;
9947
10145
  }
@@ -9953,6 +10151,12 @@ var GraphSyncController = class _GraphSyncController {
9953
10151
  if (observer) {
9954
10152
  observer.registered = true;
9955
10153
  }
10154
+ emit(
10155
+ "meta.sync_controller.signal_registered",
10156
+ buildMinimalSyncSignalContext(ctx, {
10157
+ __signal: signalName
10158
+ })
10159
+ );
9956
10160
  return { signalName };
9957
10161
  }
9958
10162
  ).then(CadenzaService.signalBroker.registerSignalTask).then(gatherSignalRegistrationTask);
@@ -9973,6 +10177,7 @@ var GraphSyncController = class _GraphSyncController {
9973
10177
  return;
9974
10178
  }
9975
10179
  for (const task of tasks) {
10180
+ if (task.hidden || !task.register || task.isDeputy) continue;
9976
10181
  if (task.registered) continue;
9977
10182
  const { __functionString, __getTagCallback } = task.export();
9978
10183
  this.tasksSynced = false;
@@ -10007,7 +10212,8 @@ var GraphSyncController = class _GraphSyncController {
10007
10212
  signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
10008
10213
  signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
10009
10214
  observed: Array.from(task.observedSignals)
10010
- }
10215
+ },
10216
+ intents: Array.from(task.handlesIntents)
10011
10217
  },
10012
10218
  __taskName: task.name
10013
10219
  };
@@ -10030,13 +10236,15 @@ var GraphSyncController = class _GraphSyncController {
10030
10236
  const registerTaskTask = CadenzaService.createMetaTask(
10031
10237
  "Record registration",
10032
10238
  (ctx, emit) => {
10033
- if (!didSyncInsertSucceed(ctx)) {
10239
+ const task = resolveLocalTaskFromSyncContext(ctx);
10240
+ const serviceName2 = resolveSyncServiceName(task);
10241
+ const insertSucceeded = didSyncInsertSucceed(ctx);
10242
+ if (!insertSucceeded) {
10034
10243
  return;
10035
10244
  }
10036
10245
  CadenzaService.debounce("meta.sync_controller.synced_resource", {
10037
10246
  delayMs: 3e3
10038
10247
  });
10039
- const task = resolveLocalTaskFromSyncContext(ctx);
10040
10248
  if (!task) {
10041
10249
  return true;
10042
10250
  }
@@ -10051,24 +10259,6 @@ var GraphSyncController = class _GraphSyncController {
10051
10259
  }
10052
10260
  ).then(gatherTaskRegistrationTask);
10053
10261
  wireSyncTaskGraph(this.splitTasksForRegistration, registerTaskGraph, registerTaskTask);
10054
- CadenzaService.createMetaTask(
10055
- "Prepare created task for immediate sync",
10056
- (ctx) => {
10057
- const task = ctx.taskInstance ?? (ctx.data?.name ? CadenzaService.get(String(ctx.data.name)) : void 0);
10058
- if (!task || task.hidden || !task.register || task.registered) {
10059
- return false;
10060
- }
10061
- return {
10062
- __syncing: true,
10063
- tasks: [task]
10064
- };
10065
- },
10066
- "Schedules newly created tasks into the graph sync registration flow without waiting for the next periodic tick.",
10067
- {
10068
- register: false,
10069
- isHidden: true
10070
- }
10071
- ).doOn("meta.task.created").then(this.splitTasksForRegistration);
10072
10262
  this.splitActorsForRegistration = CadenzaService.createMetaTask(
10073
10263
  "Split actors for registration",
10074
10264
  function* (ctx) {
@@ -10207,13 +10397,14 @@ var GraphSyncController = class _GraphSyncController {
10207
10397
  const registerSignalTask = CadenzaService.createMetaTask(
10208
10398
  "Record signal registration",
10209
10399
  (ctx) => {
10400
+ const task = resolveLocalTaskFromSyncContext(ctx);
10401
+ const serviceName2 = resolveSyncServiceName(task);
10210
10402
  if (!didSyncInsertSucceed(ctx)) {
10211
10403
  return;
10212
10404
  }
10213
10405
  CadenzaService.debounce("meta.sync_controller.synced_resource", {
10214
10406
  delayMs: 3e3
10215
10407
  });
10216
- const task = resolveLocalTaskFromSyncContext(ctx);
10217
10408
  const signalName = resolveSignalNameFromSyncContext(ctx);
10218
10409
  if (!task || !signalName) {
10219
10410
  return true;
@@ -10225,7 +10416,8 @@ var GraphSyncController = class _GraphSyncController {
10225
10416
  "Split observed signals of task",
10226
10417
  function* (ctx) {
10227
10418
  const task = ctx.task;
10228
- if (task.hidden || !task.register || !task.registered) return false;
10419
+ if (task.hidden || !task.register || task.isDeputy || !task.registered)
10420
+ return false;
10229
10421
  const serviceName2 = resolveSyncServiceName(task);
10230
10422
  if (!serviceName2) {
10231
10423
  return false;
@@ -10307,7 +10499,7 @@ var GraphSyncController = class _GraphSyncController {
10307
10499
  );
10308
10500
  const recordIntentDefinitionRegistrationTask = CadenzaService.createMetaTask(
10309
10501
  "Record intent definition registration",
10310
- (ctx) => {
10502
+ (ctx, emit) => {
10311
10503
  if (!didSyncInsertSucceed(ctx)) {
10312
10504
  return;
10313
10505
  }
@@ -10315,6 +10507,12 @@ var GraphSyncController = class _GraphSyncController {
10315
10507
  delayMs: 3e3
10316
10508
  });
10317
10509
  this.registeredIntentDefinitions.add(ctx.__intentName);
10510
+ emit(
10511
+ "meta.sync_controller.intent_registered",
10512
+ buildMinimalSyncSignalContext(ctx, {
10513
+ __intentName: ctx.__intentName
10514
+ })
10515
+ );
10318
10516
  return true;
10319
10517
  }
10320
10518
  ).then(gatherIntentRegistrationTask);
@@ -10326,13 +10524,13 @@ var GraphSyncController = class _GraphSyncController {
10326
10524
  const registerIntentTask = CadenzaService.createMetaTask(
10327
10525
  "Record intent registration",
10328
10526
  (ctx) => {
10527
+ const task = resolveLocalTaskFromSyncContext(ctx);
10329
10528
  if (!didSyncInsertSucceed(ctx)) {
10330
10529
  return;
10331
10530
  }
10332
10531
  CadenzaService.debounce("meta.sync_controller.synced_resource", {
10333
10532
  delayMs: 3e3
10334
10533
  });
10335
- const task = resolveLocalTaskFromSyncContext(ctx);
10336
10534
  if (!task) {
10337
10535
  return true;
10338
10536
  }
@@ -10344,7 +10542,8 @@ var GraphSyncController = class _GraphSyncController {
10344
10542
  "Split intents of task",
10345
10543
  function* (ctx) {
10346
10544
  const task = ctx.task;
10347
- if (task.hidden || !task.register || !task.registered) return false;
10545
+ if (task.hidden || !task.register || task.isDeputy || !task.registered)
10546
+ return false;
10348
10547
  const serviceName2 = resolveSyncServiceName(task);
10349
10548
  if (!serviceName2) {
10350
10549
  return false;
@@ -10399,30 +10598,6 @@ var GraphSyncController = class _GraphSyncController {
10399
10598
  return emittedCount > 0;
10400
10599
  }.bind(this)
10401
10600
  );
10402
- const prepareIntentDefinitionForIntentMapTask = CadenzaService.createMetaTask(
10403
- "Prepare intent definition for intent-to-task map",
10404
- (ctx) => {
10405
- if (!ctx.__intentDefinition || !ctx.__intentMapData) {
10406
- return false;
10407
- }
10408
- return {
10409
- ...ctx,
10410
- data: ctx.__intentDefinition
10411
- };
10412
- }
10413
- );
10414
- const restoreIntentToTaskMapPayloadTask = CadenzaService.createMetaTask(
10415
- "Restore intent-to-task map payload",
10416
- (ctx) => {
10417
- if (!ctx.__intentMapData) {
10418
- return false;
10419
- }
10420
- return {
10421
- ...ctx,
10422
- data: ctx.__intentMapData
10423
- };
10424
- }
10425
- );
10426
10601
  const intentToTaskMapGraph = resolveSyncInsertTask(
10427
10602
  this.isCadenzaDBReady,
10428
10603
  "intent_to_task_map",
@@ -10441,20 +10616,8 @@ var GraphSyncController = class _GraphSyncController {
10441
10616
  },
10442
10617
  { concurrency: 30 }
10443
10618
  );
10444
- this.registerIntentToTaskMapTask.then(prepareIntentDefinitionForIntentMapTask);
10445
- if (ensureIntentRegistryBeforeIntentMapTask) {
10446
- wireSyncTaskGraph(
10447
- prepareIntentDefinitionForIntentMapTask,
10448
- ensureIntentRegistryBeforeIntentMapTask,
10449
- restoreIntentToTaskMapPayloadTask
10450
- );
10451
- } else {
10452
- prepareIntentDefinitionForIntentMapTask.then(
10453
- restoreIntentToTaskMapPayloadTask
10454
- );
10455
- }
10456
10619
  wireSyncTaskGraph(
10457
- restoreIntentToTaskMapPayloadTask,
10620
+ this.registerIntentToTaskMapTask,
10458
10621
  intentToTaskMapGraph,
10459
10622
  registerIntentTask
10460
10623
  );
@@ -10465,7 +10628,7 @@ var GraphSyncController = class _GraphSyncController {
10465
10628
  CadenzaService.debounce("meta.sync_controller.synced_resource", {
10466
10629
  delayMs: 3e3
10467
10630
  });
10468
- if (task.hidden || !task.register) return;
10631
+ if (task.hidden || !task.register || task.isDeputy) return;
10469
10632
  const predecessorServiceName = resolveSyncServiceName(task);
10470
10633
  if (!predecessorServiceName) {
10471
10634
  return;
@@ -10599,452 +10762,583 @@ var GraphSyncController = class _GraphSyncController {
10599
10762
  deputyRelationshipRegistrationGraph,
10600
10763
  recordDeputyRelationshipRegistrationTask
10601
10764
  );
10602
- const reconcileTaskRegistrationFromAuthorityTask = CadenzaService.createMetaTask(
10603
- "Reconcile task registration from authority",
10604
- (ctx, emit) => {
10605
- const authoritativeTasks = resolveSyncQueryRows(ctx, "task");
10606
- let changed = false;
10607
- for (const row of authoritativeTasks) {
10608
- const taskName = typeof row.name === "string" ? row.name : "";
10609
- if (!taskName) {
10610
- continue;
10611
- }
10612
- const task = CadenzaService.get(taskName);
10613
- if (!task || task.registered) {
10614
- continue;
10615
- }
10616
- task.registered = true;
10617
- changed = true;
10618
- emit("meta.sync_controller.task_registered", {
10619
- ...ctx,
10620
- __taskName: task.name,
10621
- task,
10622
- __authoritativeReconciliation: true
10623
- });
10765
+ const hasPendingDirectionalTaskMaps = () => getRegistrableTasks().some((task) => {
10766
+ const taskWithDeputyState = task;
10767
+ if (task.isHidden || !task.register || !task.registered) {
10768
+ return false;
10769
+ }
10770
+ const predecessorServiceName = resolveSyncServiceName(task);
10771
+ if (!predecessorServiceName) {
10772
+ return false;
10773
+ }
10774
+ for (const nextTask of task.nextTasks) {
10775
+ if (task.taskMapRegistration.has(nextTask.name) || nextTask.isHidden || !nextTask.register || !nextTask.registered) {
10776
+ continue;
10624
10777
  }
10625
- if (authoritativeTasks.length > 0 || changed) {
10626
- finalizeTaskSync(emit, {
10627
- ...ctx,
10628
- __authoritativeReconciliation: true
10629
- });
10778
+ if (resolveSyncServiceName(nextTask)) {
10779
+ return true;
10780
+ }
10781
+ }
10782
+ if (task.isDeputy && !taskWithDeputyState.signalName && !taskWithDeputyState.registeredDeputyMap) {
10783
+ return Boolean(resolveSyncServiceName(task) && resolveSyncServiceName());
10784
+ }
10785
+ return false;
10786
+ });
10787
+ const hasPendingSignalTaskMaps = () => getRegistrableTasks().some((task) => {
10788
+ if (task.isHidden || !task.register || !task.registered) {
10789
+ return false;
10790
+ }
10791
+ for (const signal of task.observedSignals) {
10792
+ if (task.registeredSignals.has(signal)) {
10793
+ continue;
10794
+ }
10795
+ const signalName = signal.split(":")[0];
10796
+ if (!decomposeSignalName(signalName).isGlobal) {
10797
+ continue;
10798
+ }
10799
+ if (!CadenzaService.signalBroker.signalObservers?.get(signalName)?.registered) {
10800
+ continue;
10801
+ }
10802
+ return true;
10803
+ }
10804
+ return false;
10805
+ });
10806
+ const hasPendingIntentTaskMaps = () => getRegistrableTasks().some((task) => {
10807
+ if (task.isHidden || !task.register || !task.registered) {
10808
+ return false;
10809
+ }
10810
+ const registeredIntents = task.__registeredIntents ?? /* @__PURE__ */ new Set();
10811
+ for (const intent of task.handlesIntents) {
10812
+ if (registeredIntents.has(intent) || isLocalOnlySyncIntent(intent)) {
10813
+ continue;
10814
+ }
10815
+ if (isMetaIntentName(intent) && !task.isMeta) {
10816
+ continue;
10817
+ }
10818
+ const intentDefinition = buildIntentRegistryData(CadenzaService.inquiryBroker.intents.get(intent)) ?? buildIntentRegistryData({ name: intent });
10819
+ if (!intentDefinition) {
10820
+ continue;
10821
+ }
10822
+ return true;
10823
+ }
10824
+ return false;
10825
+ });
10826
+ const hasPendingActorTaskMaps = () => getRegistrableTasks().some((task) => {
10827
+ if (task.isHidden || !task.register || !task.registered) {
10828
+ return false;
10829
+ }
10830
+ const metadata = getActorTaskRuntimeMetadata(task.taskFunction);
10831
+ if (!metadata?.actorName) {
10832
+ return false;
10833
+ }
10834
+ const serviceName2 = resolveSyncServiceName(task);
10835
+ if (!serviceName2) {
10836
+ return false;
10837
+ }
10838
+ const registrationKey = `${metadata.actorName}|${task.name}|${task.version}|${serviceName2}`;
10839
+ return !this.registeredActorTaskMaps.has(registrationKey);
10840
+ });
10841
+ const hasPendingRoutineTaskMaps = () => getRegistrableRoutines().some((routine) => {
10842
+ if (!routine.registered) {
10843
+ return false;
10844
+ }
10845
+ for (const task of routine.tasks) {
10846
+ if (!task) {
10847
+ continue;
10630
10848
  }
10631
- return changed;
10849
+ const tasks = task.getIterator();
10850
+ while (tasks.hasNext()) {
10851
+ const nextTask = tasks.next();
10852
+ if (!nextTask?.registered) {
10853
+ continue;
10854
+ }
10855
+ if (!routine.registeredTasks.has(nextTask.name)) {
10856
+ return true;
10857
+ }
10858
+ }
10859
+ }
10860
+ return false;
10861
+ });
10862
+ const gatherDirectionalTaskMapRegistrationTask = CadenzaService.createUniqueMetaTask(
10863
+ "Gather directional task map registration",
10864
+ (ctx) => {
10865
+ if (hasPendingDirectionalTaskMaps()) {
10866
+ this.directionalTaskMapsSynced = false;
10867
+ return false;
10868
+ }
10869
+ this.directionalTaskMapsSynced = true;
10870
+ return ctx;
10632
10871
  },
10633
- "Marks local tasks as registered when authority rows already exist.",
10872
+ "Completes directional task graph registration when task edges and deputy edges are registered.",
10634
10873
  {
10635
10874
  register: false,
10636
10875
  isHidden: true
10637
10876
  }
10638
10877
  );
10639
- const reconcileRoutineRegistrationFromAuthorityTask = CadenzaService.createMetaTask(
10640
- "Reconcile routine registration from authority",
10641
- (ctx, emit) => {
10642
- const authoritativeRoutines = resolveSyncQueryRows(ctx, "routine");
10643
- let changed = false;
10644
- for (const row of authoritativeRoutines) {
10645
- const routineName = typeof row.name === "string" ? row.name : "";
10646
- if (!routineName) {
10647
- continue;
10648
- }
10649
- const routine = CadenzaService.getRoutine(routineName);
10650
- if (!routine || routine.registered) {
10651
- continue;
10652
- }
10653
- routine.registered = true;
10654
- changed = true;
10878
+ const gatherSignalTaskMapRegistrationTask = CadenzaService.createUniqueMetaTask(
10879
+ "Gather signal task map registration",
10880
+ (ctx) => {
10881
+ if (hasPendingSignalTaskMaps()) {
10882
+ this.signalTaskMapsSynced = false;
10883
+ return false;
10655
10884
  }
10656
- if (authoritativeRoutines.length > 0 || changed) {
10657
- finalizeRoutineSync(emit, {
10658
- ...ctx,
10659
- __authoritativeReconciliation: true
10660
- });
10885
+ this.signalTaskMapsSynced = true;
10886
+ return ctx;
10887
+ },
10888
+ "Completes signal-to-task map registration when all global observed signal edges are registered.",
10889
+ {
10890
+ register: false,
10891
+ isHidden: true
10892
+ }
10893
+ );
10894
+ const gatherIntentTaskMapRegistrationTask = CadenzaService.createUniqueMetaTask(
10895
+ "Gather intent task map registration",
10896
+ (ctx) => {
10897
+ if (hasPendingIntentTaskMaps()) {
10898
+ this.intentTaskMapsSynced = false;
10899
+ return false;
10661
10900
  }
10662
- return changed;
10901
+ this.intentTaskMapsSynced = true;
10902
+ return ctx;
10663
10903
  },
10664
- "Marks local routines as registered when authority rows already exist.",
10904
+ "Completes intent-to-task map registration when all task responders are registered.",
10665
10905
  {
10666
10906
  register: false,
10667
10907
  isHidden: true
10668
10908
  }
10669
10909
  );
10670
- const reconcileSignalRegistrationFromAuthorityTask = CadenzaService.createMetaTask(
10671
- "Reconcile signal registration from authority",
10672
- (ctx, emit) => {
10673
- const authoritativeSignals = resolveSyncQueryRows(ctx, "signal_registry");
10674
- const signalObservers = CadenzaService.signalBroker.signalObservers;
10675
- let changed = false;
10676
- for (const row of authoritativeSignals) {
10677
- const signalName = typeof row.name === "string" ? row.name : "";
10678
- if (!signalName) {
10679
- continue;
10680
- }
10681
- const observer = signalObservers?.get(signalName);
10682
- if (!observer || observer.registered) {
10683
- continue;
10684
- }
10685
- observer.registered = true;
10686
- changed = true;
10910
+ const gatherActorTaskMapRegistrationTask = CadenzaService.createUniqueMetaTask(
10911
+ "Gather actor task map registration",
10912
+ (ctx) => {
10913
+ if (hasPendingActorTaskMaps()) {
10914
+ this.actorTaskMapsSynced = false;
10915
+ return false;
10687
10916
  }
10688
- if (authoritativeSignals.length > 0 || changed) {
10689
- finalizeSignalSync(emit, {
10690
- ...ctx,
10691
- __authoritativeReconciliation: true
10692
- });
10917
+ this.actorTaskMapsSynced = true;
10918
+ return ctx;
10919
+ },
10920
+ "Completes actor-to-task map registration when all actor-backed tasks are registered.",
10921
+ {
10922
+ register: false,
10923
+ isHidden: true
10924
+ }
10925
+ );
10926
+ const gatherRoutineTaskMapRegistrationTask = CadenzaService.createUniqueMetaTask(
10927
+ "Gather routine task map registration",
10928
+ (ctx) => {
10929
+ if (hasPendingRoutineTaskMaps()) {
10930
+ this.routineTaskMapsSynced = false;
10931
+ return false;
10693
10932
  }
10694
- return changed;
10933
+ this.routineTaskMapsSynced = true;
10934
+ return ctx;
10695
10935
  },
10696
- "Marks local signals as registered when authority rows already exist.",
10936
+ "Completes task-to-routine map registration when all routine task memberships are registered.",
10697
10937
  {
10698
10938
  register: false,
10699
10939
  isHidden: true
10700
10940
  }
10701
10941
  );
10702
- const reconcileIntentRegistrationFromAuthorityTask = CadenzaService.createMetaTask(
10703
- "Reconcile intent registration from authority",
10942
+ const finishSyncTask = CadenzaService.createUniqueMetaTask(
10943
+ "Finish sync",
10704
10944
  (ctx, emit) => {
10705
- const authoritativeIntents = resolveSyncQueryRows(ctx, "intent_registry");
10706
- let changed = false;
10707
- for (const row of authoritativeIntents) {
10708
- const intentName = typeof row.name === "string" ? row.name : "";
10709
- if (!intentName || !CadenzaService.inquiryBroker.intents.has(intentName)) {
10710
- continue;
10711
- }
10712
- if (this.registeredIntentDefinitions.has(intentName)) {
10713
- continue;
10945
+ const syncCycleId = typeof ctx.__syncCycleId === "string" ? ctx.__syncCycleId.trim() : "";
10946
+ if (syncCycleId && this.activeSyncCycleId === syncCycleId) {
10947
+ this.activeSyncCycleId = null;
10948
+ this.activeSyncCycleStartedAt = 0;
10949
+ }
10950
+ if (this.pendingBootstrapSyncRerun) {
10951
+ this.pendingBootstrapSyncRerun = false;
10952
+ CadenzaService.debounce("meta.sync_requested", {
10953
+ delayMs: 100
10954
+ });
10955
+ }
10956
+ emit("global.meta.sync_controller.synced", {
10957
+ data: {
10958
+ is_active: true,
10959
+ is_non_responsive: false,
10960
+ is_blocked: false,
10961
+ last_active: formatTimestamp(Date.now())
10962
+ },
10963
+ filter: {
10964
+ uuid: CadenzaService.serviceRegistry.serviceInstanceId
10714
10965
  }
10715
- this.registeredIntentDefinitions.add(intentName);
10716
- changed = true;
10966
+ });
10967
+ return true;
10968
+ },
10969
+ "Marks the current bootstrap sync cycle as complete.",
10970
+ {
10971
+ register: false,
10972
+ isHidden: true
10973
+ }
10974
+ ).attachSignal("global.meta.sync_controller.synced");
10975
+ const mapPhaseBarrierTask = CadenzaService.createUniqueMetaTask(
10976
+ "Complete map sync phase",
10977
+ (ctx) => {
10978
+ const syncCycleId = typeof ctx.__syncCycleId === "string" ? ctx.__syncCycleId.trim() : "";
10979
+ if (!syncCycleId) {
10980
+ return false;
10717
10981
  }
10718
- if (authoritativeIntents.length > 0 || changed) {
10719
- finalizeIntentSync(emit, {
10720
- ...ctx,
10721
- __authoritativeReconciliation: true
10722
- });
10982
+ if (!this.directionalTaskMapsSynced || !this.signalTaskMapsSynced || !this.intentTaskMapsSynced || !this.actorTaskMapsSynced || !this.routineTaskMapsSynced) {
10983
+ return false;
10984
+ }
10985
+ if (!markCompletedSyncCycle(this.mapPhaseCompletedCycles, syncCycleId)) {
10986
+ return false;
10723
10987
  }
10724
- return changed;
10988
+ return ctx;
10725
10989
  },
10726
- "Marks local intents as registered when authority rows already exist.",
10990
+ "Fans in map branch completion and ends the current sync cycle once every map branch is complete.",
10991
+ {
10992
+ register: false,
10993
+ isHidden: true
10994
+ }
10995
+ ).then(finishSyncTask);
10996
+ const startDirectionalTaskMapSyncTask = CadenzaService.createMetaTask(
10997
+ "Start directional task map sync",
10998
+ (ctx) => ctx,
10999
+ "Starts the directional task graph map branch for the current sync cycle.",
10727
11000
  {
10728
11001
  register: false,
10729
11002
  isHidden: true
10730
11003
  }
10731
11004
  );
10732
- const skipAuthoritativeTaskReconciliationTask = CadenzaService.createMetaTask(
10733
- "Skip authoritative task reconciliation",
10734
- () => false,
10735
- "Skips task reconciliation when no authority query task is available.",
11005
+ const startSignalTaskMapSyncTask = CadenzaService.createMetaTask(
11006
+ "Start signal task map sync",
11007
+ (ctx) => ctx,
11008
+ "Starts the signal-to-task map branch for the current sync cycle.",
10736
11009
  {
10737
11010
  register: false,
10738
11011
  isHidden: true
10739
11012
  }
10740
11013
  );
10741
- const skipAuthoritativeRoutineReconciliationTask = CadenzaService.createMetaTask(
10742
- "Skip authoritative routine reconciliation",
10743
- () => false,
10744
- "Skips routine reconciliation when no authority query task is available.",
11014
+ const startIntentTaskMapSyncTask = CadenzaService.createMetaTask(
11015
+ "Start intent task map sync",
11016
+ (ctx) => ctx,
11017
+ "Starts the intent-to-task map branch for the current sync cycle.",
10745
11018
  {
10746
11019
  register: false,
10747
11020
  isHidden: true
10748
11021
  }
10749
11022
  );
10750
- const skipAuthoritativeSignalReconciliationTask = CadenzaService.createMetaTask(
10751
- "Skip authoritative signal reconciliation",
10752
- () => false,
10753
- "Skips signal reconciliation when no authority query task is available.",
11023
+ const startActorTaskMapSyncTask = CadenzaService.createMetaTask(
11024
+ "Start actor task map sync",
11025
+ (ctx) => ctx,
11026
+ "Starts the actor-to-task map branch for the current sync cycle.",
10754
11027
  {
10755
11028
  register: false,
10756
11029
  isHidden: true
10757
11030
  }
10758
11031
  );
10759
- const skipAuthoritativeIntentReconciliationTask = CadenzaService.createMetaTask(
10760
- "Skip authoritative intent reconciliation",
10761
- () => false,
10762
- "Skips intent reconciliation when no authority query task is available.",
11032
+ const startRoutineTaskMapSyncTask = CadenzaService.createMetaTask(
11033
+ "Start routine task map sync",
11034
+ (ctx) => ctx,
11035
+ "Starts the task-to-routine map branch for the current sync cycle.",
10763
11036
  {
10764
11037
  register: false,
10765
11038
  isHidden: true
10766
11039
  }
10767
11040
  );
10768
- if (authoritativeTaskQueryGraph) {
10769
- authoritativeTaskQueryGraph.completionTask.then(
10770
- reconcileTaskRegistrationFromAuthorityTask
10771
- );
10772
- }
10773
- if (authoritativeRoutineQueryGraph) {
10774
- authoritativeRoutineQueryGraph.completionTask.then(
10775
- reconcileRoutineRegistrationFromAuthorityTask
10776
- );
10777
- }
10778
- if (authoritativeSignalQueryGraph) {
10779
- authoritativeSignalQueryGraph.completionTask.then(
10780
- reconcileSignalRegistrationFromAuthorityTask
10781
- );
10782
- }
10783
- if (authoritativeIntentQueryGraph) {
10784
- authoritativeIntentQueryGraph.completionTask.then(
10785
- reconcileIntentRegistrationFromAuthorityTask
10786
- );
10787
- }
10788
- const authoritativeRegistrationTriggers = [
10789
- "meta.service_registry.initial_sync_complete",
10790
- "meta.sync_requested",
10791
- "meta.sync_controller.synced_resource",
10792
- "meta.sync_controller.authority_registration_reconciliation_requested"
10793
- ];
10794
- CadenzaService.createMetaTask(
10795
- "Prepare authoritative task registration query",
11041
+ const primitivePhaseBarrierTask = CadenzaService.createUniqueMetaTask(
11042
+ "Complete primitive sync phase",
10796
11043
  (ctx) => {
10797
- if (!this.isCadenzaDBReady) {
11044
+ const syncCycleId = typeof ctx.__syncCycleId === "string" ? ctx.__syncCycleId.trim() : "";
11045
+ if (!syncCycleId) {
10798
11046
  return false;
10799
11047
  }
10800
- const serviceName2 = resolveSyncServiceName();
10801
- if (!serviceName2) {
11048
+ const serviceName2 = typeof ctx.__serviceName === "string" ? ctx.__serviceName : resolveSyncServiceName();
11049
+ if (!this.tasksSynced || !this.signalsSynced || !this.intentsSynced || !this.actorsSynced || !this.routinesSynced) {
10802
11050
  return false;
10803
11051
  }
10804
- return {
10805
- ...ctx,
10806
- __syncServiceName: serviceName2,
10807
- queryData: {
10808
- filter: {
10809
- service_name: serviceName2
10810
- },
10811
- fields: ["name", "version", "service_name"]
10812
- }
10813
- };
11052
+ if (!markCompletedSyncCycle(this.primitivePhaseCompletedCycles, syncCycleId)) {
11053
+ return false;
11054
+ }
11055
+ this.directionalTaskMapsSynced = false;
11056
+ this.signalTaskMapsSynced = false;
11057
+ this.intentTaskMapsSynced = false;
11058
+ this.actorTaskMapsSynced = false;
11059
+ this.routineTaskMapsSynced = false;
11060
+ return ctx;
10814
11061
  },
10815
- "Builds the authority task query payload for the current service.",
11062
+ "Fans in primitive registration and opens the map registration phase once every primitive branch is complete.",
10816
11063
  {
10817
11064
  register: false,
10818
11065
  isHidden: true
10819
11066
  }
10820
- ).doOn(...authoritativeRegistrationTriggers).then(
10821
- authoritativeTaskQueryGraph?.entryTask ?? skipAuthoritativeTaskReconciliationTask
10822
- );
10823
- CadenzaService.createMetaTask(
10824
- "Prepare authoritative routine registration query",
11067
+ ).then(
11068
+ startDirectionalTaskMapSyncTask,
11069
+ startSignalTaskMapSyncTask,
11070
+ startIntentTaskMapSyncTask,
11071
+ startActorTaskMapSyncTask,
11072
+ startRoutineTaskMapSyncTask
11073
+ );
11074
+ gatherTaskRegistrationTask.then(primitivePhaseBarrierTask);
11075
+ gatherSignalRegistrationTask.then(primitivePhaseBarrierTask);
11076
+ gatherIntentRegistrationTask.then(primitivePhaseBarrierTask);
11077
+ gatherActorRegistrationTask.then(primitivePhaseBarrierTask);
11078
+ gatherRoutineRegistrationTask.then(primitivePhaseBarrierTask);
11079
+ const markLocalServiceInsertedForBootstrapSyncTask = CadenzaService.createUniqueMetaTask(
11080
+ "Mark local service inserted for bootstrap sync",
10825
11081
  (ctx) => {
10826
- if (!this.isCadenzaDBReady) {
10827
- return false;
10828
- }
10829
11082
  const serviceName2 = resolveSyncServiceName();
10830
- if (!serviceName2) {
11083
+ const insertedServiceName = typeof ctx.__serviceName === "string" ? ctx.__serviceName : typeof ctx.service_name === "string" ? ctx.service_name : null;
11084
+ if (!serviceName2 || insertedServiceName !== serviceName2) {
10831
11085
  return false;
10832
11086
  }
10833
- return {
10834
- ...ctx,
10835
- __syncServiceName: serviceName2,
10836
- queryData: {
10837
- filter: {
10838
- service_name: serviceName2
10839
- },
10840
- fields: ["name", "version", "service_name"]
10841
- }
10842
- };
11087
+ this.localServiceInserted = true;
11088
+ return true;
10843
11089
  },
10844
- "Builds the authority routine query payload for the current service.",
11090
+ "Marks that the local service row has been inserted in authority so bootstrap sync can start only after that prerequisite.",
10845
11091
  {
10846
11092
  register: false,
10847
11093
  isHidden: true
10848
11094
  }
10849
- ).doOn(...authoritativeRegistrationTriggers).then(
10850
- authoritativeRoutineQueryGraph?.entryTask ?? skipAuthoritativeRoutineReconciliationTask
10851
- );
10852
- CadenzaService.createMetaTask(
10853
- "Prepare authoritative signal registration query",
11095
+ ).doOn("meta.service_registry.service_inserted");
11096
+ const markLocalServiceInstanceInsertedForBootstrapSyncTask = CadenzaService.createUniqueMetaTask(
11097
+ "Mark local service instance inserted for bootstrap sync",
10854
11098
  (ctx) => {
10855
- if (!this.isCadenzaDBReady) {
11099
+ const serviceName2 = resolveSyncServiceName();
11100
+ const insertedServiceName = typeof ctx.__serviceName === "string" ? ctx.__serviceName : typeof ctx.service_name === "string" ? ctx.service_name : null;
11101
+ if (!serviceName2 || insertedServiceName !== serviceName2) {
10856
11102
  return false;
10857
11103
  }
10858
- return {
10859
- ...ctx,
10860
- queryData: {
10861
- fields: ["name"]
10862
- }
10863
- };
11104
+ this.localServiceInstanceInserted = true;
11105
+ return true;
10864
11106
  },
10865
- "Builds the authority signal query payload for local reconciliation.",
11107
+ "Marks that the local service instance row has been inserted in authority so bootstrap sync can start only after that prerequisite.",
10866
11108
  {
10867
11109
  register: false,
10868
11110
  isHidden: true
10869
11111
  }
10870
- ).doOn(...authoritativeRegistrationTriggers).then(
10871
- authoritativeSignalQueryGraph?.entryTask ?? skipAuthoritativeSignalReconciliationTask
10872
- );
10873
- CadenzaService.createMetaTask(
10874
- "Prepare authoritative intent registration query",
11112
+ ).doOn("meta.service_registry.instance_inserted");
11113
+ const startBootstrapSyncTask = CadenzaService.createUniqueMetaTask(
11114
+ "Start bootstrap graph sync",
10875
11115
  (ctx) => {
10876
- if (!this.isCadenzaDBReady) {
11116
+ const now = Date.now();
11117
+ const serviceName2 = resolveSyncServiceName();
11118
+ const serviceInstanceId = CadenzaService.serviceRegistry.serviceInstanceId;
11119
+ if (!serviceName2 || !serviceInstanceId) {
11120
+ return false;
11121
+ }
11122
+ if (!this.localServiceInserted) {
11123
+ return false;
11124
+ }
11125
+ if (!this.localServiceInstanceInserted) {
10877
11126
  return false;
10878
11127
  }
11128
+ if (!ServiceRegistry.instance.hasLocalInstanceRegistered()) {
11129
+ return false;
11130
+ }
11131
+ if (this.activeSyncCycleId) {
11132
+ const activeCycleAgeMs = now - this.activeSyncCycleStartedAt;
11133
+ if (activeCycleAgeMs < BOOTSTRAP_SYNC_STALE_CYCLE_MS) {
11134
+ this.pendingBootstrapSyncRerun = true;
11135
+ return false;
11136
+ }
11137
+ }
11138
+ const syncCycleId = `${now}-${++this.syncCycleCounter}`;
11139
+ this.activeSyncCycleId = syncCycleId;
11140
+ this.activeSyncCycleStartedAt = now;
11141
+ this.pendingBootstrapSyncRerun = false;
11142
+ this.tasksSynced = false;
11143
+ this.signalsSynced = false;
11144
+ this.intentsSynced = false;
11145
+ this.actorsSynced = false;
11146
+ this.routinesSynced = false;
10879
11147
  return {
10880
11148
  ...ctx,
10881
- queryData: {
10882
- fields: ["name"]
10883
- }
11149
+ __syncing: true,
11150
+ __syncCycleId: syncCycleId,
11151
+ __serviceName: serviceName2,
11152
+ __serviceInstanceId: serviceInstanceId
10884
11153
  };
10885
11154
  },
10886
- "Builds the authority intent query payload for local reconciliation.",
11155
+ "Starts a deterministic bootstrap sync cycle once the local service instance exists.",
10887
11156
  {
10888
11157
  register: false,
10889
11158
  isHidden: true
10890
11159
  }
10891
- ).doOn(...authoritativeRegistrationTriggers).then(
10892
- authoritativeIntentQueryGraph?.entryTask ?? skipAuthoritativeIntentReconciliationTask
10893
- );
10894
- CadenzaService.signalBroker.getSignalsTask.clone().doOn(
10895
- "meta.sync_controller.sync_tick",
10896
- "meta.service_registry.initial_sync_complete",
10897
- "meta.sync_requested"
10898
- ).then(this.splitSignalsTask);
10899
- CadenzaService.registry.getAllTasks.clone().doOn(
10900
- "meta.sync_controller.sync_tick",
10901
- "meta.sync_controller.synced_signals",
10902
- "meta.sync_requested"
10903
- ).then(this.splitTasksForRegistration);
10904
- CadenzaService.createMetaTask("Get all intents", (ctx) => {
10905
- return {
10906
- ...ctx,
10907
- intents: Array.from(CadenzaService.inquiryBroker.intents.values())
10908
- };
10909
- }).doOn(
10910
- "meta.sync_controller.sync_tick",
10911
- "meta.service_registry.initial_sync_complete",
10912
- "meta.sync_requested"
10913
- ).then(this.splitIntentsTask);
10914
- CadenzaService.registry.getAllRoutines.clone().doOn(
10915
- "meta.sync_controller.sync_tick",
10916
- "meta.service_registry.initial_sync_complete",
10917
- "meta.sync_requested"
10918
- ).then(this.splitRoutinesTask);
10919
- CadenzaService.createMetaTask("Get all actors", (ctx) => {
10920
- return {
10921
- ...ctx,
10922
- actors: CadenzaService.getAllActors()
10923
- };
10924
- }).doOn(
11160
+ ).doOn(
11161
+ "meta.service_registry.service_inserted",
11162
+ "meta.service_registry.instance_inserted",
10925
11163
  "meta.sync_controller.sync_tick",
10926
- "meta.service_registry.initial_sync_complete",
10927
11164
  "meta.sync_requested"
10928
- ).then(this.splitActorsForRegistration);
10929
- CadenzaService.createMetaTask("Get registered task for task graph sync", (ctx) => {
10930
- const task = ctx.task ?? (ctx.__taskName ? CadenzaService.get(ctx.__taskName) : void 0);
10931
- if (!task) {
10932
- return false;
11165
+ );
11166
+ const startTaskPrimitiveSyncTask = CadenzaService.createMetaTask(
11167
+ "Start task primitive sync",
11168
+ (ctx) => ctx,
11169
+ "Starts the task registration branch for the current sync cycle.",
11170
+ {
11171
+ register: false,
11172
+ isHidden: true
10933
11173
  }
10934
- return {
10935
- ...ctx,
10936
- task
10937
- };
10938
- }).doOn("meta.sync_controller.task_registered").then(
10939
- this.registerTaskMapTask,
10940
- this.registerDeputyRelationshipTask
10941
11174
  );
10942
- CadenzaService.registry.doForEachTask.clone().doOn(
10943
- "meta.sync_controller.synced_signals",
10944
- "meta.sync_controller.synced_tasks",
10945
- "meta.sync_requested"
10946
- ).then(this.registerSignalToTaskMapTask);
10947
- CadenzaService.createMetaTask("Get registered task for signal sync", (ctx) => {
10948
- const task = ctx.task ?? (ctx.__taskName ? CadenzaService.get(ctx.__taskName) : void 0);
10949
- if (!task) {
10950
- return false;
11175
+ const startSignalPrimitiveSyncTask = CadenzaService.createMetaTask(
11176
+ "Start signal primitive sync",
11177
+ (ctx) => ctx,
11178
+ "Starts the signal registration branch for the current sync cycle.",
11179
+ {
11180
+ register: false,
11181
+ isHidden: true
10951
11182
  }
10952
- return {
10953
- ...ctx,
10954
- task
10955
- };
10956
- }).doOn("meta.sync_controller.task_registered").then(this.registerSignalToTaskMapTask);
10957
- CadenzaService.registry.doForEachTask.clone().doOn(
10958
- "meta.sync_controller.synced_intents",
10959
- "meta.sync_controller.synced_tasks",
10960
- "meta.sync_requested"
10961
- ).then(this.registerIntentToTaskMapTask);
10962
- CadenzaService.createMetaTask("Get registered task for intent sync", (ctx) => {
10963
- const task = ctx.task ?? (ctx.__taskName ? CadenzaService.get(ctx.__taskName) : void 0);
10964
- if (!task) {
10965
- return false;
11183
+ );
11184
+ const startIntentPrimitiveSyncTask = CadenzaService.createMetaTask(
11185
+ "Start intent primitive sync",
11186
+ (ctx) => ctx,
11187
+ "Starts the intent registration branch for the current sync cycle.",
11188
+ {
11189
+ register: false,
11190
+ isHidden: true
10966
11191
  }
10967
- return {
11192
+ );
11193
+ const startActorPrimitiveSyncTask = CadenzaService.createMetaTask(
11194
+ "Start actor primitive sync",
11195
+ (ctx) => ctx,
11196
+ "Starts the actor registration branch for the current sync cycle.",
11197
+ {
11198
+ register: false,
11199
+ isHidden: true
11200
+ }
11201
+ );
11202
+ const startRoutinePrimitiveSyncTask = CadenzaService.createMetaTask(
11203
+ "Start routine primitive sync",
11204
+ (ctx) => ctx,
11205
+ "Starts the routine registration branch for the current sync cycle.",
11206
+ {
11207
+ register: false,
11208
+ isHidden: true
11209
+ }
11210
+ );
11211
+ startBootstrapSyncTask.then(
11212
+ startTaskPrimitiveSyncTask,
11213
+ startSignalPrimitiveSyncTask,
11214
+ startIntentPrimitiveSyncTask,
11215
+ startActorPrimitiveSyncTask,
11216
+ startRoutinePrimitiveSyncTask
11217
+ );
11218
+ const getAllTasksForSyncTask = CadenzaService.registry.getAllTasks.clone();
11219
+ startTaskPrimitiveSyncTask.then(
11220
+ getAllTasksForSyncTask,
11221
+ gatherTaskRegistrationTask
11222
+ );
11223
+ getAllTasksForSyncTask.then(this.splitTasksForRegistration);
11224
+ const getSignalsForSyncTask = CadenzaService.signalBroker.getSignalsTask.clone();
11225
+ startSignalPrimitiveSyncTask.then(
11226
+ getSignalsForSyncTask,
11227
+ gatherSignalRegistrationTask
11228
+ );
11229
+ getSignalsForSyncTask.then(this.splitSignalsTask);
11230
+ const getAllIntentsForSyncTask = CadenzaService.createUniqueMetaTask(
11231
+ "Get all intents for sync",
11232
+ (ctx) => ({
10968
11233
  ...ctx,
10969
- task
10970
- };
10971
- }).doOn("meta.sync_controller.task_registered").then(this.registerIntentToTaskMapTask);
10972
- CadenzaService.registry.doForEachTask.clone().doOn(
10973
- "meta.sync_controller.synced_actors",
10974
- "meta.sync_controller.synced_tasks",
10975
- "meta.sync_requested"
10976
- ).then(this.registerActorTaskMapTask);
10977
- CadenzaService.createMetaTask("Get registered task for actor sync", (ctx) => {
10978
- const task = ctx.task ?? (ctx.__taskName ? CadenzaService.get(ctx.__taskName) : void 0);
10979
- if (!task) {
10980
- return false;
11234
+ intents: Array.from(CadenzaService.inquiryBroker.intents.values())
11235
+ }),
11236
+ "Collects local intents for the primitive sync phase.",
11237
+ {
11238
+ register: false,
11239
+ isHidden: true
10981
11240
  }
10982
- return {
11241
+ );
11242
+ startIntentPrimitiveSyncTask.then(
11243
+ getAllIntentsForSyncTask,
11244
+ gatherIntentRegistrationTask
11245
+ );
11246
+ getAllIntentsForSyncTask.then(this.splitIntentsTask);
11247
+ const getAllActorsForSyncTask = CadenzaService.createUniqueMetaTask(
11248
+ "Get all actors for sync",
11249
+ (ctx) => ({
10983
11250
  ...ctx,
10984
- task
10985
- };
10986
- }).doOn("meta.sync_controller.task_registered").then(
10987
- CadenzaService.createMetaTask(
10988
- "Ensure actor and task sync ready from task registration",
10989
- (ctx) => {
10990
- if (!this.tasksSynced || !this.actorsSynced) {
10991
- return false;
10992
- }
10993
- return ctx;
10994
- }
10995
- ).then(this.registerActorTaskMapTask)
11251
+ actors: CadenzaService.getAllActors()
11252
+ }),
11253
+ "Collects local actors for the primitive sync phase.",
11254
+ {
11255
+ register: false,
11256
+ isHidden: true
11257
+ }
10996
11258
  );
10997
- CadenzaService.registry.getAllRoutines.clone().doOn(
10998
- "meta.sync_controller.synced_routines",
10999
- "meta.sync_controller.synced_tasks",
11000
- "meta.sync_requested"
11001
- ).then(
11002
- CadenzaService.createMetaTask(
11003
- "Ensure routine and task sync ready",
11004
- (ctx) => {
11005
- if (!this.tasksSynced || !this.routinesSynced) {
11006
- return false;
11007
- }
11008
- return ctx;
11009
- }
11010
- ).then(this.splitTasksInRoutines)
11259
+ startActorPrimitiveSyncTask.then(
11260
+ getAllActorsForSyncTask,
11261
+ gatherActorRegistrationTask
11011
11262
  );
11012
- CadenzaService.createMetaTask("Finish sync", (ctx, emit) => {
11013
- emit("global.meta.sync_controller.synced", {
11014
- data: {
11015
- is_active: true,
11016
- is_non_responsive: false,
11017
- is_blocked: false,
11018
- last_active: formatTimestamp(Date.now())
11019
- },
11020
- filter: {
11021
- uuid: CadenzaService.serviceRegistry.serviceInstanceId
11263
+ getAllActorsForSyncTask.then(this.splitActorsForRegistration);
11264
+ const getAllRoutinesForSyncTask = CadenzaService.registry.getAllRoutines.clone();
11265
+ startRoutinePrimitiveSyncTask.then(
11266
+ getAllRoutinesForSyncTask,
11267
+ gatherRoutineRegistrationTask
11268
+ );
11269
+ getAllRoutinesForSyncTask.then(this.splitRoutinesTask);
11270
+ const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
11271
+ startDirectionalTaskMapSyncTask.then(
11272
+ iterateTasksForDirectionalTaskMapSyncTask,
11273
+ gatherDirectionalTaskMapRegistrationTask
11274
+ );
11275
+ iterateTasksForDirectionalTaskMapSyncTask.then(
11276
+ this.registerTaskMapTask,
11277
+ this.registerDeputyRelationshipTask
11278
+ );
11279
+ recordTaskMapRegistrationTask.then(gatherDirectionalTaskMapRegistrationTask);
11280
+ recordDeputyRelationshipRegistrationTask.then(
11281
+ gatherDirectionalTaskMapRegistrationTask
11282
+ );
11283
+ gatherDirectionalTaskMapRegistrationTask.then(mapPhaseBarrierTask);
11284
+ const iterateTasksForSignalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
11285
+ startSignalTaskMapSyncTask.then(
11286
+ iterateTasksForSignalTaskMapSyncTask,
11287
+ gatherSignalTaskMapRegistrationTask
11288
+ );
11289
+ iterateTasksForSignalTaskMapSyncTask.then(this.registerSignalToTaskMapTask);
11290
+ registerSignalTask.then(gatherSignalTaskMapRegistrationTask);
11291
+ gatherSignalTaskMapRegistrationTask.then(mapPhaseBarrierTask);
11292
+ const iterateTasksForIntentTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
11293
+ startIntentTaskMapSyncTask.then(
11294
+ iterateTasksForIntentTaskMapSyncTask,
11295
+ gatherIntentTaskMapRegistrationTask
11296
+ );
11297
+ iterateTasksForIntentTaskMapSyncTask.then(this.registerIntentToTaskMapTask);
11298
+ registerIntentTask.then(gatherIntentTaskMapRegistrationTask);
11299
+ gatherIntentTaskMapRegistrationTask.then(mapPhaseBarrierTask);
11300
+ const iterateTasksForActorTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
11301
+ startActorTaskMapSyncTask.then(
11302
+ iterateTasksForActorTaskMapSyncTask,
11303
+ gatherActorTaskMapRegistrationTask
11304
+ );
11305
+ iterateTasksForActorTaskMapSyncTask.then(this.registerActorTaskMapTask);
11306
+ recordActorTaskMapRegistrationTask.then(gatherActorTaskMapRegistrationTask);
11307
+ gatherActorTaskMapRegistrationTask.then(mapPhaseBarrierTask);
11308
+ const getAllRoutinesForTaskMapSyncTask = CadenzaService.registry.getAllRoutines.clone();
11309
+ startRoutineTaskMapSyncTask.then(
11310
+ getAllRoutinesForTaskMapSyncTask,
11311
+ gatherRoutineTaskMapRegistrationTask
11312
+ );
11313
+ getAllRoutinesForTaskMapSyncTask.then(this.splitTasksInRoutines);
11314
+ registerTaskToRoutineMapTask.then(gatherRoutineTaskMapRegistrationTask);
11315
+ gatherRoutineTaskMapRegistrationTask.then(mapPhaseBarrierTask);
11316
+ CadenzaService.createMetaTask(
11317
+ "Request sync after local service instance registration",
11318
+ (ctx) => {
11319
+ for (const delayMs of EARLY_SYNC_TICK_DELAYS_MS) {
11320
+ CadenzaService.schedule(
11321
+ "meta.sync_controller.sync_tick",
11322
+ {
11323
+ ...buildMinimalSyncSignalContext(ctx),
11324
+ __syncing: true
11325
+ },
11326
+ delayMs
11327
+ );
11022
11328
  }
11023
- });
11024
- CadenzaService.log("Synced resources...");
11025
- }).attachSignal("global.meta.sync_controller.synced").doOn("meta.sync_controller.synced_resource");
11026
- if (!this.isCadenzaDBReady) {
11027
- CadenzaService.interval(
11028
- "meta.sync_controller.sync_tick",
11029
- { __syncing: true },
11030
- 3e5,
11031
- true
11032
- );
11033
- } else {
11034
- CadenzaService.interval(
11035
- "meta.sync_controller.sync_tick",
11036
- { __syncing: true },
11037
- 18e4
11038
- );
11039
- CadenzaService.schedule(
11040
- "meta.sync_controller.sync_tick",
11041
- { __syncing: true },
11042
- 250
11043
- );
11044
- for (const delayMs of EARLY_SYNC_REQUEST_DELAYS_MS) {
11045
- CadenzaService.schedule("meta.sync_requested", { __syncing: true }, delayMs);
11329
+ return true;
11330
+ },
11331
+ "Schedules the early bootstrap sync burst after local instance registration so startup-defined primitives can converge deterministically.",
11332
+ {
11333
+ register: false,
11334
+ isHidden: true
11046
11335
  }
11047
- }
11336
+ ).doOn("meta.service_registry.instance_inserted");
11337
+ CadenzaService.interval(
11338
+ "meta.sync_controller.sync_tick",
11339
+ { __syncing: true },
11340
+ this.isCadenzaDBReady ? 18e4 : 3e5
11341
+ );
11048
11342
  }
11049
11343
  };
11050
11344
 
@@ -11219,6 +11513,47 @@ function resolveBootstrapEndpoint(options) {
11219
11513
 
11220
11514
  // src/Cadenza.ts
11221
11515
  var CadenzaService = class {
11516
+ static replayRegisteredTaskIntentAssociations() {
11517
+ for (const task of this.registry.tasks.values()) {
11518
+ if (!task.register || task.isHidden || task.handlesIntents.size === 0) {
11519
+ continue;
11520
+ }
11521
+ for (const intentName of task.handlesIntents) {
11522
+ task.emitWithMetadata("meta.task.intent_associated", {
11523
+ data: {
11524
+ intentName,
11525
+ taskName: task.name,
11526
+ taskVersion: task.version
11527
+ },
11528
+ taskInstance: task,
11529
+ __isSubMeta: task.isSubMeta
11530
+ });
11531
+ }
11532
+ }
11533
+ }
11534
+ static replayRegisteredTaskSignalObservations() {
11535
+ for (const task of this.registry.tasks.values()) {
11536
+ if (!task.register || task.isHidden || task.observedSignals.size === 0) {
11537
+ continue;
11538
+ }
11539
+ for (const signalName of task.observedSignals) {
11540
+ task.emitWithMetadata("meta.task.observed_signal", {
11541
+ data: {
11542
+ signalName,
11543
+ taskName: task.name,
11544
+ taskVersion: task.version
11545
+ },
11546
+ taskInstance: task,
11547
+ signalName,
11548
+ __isSubMeta: task.isSubMeta
11549
+ });
11550
+ }
11551
+ }
11552
+ }
11553
+ static replayRegisteredTaskGraphMetadata() {
11554
+ this.replayRegisteredTaskSignalObservations();
11555
+ this.replayRegisteredTaskIntentAssociations();
11556
+ }
11222
11557
  static buildLegacyLocalCadenzaDBTaskName(tableName, operation) {
11223
11558
  const operationPrefix = operation.charAt(0).toUpperCase() + operation.slice(1);
11224
11559
  const helperSuffix = (0, import_lodash_es2.camelCase)(String(tableName ?? "").trim());
@@ -12087,6 +12422,7 @@ var CadenzaService = class {
12087
12422
  const serviceId = options.customServiceId ?? (0, import_uuid6.v4)();
12088
12423
  this.serviceRegistry.serviceName = serviceName;
12089
12424
  this.serviceRegistry.serviceInstanceId = serviceId;
12425
+ this.serviceRegistry.connectsToCadenzaDB = !!options.cadenzaDB?.connect;
12090
12426
  this.setHydrationResults(options.hydration);
12091
12427
  const explicitFrontendMode = options.isFrontend;
12092
12428
  options = {
@@ -12115,6 +12451,22 @@ var CadenzaService = class {
12115
12451
  this.serviceRegistry.useSocket = !!options.useSocket;
12116
12452
  this.serviceRegistry.retryCount = options.retryCount ?? 3;
12117
12453
  this.ensureTransportControllers(isFrontend);
12454
+ if (!isFrontend) {
12455
+ this.createMetaTask(
12456
+ "Initialize graph metadata controller after initial sync",
12457
+ () => {
12458
+ GraphMetadataController.instance;
12459
+ return true;
12460
+ },
12461
+ "Delays direct graph-metadata registration until the bootstrap sync has completed.",
12462
+ {
12463
+ register: false,
12464
+ isHidden: true
12465
+ }
12466
+ ).doOn("meta.service_registry.initial_sync_complete");
12467
+ GraphSyncController.instance.isCadenzaDBReady = serviceName === "CadenzaDB";
12468
+ GraphSyncController.instance.init();
12469
+ }
12118
12470
  const resolvedBootstrapEndpoint = options.cadenzaDB?.connect ? resolveBootstrapEndpoint({
12119
12471
  runtime: isFrontend ? "browser" : "server",
12120
12472
  bootstrap: options.bootstrap,
@@ -12226,14 +12578,13 @@ var CadenzaService = class {
12226
12578
  );
12227
12579
  }).doOn("meta.rest.handshake", "meta.socket.handshake");
12228
12580
  }
12229
- this.createMetaTask("Handle service setup completion", () => {
12581
+ this.createMetaTask("Handle service setup completion", (ctx, emit) => {
12582
+ if (options.cadenzaDB?.connect) {
12583
+ this.serviceRegistry.bootstrapFullSync(emit, ctx, "service_setup_completed");
12584
+ }
12230
12585
  if (isFrontend) {
12231
12586
  registerActorSessionPersistenceTasks();
12232
12587
  this.ensureFrontendSyncLoop();
12233
- } else {
12234
- GraphMetadataController.instance;
12235
- GraphSyncController.instance.isCadenzaDBReady = serviceName === "CadenzaDB" || !!options.cadenzaDB?.connect;
12236
- GraphSyncController.instance.init();
12237
12588
  }
12238
12589
  this.log("Service created.");
12239
12590
  return true;
@@ -12262,7 +12613,15 @@ var CadenzaService = class {
12262
12613
  is_blocked: false,
12263
12614
  health: {}
12264
12615
  },
12265
- __transportData: [],
12616
+ __transportData: declaredTransports.map((transport) => ({
12617
+ uuid: transport.uuid,
12618
+ service_instance_id: serviceId,
12619
+ role: transport.role,
12620
+ origin: transport.origin,
12621
+ protocols: transport.protocols ?? ["rest", "socket"],
12622
+ ...transport.securityProfile ? { security_profile: transport.securityProfile } : {},
12623
+ ...transport.authStrategy ? { auth_strategy: transport.authStrategy } : {}
12624
+ })),
12266
12625
  __serviceName: serviceName,
12267
12626
  __serviceInstanceId: serviceId,
12268
12627
  __useSocket: options.useSocket,