@cadenza.io/service 2.18.0 → 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.mjs CHANGED
@@ -686,6 +686,21 @@ var CADENZA_DB_GATHERED_SYNC_SIGNAL = "global.meta.cadenza_db.gathered_sync_data
686
686
  var META_GATHERED_SYNC_TRANSMISSION_RECONCILE_SIGNAL = "meta.service_registry.gathered_sync_transmission_reconcile_requested";
687
687
  var META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL = "meta.service_registry.runtime_status.heartbeat_tick";
688
688
  var META_RUNTIME_STATUS_MONITOR_TICK_SIGNAL = "meta.service_registry.runtime_status.monitor_tick";
689
+ var EARLY_FULL_SYNC_DELAYS_MS = [
690
+ 100,
691
+ 1500,
692
+ 5e3,
693
+ 12e3,
694
+ 25e3,
695
+ 45e3,
696
+ 7e4
697
+ ];
698
+ var BOOTSTRAP_FULL_SYNC_RESPONDER_TASKS = [
699
+ "Query service_instance",
700
+ "Query service_instance_transport",
701
+ "Query signal_to_task_map",
702
+ "Query intent_to_task_map"
703
+ ];
689
704
  var INTERNAL_RUNTIME_STATUS_TASK_NAMES = /* @__PURE__ */ new Set([
690
705
  "Track local routine start",
691
706
  "Track local routine end",
@@ -827,6 +842,18 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
827
842
  ctx.__resolverQueryData ?? ctx.queryData ?? {},
828
843
  ctx
829
844
  );
845
+ if (tableName === "service_instance" && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
846
+ console.log("[CADENZA_INSTANCE_DEBUG] finalize_service_registry_insert", {
847
+ tableName,
848
+ hasNormalized: !!normalized,
849
+ normalizedKeys: normalized && typeof normalized === "object" ? Object.keys(normalized) : [],
850
+ uuid: normalized && typeof normalized === "object" ? normalized.uuid ?? normalized.data?.uuid ?? normalized.queryData?.data?.uuid ?? null : null,
851
+ serviceName: normalized && typeof normalized === "object" ? normalized.__serviceName ?? normalized.data?.service_name ?? normalized.queryData?.data?.service_name ?? null : null,
852
+ errored: normalized && typeof normalized === "object" ? normalized.errored === true : false,
853
+ error: normalized && typeof normalized === "object" ? normalized.__error ?? null : null,
854
+ inquiryMeta: normalized && typeof normalized === "object" ? normalized.__inquiryMeta ?? null : null
855
+ });
856
+ }
830
857
  if (!normalized || typeof normalized !== "object") {
831
858
  return normalized;
832
859
  }
@@ -871,6 +898,18 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
871
898
  ).doOn(executionResolvedSignal, executionFailedSignal);
872
899
  const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
873
900
  const executionSignal = localInsertTask ? localExecutionRequestedSignal : remoteExecutionRequestedSignal;
901
+ if (tableName === "service_instance" && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
902
+ console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert", {
903
+ tableName,
904
+ executionSignal,
905
+ hasLocalInsertTask: !!localInsertTask,
906
+ serviceName: ctx.__serviceName ?? ctx.data?.service_name ?? null,
907
+ serviceInstanceId: ctx.__serviceInstanceId ?? ctx.data?.uuid ?? null,
908
+ hasData: !!ctx.data,
909
+ dataKeys: ctx.data && typeof ctx.data === "object" ? Object.keys(ctx.data) : [],
910
+ registrationKeys: ctx.__registrationData && typeof ctx.__registrationData === "object" ? Object.keys(ctx.__registrationData) : []
911
+ });
912
+ }
874
913
  if (localInsertTask && !wiredLocalTaskNames.has(localInsertTask.name)) {
875
914
  wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
876
915
  wiredLocalTaskNames.add(localInsertTask.name);
@@ -953,6 +992,7 @@ var ServiceRegistry = class _ServiceRegistry {
953
992
  this.useSocket = false;
954
993
  this.retryCount = 3;
955
994
  this.isFrontend = false;
995
+ this.connectsToCadenzaDB = false;
956
996
  CadenzaService.defineIntent({
957
997
  name: META_RUNTIME_TRANSPORT_DIAGNOSTICS_INTENT,
958
998
  description: "Gather transport diagnostics across all services and communication clients.",
@@ -1327,7 +1367,10 @@ var ServiceRegistry = class _ServiceRegistry {
1327
1367
  return true;
1328
1368
  },
1329
1369
  "Handles registration of remote signals"
1330
- ).emits("meta.service_registry.registered_global_signals").doOn("global.meta.cadenza_db.gathered_sync_data");
1370
+ ).emits("meta.service_registry.registered_global_signals").doOn(
1371
+ "global.meta.cadenza_db.gathered_sync_data",
1372
+ "global.meta.graph_metadata.task_signal_observed"
1373
+ );
1331
1374
  this.reconcileGatheredSyncTransmissionsTask = CadenzaService.createMetaTask(
1332
1375
  "Reconcile gathered sync signal transmissions",
1333
1376
  (ctx, emit) => this.reconcileGatheredSyncTransmissions(ctx, emit),
@@ -1481,7 +1524,7 @@ var ServiceRegistry = class _ServiceRegistry {
1481
1524
  );
1482
1525
  this.handleSocketStatusUpdateTask = CadenzaService.createMetaTask(
1483
1526
  "Handle Socket Status Update",
1484
- (ctx) => {
1527
+ (ctx, emit) => {
1485
1528
  const report = this.normalizeRuntimeStatusReport(ctx);
1486
1529
  if (!report) {
1487
1530
  return false;
@@ -1524,6 +1567,13 @@ var ServiceRegistry = class _ServiceRegistry {
1524
1567
  if (!applied) {
1525
1568
  return false;
1526
1569
  }
1570
+ const updatedInstance = this.getInstance(
1571
+ report.serviceName,
1572
+ report.serviceInstanceId
1573
+ );
1574
+ if (updatedInstance && !updatedInstance.isFrontend && (this.deputies.has(report.serviceName) || this.remoteIntents.has(report.serviceName) || this.remoteSignals.has(report.serviceName))) {
1575
+ this.ensureDependeeClientForInstance(updatedInstance, emit, ctx);
1576
+ }
1527
1577
  this.registerDependee(report.serviceName, report.serviceInstanceId);
1528
1578
  this.lastHeartbeatAtByInstance.set(report.serviceInstanceId, Date.now());
1529
1579
  this.missedHeartbeatsByInstance.set(report.serviceInstanceId, 0);
@@ -1534,9 +1584,23 @@ var ServiceRegistry = class _ServiceRegistry {
1534
1584
  },
1535
1585
  "Handles status update from socket broadcast"
1536
1586
  ).doOn("meta.socket_client.status_received");
1587
+ CadenzaService.createMetaTask(
1588
+ "Request full sync after CadenzaDB fetch handshake",
1589
+ (ctx) => {
1590
+ const serviceName = typeof ctx.serviceName === "string" ? ctx.serviceName.trim() : typeof ctx.__serviceName === "string" ? ctx.__serviceName.trim() : "";
1591
+ if (serviceName !== "CadenzaDB") {
1592
+ return false;
1593
+ }
1594
+ return this.scheduleEarlyFullSyncRequests("cadenza_db_fetch_handshake");
1595
+ },
1596
+ "Schedules a few early service-registry full-sync retries after the authority fetch transport comes up."
1597
+ ).doOn("meta.fetch.handshake_complete");
1537
1598
  this.fullSyncTask = CadenzaService.createMetaTask(
1538
1599
  "Full sync",
1539
1600
  async (ctx) => {
1601
+ if (this.connectsToCadenzaDB && this.serviceName !== "CadenzaDB" && !this.hasBootstrapFullSyncDeputies()) {
1602
+ return false;
1603
+ }
1540
1604
  const inquiryResult = await CadenzaService.inquire(
1541
1605
  META_SERVICE_REGISTRY_FULL_SYNC_INTENT,
1542
1606
  {
@@ -1593,7 +1657,7 @@ var ServiceRegistry = class _ServiceRegistry {
1593
1657
  );
1594
1658
  this.handleDeputyRegistrationTask = CadenzaService.createMetaTask(
1595
1659
  "Handle Deputy Registration",
1596
- (ctx) => {
1660
+ (ctx, emit) => {
1597
1661
  const { serviceName } = ctx;
1598
1662
  if (!this.deputies.has(serviceName)) this.deputies.set(serviceName, []);
1599
1663
  this.deputies.get(serviceName).push({
@@ -1603,6 +1667,7 @@ var ServiceRegistry = class _ServiceRegistry {
1603
1667
  localTaskName: ctx.localTaskName,
1604
1668
  communicationType: ctx.communicationType
1605
1669
  });
1670
+ this.ensureDependeeClientsForService(serviceName, emit, ctx);
1606
1671
  }
1607
1672
  ).doOn("meta.deputy.created");
1608
1673
  this.getAllInstances = CadenzaService.createMetaTask(
@@ -2155,9 +2220,29 @@ var ServiceRegistry = class _ServiceRegistry {
2155
2220
  retryDelayFactor: 1.3
2156
2221
  }
2157
2222
  ).emits("meta.service_registry.service_inserted").emitsOnFail("meta.service_registry.service_insertion_failed");
2158
- this.insertServiceInstanceTask = resolveServiceRegistryInsertTask(
2223
+ const insertServiceInstanceResolverTask = resolveServiceRegistryInsertTask(
2159
2224
  "service_instance",
2160
- {},
2225
+ {
2226
+ onConflict: {
2227
+ target: ["uuid"],
2228
+ action: {
2229
+ do: "update",
2230
+ set: {
2231
+ process_pid: "excluded",
2232
+ is_primary: "excluded",
2233
+ service_name: "excluded",
2234
+ is_database: "excluded",
2235
+ is_frontend: "excluded",
2236
+ is_blocked: "excluded",
2237
+ is_non_responsive: "excluded",
2238
+ is_active: "excluded",
2239
+ last_active: "excluded",
2240
+ health: "excluded",
2241
+ deleted: "false"
2242
+ }
2243
+ }
2244
+ }
2245
+ },
2161
2246
  {
2162
2247
  inputSchema: {
2163
2248
  type: "object",
@@ -2213,7 +2298,8 @@ var ServiceRegistry = class _ServiceRegistry {
2213
2298
  retryCount: 5,
2214
2299
  retryDelay: 1e3
2215
2300
  }
2216
- ).then(
2301
+ ).emitsOnFail("meta.service_registry.instance_insertion_failed");
2302
+ this.insertServiceInstanceTask = insertServiceInstanceResolverTask.then(
2217
2303
  CadenzaService.createMetaTask(
2218
2304
  "Setup service",
2219
2305
  (ctx) => {
@@ -2230,6 +2316,21 @@ var ServiceRegistry = class _ServiceRegistry {
2230
2316
  transports: ctx.__transportData ?? ctx.transportData ?? []
2231
2317
  });
2232
2318
  if (!normalizedLocalInstance?.uuid || !normalizedLocalInstance.serviceName) {
2319
+ if (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") {
2320
+ console.log("[CADENZA_INSTANCE_DEBUG] setup_service_rejected_instance", {
2321
+ hasServiceInstance: !!serviceInstance,
2322
+ hasData: !!data,
2323
+ hasQueryDataData: !!queryData?.data,
2324
+ serviceInstanceKeys: serviceInstance && typeof serviceInstance === "object" ? Object.keys(serviceInstance) : [],
2325
+ dataKeys: data && typeof data === "object" ? Object.keys(data) : [],
2326
+ queryDataDataKeys: queryData?.data && typeof queryData.data === "object" ? Object.keys(queryData.data) : [],
2327
+ normalizedLocalInstance,
2328
+ transportCount: Array.isArray(ctx.__transportData) ? ctx.__transportData.length : Array.isArray(ctx.transportData) ? ctx.transportData.length : 0,
2329
+ errored: ctx.errored === true,
2330
+ error: ctx.__error ?? null,
2331
+ inquiryMeta: ctx.__inquiryMeta ?? null
2332
+ });
2333
+ }
2233
2334
  return false;
2234
2335
  }
2235
2336
  this.serviceInstanceId = normalizedLocalInstance.uuid;
@@ -2281,9 +2382,41 @@ var ServiceRegistry = class _ServiceRegistry {
2281
2382
  ).attachSignal("meta.service_registry.transport_registration_requested")
2282
2383
  )
2283
2384
  );
2385
+ CadenzaService.createMetaTask(
2386
+ "Retry local service instance registration after failed insert",
2387
+ (ctx) => {
2388
+ const serviceName = String(
2389
+ ctx.__serviceName ?? ctx.data?.service_name ?? this.serviceName ?? ""
2390
+ ).trim();
2391
+ if (!serviceName || serviceName !== this.serviceName) {
2392
+ return false;
2393
+ }
2394
+ CadenzaService.schedule(
2395
+ "meta.service_registry.instance_registration_requested",
2396
+ { ...ctx },
2397
+ 5e3
2398
+ );
2399
+ return true;
2400
+ },
2401
+ "Retries local service instance registration only after the previous insert attempt has failed.",
2402
+ {
2403
+ register: false,
2404
+ isHidden: true
2405
+ }
2406
+ ).doOn("meta.service_registry.instance_insertion_failed");
2284
2407
  CadenzaService.createMetaTask(
2285
2408
  "Prepare service instance registration",
2286
2409
  (ctx) => {
2410
+ if (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") {
2411
+ console.log("[CADENZA_INSTANCE_DEBUG] prepare_service_instance_registration", {
2412
+ serviceName: ctx.data?.service_name ?? ctx.__serviceName ?? this.serviceName ?? null,
2413
+ serviceInstanceId: ctx.data?.uuid ?? ctx.__serviceInstanceId ?? this.serviceInstanceId ?? null,
2414
+ hasData: !!ctx.data,
2415
+ dataKeys: ctx.data && typeof ctx.data === "object" ? Object.keys(ctx.data) : [],
2416
+ transportCount: Array.isArray(ctx.__transportData) ? ctx.__transportData.length : Array.isArray(ctx.transportData) ? ctx.transportData.length : 0,
2417
+ skipRemoteExecution: ctx.__skipRemoteExecution === true
2418
+ });
2419
+ }
2287
2420
  const serviceName = String(
2288
2421
  ctx.data?.service_name ?? ctx.__serviceName ?? this.serviceName ?? ""
2289
2422
  ).trim();
@@ -2476,21 +2609,40 @@ var ServiceRegistry = class _ServiceRegistry {
2476
2609
  return [];
2477
2610
  }
2478
2611
  normalizeSignalMaps(ctx) {
2479
- return this.readArrayPayload(ctx, [
2612
+ const arrayPayload = this.readArrayPayload(ctx, [
2480
2613
  "signalToTaskMaps",
2481
2614
  "signal_to_task_maps",
2482
2615
  "signalToTaskMap",
2483
2616
  "signal_to_task_map"
2484
- ]).map((map) => ({
2485
- signalName: String(
2486
- map.signalName ?? map.signal_name ?? ""
2487
- ).trim(),
2488
- serviceName: String(
2489
- map.serviceName ?? map.service_name ?? ""
2490
- ).trim(),
2491
- isGlobal: Boolean(map.isGlobal ?? map.is_global ?? false),
2492
- deleted: Boolean(map.deleted)
2493
- })).filter((map) => map.signalName && map.serviceName);
2617
+ ]);
2618
+ if (arrayPayload.length > 0) {
2619
+ return arrayPayload.map((map) => ({
2620
+ signalName: String(
2621
+ map.signalName ?? map.signal_name ?? ""
2622
+ ).trim(),
2623
+ serviceName: String(
2624
+ map.serviceName ?? map.service_name ?? ""
2625
+ ).trim(),
2626
+ isGlobal: Boolean(map.isGlobal ?? map.is_global ?? false),
2627
+ deleted: Boolean(map.deleted)
2628
+ })).filter((map) => map.signalName && map.serviceName);
2629
+ }
2630
+ const single = ctx.signalToTaskMap ?? ctx.signal_to_task_map ?? ctx.data ?? (ctx.signalName ?? ctx.signal_name ? ctx : void 0);
2631
+ if (!single || typeof single !== "object") {
2632
+ return [];
2633
+ }
2634
+ return [
2635
+ {
2636
+ signalName: String(
2637
+ single.signalName ?? single.signal_name ?? ""
2638
+ ).trim(),
2639
+ serviceName: String(
2640
+ single.serviceName ?? single.service_name ?? ""
2641
+ ).trim(),
2642
+ isGlobal: Boolean(single.isGlobal ?? single.is_global ?? false),
2643
+ deleted: Boolean(single.deleted)
2644
+ }
2645
+ ].filter((map) => map.signalName && map.serviceName);
2494
2646
  }
2495
2647
  normalizeIntentMaps(ctx) {
2496
2648
  const arrayPayload = this.readArrayPayload(ctx, [
@@ -2605,7 +2757,7 @@ var ServiceRegistry = class _ServiceRegistry {
2605
2757
  )?.destroy();
2606
2758
  this.gatheredSyncTransmissionServices.delete(serviceName);
2607
2759
  }
2608
- if (createdRecipients.length > 0 && ctx.__signalName === CADENZA_DB_GATHERED_SYNC_SIGNAL) {
2760
+ if (createdRecipients.length > 0) {
2609
2761
  emit("meta.cadenza_db.sync_tick", {
2610
2762
  __syncing: true,
2611
2763
  __reason: "gathered_sync_transmissions_reconciled"
@@ -2680,6 +2832,56 @@ var ServiceRegistry = class _ServiceRegistry {
2680
2832
  }
2681
2833
  }
2682
2834
  }
2835
+ registerBootstrapFullSyncDeputies(emit, ctx) {
2836
+ if (!this.serviceName || this.serviceName === "CadenzaDB") {
2837
+ return false;
2838
+ }
2839
+ CadenzaService.inquiryBroker.addIntent({
2840
+ name: META_SERVICE_REGISTRY_FULL_SYNC_INTENT
2841
+ });
2842
+ for (const taskName of BOOTSTRAP_FULL_SYNC_RESPONDER_TASKS) {
2843
+ this.registerRemoteIntentDeputy({
2844
+ intentName: META_SERVICE_REGISTRY_FULL_SYNC_INTENT,
2845
+ serviceName: "CadenzaDB",
2846
+ taskName,
2847
+ taskVersion: 1
2848
+ });
2849
+ }
2850
+ this.ensureDependeeClientsForService("CadenzaDB", emit, ctx);
2851
+ return true;
2852
+ }
2853
+ hasBootstrapFullSyncDeputies() {
2854
+ if (!this.serviceName || this.serviceName === "CadenzaDB") {
2855
+ return true;
2856
+ }
2857
+ return BOOTSTRAP_FULL_SYNC_RESPONDER_TASKS.every(
2858
+ (taskName) => this.remoteIntentDeputiesByKey.has(
2859
+ this.buildRemoteIntentDeputyKey({
2860
+ intentName: META_SERVICE_REGISTRY_FULL_SYNC_INTENT,
2861
+ serviceName: "CadenzaDB",
2862
+ taskName,
2863
+ taskVersion: 1
2864
+ })
2865
+ )
2866
+ );
2867
+ }
2868
+ scheduleEarlyFullSyncRequests(reason) {
2869
+ for (const delayMs of EARLY_FULL_SYNC_DELAYS_MS) {
2870
+ CadenzaService.schedule(
2871
+ "meta.sync_requested",
2872
+ {
2873
+ __syncing: false,
2874
+ __reason: reason
2875
+ },
2876
+ delayMs
2877
+ );
2878
+ }
2879
+ return true;
2880
+ }
2881
+ bootstrapFullSync(emit, ctx, reason = "local_instance_inserted") {
2882
+ this.registerBootstrapFullSyncDeputies(emit, ctx);
2883
+ return this.scheduleEarlyFullSyncRequests(reason);
2884
+ }
2683
2885
  getInquiryResponderDescriptor(task) {
2684
2886
  const remote = this.remoteIntentDeputiesByTask.get(task);
2685
2887
  if (remote) {
@@ -2708,6 +2910,9 @@ var ServiceRegistry = class _ServiceRegistry {
2708
2910
  }
2709
2911
  return this.getInstance(this.serviceName, this.serviceInstanceId);
2710
2912
  }
2913
+ hasLocalInstanceRegistered() {
2914
+ return Boolean(this.getLocalInstance());
2915
+ }
2711
2916
  summarizeTransportForDebug(transport) {
2712
2917
  if (!transport) {
2713
2918
  return void 0;
@@ -3705,6 +3910,7 @@ import fs from "fs";
3705
3910
  import https from "https";
3706
3911
  import fetch from "node-fetch";
3707
3912
  import { v4 as uuid5 } from "uuid";
3913
+ var FETCH_HANDSHAKE_TIMEOUT_MS = 5e3;
3708
3914
  var RestController = class _RestController {
3709
3915
  /**
3710
3916
  * Constructor for initializing the REST server and related configurations.
@@ -3796,7 +4002,15 @@ var RestController = class _RestController {
3796
4002
  is_blocked: false,
3797
4003
  health: {}
3798
4004
  },
3799
- __transportData: []
4005
+ __transportData: Array.isArray(ctx.__declaredTransports) ? ctx.__declaredTransports.map((transport) => ({
4006
+ uuid: transport.uuid,
4007
+ service_instance_id: ctx.__serviceInstanceId,
4008
+ role: transport.role,
4009
+ origin: transport.origin,
4010
+ protocols: transport.protocols ?? ["rest", "socket"],
4011
+ ...transport.securityProfile ? { security_profile: transport.securityProfile } : {},
4012
+ ...transport.authStrategy ? { auth_strategy: transport.authStrategy } : {}
4013
+ })) : []
3800
4014
  });
3801
4015
  return;
3802
4016
  }
@@ -4128,6 +4342,19 @@ var RestController = class _RestController {
4128
4342
  ...ctx.data
4129
4343
  };
4130
4344
  ctx.__transportData = transportData;
4345
+ if (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") {
4346
+ console.log("[CADENZA_INSTANCE_DEBUG] configure_network_emit", {
4347
+ serviceName: ctx.__serviceName,
4348
+ serviceInstanceId: ctx.__serviceInstanceId,
4349
+ isDatabase: ctx.__isDatabase === true,
4350
+ transportCount: transportData.length,
4351
+ transports: transportData.map((transport) => ({
4352
+ role: transport.role,
4353
+ origin: transport.origin,
4354
+ protocols: transport.protocols
4355
+ }))
4356
+ });
4357
+ }
4131
4358
  delete ctx.__app;
4132
4359
  CadenzaService.emit(
4133
4360
  "meta.service_registry.instance_registration_requested",
@@ -4188,6 +4415,7 @@ var RestController = class _RestController {
4188
4415
  if (!serviceName || !URL2 || !fetchId) {
4189
4416
  return false;
4190
4417
  }
4418
+ const clientTaskSuffix = `${URL2} (${fetchId})`;
4191
4419
  const fetchDiagnostics = this.ensureFetchClientDiagnostics(
4192
4420
  fetchId,
4193
4421
  serviceName,
@@ -4195,12 +4423,12 @@ var RestController = class _RestController {
4195
4423
  );
4196
4424
  fetchDiagnostics.destroyed = false;
4197
4425
  fetchDiagnostics.updatedAt = Date.now();
4198
- if (CadenzaService.get(`Send Handshake to ${URL2}`)) {
4199
- console.error("Fetch client already exists", URL2);
4426
+ if (CadenzaService.get(`Send Handshake to ${clientTaskSuffix}`)) {
4427
+ console.error("Fetch client already exists", { URL: URL2, fetchId });
4200
4428
  return;
4201
4429
  }
4202
4430
  const handshakeTask = CadenzaService.createMetaTask(
4203
- `Send Handshake to ${URL2}`,
4431
+ `Send Handshake to ${clientTaskSuffix}`,
4204
4432
  async (ctx2, emit) => {
4205
4433
  try {
4206
4434
  const response = await this.fetchDataWithTimeout(
@@ -4212,7 +4440,7 @@ var RestController = class _RestController {
4212
4440
  method: "POST",
4213
4441
  body: JSON.stringify(ctx2.handshakeData)
4214
4442
  },
4215
- 1e3
4443
+ FETCH_HANDSHAKE_TIMEOUT_MS
4216
4444
  );
4217
4445
  if (response.__status !== "success") {
4218
4446
  const error = response.__error ?? `Failed to connect to service ${serviceName} ${ctx2.serviceInstanceId}`;
@@ -4269,7 +4497,7 @@ var RestController = class _RestController {
4269
4497
  "global.meta.fetch.service_communication_established"
4270
4498
  );
4271
4499
  const delegateTask = CadenzaService.createMetaTask(
4272
- `Delegate flow to REST server ${URL2}`,
4500
+ `Delegate flow to REST server ${clientTaskSuffix}`,
4273
4501
  async (ctx2, emit) => {
4274
4502
  if (ctx2.__remoteRoutineName === void 0) {
4275
4503
  return;
@@ -4323,7 +4551,7 @@ var RestController = class _RestController {
4323
4551
  `meta.service_registry.socket_failed:${fetchId}`
4324
4552
  ).emitsOnFail("meta.fetch.delegate_failed").attachSignal("meta.fetch.delegated");
4325
4553
  const transmitTask = CadenzaService.createMetaTask(
4326
- `Transmit signal to server ${URL2}`,
4554
+ `Transmit signal to server ${clientTaskSuffix}`,
4327
4555
  async (ctx2, emit) => {
4328
4556
  if (ctx2.__signalName === void 0) {
4329
4557
  return;
@@ -4376,7 +4604,7 @@ var RestController = class _RestController {
4376
4604
  "meta.signal_controller.wildcard_signal_registered"
4377
4605
  ).emitsOnFail("meta.fetch.signal_transmission_failed").attachSignal("meta.fetch.transmitted");
4378
4606
  const statusTask = CadenzaService.createMetaTask(
4379
- `Request status from ${URL2}`,
4607
+ `Request status from ${clientTaskSuffix}`,
4380
4608
  async (ctx2) => {
4381
4609
  fetchDiagnostics.statusChecks++;
4382
4610
  fetchDiagnostics.updatedAt = Date.now();
@@ -4413,7 +4641,7 @@ var RestController = class _RestController {
4413
4641
  },
4414
4642
  "Requests status"
4415
4643
  ).doOn("meta.fetch.status_check_requested").emits("meta.fetch.status_checked").emitsOnFail("meta.fetch.status_check_failed");
4416
- CadenzaService.createEphemeralMetaTask("Destroy fetch client", () => {
4644
+ CadenzaService.createEphemeralMetaTask(`Destroy fetch client ${fetchId}`, () => {
4417
4645
  fetchDiagnostics.connected = false;
4418
4646
  fetchDiagnostics.destroyed = true;
4419
4647
  fetchDiagnostics.updatedAt = Date.now();
@@ -6731,6 +6959,12 @@ var GraphMetadataController = class _GraphMetadataController {
6731
6959
  }
6732
6960
  );
6733
6961
  }).doOn("meta.task.attached_signal").emits("global.meta.graph_metadata.task_attached_signal");
6962
+ CadenzaService.createMetaTask("Handle task intent association", (ctx) => {
6963
+ return buildDatabaseTriggerContext({
6964
+ ...ctx.data,
6965
+ serviceName: CadenzaService.serviceRegistry.serviceName
6966
+ });
6967
+ }).doOn("meta.task.intent_associated").emits("global.meta.graph_metadata.task_intent_associated");
6734
6968
  CadenzaService.createMetaTask("Handle task unsubscribing signal", (ctx) => {
6735
6969
  return buildDatabaseTriggerContext(
6736
6970
  {
@@ -6948,6 +7182,7 @@ var AUTHORITY_SYNC_DEBUG_TASK_NAMES = /* @__PURE__ */ new Set([
6948
7182
  "Prepare for signal sync"
6949
7183
  ]);
6950
7184
  var AUTHORITY_SYNC_DEBUG_ROUTINE_NAMES = /* @__PURE__ */ new Set(["Sync services"]);
7185
+ var INTENT_MAP_DEBUG_ENABLED = process.env.CADENZA_INTENT_MAP_DEBUG === "1" || process.env.CADENZA_INTENT_MAP_DEBUG === "true";
6951
7186
  function logAuthoritySyncDebug(event, payload) {
6952
7187
  if (!AUTHORITY_SYNC_DEBUG_ENABLED) {
6953
7188
  return;
@@ -6987,6 +7222,12 @@ function shouldDebugAuthoritySyncPayload(tableName, payload) {
6987
7222
  }
6988
7223
  return false;
6989
7224
  }
7225
+ function logIntentMapSetupDebug(event, payload) {
7226
+ if (!INTENT_MAP_DEBUG_ENABLED) {
7227
+ return;
7228
+ }
7229
+ console.log("[CADENZA_INTENT_MAP_DEBUG]", event, payload);
7230
+ }
6990
7231
  function buildAuthoritySyncDebugSummary(payload, context) {
6991
7232
  const data = payload.data && typeof payload.data === "object" && !Array.isArray(payload.data) ? payload.data : {};
6992
7233
  return {
@@ -7008,6 +7249,9 @@ function normalizeIntentToken(value) {
7008
7249
  }
7009
7250
  return normalized;
7010
7251
  }
7252
+ function shouldValidateGeneratedDbTaskInput(registration) {
7253
+ return registration.options.securityProfile !== "low" && !registration.options.isMeta;
7254
+ }
7011
7255
  function buildPostgresActorName(name) {
7012
7256
  return `${String(name ?? "").trim()}PostgresActor`;
7013
7257
  }
@@ -7468,6 +7712,18 @@ var DatabaseController = class _DatabaseController {
7468
7712
  if (!registration.tasksGenerated) {
7469
7713
  this.generateDatabaseTasks(registration);
7470
7714
  registration.tasksGenerated = true;
7715
+ const localTasks = Array.from(CadenzaService.registry.tasks.values());
7716
+ logIntentMapSetupDebug("generated_database_tasks", {
7717
+ actorName: registration.actorName,
7718
+ ownerServiceName: registration.ownerServiceName,
7719
+ totalLocalTasks: localTasks.length,
7720
+ generatedTaskNames: localTasks.map((task) => task.name).filter(
7721
+ (taskName) => /(Query|Insert|Update|Delete|COUNT|EXISTS|ONE|AGGREGATE|UPSERT) /.test(
7722
+ taskName
7723
+ )
7724
+ ).slice(0, 24)
7725
+ });
7726
+ CadenzaService.schedule("meta.sync_requested", { __syncing: true }, 250);
7471
7727
  }
7472
7728
  const nowIso = (/* @__PURE__ */ new Date()).toISOString();
7473
7729
  setRuntimeState({
@@ -8273,7 +8529,7 @@ var DatabaseController = class _DatabaseController {
8273
8529
  {
8274
8530
  isMeta: registration.options.isMeta,
8275
8531
  isSubMeta: registration.options.isMeta,
8276
- validateInputContext: registration.options.securityProfile !== "low",
8532
+ validateInputContext: shouldValidateGeneratedDbTaskInput(registration),
8277
8533
  inputSchema: querySchema
8278
8534
  }
8279
8535
  ).respondsTo(intentName);
@@ -8316,7 +8572,7 @@ var DatabaseController = class _DatabaseController {
8316
8572
  {
8317
8573
  isMeta: registration.options.isMeta,
8318
8574
  isSubMeta: registration.options.isMeta,
8319
- validateInputContext: registration.options.securityProfile !== "low",
8575
+ validateInputContext: shouldValidateGeneratedDbTaskInput(registration),
8320
8576
  inputSchema: insertSchema
8321
8577
  }
8322
8578
  ).respondsTo(upsertIntentName);
@@ -8457,7 +8713,7 @@ var DatabaseController = class _DatabaseController {
8457
8713
  {
8458
8714
  isMeta: registration.options.isMeta,
8459
8715
  isSubMeta: registration.options.isMeta,
8460
- validateInputContext: registration.options.securityProfile !== "low",
8716
+ validateInputContext: shouldValidateGeneratedDbTaskInput(registration),
8461
8717
  inputSchema: schema
8462
8718
  }
8463
8719
  ).doOn(
@@ -9192,34 +9448,7 @@ function buildSyncInsertQueryData(ctx, queryData = {}) {
9192
9448
  }
9193
9449
  return nextQueryData;
9194
9450
  }
9195
- function buildSyncQueryQueryData(ctx, queryData = {}) {
9196
- const joinedQueryData = getJoinedContextValue(ctx, "queryData");
9197
- const existingQueryData = ctx.queryData && typeof ctx.queryData === "object" ? ctx.queryData : joinedQueryData && typeof joinedQueryData === "object" ? joinedQueryData : {};
9198
- const nextQueryData = {};
9199
- const allowedKeys = [
9200
- "transaction",
9201
- "filter",
9202
- "fields",
9203
- "joins",
9204
- "sort",
9205
- "limit",
9206
- "offset",
9207
- "queryMode",
9208
- "aggregates",
9209
- "groupBy"
9210
- ];
9211
- for (const key of allowedKeys) {
9212
- if (Object.prototype.hasOwnProperty.call(existingQueryData, key)) {
9213
- nextQueryData[key] = existingQueryData[key];
9214
- }
9215
- }
9216
- return {
9217
- ...nextQueryData,
9218
- ...queryData
9219
- };
9220
- }
9221
9451
  var REMOTE_AUTHORITY_SYNC_INSERT_CONCURRENCY = 5;
9222
- var REMOTE_AUTHORITY_SYNC_QUERY_CONCURRENCY = 3;
9223
9452
  function wireSyncTaskGraph(predecessorTask, graph, ...completionTasks) {
9224
9453
  if (!graph) {
9225
9454
  return void 0;
@@ -9232,11 +9461,27 @@ function wireSyncTaskGraph(predecessorTask, graph, ...completionTasks) {
9232
9461
  }
9233
9462
  function buildSyncExecutionEnvelope(ctx, queryData) {
9234
9463
  const originalContext = { ...ctx };
9464
+ 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();
9465
+ const rootDbOperationFields = {};
9466
+ for (const key of [
9467
+ "data",
9468
+ "batch",
9469
+ "transaction",
9470
+ "onConflict",
9471
+ "filter",
9472
+ "fields"
9473
+ ]) {
9474
+ if (Object.prototype.hasOwnProperty.call(queryData, key)) {
9475
+ rootDbOperationFields[key] = queryData[key];
9476
+ }
9477
+ }
9235
9478
  const nextContext = {
9236
9479
  __syncing: ctx.__syncing === true || ctx.__metadata?.__syncing === true || false,
9480
+ __syncSourceServiceName: syncSourceServiceName,
9237
9481
  __preferredTransportProtocol: "rest",
9238
9482
  __resolverOriginalContext: originalContext,
9239
9483
  __resolverQueryData: queryData,
9484
+ ...rootDbOperationFields,
9240
9485
  queryData
9241
9486
  };
9242
9487
  if (typeof ctx.__reason === "string" && ctx.__reason.trim().length > 0) {
@@ -9244,9 +9489,26 @@ function buildSyncExecutionEnvelope(ctx, queryData) {
9244
9489
  }
9245
9490
  return nextContext;
9246
9491
  }
9492
+ function markCompletedSyncCycle(completedCycles, cycleId, limit = 32) {
9493
+ if (!cycleId) {
9494
+ return false;
9495
+ }
9496
+ if (completedCycles.has(cycleId)) {
9497
+ return false;
9498
+ }
9499
+ completedCycles.add(cycleId);
9500
+ while (completedCycles.size > limit) {
9501
+ const oldestCycleId = completedCycles.values().next().value;
9502
+ if (!oldestCycleId) {
9503
+ break;
9504
+ }
9505
+ completedCycles.delete(oldestCycleId);
9506
+ }
9507
+ return true;
9508
+ }
9247
9509
  function resolveSyncInsertTask(isCadenzaDBReady, tableName, queryData = {}, options = {}) {
9248
9510
  const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
9249
- if (!localInsertTask && !isCadenzaDBReady) {
9511
+ if (isCadenzaDBReady && !localInsertTask) {
9250
9512
  return void 0;
9251
9513
  }
9252
9514
  const targetTask = localInsertTask ?? CadenzaService.createCadenzaDBInsertTask(tableName, queryData, {
@@ -9297,6 +9559,11 @@ function resolveSyncInsertTask(isCadenzaDBReady, tableName, queryData = {}, opti
9297
9559
  ...ctx,
9298
9560
  queryData: ctx.queryData && typeof ctx.queryData === "object" ? ctx.queryData : originalQueryData
9299
9561
  };
9562
+ if (originalContext.__syncing === true && !didSyncInsertSucceed(normalizedContext)) {
9563
+ CadenzaService.debounce("meta.sync_requested", {
9564
+ delayMs: 1e3
9565
+ });
9566
+ }
9300
9567
  return normalizedContext;
9301
9568
  },
9302
9569
  `Finalizes ${tableName} graph-sync insert execution after the authority task finishes.`,
@@ -9324,63 +9591,16 @@ var CADENZA_DB_REQUIRED_LOCAL_SYNC_INSERT_TABLES = [
9324
9591
  "intent_to_task_map",
9325
9592
  "directional_task_graph_map"
9326
9593
  ];
9327
- var AUTHORITY_QUERY_RESULT_KEYS = {
9328
- task: "tasks",
9329
- routine: "routines",
9330
- signal_registry: "signalRegistrys",
9331
- intent_registry: "intentRegistrys"
9332
- };
9333
- var EARLY_SYNC_REQUEST_DELAYS_MS = [2e3, 1e4, 3e4];
9334
- function resolveSyncQueryRows(ctx, tableName) {
9335
- const resultKey = AUTHORITY_QUERY_RESULT_KEYS[tableName];
9336
- const rows = ctx?.[resultKey];
9337
- return Array.isArray(rows) ? rows : [];
9338
- }
9339
- function resolveSyncQueryTask(isCadenzaDBReady, tableName, queryData = {}, options = {}) {
9340
- const localQueryTask = CadenzaService.getLocalCadenzaDBQueryTask(tableName);
9341
- if (!localQueryTask && !isCadenzaDBReady) {
9342
- return void 0;
9343
- }
9344
- const targetTask = localQueryTask ?? CadenzaService.createCadenzaDBQueryTask(tableName, queryData, {
9345
- ...options,
9346
- concurrency: Number(options.concurrency) > 0 ? Math.min(
9347
- Number(options.concurrency),
9348
- REMOTE_AUTHORITY_SYNC_QUERY_CONCURRENCY
9349
- ) : REMOTE_AUTHORITY_SYNC_QUERY_CONCURRENCY,
9350
- register: false,
9351
- isHidden: true
9352
- });
9353
- const prepareQueryTask = CadenzaService.createMetaTask(
9354
- `Prepare graph sync query for ${tableName}`,
9355
- (ctx) => buildSyncExecutionEnvelope(
9356
- ctx,
9357
- buildSyncQueryQueryData(ctx, queryData)
9358
- ),
9359
- `Prepares ${tableName} graph-sync query payloads.`,
9360
- {
9361
- register: false,
9362
- isHidden: true
9363
- }
9364
- );
9365
- const finalizeQueryTask = CadenzaService.createMetaTask(
9366
- `Finalize graph sync query for ${tableName}`,
9367
- (ctx) => ctx,
9368
- `Finalizes ${tableName} graph-sync query payloads after authority lookup.`,
9369
- {
9370
- register: false,
9371
- isHidden: true
9372
- }
9373
- );
9374
- prepareQueryTask.then(targetTask);
9375
- targetTask.then(finalizeQueryTask);
9376
- return {
9377
- entryTask: prepareQueryTask,
9378
- completionTask: finalizeQueryTask
9379
- };
9380
- }
9594
+ var BOOTSTRAP_SYNC_STALE_CYCLE_MS = 15e3;
9595
+ var EARLY_SYNC_TICK_DELAYS_MS = [
9596
+ 400,
9597
+ BOOTSTRAP_SYNC_STALE_CYCLE_MS + 1e3,
9598
+ BOOTSTRAP_SYNC_STALE_CYCLE_MS * 2 + 2e3,
9599
+ BOOTSTRAP_SYNC_STALE_CYCLE_MS * 3 + 3e3
9600
+ ];
9381
9601
  function getRegistrableTasks() {
9382
9602
  return Array.from(CadenzaService.registry.tasks.values()).filter(
9383
- (task) => task.register && !task.isHidden
9603
+ (task) => task.register && !task.isHidden && !task.isDeputy
9384
9604
  );
9385
9605
  }
9386
9606
  function getRegistrableRoutines() {
@@ -9445,10 +9665,23 @@ var GraphSyncController = class _GraphSyncController {
9445
9665
  this.signalsSynced = false;
9446
9666
  this.intentsSynced = false;
9447
9667
  this.routinesSynced = false;
9668
+ this.directionalTaskMapsSynced = false;
9669
+ this.signalTaskMapsSynced = false;
9670
+ this.intentTaskMapsSynced = false;
9671
+ this.actorTaskMapsSynced = false;
9672
+ this.routineTaskMapsSynced = false;
9448
9673
  this.isCadenzaDBReady = false;
9449
9674
  this.initialized = false;
9450
9675
  this.initRetryScheduled = false;
9451
9676
  this.lastMissingLocalCadenzaDBInsertTablesKey = "";
9677
+ this.syncCycleCounter = 0;
9678
+ this.primitivePhaseCompletedCycles = /* @__PURE__ */ new Set();
9679
+ this.mapPhaseCompletedCycles = /* @__PURE__ */ new Set();
9680
+ this.activeSyncCycleId = null;
9681
+ this.activeSyncCycleStartedAt = 0;
9682
+ this.pendingBootstrapSyncRerun = false;
9683
+ this.localServiceInserted = false;
9684
+ this.localServiceInstanceInserted = false;
9452
9685
  }
9453
9686
  static get instance() {
9454
9687
  if (!this._instance) this._instance = new _GraphSyncController();
@@ -9522,45 +9755,9 @@ var GraphSyncController = class _GraphSyncController {
9522
9755
  },
9523
9756
  { concurrency: 30 }
9524
9757
  );
9525
- const ensureIntentRegistryBeforeIntentMapTask = resolveSyncInsertTask(
9526
- this.isCadenzaDBReady,
9527
- "intent_registry",
9528
- {
9529
- onConflict: {
9530
- target: ["name"],
9531
- action: {
9532
- do: "nothing"
9533
- }
9534
- }
9535
- },
9536
- { concurrency: 30 }
9537
- );
9538
- const authoritativeTaskQueryGraph = resolveSyncQueryTask(
9539
- this.isCadenzaDBReady,
9540
- "task",
9541
- {},
9542
- { concurrency: 10 }
9543
- );
9544
- const authoritativeRoutineQueryGraph = resolveSyncQueryTask(
9545
- this.isCadenzaDBReady,
9546
- "routine",
9547
- {},
9548
- { concurrency: 10 }
9549
- );
9550
- const authoritativeSignalQueryGraph = resolveSyncQueryTask(
9551
- this.isCadenzaDBReady,
9552
- "signal_registry",
9553
- {},
9554
- { concurrency: 10 }
9555
- );
9556
- const authoritativeIntentQueryGraph = resolveSyncQueryTask(
9557
- this.isCadenzaDBReady,
9558
- "intent_registry",
9559
- {},
9560
- { concurrency: 10 }
9561
- );
9562
9758
  const finalizeTaskSync = (emit, ctx) => {
9563
9759
  const pendingTasks = getRegistrableTasks().filter((task) => !task.registered);
9760
+ const serviceName2 = typeof ctx.__serviceName === "string" ? ctx.__serviceName : resolveSyncServiceName();
9564
9761
  if (pendingTasks.length > 0) {
9565
9762
  this.tasksSynced = false;
9566
9763
  return false;
@@ -9579,6 +9776,7 @@ var GraphSyncController = class _GraphSyncController {
9579
9776
  const pendingRoutines = getRegistrableRoutines().filter(
9580
9777
  (routine) => !routine.registered
9581
9778
  );
9779
+ const serviceName2 = typeof ctx.__serviceName === "string" ? ctx.__serviceName : resolveSyncServiceName();
9582
9780
  if (pendingRoutines.length > 0) {
9583
9781
  this.routinesSynced = false;
9584
9782
  return false;
@@ -9597,6 +9795,7 @@ var GraphSyncController = class _GraphSyncController {
9597
9795
  const pendingSignals = getRegistrableSignalObservers().filter(
9598
9796
  (observer) => observer.registered !== true
9599
9797
  );
9798
+ const serviceName2 = typeof ctx.__serviceName === "string" ? ctx.__serviceName : resolveSyncServiceName();
9600
9799
  if (pendingSignals.length > 0) {
9601
9800
  this.signalsSynced = false;
9602
9801
  return false;
@@ -9615,6 +9814,7 @@ var GraphSyncController = class _GraphSyncController {
9615
9814
  const pendingIntentNames = getRegistrableIntentNames().filter(
9616
9815
  (intentName) => !this.registeredIntentDefinitions.has(intentName)
9617
9816
  );
9817
+ const serviceName2 = typeof ctx.__serviceName === "string" ? ctx.__serviceName : resolveSyncServiceName();
9618
9818
  if (pendingIntentNames.length > 0) {
9619
9819
  this.intentsSynced = false;
9620
9820
  return false;
@@ -9880,14 +10080,15 @@ var GraphSyncController = class _GraphSyncController {
9880
10080
  );
9881
10081
  const processSignalRegistrationTask = CadenzaService.createMetaTask(
9882
10082
  "Process signal registration",
9883
- (ctx) => {
9884
- if (!didSyncInsertSucceed(ctx)) {
10083
+ (ctx, emit) => {
10084
+ const insertSucceeded = didSyncInsertSucceed(ctx);
10085
+ const signalName = resolveSignalNameFromSyncContext(ctx);
10086
+ if (!insertSucceeded) {
9885
10087
  return;
9886
10088
  }
9887
10089
  CadenzaService.debounce("meta.sync_controller.synced_resource", {
9888
10090
  delayMs: 3e3
9889
10091
  });
9890
- const signalName = resolveSignalNameFromSyncContext(ctx);
9891
10092
  if (!signalName) {
9892
10093
  return false;
9893
10094
  }
@@ -9899,6 +10100,12 @@ var GraphSyncController = class _GraphSyncController {
9899
10100
  if (observer) {
9900
10101
  observer.registered = true;
9901
10102
  }
10103
+ emit(
10104
+ "meta.sync_controller.signal_registered",
10105
+ buildMinimalSyncSignalContext(ctx, {
10106
+ __signal: signalName
10107
+ })
10108
+ );
9902
10109
  return { signalName };
9903
10110
  }
9904
10111
  ).then(CadenzaService.signalBroker.registerSignalTask).then(gatherSignalRegistrationTask);
@@ -9919,6 +10126,7 @@ var GraphSyncController = class _GraphSyncController {
9919
10126
  return;
9920
10127
  }
9921
10128
  for (const task of tasks) {
10129
+ if (task.hidden || !task.register || task.isDeputy) continue;
9922
10130
  if (task.registered) continue;
9923
10131
  const { __functionString, __getTagCallback } = task.export();
9924
10132
  this.tasksSynced = false;
@@ -9953,7 +10161,8 @@ var GraphSyncController = class _GraphSyncController {
9953
10161
  signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
9954
10162
  signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
9955
10163
  observed: Array.from(task.observedSignals)
9956
- }
10164
+ },
10165
+ intents: Array.from(task.handlesIntents)
9957
10166
  },
9958
10167
  __taskName: task.name
9959
10168
  };
@@ -9976,13 +10185,15 @@ var GraphSyncController = class _GraphSyncController {
9976
10185
  const registerTaskTask = CadenzaService.createMetaTask(
9977
10186
  "Record registration",
9978
10187
  (ctx, emit) => {
9979
- if (!didSyncInsertSucceed(ctx)) {
10188
+ const task = resolveLocalTaskFromSyncContext(ctx);
10189
+ const serviceName2 = resolveSyncServiceName(task);
10190
+ const insertSucceeded = didSyncInsertSucceed(ctx);
10191
+ if (!insertSucceeded) {
9980
10192
  return;
9981
10193
  }
9982
10194
  CadenzaService.debounce("meta.sync_controller.synced_resource", {
9983
10195
  delayMs: 3e3
9984
10196
  });
9985
- const task = resolveLocalTaskFromSyncContext(ctx);
9986
10197
  if (!task) {
9987
10198
  return true;
9988
10199
  }
@@ -9997,24 +10208,6 @@ var GraphSyncController = class _GraphSyncController {
9997
10208
  }
9998
10209
  ).then(gatherTaskRegistrationTask);
9999
10210
  wireSyncTaskGraph(this.splitTasksForRegistration, registerTaskGraph, registerTaskTask);
10000
- CadenzaService.createMetaTask(
10001
- "Prepare created task for immediate sync",
10002
- (ctx) => {
10003
- const task = ctx.taskInstance ?? (ctx.data?.name ? CadenzaService.get(String(ctx.data.name)) : void 0);
10004
- if (!task || task.hidden || !task.register || task.registered) {
10005
- return false;
10006
- }
10007
- return {
10008
- __syncing: true,
10009
- tasks: [task]
10010
- };
10011
- },
10012
- "Schedules newly created tasks into the graph sync registration flow without waiting for the next periodic tick.",
10013
- {
10014
- register: false,
10015
- isHidden: true
10016
- }
10017
- ).doOn("meta.task.created").then(this.splitTasksForRegistration);
10018
10211
  this.splitActorsForRegistration = CadenzaService.createMetaTask(
10019
10212
  "Split actors for registration",
10020
10213
  function* (ctx) {
@@ -10153,13 +10346,14 @@ var GraphSyncController = class _GraphSyncController {
10153
10346
  const registerSignalTask = CadenzaService.createMetaTask(
10154
10347
  "Record signal registration",
10155
10348
  (ctx) => {
10349
+ const task = resolveLocalTaskFromSyncContext(ctx);
10350
+ const serviceName2 = resolveSyncServiceName(task);
10156
10351
  if (!didSyncInsertSucceed(ctx)) {
10157
10352
  return;
10158
10353
  }
10159
10354
  CadenzaService.debounce("meta.sync_controller.synced_resource", {
10160
10355
  delayMs: 3e3
10161
10356
  });
10162
- const task = resolveLocalTaskFromSyncContext(ctx);
10163
10357
  const signalName = resolveSignalNameFromSyncContext(ctx);
10164
10358
  if (!task || !signalName) {
10165
10359
  return true;
@@ -10171,7 +10365,8 @@ var GraphSyncController = class _GraphSyncController {
10171
10365
  "Split observed signals of task",
10172
10366
  function* (ctx) {
10173
10367
  const task = ctx.task;
10174
- if (task.hidden || !task.register || !task.registered) return false;
10368
+ if (task.hidden || !task.register || task.isDeputy || !task.registered)
10369
+ return false;
10175
10370
  const serviceName2 = resolveSyncServiceName(task);
10176
10371
  if (!serviceName2) {
10177
10372
  return false;
@@ -10253,7 +10448,7 @@ var GraphSyncController = class _GraphSyncController {
10253
10448
  );
10254
10449
  const recordIntentDefinitionRegistrationTask = CadenzaService.createMetaTask(
10255
10450
  "Record intent definition registration",
10256
- (ctx) => {
10451
+ (ctx, emit) => {
10257
10452
  if (!didSyncInsertSucceed(ctx)) {
10258
10453
  return;
10259
10454
  }
@@ -10261,6 +10456,12 @@ var GraphSyncController = class _GraphSyncController {
10261
10456
  delayMs: 3e3
10262
10457
  });
10263
10458
  this.registeredIntentDefinitions.add(ctx.__intentName);
10459
+ emit(
10460
+ "meta.sync_controller.intent_registered",
10461
+ buildMinimalSyncSignalContext(ctx, {
10462
+ __intentName: ctx.__intentName
10463
+ })
10464
+ );
10264
10465
  return true;
10265
10466
  }
10266
10467
  ).then(gatherIntentRegistrationTask);
@@ -10272,13 +10473,13 @@ var GraphSyncController = class _GraphSyncController {
10272
10473
  const registerIntentTask = CadenzaService.createMetaTask(
10273
10474
  "Record intent registration",
10274
10475
  (ctx) => {
10476
+ const task = resolveLocalTaskFromSyncContext(ctx);
10275
10477
  if (!didSyncInsertSucceed(ctx)) {
10276
10478
  return;
10277
10479
  }
10278
10480
  CadenzaService.debounce("meta.sync_controller.synced_resource", {
10279
10481
  delayMs: 3e3
10280
10482
  });
10281
- const task = resolveLocalTaskFromSyncContext(ctx);
10282
10483
  if (!task) {
10283
10484
  return true;
10284
10485
  }
@@ -10290,7 +10491,8 @@ var GraphSyncController = class _GraphSyncController {
10290
10491
  "Split intents of task",
10291
10492
  function* (ctx) {
10292
10493
  const task = ctx.task;
10293
- if (task.hidden || !task.register || !task.registered) return false;
10494
+ if (task.hidden || !task.register || task.isDeputy || !task.registered)
10495
+ return false;
10294
10496
  const serviceName2 = resolveSyncServiceName(task);
10295
10497
  if (!serviceName2) {
10296
10498
  return false;
@@ -10345,30 +10547,6 @@ var GraphSyncController = class _GraphSyncController {
10345
10547
  return emittedCount > 0;
10346
10548
  }.bind(this)
10347
10549
  );
10348
- const prepareIntentDefinitionForIntentMapTask = CadenzaService.createMetaTask(
10349
- "Prepare intent definition for intent-to-task map",
10350
- (ctx) => {
10351
- if (!ctx.__intentDefinition || !ctx.__intentMapData) {
10352
- return false;
10353
- }
10354
- return {
10355
- ...ctx,
10356
- data: ctx.__intentDefinition
10357
- };
10358
- }
10359
- );
10360
- const restoreIntentToTaskMapPayloadTask = CadenzaService.createMetaTask(
10361
- "Restore intent-to-task map payload",
10362
- (ctx) => {
10363
- if (!ctx.__intentMapData) {
10364
- return false;
10365
- }
10366
- return {
10367
- ...ctx,
10368
- data: ctx.__intentMapData
10369
- };
10370
- }
10371
- );
10372
10550
  const intentToTaskMapGraph = resolveSyncInsertTask(
10373
10551
  this.isCadenzaDBReady,
10374
10552
  "intent_to_task_map",
@@ -10387,20 +10565,8 @@ var GraphSyncController = class _GraphSyncController {
10387
10565
  },
10388
10566
  { concurrency: 30 }
10389
10567
  );
10390
- this.registerIntentToTaskMapTask.then(prepareIntentDefinitionForIntentMapTask);
10391
- if (ensureIntentRegistryBeforeIntentMapTask) {
10392
- wireSyncTaskGraph(
10393
- prepareIntentDefinitionForIntentMapTask,
10394
- ensureIntentRegistryBeforeIntentMapTask,
10395
- restoreIntentToTaskMapPayloadTask
10396
- );
10397
- } else {
10398
- prepareIntentDefinitionForIntentMapTask.then(
10399
- restoreIntentToTaskMapPayloadTask
10400
- );
10401
- }
10402
10568
  wireSyncTaskGraph(
10403
- restoreIntentToTaskMapPayloadTask,
10569
+ this.registerIntentToTaskMapTask,
10404
10570
  intentToTaskMapGraph,
10405
10571
  registerIntentTask
10406
10572
  );
@@ -10411,7 +10577,7 @@ var GraphSyncController = class _GraphSyncController {
10411
10577
  CadenzaService.debounce("meta.sync_controller.synced_resource", {
10412
10578
  delayMs: 3e3
10413
10579
  });
10414
- if (task.hidden || !task.register) return;
10580
+ if (task.hidden || !task.register || task.isDeputy) return;
10415
10581
  const predecessorServiceName = resolveSyncServiceName(task);
10416
10582
  if (!predecessorServiceName) {
10417
10583
  return;
@@ -10545,452 +10711,583 @@ var GraphSyncController = class _GraphSyncController {
10545
10711
  deputyRelationshipRegistrationGraph,
10546
10712
  recordDeputyRelationshipRegistrationTask
10547
10713
  );
10548
- const reconcileTaskRegistrationFromAuthorityTask = CadenzaService.createMetaTask(
10549
- "Reconcile task registration from authority",
10550
- (ctx, emit) => {
10551
- const authoritativeTasks = resolveSyncQueryRows(ctx, "task");
10552
- let changed = false;
10553
- for (const row of authoritativeTasks) {
10554
- const taskName = typeof row.name === "string" ? row.name : "";
10555
- if (!taskName) {
10556
- continue;
10557
- }
10558
- const task = CadenzaService.get(taskName);
10559
- if (!task || task.registered) {
10560
- continue;
10561
- }
10562
- task.registered = true;
10563
- changed = true;
10564
- emit("meta.sync_controller.task_registered", {
10565
- ...ctx,
10566
- __taskName: task.name,
10567
- task,
10568
- __authoritativeReconciliation: true
10569
- });
10714
+ const hasPendingDirectionalTaskMaps = () => getRegistrableTasks().some((task) => {
10715
+ const taskWithDeputyState = task;
10716
+ if (task.isHidden || !task.register || !task.registered) {
10717
+ return false;
10718
+ }
10719
+ const predecessorServiceName = resolveSyncServiceName(task);
10720
+ if (!predecessorServiceName) {
10721
+ return false;
10722
+ }
10723
+ for (const nextTask of task.nextTasks) {
10724
+ if (task.taskMapRegistration.has(nextTask.name) || nextTask.isHidden || !nextTask.register || !nextTask.registered) {
10725
+ continue;
10570
10726
  }
10571
- if (authoritativeTasks.length > 0 || changed) {
10572
- finalizeTaskSync(emit, {
10573
- ...ctx,
10574
- __authoritativeReconciliation: true
10575
- });
10727
+ if (resolveSyncServiceName(nextTask)) {
10728
+ return true;
10729
+ }
10730
+ }
10731
+ if (task.isDeputy && !taskWithDeputyState.signalName && !taskWithDeputyState.registeredDeputyMap) {
10732
+ return Boolean(resolveSyncServiceName(task) && resolveSyncServiceName());
10733
+ }
10734
+ return false;
10735
+ });
10736
+ const hasPendingSignalTaskMaps = () => getRegistrableTasks().some((task) => {
10737
+ if (task.isHidden || !task.register || !task.registered) {
10738
+ return false;
10739
+ }
10740
+ for (const signal of task.observedSignals) {
10741
+ if (task.registeredSignals.has(signal)) {
10742
+ continue;
10743
+ }
10744
+ const signalName = signal.split(":")[0];
10745
+ if (!decomposeSignalName(signalName).isGlobal) {
10746
+ continue;
10747
+ }
10748
+ if (!CadenzaService.signalBroker.signalObservers?.get(signalName)?.registered) {
10749
+ continue;
10750
+ }
10751
+ return true;
10752
+ }
10753
+ return false;
10754
+ });
10755
+ const hasPendingIntentTaskMaps = () => getRegistrableTasks().some((task) => {
10756
+ if (task.isHidden || !task.register || !task.registered) {
10757
+ return false;
10758
+ }
10759
+ const registeredIntents = task.__registeredIntents ?? /* @__PURE__ */ new Set();
10760
+ for (const intent of task.handlesIntents) {
10761
+ if (registeredIntents.has(intent) || isLocalOnlySyncIntent(intent)) {
10762
+ continue;
10763
+ }
10764
+ if (isMetaIntentName(intent) && !task.isMeta) {
10765
+ continue;
10766
+ }
10767
+ const intentDefinition = buildIntentRegistryData(CadenzaService.inquiryBroker.intents.get(intent)) ?? buildIntentRegistryData({ name: intent });
10768
+ if (!intentDefinition) {
10769
+ continue;
10576
10770
  }
10577
- return changed;
10771
+ return true;
10772
+ }
10773
+ return false;
10774
+ });
10775
+ const hasPendingActorTaskMaps = () => getRegistrableTasks().some((task) => {
10776
+ if (task.isHidden || !task.register || !task.registered) {
10777
+ return false;
10778
+ }
10779
+ const metadata = getActorTaskRuntimeMetadata(task.taskFunction);
10780
+ if (!metadata?.actorName) {
10781
+ return false;
10782
+ }
10783
+ const serviceName2 = resolveSyncServiceName(task);
10784
+ if (!serviceName2) {
10785
+ return false;
10786
+ }
10787
+ const registrationKey = `${metadata.actorName}|${task.name}|${task.version}|${serviceName2}`;
10788
+ return !this.registeredActorTaskMaps.has(registrationKey);
10789
+ });
10790
+ const hasPendingRoutineTaskMaps = () => getRegistrableRoutines().some((routine) => {
10791
+ if (!routine.registered) {
10792
+ return false;
10793
+ }
10794
+ for (const task of routine.tasks) {
10795
+ if (!task) {
10796
+ continue;
10797
+ }
10798
+ const tasks = task.getIterator();
10799
+ while (tasks.hasNext()) {
10800
+ const nextTask = tasks.next();
10801
+ if (!nextTask?.registered) {
10802
+ continue;
10803
+ }
10804
+ if (!routine.registeredTasks.has(nextTask.name)) {
10805
+ return true;
10806
+ }
10807
+ }
10808
+ }
10809
+ return false;
10810
+ });
10811
+ const gatherDirectionalTaskMapRegistrationTask = CadenzaService.createUniqueMetaTask(
10812
+ "Gather directional task map registration",
10813
+ (ctx) => {
10814
+ if (hasPendingDirectionalTaskMaps()) {
10815
+ this.directionalTaskMapsSynced = false;
10816
+ return false;
10817
+ }
10818
+ this.directionalTaskMapsSynced = true;
10819
+ return ctx;
10578
10820
  },
10579
- "Marks local tasks as registered when authority rows already exist.",
10821
+ "Completes directional task graph registration when task edges and deputy edges are registered.",
10580
10822
  {
10581
10823
  register: false,
10582
10824
  isHidden: true
10583
10825
  }
10584
10826
  );
10585
- const reconcileRoutineRegistrationFromAuthorityTask = CadenzaService.createMetaTask(
10586
- "Reconcile routine registration from authority",
10587
- (ctx, emit) => {
10588
- const authoritativeRoutines = resolveSyncQueryRows(ctx, "routine");
10589
- let changed = false;
10590
- for (const row of authoritativeRoutines) {
10591
- const routineName = typeof row.name === "string" ? row.name : "";
10592
- if (!routineName) {
10593
- continue;
10594
- }
10595
- const routine = CadenzaService.getRoutine(routineName);
10596
- if (!routine || routine.registered) {
10597
- continue;
10598
- }
10599
- routine.registered = true;
10600
- changed = true;
10827
+ const gatherSignalTaskMapRegistrationTask = CadenzaService.createUniqueMetaTask(
10828
+ "Gather signal task map registration",
10829
+ (ctx) => {
10830
+ if (hasPendingSignalTaskMaps()) {
10831
+ this.signalTaskMapsSynced = false;
10832
+ return false;
10601
10833
  }
10602
- if (authoritativeRoutines.length > 0 || changed) {
10603
- finalizeRoutineSync(emit, {
10604
- ...ctx,
10605
- __authoritativeReconciliation: true
10606
- });
10834
+ this.signalTaskMapsSynced = true;
10835
+ return ctx;
10836
+ },
10837
+ "Completes signal-to-task map registration when all global observed signal edges are registered.",
10838
+ {
10839
+ register: false,
10840
+ isHidden: true
10841
+ }
10842
+ );
10843
+ const gatherIntentTaskMapRegistrationTask = CadenzaService.createUniqueMetaTask(
10844
+ "Gather intent task map registration",
10845
+ (ctx) => {
10846
+ if (hasPendingIntentTaskMaps()) {
10847
+ this.intentTaskMapsSynced = false;
10848
+ return false;
10607
10849
  }
10608
- return changed;
10850
+ this.intentTaskMapsSynced = true;
10851
+ return ctx;
10609
10852
  },
10610
- "Marks local routines as registered when authority rows already exist.",
10853
+ "Completes intent-to-task map registration when all task responders are registered.",
10611
10854
  {
10612
10855
  register: false,
10613
10856
  isHidden: true
10614
10857
  }
10615
10858
  );
10616
- const reconcileSignalRegistrationFromAuthorityTask = CadenzaService.createMetaTask(
10617
- "Reconcile signal registration from authority",
10618
- (ctx, emit) => {
10619
- const authoritativeSignals = resolveSyncQueryRows(ctx, "signal_registry");
10620
- const signalObservers = CadenzaService.signalBroker.signalObservers;
10621
- let changed = false;
10622
- for (const row of authoritativeSignals) {
10623
- const signalName = typeof row.name === "string" ? row.name : "";
10624
- if (!signalName) {
10625
- continue;
10626
- }
10627
- const observer = signalObservers?.get(signalName);
10628
- if (!observer || observer.registered) {
10629
- continue;
10630
- }
10631
- observer.registered = true;
10632
- changed = true;
10859
+ const gatherActorTaskMapRegistrationTask = CadenzaService.createUniqueMetaTask(
10860
+ "Gather actor task map registration",
10861
+ (ctx) => {
10862
+ if (hasPendingActorTaskMaps()) {
10863
+ this.actorTaskMapsSynced = false;
10864
+ return false;
10633
10865
  }
10634
- if (authoritativeSignals.length > 0 || changed) {
10635
- finalizeSignalSync(emit, {
10636
- ...ctx,
10637
- __authoritativeReconciliation: true
10638
- });
10866
+ this.actorTaskMapsSynced = true;
10867
+ return ctx;
10868
+ },
10869
+ "Completes actor-to-task map registration when all actor-backed tasks are registered.",
10870
+ {
10871
+ register: false,
10872
+ isHidden: true
10873
+ }
10874
+ );
10875
+ const gatherRoutineTaskMapRegistrationTask = CadenzaService.createUniqueMetaTask(
10876
+ "Gather routine task map registration",
10877
+ (ctx) => {
10878
+ if (hasPendingRoutineTaskMaps()) {
10879
+ this.routineTaskMapsSynced = false;
10880
+ return false;
10639
10881
  }
10640
- return changed;
10882
+ this.routineTaskMapsSynced = true;
10883
+ return ctx;
10641
10884
  },
10642
- "Marks local signals as registered when authority rows already exist.",
10885
+ "Completes task-to-routine map registration when all routine task memberships are registered.",
10643
10886
  {
10644
10887
  register: false,
10645
10888
  isHidden: true
10646
10889
  }
10647
10890
  );
10648
- const reconcileIntentRegistrationFromAuthorityTask = CadenzaService.createMetaTask(
10649
- "Reconcile intent registration from authority",
10891
+ const finishSyncTask = CadenzaService.createUniqueMetaTask(
10892
+ "Finish sync",
10650
10893
  (ctx, emit) => {
10651
- const authoritativeIntents = resolveSyncQueryRows(ctx, "intent_registry");
10652
- let changed = false;
10653
- for (const row of authoritativeIntents) {
10654
- const intentName = typeof row.name === "string" ? row.name : "";
10655
- if (!intentName || !CadenzaService.inquiryBroker.intents.has(intentName)) {
10656
- continue;
10657
- }
10658
- if (this.registeredIntentDefinitions.has(intentName)) {
10659
- continue;
10894
+ const syncCycleId = typeof ctx.__syncCycleId === "string" ? ctx.__syncCycleId.trim() : "";
10895
+ if (syncCycleId && this.activeSyncCycleId === syncCycleId) {
10896
+ this.activeSyncCycleId = null;
10897
+ this.activeSyncCycleStartedAt = 0;
10898
+ }
10899
+ if (this.pendingBootstrapSyncRerun) {
10900
+ this.pendingBootstrapSyncRerun = false;
10901
+ CadenzaService.debounce("meta.sync_requested", {
10902
+ delayMs: 100
10903
+ });
10904
+ }
10905
+ emit("global.meta.sync_controller.synced", {
10906
+ data: {
10907
+ is_active: true,
10908
+ is_non_responsive: false,
10909
+ is_blocked: false,
10910
+ last_active: formatTimestamp(Date.now())
10911
+ },
10912
+ filter: {
10913
+ uuid: CadenzaService.serviceRegistry.serviceInstanceId
10660
10914
  }
10661
- this.registeredIntentDefinitions.add(intentName);
10662
- changed = true;
10915
+ });
10916
+ return true;
10917
+ },
10918
+ "Marks the current bootstrap sync cycle as complete.",
10919
+ {
10920
+ register: false,
10921
+ isHidden: true
10922
+ }
10923
+ ).attachSignal("global.meta.sync_controller.synced");
10924
+ const mapPhaseBarrierTask = CadenzaService.createUniqueMetaTask(
10925
+ "Complete map sync phase",
10926
+ (ctx) => {
10927
+ const syncCycleId = typeof ctx.__syncCycleId === "string" ? ctx.__syncCycleId.trim() : "";
10928
+ if (!syncCycleId) {
10929
+ return false;
10663
10930
  }
10664
- if (authoritativeIntents.length > 0 || changed) {
10665
- finalizeIntentSync(emit, {
10666
- ...ctx,
10667
- __authoritativeReconciliation: true
10668
- });
10931
+ if (!this.directionalTaskMapsSynced || !this.signalTaskMapsSynced || !this.intentTaskMapsSynced || !this.actorTaskMapsSynced || !this.routineTaskMapsSynced) {
10932
+ return false;
10933
+ }
10934
+ if (!markCompletedSyncCycle(this.mapPhaseCompletedCycles, syncCycleId)) {
10935
+ return false;
10669
10936
  }
10670
- return changed;
10937
+ return ctx;
10671
10938
  },
10672
- "Marks local intents as registered when authority rows already exist.",
10939
+ "Fans in map branch completion and ends the current sync cycle once every map branch is complete.",
10940
+ {
10941
+ register: false,
10942
+ isHidden: true
10943
+ }
10944
+ ).then(finishSyncTask);
10945
+ const startDirectionalTaskMapSyncTask = CadenzaService.createMetaTask(
10946
+ "Start directional task map sync",
10947
+ (ctx) => ctx,
10948
+ "Starts the directional task graph map branch for the current sync cycle.",
10673
10949
  {
10674
10950
  register: false,
10675
10951
  isHidden: true
10676
10952
  }
10677
10953
  );
10678
- const skipAuthoritativeTaskReconciliationTask = CadenzaService.createMetaTask(
10679
- "Skip authoritative task reconciliation",
10680
- () => false,
10681
- "Skips task reconciliation when no authority query task is available.",
10954
+ const startSignalTaskMapSyncTask = CadenzaService.createMetaTask(
10955
+ "Start signal task map sync",
10956
+ (ctx) => ctx,
10957
+ "Starts the signal-to-task map branch for the current sync cycle.",
10682
10958
  {
10683
10959
  register: false,
10684
10960
  isHidden: true
10685
10961
  }
10686
10962
  );
10687
- const skipAuthoritativeRoutineReconciliationTask = CadenzaService.createMetaTask(
10688
- "Skip authoritative routine reconciliation",
10689
- () => false,
10690
- "Skips routine reconciliation when no authority query task is available.",
10963
+ const startIntentTaskMapSyncTask = CadenzaService.createMetaTask(
10964
+ "Start intent task map sync",
10965
+ (ctx) => ctx,
10966
+ "Starts the intent-to-task map branch for the current sync cycle.",
10691
10967
  {
10692
10968
  register: false,
10693
10969
  isHidden: true
10694
10970
  }
10695
10971
  );
10696
- const skipAuthoritativeSignalReconciliationTask = CadenzaService.createMetaTask(
10697
- "Skip authoritative signal reconciliation",
10698
- () => false,
10699
- "Skips signal reconciliation when no authority query task is available.",
10972
+ const startActorTaskMapSyncTask = CadenzaService.createMetaTask(
10973
+ "Start actor task map sync",
10974
+ (ctx) => ctx,
10975
+ "Starts the actor-to-task map branch for the current sync cycle.",
10700
10976
  {
10701
10977
  register: false,
10702
10978
  isHidden: true
10703
10979
  }
10704
10980
  );
10705
- const skipAuthoritativeIntentReconciliationTask = CadenzaService.createMetaTask(
10706
- "Skip authoritative intent reconciliation",
10707
- () => false,
10708
- "Skips intent reconciliation when no authority query task is available.",
10981
+ const startRoutineTaskMapSyncTask = CadenzaService.createMetaTask(
10982
+ "Start routine task map sync",
10983
+ (ctx) => ctx,
10984
+ "Starts the task-to-routine map branch for the current sync cycle.",
10709
10985
  {
10710
10986
  register: false,
10711
10987
  isHidden: true
10712
10988
  }
10713
10989
  );
10714
- if (authoritativeTaskQueryGraph) {
10715
- authoritativeTaskQueryGraph.completionTask.then(
10716
- reconcileTaskRegistrationFromAuthorityTask
10717
- );
10718
- }
10719
- if (authoritativeRoutineQueryGraph) {
10720
- authoritativeRoutineQueryGraph.completionTask.then(
10721
- reconcileRoutineRegistrationFromAuthorityTask
10722
- );
10723
- }
10724
- if (authoritativeSignalQueryGraph) {
10725
- authoritativeSignalQueryGraph.completionTask.then(
10726
- reconcileSignalRegistrationFromAuthorityTask
10727
- );
10728
- }
10729
- if (authoritativeIntentQueryGraph) {
10730
- authoritativeIntentQueryGraph.completionTask.then(
10731
- reconcileIntentRegistrationFromAuthorityTask
10732
- );
10733
- }
10734
- const authoritativeRegistrationTriggers = [
10735
- "meta.service_registry.initial_sync_complete",
10736
- "meta.sync_requested",
10737
- "meta.sync_controller.synced_resource",
10738
- "meta.sync_controller.authority_registration_reconciliation_requested"
10739
- ];
10740
- CadenzaService.createMetaTask(
10741
- "Prepare authoritative task registration query",
10990
+ const primitivePhaseBarrierTask = CadenzaService.createUniqueMetaTask(
10991
+ "Complete primitive sync phase",
10742
10992
  (ctx) => {
10743
- if (!this.isCadenzaDBReady) {
10993
+ const syncCycleId = typeof ctx.__syncCycleId === "string" ? ctx.__syncCycleId.trim() : "";
10994
+ if (!syncCycleId) {
10744
10995
  return false;
10745
10996
  }
10746
- const serviceName2 = resolveSyncServiceName();
10747
- if (!serviceName2) {
10997
+ const serviceName2 = typeof ctx.__serviceName === "string" ? ctx.__serviceName : resolveSyncServiceName();
10998
+ if (!this.tasksSynced || !this.signalsSynced || !this.intentsSynced || !this.actorsSynced || !this.routinesSynced) {
10748
10999
  return false;
10749
11000
  }
10750
- return {
10751
- ...ctx,
10752
- __syncServiceName: serviceName2,
10753
- queryData: {
10754
- filter: {
10755
- service_name: serviceName2
10756
- },
10757
- fields: ["name", "version", "service_name"]
10758
- }
10759
- };
11001
+ if (!markCompletedSyncCycle(this.primitivePhaseCompletedCycles, syncCycleId)) {
11002
+ return false;
11003
+ }
11004
+ this.directionalTaskMapsSynced = false;
11005
+ this.signalTaskMapsSynced = false;
11006
+ this.intentTaskMapsSynced = false;
11007
+ this.actorTaskMapsSynced = false;
11008
+ this.routineTaskMapsSynced = false;
11009
+ return ctx;
10760
11010
  },
10761
- "Builds the authority task query payload for the current service.",
11011
+ "Fans in primitive registration and opens the map registration phase once every primitive branch is complete.",
10762
11012
  {
10763
11013
  register: false,
10764
11014
  isHidden: true
10765
11015
  }
10766
- ).doOn(...authoritativeRegistrationTriggers).then(
10767
- authoritativeTaskQueryGraph?.entryTask ?? skipAuthoritativeTaskReconciliationTask
10768
- );
10769
- CadenzaService.createMetaTask(
10770
- "Prepare authoritative routine registration query",
11016
+ ).then(
11017
+ startDirectionalTaskMapSyncTask,
11018
+ startSignalTaskMapSyncTask,
11019
+ startIntentTaskMapSyncTask,
11020
+ startActorTaskMapSyncTask,
11021
+ startRoutineTaskMapSyncTask
11022
+ );
11023
+ gatherTaskRegistrationTask.then(primitivePhaseBarrierTask);
11024
+ gatherSignalRegistrationTask.then(primitivePhaseBarrierTask);
11025
+ gatherIntentRegistrationTask.then(primitivePhaseBarrierTask);
11026
+ gatherActorRegistrationTask.then(primitivePhaseBarrierTask);
11027
+ gatherRoutineRegistrationTask.then(primitivePhaseBarrierTask);
11028
+ const markLocalServiceInsertedForBootstrapSyncTask = CadenzaService.createUniqueMetaTask(
11029
+ "Mark local service inserted for bootstrap sync",
10771
11030
  (ctx) => {
10772
- if (!this.isCadenzaDBReady) {
10773
- return false;
10774
- }
10775
11031
  const serviceName2 = resolveSyncServiceName();
10776
- if (!serviceName2) {
11032
+ const insertedServiceName = typeof ctx.__serviceName === "string" ? ctx.__serviceName : typeof ctx.service_name === "string" ? ctx.service_name : null;
11033
+ if (!serviceName2 || insertedServiceName !== serviceName2) {
10777
11034
  return false;
10778
11035
  }
10779
- return {
10780
- ...ctx,
10781
- __syncServiceName: serviceName2,
10782
- queryData: {
10783
- filter: {
10784
- service_name: serviceName2
10785
- },
10786
- fields: ["name", "version", "service_name"]
10787
- }
10788
- };
11036
+ this.localServiceInserted = true;
11037
+ return true;
10789
11038
  },
10790
- "Builds the authority routine query payload for the current service.",
11039
+ "Marks that the local service row has been inserted in authority so bootstrap sync can start only after that prerequisite.",
10791
11040
  {
10792
11041
  register: false,
10793
11042
  isHidden: true
10794
11043
  }
10795
- ).doOn(...authoritativeRegistrationTriggers).then(
10796
- authoritativeRoutineQueryGraph?.entryTask ?? skipAuthoritativeRoutineReconciliationTask
10797
- );
10798
- CadenzaService.createMetaTask(
10799
- "Prepare authoritative signal registration query",
11044
+ ).doOn("meta.service_registry.service_inserted");
11045
+ const markLocalServiceInstanceInsertedForBootstrapSyncTask = CadenzaService.createUniqueMetaTask(
11046
+ "Mark local service instance inserted for bootstrap sync",
10800
11047
  (ctx) => {
10801
- if (!this.isCadenzaDBReady) {
11048
+ const serviceName2 = resolveSyncServiceName();
11049
+ const insertedServiceName = typeof ctx.__serviceName === "string" ? ctx.__serviceName : typeof ctx.service_name === "string" ? ctx.service_name : null;
11050
+ if (!serviceName2 || insertedServiceName !== serviceName2) {
10802
11051
  return false;
10803
11052
  }
10804
- return {
10805
- ...ctx,
10806
- queryData: {
10807
- fields: ["name"]
10808
- }
10809
- };
11053
+ this.localServiceInstanceInserted = true;
11054
+ return true;
10810
11055
  },
10811
- "Builds the authority signal query payload for local reconciliation.",
11056
+ "Marks that the local service instance row has been inserted in authority so bootstrap sync can start only after that prerequisite.",
10812
11057
  {
10813
11058
  register: false,
10814
11059
  isHidden: true
10815
11060
  }
10816
- ).doOn(...authoritativeRegistrationTriggers).then(
10817
- authoritativeSignalQueryGraph?.entryTask ?? skipAuthoritativeSignalReconciliationTask
10818
- );
10819
- CadenzaService.createMetaTask(
10820
- "Prepare authoritative intent registration query",
11061
+ ).doOn("meta.service_registry.instance_inserted");
11062
+ const startBootstrapSyncTask = CadenzaService.createUniqueMetaTask(
11063
+ "Start bootstrap graph sync",
10821
11064
  (ctx) => {
10822
- if (!this.isCadenzaDBReady) {
11065
+ const now = Date.now();
11066
+ const serviceName2 = resolveSyncServiceName();
11067
+ const serviceInstanceId = CadenzaService.serviceRegistry.serviceInstanceId;
11068
+ if (!serviceName2 || !serviceInstanceId) {
11069
+ return false;
11070
+ }
11071
+ if (!this.localServiceInserted) {
11072
+ return false;
11073
+ }
11074
+ if (!this.localServiceInstanceInserted) {
10823
11075
  return false;
10824
11076
  }
11077
+ if (!ServiceRegistry.instance.hasLocalInstanceRegistered()) {
11078
+ return false;
11079
+ }
11080
+ if (this.activeSyncCycleId) {
11081
+ const activeCycleAgeMs = now - this.activeSyncCycleStartedAt;
11082
+ if (activeCycleAgeMs < BOOTSTRAP_SYNC_STALE_CYCLE_MS) {
11083
+ this.pendingBootstrapSyncRerun = true;
11084
+ return false;
11085
+ }
11086
+ }
11087
+ const syncCycleId = `${now}-${++this.syncCycleCounter}`;
11088
+ this.activeSyncCycleId = syncCycleId;
11089
+ this.activeSyncCycleStartedAt = now;
11090
+ this.pendingBootstrapSyncRerun = false;
11091
+ this.tasksSynced = false;
11092
+ this.signalsSynced = false;
11093
+ this.intentsSynced = false;
11094
+ this.actorsSynced = false;
11095
+ this.routinesSynced = false;
10825
11096
  return {
10826
11097
  ...ctx,
10827
- queryData: {
10828
- fields: ["name"]
10829
- }
11098
+ __syncing: true,
11099
+ __syncCycleId: syncCycleId,
11100
+ __serviceName: serviceName2,
11101
+ __serviceInstanceId: serviceInstanceId
10830
11102
  };
10831
11103
  },
10832
- "Builds the authority intent query payload for local reconciliation.",
11104
+ "Starts a deterministic bootstrap sync cycle once the local service instance exists.",
10833
11105
  {
10834
11106
  register: false,
10835
11107
  isHidden: true
10836
11108
  }
10837
- ).doOn(...authoritativeRegistrationTriggers).then(
10838
- authoritativeIntentQueryGraph?.entryTask ?? skipAuthoritativeIntentReconciliationTask
10839
- );
10840
- CadenzaService.signalBroker.getSignalsTask.clone().doOn(
10841
- "meta.sync_controller.sync_tick",
10842
- "meta.service_registry.initial_sync_complete",
10843
- "meta.sync_requested"
10844
- ).then(this.splitSignalsTask);
10845
- CadenzaService.registry.getAllTasks.clone().doOn(
10846
- "meta.sync_controller.sync_tick",
10847
- "meta.sync_controller.synced_signals",
10848
- "meta.sync_requested"
10849
- ).then(this.splitTasksForRegistration);
10850
- CadenzaService.createMetaTask("Get all intents", (ctx) => {
10851
- return {
10852
- ...ctx,
10853
- intents: Array.from(CadenzaService.inquiryBroker.intents.values())
10854
- };
10855
- }).doOn(
10856
- "meta.sync_controller.sync_tick",
10857
- "meta.service_registry.initial_sync_complete",
10858
- "meta.sync_requested"
10859
- ).then(this.splitIntentsTask);
10860
- CadenzaService.registry.getAllRoutines.clone().doOn(
10861
- "meta.sync_controller.sync_tick",
10862
- "meta.service_registry.initial_sync_complete",
10863
- "meta.sync_requested"
10864
- ).then(this.splitRoutinesTask);
10865
- CadenzaService.createMetaTask("Get all actors", (ctx) => {
10866
- return {
10867
- ...ctx,
10868
- actors: CadenzaService.getAllActors()
10869
- };
10870
- }).doOn(
11109
+ ).doOn(
11110
+ "meta.service_registry.service_inserted",
11111
+ "meta.service_registry.instance_inserted",
10871
11112
  "meta.sync_controller.sync_tick",
10872
- "meta.service_registry.initial_sync_complete",
10873
11113
  "meta.sync_requested"
10874
- ).then(this.splitActorsForRegistration);
10875
- CadenzaService.createMetaTask("Get registered task for task graph sync", (ctx) => {
10876
- const task = ctx.task ?? (ctx.__taskName ? CadenzaService.get(ctx.__taskName) : void 0);
10877
- if (!task) {
10878
- return false;
11114
+ );
11115
+ const startTaskPrimitiveSyncTask = CadenzaService.createMetaTask(
11116
+ "Start task primitive sync",
11117
+ (ctx) => ctx,
11118
+ "Starts the task registration branch for the current sync cycle.",
11119
+ {
11120
+ register: false,
11121
+ isHidden: true
10879
11122
  }
10880
- return {
10881
- ...ctx,
10882
- task
10883
- };
10884
- }).doOn("meta.sync_controller.task_registered").then(
10885
- this.registerTaskMapTask,
10886
- this.registerDeputyRelationshipTask
10887
11123
  );
10888
- CadenzaService.registry.doForEachTask.clone().doOn(
10889
- "meta.sync_controller.synced_signals",
10890
- "meta.sync_controller.synced_tasks",
10891
- "meta.sync_requested"
10892
- ).then(this.registerSignalToTaskMapTask);
10893
- CadenzaService.createMetaTask("Get registered task for signal sync", (ctx) => {
10894
- const task = ctx.task ?? (ctx.__taskName ? CadenzaService.get(ctx.__taskName) : void 0);
10895
- if (!task) {
10896
- return false;
11124
+ const startSignalPrimitiveSyncTask = CadenzaService.createMetaTask(
11125
+ "Start signal primitive sync",
11126
+ (ctx) => ctx,
11127
+ "Starts the signal registration branch for the current sync cycle.",
11128
+ {
11129
+ register: false,
11130
+ isHidden: true
10897
11131
  }
10898
- return {
10899
- ...ctx,
10900
- task
10901
- };
10902
- }).doOn("meta.sync_controller.task_registered").then(this.registerSignalToTaskMapTask);
10903
- CadenzaService.registry.doForEachTask.clone().doOn(
10904
- "meta.sync_controller.synced_intents",
10905
- "meta.sync_controller.synced_tasks",
10906
- "meta.sync_requested"
10907
- ).then(this.registerIntentToTaskMapTask);
10908
- CadenzaService.createMetaTask("Get registered task for intent sync", (ctx) => {
10909
- const task = ctx.task ?? (ctx.__taskName ? CadenzaService.get(ctx.__taskName) : void 0);
10910
- if (!task) {
10911
- return false;
11132
+ );
11133
+ const startIntentPrimitiveSyncTask = CadenzaService.createMetaTask(
11134
+ "Start intent primitive sync",
11135
+ (ctx) => ctx,
11136
+ "Starts the intent registration branch for the current sync cycle.",
11137
+ {
11138
+ register: false,
11139
+ isHidden: true
10912
11140
  }
10913
- return {
11141
+ );
11142
+ const startActorPrimitiveSyncTask = CadenzaService.createMetaTask(
11143
+ "Start actor primitive sync",
11144
+ (ctx) => ctx,
11145
+ "Starts the actor registration branch for the current sync cycle.",
11146
+ {
11147
+ register: false,
11148
+ isHidden: true
11149
+ }
11150
+ );
11151
+ const startRoutinePrimitiveSyncTask = CadenzaService.createMetaTask(
11152
+ "Start routine primitive sync",
11153
+ (ctx) => ctx,
11154
+ "Starts the routine registration branch for the current sync cycle.",
11155
+ {
11156
+ register: false,
11157
+ isHidden: true
11158
+ }
11159
+ );
11160
+ startBootstrapSyncTask.then(
11161
+ startTaskPrimitiveSyncTask,
11162
+ startSignalPrimitiveSyncTask,
11163
+ startIntentPrimitiveSyncTask,
11164
+ startActorPrimitiveSyncTask,
11165
+ startRoutinePrimitiveSyncTask
11166
+ );
11167
+ const getAllTasksForSyncTask = CadenzaService.registry.getAllTasks.clone();
11168
+ startTaskPrimitiveSyncTask.then(
11169
+ getAllTasksForSyncTask,
11170
+ gatherTaskRegistrationTask
11171
+ );
11172
+ getAllTasksForSyncTask.then(this.splitTasksForRegistration);
11173
+ const getSignalsForSyncTask = CadenzaService.signalBroker.getSignalsTask.clone();
11174
+ startSignalPrimitiveSyncTask.then(
11175
+ getSignalsForSyncTask,
11176
+ gatherSignalRegistrationTask
11177
+ );
11178
+ getSignalsForSyncTask.then(this.splitSignalsTask);
11179
+ const getAllIntentsForSyncTask = CadenzaService.createUniqueMetaTask(
11180
+ "Get all intents for sync",
11181
+ (ctx) => ({
10914
11182
  ...ctx,
10915
- task
10916
- };
10917
- }).doOn("meta.sync_controller.task_registered").then(this.registerIntentToTaskMapTask);
10918
- CadenzaService.registry.doForEachTask.clone().doOn(
10919
- "meta.sync_controller.synced_actors",
10920
- "meta.sync_controller.synced_tasks",
10921
- "meta.sync_requested"
10922
- ).then(this.registerActorTaskMapTask);
10923
- CadenzaService.createMetaTask("Get registered task for actor sync", (ctx) => {
10924
- const task = ctx.task ?? (ctx.__taskName ? CadenzaService.get(ctx.__taskName) : void 0);
10925
- if (!task) {
10926
- return false;
11183
+ intents: Array.from(CadenzaService.inquiryBroker.intents.values())
11184
+ }),
11185
+ "Collects local intents for the primitive sync phase.",
11186
+ {
11187
+ register: false,
11188
+ isHidden: true
10927
11189
  }
10928
- return {
11190
+ );
11191
+ startIntentPrimitiveSyncTask.then(
11192
+ getAllIntentsForSyncTask,
11193
+ gatherIntentRegistrationTask
11194
+ );
11195
+ getAllIntentsForSyncTask.then(this.splitIntentsTask);
11196
+ const getAllActorsForSyncTask = CadenzaService.createUniqueMetaTask(
11197
+ "Get all actors for sync",
11198
+ (ctx) => ({
10929
11199
  ...ctx,
10930
- task
10931
- };
10932
- }).doOn("meta.sync_controller.task_registered").then(
10933
- CadenzaService.createMetaTask(
10934
- "Ensure actor and task sync ready from task registration",
10935
- (ctx) => {
10936
- if (!this.tasksSynced || !this.actorsSynced) {
10937
- return false;
10938
- }
10939
- return ctx;
10940
- }
10941
- ).then(this.registerActorTaskMapTask)
11200
+ actors: CadenzaService.getAllActors()
11201
+ }),
11202
+ "Collects local actors for the primitive sync phase.",
11203
+ {
11204
+ register: false,
11205
+ isHidden: true
11206
+ }
10942
11207
  );
10943
- CadenzaService.registry.getAllRoutines.clone().doOn(
10944
- "meta.sync_controller.synced_routines",
10945
- "meta.sync_controller.synced_tasks",
10946
- "meta.sync_requested"
10947
- ).then(
10948
- CadenzaService.createMetaTask(
10949
- "Ensure routine and task sync ready",
10950
- (ctx) => {
10951
- if (!this.tasksSynced || !this.routinesSynced) {
10952
- return false;
10953
- }
10954
- return ctx;
10955
- }
10956
- ).then(this.splitTasksInRoutines)
11208
+ startActorPrimitiveSyncTask.then(
11209
+ getAllActorsForSyncTask,
11210
+ gatherActorRegistrationTask
10957
11211
  );
10958
- CadenzaService.createMetaTask("Finish sync", (ctx, emit) => {
10959
- emit("global.meta.sync_controller.synced", {
10960
- data: {
10961
- is_active: true,
10962
- is_non_responsive: false,
10963
- is_blocked: false,
10964
- last_active: formatTimestamp(Date.now())
10965
- },
10966
- filter: {
10967
- uuid: CadenzaService.serviceRegistry.serviceInstanceId
11212
+ getAllActorsForSyncTask.then(this.splitActorsForRegistration);
11213
+ const getAllRoutinesForSyncTask = CadenzaService.registry.getAllRoutines.clone();
11214
+ startRoutinePrimitiveSyncTask.then(
11215
+ getAllRoutinesForSyncTask,
11216
+ gatherRoutineRegistrationTask
11217
+ );
11218
+ getAllRoutinesForSyncTask.then(this.splitRoutinesTask);
11219
+ const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
11220
+ startDirectionalTaskMapSyncTask.then(
11221
+ iterateTasksForDirectionalTaskMapSyncTask,
11222
+ gatherDirectionalTaskMapRegistrationTask
11223
+ );
11224
+ iterateTasksForDirectionalTaskMapSyncTask.then(
11225
+ this.registerTaskMapTask,
11226
+ this.registerDeputyRelationshipTask
11227
+ );
11228
+ recordTaskMapRegistrationTask.then(gatherDirectionalTaskMapRegistrationTask);
11229
+ recordDeputyRelationshipRegistrationTask.then(
11230
+ gatherDirectionalTaskMapRegistrationTask
11231
+ );
11232
+ gatherDirectionalTaskMapRegistrationTask.then(mapPhaseBarrierTask);
11233
+ const iterateTasksForSignalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
11234
+ startSignalTaskMapSyncTask.then(
11235
+ iterateTasksForSignalTaskMapSyncTask,
11236
+ gatherSignalTaskMapRegistrationTask
11237
+ );
11238
+ iterateTasksForSignalTaskMapSyncTask.then(this.registerSignalToTaskMapTask);
11239
+ registerSignalTask.then(gatherSignalTaskMapRegistrationTask);
11240
+ gatherSignalTaskMapRegistrationTask.then(mapPhaseBarrierTask);
11241
+ const iterateTasksForIntentTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
11242
+ startIntentTaskMapSyncTask.then(
11243
+ iterateTasksForIntentTaskMapSyncTask,
11244
+ gatherIntentTaskMapRegistrationTask
11245
+ );
11246
+ iterateTasksForIntentTaskMapSyncTask.then(this.registerIntentToTaskMapTask);
11247
+ registerIntentTask.then(gatherIntentTaskMapRegistrationTask);
11248
+ gatherIntentTaskMapRegistrationTask.then(mapPhaseBarrierTask);
11249
+ const iterateTasksForActorTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
11250
+ startActorTaskMapSyncTask.then(
11251
+ iterateTasksForActorTaskMapSyncTask,
11252
+ gatherActorTaskMapRegistrationTask
11253
+ );
11254
+ iterateTasksForActorTaskMapSyncTask.then(this.registerActorTaskMapTask);
11255
+ recordActorTaskMapRegistrationTask.then(gatherActorTaskMapRegistrationTask);
11256
+ gatherActorTaskMapRegistrationTask.then(mapPhaseBarrierTask);
11257
+ const getAllRoutinesForTaskMapSyncTask = CadenzaService.registry.getAllRoutines.clone();
11258
+ startRoutineTaskMapSyncTask.then(
11259
+ getAllRoutinesForTaskMapSyncTask,
11260
+ gatherRoutineTaskMapRegistrationTask
11261
+ );
11262
+ getAllRoutinesForTaskMapSyncTask.then(this.splitTasksInRoutines);
11263
+ registerTaskToRoutineMapTask.then(gatherRoutineTaskMapRegistrationTask);
11264
+ gatherRoutineTaskMapRegistrationTask.then(mapPhaseBarrierTask);
11265
+ CadenzaService.createMetaTask(
11266
+ "Request sync after local service instance registration",
11267
+ (ctx) => {
11268
+ for (const delayMs of EARLY_SYNC_TICK_DELAYS_MS) {
11269
+ CadenzaService.schedule(
11270
+ "meta.sync_controller.sync_tick",
11271
+ {
11272
+ ...buildMinimalSyncSignalContext(ctx),
11273
+ __syncing: true
11274
+ },
11275
+ delayMs
11276
+ );
10968
11277
  }
10969
- });
10970
- CadenzaService.log("Synced resources...");
10971
- }).attachSignal("global.meta.sync_controller.synced").doOn("meta.sync_controller.synced_resource");
10972
- if (!this.isCadenzaDBReady) {
10973
- CadenzaService.interval(
10974
- "meta.sync_controller.sync_tick",
10975
- { __syncing: true },
10976
- 3e5,
10977
- true
10978
- );
10979
- } else {
10980
- CadenzaService.interval(
10981
- "meta.sync_controller.sync_tick",
10982
- { __syncing: true },
10983
- 18e4
10984
- );
10985
- CadenzaService.schedule(
10986
- "meta.sync_controller.sync_tick",
10987
- { __syncing: true },
10988
- 250
10989
- );
10990
- for (const delayMs of EARLY_SYNC_REQUEST_DELAYS_MS) {
10991
- CadenzaService.schedule("meta.sync_requested", { __syncing: true }, delayMs);
11278
+ return true;
11279
+ },
11280
+ "Schedules the early bootstrap sync burst after local instance registration so startup-defined primitives can converge deterministically.",
11281
+ {
11282
+ register: false,
11283
+ isHidden: true
10992
11284
  }
10993
- }
11285
+ ).doOn("meta.service_registry.instance_inserted");
11286
+ CadenzaService.interval(
11287
+ "meta.sync_controller.sync_tick",
11288
+ { __syncing: true },
11289
+ this.isCadenzaDBReady ? 18e4 : 3e5
11290
+ );
10994
11291
  }
10995
11292
  };
10996
11293
 
@@ -11165,6 +11462,47 @@ function resolveBootstrapEndpoint(options) {
11165
11462
 
11166
11463
  // src/Cadenza.ts
11167
11464
  var CadenzaService = class {
11465
+ static replayRegisteredTaskIntentAssociations() {
11466
+ for (const task of this.registry.tasks.values()) {
11467
+ if (!task.register || task.isHidden || task.handlesIntents.size === 0) {
11468
+ continue;
11469
+ }
11470
+ for (const intentName of task.handlesIntents) {
11471
+ task.emitWithMetadata("meta.task.intent_associated", {
11472
+ data: {
11473
+ intentName,
11474
+ taskName: task.name,
11475
+ taskVersion: task.version
11476
+ },
11477
+ taskInstance: task,
11478
+ __isSubMeta: task.isSubMeta
11479
+ });
11480
+ }
11481
+ }
11482
+ }
11483
+ static replayRegisteredTaskSignalObservations() {
11484
+ for (const task of this.registry.tasks.values()) {
11485
+ if (!task.register || task.isHidden || task.observedSignals.size === 0) {
11486
+ continue;
11487
+ }
11488
+ for (const signalName of task.observedSignals) {
11489
+ task.emitWithMetadata("meta.task.observed_signal", {
11490
+ data: {
11491
+ signalName,
11492
+ taskName: task.name,
11493
+ taskVersion: task.version
11494
+ },
11495
+ taskInstance: task,
11496
+ signalName,
11497
+ __isSubMeta: task.isSubMeta
11498
+ });
11499
+ }
11500
+ }
11501
+ }
11502
+ static replayRegisteredTaskGraphMetadata() {
11503
+ this.replayRegisteredTaskSignalObservations();
11504
+ this.replayRegisteredTaskIntentAssociations();
11505
+ }
11168
11506
  static buildLegacyLocalCadenzaDBTaskName(tableName, operation) {
11169
11507
  const operationPrefix = operation.charAt(0).toUpperCase() + operation.slice(1);
11170
11508
  const helperSuffix = camelCase2(String(tableName ?? "").trim());
@@ -12033,6 +12371,7 @@ var CadenzaService = class {
12033
12371
  const serviceId = options.customServiceId ?? uuid6();
12034
12372
  this.serviceRegistry.serviceName = serviceName;
12035
12373
  this.serviceRegistry.serviceInstanceId = serviceId;
12374
+ this.serviceRegistry.connectsToCadenzaDB = !!options.cadenzaDB?.connect;
12036
12375
  this.setHydrationResults(options.hydration);
12037
12376
  const explicitFrontendMode = options.isFrontend;
12038
12377
  options = {
@@ -12061,6 +12400,22 @@ var CadenzaService = class {
12061
12400
  this.serviceRegistry.useSocket = !!options.useSocket;
12062
12401
  this.serviceRegistry.retryCount = options.retryCount ?? 3;
12063
12402
  this.ensureTransportControllers(isFrontend);
12403
+ if (!isFrontend) {
12404
+ this.createMetaTask(
12405
+ "Initialize graph metadata controller after initial sync",
12406
+ () => {
12407
+ GraphMetadataController.instance;
12408
+ return true;
12409
+ },
12410
+ "Delays direct graph-metadata registration until the bootstrap sync has completed.",
12411
+ {
12412
+ register: false,
12413
+ isHidden: true
12414
+ }
12415
+ ).doOn("meta.service_registry.initial_sync_complete");
12416
+ GraphSyncController.instance.isCadenzaDBReady = serviceName === "CadenzaDB";
12417
+ GraphSyncController.instance.init();
12418
+ }
12064
12419
  const resolvedBootstrapEndpoint = options.cadenzaDB?.connect ? resolveBootstrapEndpoint({
12065
12420
  runtime: isFrontend ? "browser" : "server",
12066
12421
  bootstrap: options.bootstrap,
@@ -12172,14 +12527,13 @@ var CadenzaService = class {
12172
12527
  );
12173
12528
  }).doOn("meta.rest.handshake", "meta.socket.handshake");
12174
12529
  }
12175
- this.createMetaTask("Handle service setup completion", () => {
12530
+ this.createMetaTask("Handle service setup completion", (ctx, emit) => {
12531
+ if (options.cadenzaDB?.connect) {
12532
+ this.serviceRegistry.bootstrapFullSync(emit, ctx, "service_setup_completed");
12533
+ }
12176
12534
  if (isFrontend) {
12177
12535
  registerActorSessionPersistenceTasks();
12178
12536
  this.ensureFrontendSyncLoop();
12179
- } else {
12180
- GraphMetadataController.instance;
12181
- GraphSyncController.instance.isCadenzaDBReady = serviceName === "CadenzaDB" || !!options.cadenzaDB?.connect;
12182
- GraphSyncController.instance.init();
12183
12537
  }
12184
12538
  this.log("Service created.");
12185
12539
  return true;
@@ -12208,7 +12562,15 @@ var CadenzaService = class {
12208
12562
  is_blocked: false,
12209
12563
  health: {}
12210
12564
  },
12211
- __transportData: [],
12565
+ __transportData: declaredTransports.map((transport) => ({
12566
+ uuid: transport.uuid,
12567
+ service_instance_id: serviceId,
12568
+ role: transport.role,
12569
+ origin: transport.origin,
12570
+ protocols: transport.protocols ?? ["rest", "socket"],
12571
+ ...transport.securityProfile ? { security_profile: transport.securityProfile } : {},
12572
+ ...transport.authStrategy ? { auth_strategy: transport.authStrategy } : {}
12573
+ })),
12212
12574
  __serviceName: serviceName,
12213
12575
  __serviceInstanceId: serviceId,
12214
12576
  __useSocket: options.useSocket,