From ce0cad0d6913315986adb901f129adcb161c7f73 Mon Sep 17 00:00:00 2001
From: Sweet Tea Dorminy <sweettea-kernel@dorminy.me>
Date: Sat, 7 Nov 2026 17:39:32 -0800
Subject: [PATCH] ai/default: Do not swap the first defender for a veterancy
 building

adjust_ai_unit_choice() replaces any non-veteran military unit choice
with the building that grants veterancy, with no look at the city. The
walls path in military_advisor_choose_build() refuses to build walls
before the first defender; the veterancy path happily queues Barracks
in an empty city for an army that does not exist, at gold upkeep. Keep
the unit choice when no defender of ours stands in the city.

Signed-off-by: Sweet Tea Dorminy <sweettea-kernel@dorminy.me>
---
 ai/default/daimilitary.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/ai/default/daimilitary.c b/ai/default/daimilitary.c
index fd456a347b..24819d459d 100644
--- a/ai/default/daimilitary.c
+++ b/ai/default/daimilitary.c
@@ -1768,6 +1768,7 @@ static void adjust_ai_unit_choice(struct city *pcity,
                                   struct adv_choice *choice)
 {
   Impr_type_id id;
+  bool has_defender = FALSE;
 
   /* Sanity */
   if (!is_unit_choice_type(choice->type)
@@ -1776,6 +1777,20 @@ static void adjust_ai_unit_choice(struct city *pcity,
     return;
   }
 
+  /* A veterancy building helps nothing if there is nobody to garrison
+   * the city; the first defender comes first. */
+  unit_list_iterate(city_tile(pcity)->units, punit) {
+    if (unit_owner(punit) == city_owner(pcity)
+        && !unit_has_type_flag(punit, UTYF_CIVILIAN)
+        && unit_type_get(punit)->defense_strength > 0) {
+      has_defender = TRUE;
+      break;
+    }
+  } unit_list_iterate_end;
+  if (!has_defender) {
+    return;
+  }
+
   /*  N.B.: have to check that we haven't already built the building --mck */
   if ((id = dai_find_source_building(pcity, EFT_VETERAN_BUILD,
                                      choice->value.utype)) != B_LAST
-- 
2.55.0

