1use std::collections::{BTreeMap, HashSet};
9use std::path::{Path, PathBuf};
10
11use serde_json::Value;
12
13use super::home::{fold, has_agent_slugs, has_column, open_ro, place, table_exists, Home, Install};
14use crate::backend::rpc_types::{
15 ForkSlugBlocker, ForkSlugBlockerKind, ForkSlugCandidate, ForkSlugChoice, ForkSlugDuplicate, ForkSlugPlan, ForkSlugSkipped,
16};
17use agentmux_common::slug::{agent_route_name, definition_slug, fork_slug, is_agent_id};
18use rusqlite::OptionalExtension;
19
20#[derive(Debug, Clone, Default)]
22pub(super) struct Def {
23 pub uid: String,
24 pub name: String,
25 pub slug: String,
26 pub former: Vec<String>,
27 pub parent_id: String,
28 pub branch_label: String,
29 pub created_at: i64,
30 pub path: PathBuf,
31}
32
33pub(super) fn load_defs(home: &Home) -> Result<(Vec<Def>, Vec<String>), String> {
37 let dir = home.definitions();
38 let entries = match std::fs::read_dir(&dir) {
39 Ok(e) => e,
40 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((Vec::new(), Vec::new())),
41 Err(e) => return Err(format!("{} can't be listed: {e}", dir.display())),
42 };
43 let mut defs = Vec::new();
44 let mut unreadable = Vec::new();
45 for entry in entries {
46 let path = entry.map_err(|e| format!("{} can't be listed: {e}", dir.display()))?.path();
47 if path.extension().and_then(|e| e.to_str()) != Some("json") || !path.is_file() {
48 continue;
49 }
50 let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or_default().to_string();
51 match std::fs::read(&path).map_err(|e| e.to_string()).and_then(|b| parse_def(&stem, &b, &path)) {
52 Ok(def) => defs.push(def),
53 Err(why) => unreadable.push(format!("{}: {why}", path.display())),
54 }
55 }
56 defs.sort_by(|a, b| a.uid.cmp(&b.uid));
57 Ok((defs, unreadable))
58}
59
60fn parse_def(stem: &str, bytes: &[u8], path: &Path) -> Result<Def, String> {
61 let json: Value = serde_json::from_slice(bytes).map_err(|e| format!("not JSON ({e})"))?;
62 let data = json.get("data").and_then(Value::as_object).ok_or("no `data` object")?;
63 let text = |k: &str| data.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
64 if text("id") != stem {
65 return Err("its `data.id` doesn't name this file".into());
66 }
67 let former = match data.get("former_slugs") {
68 None | Some(Value::Null) => Vec::new(),
69 Some(Value::Array(list)) => list
70 .iter()
71 .map(|f| f.get("slug").and_then(Value::as_str).map(str::to_string))
72 .collect::<Option<Vec<_>>>()
73 .ok_or("a `former_slugs` entry has no slug")?,
74 Some(_) => return Err("`former_slugs` isn't a list".into()),
75 };
76 Ok(Def {
77 uid: stem.to_string(),
78 name: text("name"),
79 slug: text("slug"),
80 former,
81 parent_id: text("parent_id"),
82 branch_label: text("branch_label"),
83 created_at: data.get("created_at").and_then(Value::as_i64).unwrap_or(0),
84 path: path.to_path_buf(),
85 })
86}
87
88#[derive(Debug, Clone)]
90pub(super) struct Found {
91 pub def: Def,
92 pub new_slug: String,
93 pub depth: usize,
94}
95
96pub(super) fn find_candidates(defs: &[Def]) -> (Vec<Found>, Vec<ForkSlugSkipped>) {
101 let by_id: BTreeMap<&str, &Def> = defs.iter().map(|d| (d.uid.as_str(), d)).collect();
102 let mut found = Vec::new();
103 let mut skipped = Vec::new();
104 for def in defs.iter().filter(|d| !d.parent_id.trim().is_empty() && !d.branch_label.is_empty()) {
108 let skip = |reason: &str| ForkSlugSkipped {
109 uid: def.uid.clone(),
110 name: def.name.clone(),
111 slug: def.slug.clone(),
112 reason: reason.to_string(),
113 };
114 let Some(parent) = by_id.get(def.parent_id.as_str()) else {
115 skipped.push(skip("its parent is missing, so the old rule can't be recomputed"));
116 continue;
117 };
118 let Some((root, depth)) = lineage_root(&by_id, def) else {
119 skipped.push(skip("its lineage root is missing"));
120 continue;
121 };
122 if root.slug.trim().is_empty() {
123 skipped.push(skip("its lineage root has no slug"));
124 continue;
125 }
126 let new_slug = fork_slug(&root.slug, &root.name, &def.branch_label);
127 if fold(&def.slug) == fold(&new_slug) {
128 continue;
129 }
130 let label = definition_slug(&def.branch_label);
131 let chained = std::iter::once(&parent.slug).chain(&parent.former).any(|p| {
132 let old_rule = format!("{p}-{label}");
133 fold(&def.slug) == fold(&old_rule) || fold(&def.slug) == definition_slug(&old_rule)
134 });
135 if !chained {
136 skipped.push(skip("not a pre-fix chain: its slug isn't its parent's plus its label"));
137 continue;
138 }
139 if !is_agent_id(&new_slug) {
140 skipped.push(skip(&format!("its new id {new_slug:?} isn't a valid agent id")));
141 continue;
142 }
143 found.push(Found { def: def.clone(), new_slug, depth });
144 }
145 found.sort_by(|a, b| a.depth.cmp(&b.depth).then_with(|| a.def.name.cmp(&b.def.name)));
147 (found, skipped)
148}
149
150fn lineage_root<'a>(by_id: &BTreeMap<&str, &'a Def>, def: &'a Def) -> Option<(&'a Def, usize)> {
156 let mut seen = HashSet::new();
157 let mut cur = def;
158 let mut depth = 0;
159 while !cur.branch_label.is_empty() && !cur.parent_id.is_empty() {
162 if !seen.insert(cur.uid.as_str()) {
163 return None;
164 }
165 cur = by_id.get(cur.parent_id.as_str())?;
166 depth += 1;
167 }
168 Some((cur, depth))
169}
170
171fn routes_to(name: &str, folded: &str) -> bool {
174 !name.trim().is_empty() && fold(&agent_route_name(name)) == folded
175}
176
177pub(super) fn holder_of(
189 home: &Home,
190 installs: &[Install],
191 defs: &[Def],
192 taken: &BTreeMap<String, String>,
193 uid: &str,
194 target: &str,
195) -> Result<Option<String>, String> {
196 let t = fold(target);
197 for d in defs.iter().filter(|d| d.uid != uid) {
198 if fold(&d.slug) == t {
199 return Ok(Some(format!("agent {} ({}) has it as its id", d.name, d.uid)));
200 }
201 if d.former.iter().any(|f| fold(f) == t) {
202 return Ok(Some(format!("agent {} ({}) was renamed from it, and it stays reserved", d.name, d.uid)));
203 }
204 if routes_to(&d.name, &t) {
205 return Ok(Some(format!("messages to it reach agent {} ({}), whose name routes there", d.name, d.uid)));
206 }
207 if routes_to(&d.branch_label, &t) {
209 return Ok(Some(format!("messages to it reach agent {} ({}), whose branch label routes there", d.name, d.uid)));
210 }
211 }
212 if let Some(other) = taken.get(&t).filter(|o| o.as_str() != uid) {
213 return Ok(Some(format!("this run renames agent {other} to it")));
214 }
215 for install in installs {
216 for version in &install.versions {
217 let db = version.objects_db();
218 let failed = |e: rusqlite::Error| format!("{} can't be read: {e}", db.display());
219 let conn = open_ro(&db)?;
220 let slugs = has_agent_slugs(&conn);
221 let row: Option<String> = if slugs {
222 conn.query_row("SELECT id FROM db_agents WHERE slug = ?1 COLLATE NOCASE AND id != ?2 LIMIT 1", [&t, uid], |r| r.get(0))
223 .optional()
224 .map_err(failed)?
225 } else {
226 None
227 };
228 if let Some(id) = row {
229 return Ok(Some(format!("agent {id} has it in {}", place(install, version))));
230 }
231 let routed: Option<(String, String)> = if !slugs {
232 None
233 } else {
234 let col = |c: &str| if has_column(&conn, "db_agents", c) { format!("COALESCE({c}, '')") } else { "''".to_string() };
236 let (name, instance, label) = (col("name"), col("instance_name"), col("branch_label"));
237 let mut stmt = conn
238 .prepare(&format!("SELECT id, {name}, {instance}, {label} FROM db_agents WHERE id != ?1"))
239 .map_err(failed)?;
240 let rows = stmt
241 .query_map([uid], |r| {
242 Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?))
243 })
244 .map_err(failed)?;
245 let mut hit = None;
246 for row in rows {
247 let (id, name, instance, branch_label) = row.map_err(failed)?;
248 if let Some(route) = [name, instance, branch_label].into_iter().find(|n| routes_to(n, &t)) {
249 hit = Some((id, route));
250 break;
251 }
252 }
253 hit
254 };
255 if let Some((id, name)) = routed {
256 return Ok(Some(format!("messages to it reach agent {id} in {}, whose name {name:?} routes there", place(install, version))));
257 }
258 if table_exists(&conn, "db_agent_former_slugs") {
259 let former: Option<String> = conn
260 .query_row(
261 "SELECT agent_uid FROM db_agent_former_slugs WHERE slug = ?1 COLLATE NOCASE AND agent_uid != ?2 LIMIT 1",
262 [&t, uid],
263 |r| r.get(0),
264 )
265 .optional()
266 .map_err(failed)?;
267 if let Some(id) = former {
268 return Ok(Some(format!("agent {id} was renamed from it in {}", place(install, version))));
269 }
270 }
271 if table_exists(&conn, "db_agent_former_names") {
272 let mut stmt = conn.prepare("SELECT agent_id, name FROM db_agent_former_names WHERE agent_id != ?1").map_err(failed)?;
273 let rows = stmt.query_map([uid], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(failed)?;
274 for row in rows {
275 let (id, name) = row.map_err(failed)?;
276 if routes_to(&name, &t) {
277 return Ok(Some(format!(
278 "agent {id} was called {name:?} in {}, and messages to that name still reach it",
279 place(install, version)
280 )));
281 }
282 }
283 }
284 if let Some(entry) = super::running::registration(&version.registrations(), &t) {
285 let owner = super::running::block_agent(&conn, &entry.block_id);
286 if owner.as_deref() != Some(uid) {
287 return Ok(Some(format!("a running pane is registered as it in {}", place(install, version))));
288 }
289 }
290 }
291 }
292 for entry in super::running::shared_entries(home, &t) {
293 if entry.uid != uid {
294 return Ok(Some(format!("a running pane in channel {} is registered as it", entry.channel)));
295 }
296 }
297 Ok(None)
298}
299
300pub fn plan(home: &Home, quick: bool) -> Result<ForkSlugPlan, String> {
304 plan_with(home, quick, true, &[])
305}
306
307pub fn plan_choosing(home: &Home, quick: bool, choices: &[ForkSlugChoice]) -> Result<ForkSlugPlan, String> {
309 plan_with(home, quick, true, choices)
310}
311
312fn apply_choices(found: &mut [Found], choices: &[ForkSlugChoice]) -> Result<(), String> {
317 for choice in choices {
318 let slug = choice.new_slug.trim();
319 let Some(f) = found.iter_mut().find(|f| f.def.uid == choice.uid) else {
320 return Err(format!("{} isn't an agent with an outdated id", choice.uid));
321 };
322 if !is_agent_id(slug) {
323 return Err(format!("{slug:?} isn't a valid agent id"));
324 }
325 if fold(slug) == fold(&f.def.slug) {
326 return Err(format!("{} already has the id {slug}", f.def.name));
327 }
328 f.new_slug = slug.to_string();
329 }
330 Ok(())
331}
332
333pub(super) fn plan_with(home: &Home, quick: bool, check_lock: bool, choices: &[ForkSlugChoice]) -> Result<ForkSlugPlan, String> {
336 let (defs, unreadable) = load_defs(home)?;
337 let (mut found, skipped) = find_candidates(&defs);
338 if !quick {
339 apply_choices(&mut found, choices)?;
340 }
341 if quick {
342 let candidates = found.into_iter().map(|f| bare(&f)).collect::<Vec<_>>();
343 let summary = summary(&candidates, &skipped, &[], &[]);
344 return Ok(ForkSlugPlan { candidates, skipped, blockers: Vec::new(), summary, last_run: last_run(home), duplicates: Vec::new() });
345 }
346 let installs = home.installs()?;
347 let mut blockers: Vec<ForkSlugBlocker> = unreadable
348 .iter()
349 .map(|u| ForkSlugBlocker::new(ForkSlugBlockerKind::Unreadable, format!("A shared definition can't be read, so no new id can be checked: {u}")))
350 .collect();
351 blockers.extend(unreadable_stores(home, &installs).into_iter().map(|u| {
352 ForkSlugBlocker::new(ForkSlugBlockerKind::Unreadable, format!("A database can't be read, so no new id can be checked: {u}"))
353 }));
354 if !blockers.is_empty() {
355 let candidates: Vec<ForkSlugCandidate> = found
358 .iter()
359 .map(|f| ForkSlugCandidate { refused: Some("not every store can be read, so its new id can't be checked".into()), ..bare(f) })
360 .collect();
361 let duplicates = super::duplicates::duplicates(home, &installs, &defs, &BTreeMap::new(), false);
364 let summary = summary(&candidates, &skipped, &blockers, &duplicates);
365 return Ok(ForkSlugPlan { candidates, skipped, blockers, summary, last_run: last_run(home), duplicates });
366 }
367 let mut taken: BTreeMap<String, String> = BTreeMap::new();
368 let mut candidates = Vec::new();
369 for f in &found {
370 let mut c = bare(f);
371 match holder_of(home, &installs, &defs, &taken, &f.def.uid, &f.new_slug) {
372 Ok(Some(holder)) => {
373 c.refused = Some(format!("{} is taken: {holder}", f.new_slug));
374 c.suggestion = suggest(home, &installs, &defs, &taken, &f.def.uid, &f.new_slug).unwrap_or(None);
375 }
376 Ok(None) => {
377 taken.insert(fold(&f.new_slug), f.def.uid.clone());
378 }
379 Err(e) => {
380 c.refused = Some("its new id can't be checked".into());
381 blockers.push(ForkSlugBlocker::new(ForkSlugBlockerKind::Unreadable, format!("A database can't be read, so no new id can be checked: {e}")));
382 candidates.push(c);
383 continue;
384 }
385 }
386 c.locations = super::locations::locations(home, &installs, &f.def, &f.new_slug)?;
387 c.running = super::running::running(home, &installs, &f.def)?;
388 candidates.push(c);
389 }
390 if candidates.iter().any(|c| c.refused.is_none()) {
391 blockers.extend(super::preconditions::blockers(home, &installs, &candidates, check_lock));
392 }
393 let duplicates = super::duplicates::duplicates(home, &installs, &defs, &taken, true);
394 let summary = summary(&candidates, &skipped, &blockers, &duplicates);
395 Ok(ForkSlugPlan { candidates, skipped, blockers, summary, last_run: last_run(home), duplicates })
396}
397
398fn last_run(home: &Home) -> Option<crate::backend::rpc_types::ForkSlugLastRun> {
401 let (path, journal) = super::journal::journals(&home.backups())
402 .into_iter()
403 .find_map(|p| super::journal::Journal::read(&p).ok().map(|j| (p, j)))?;
404 if journal.rolled_back() {
405 return None;
406 }
407 Some(crate::backend::rpc_types::ForkSlugLastRun {
408 journal: path.display().to_string(),
409 finished: journal.finished().is_some(),
410 failed: journal.last_failure(),
411 })
412}
413
414pub(super) fn unreadable_stores(home: &Home, installs: &[Install]) -> Vec<String> {
419 let mut out = Vec::new();
420 let probe = |db: &Path, sql: &str, out: &mut Vec<String>| {
421 let result = open_ro(db).and_then(|c| {
422 c.query_row(sql, [], |_| Ok(())).optional().map(|_| ()).map_err(|e| e.to_string())
423 });
424 if let Err(e) = result {
425 out.push(format!("{} ({e})", db.display()));
426 }
427 };
428 for install in installs {
429 for version in &install.versions {
430 probe(&version.objects_db(), "SELECT name FROM sqlite_master LIMIT 1", &mut out);
433 }
434 if let Some(wan) = install.wan_db() {
435 probe(&wan, "SELECT name FROM sqlite_master LIMIT 1", &mut out);
436 }
437 }
438 for db in home.host_stores(installs) {
439 probe(&db, "SELECT name FROM sqlite_master LIMIT 1", &mut out);
440 }
441 out
442}
443
444fn bare(f: &Found) -> ForkSlugCandidate {
445 ForkSlugCandidate {
446 uid: f.def.uid.clone(),
447 name: f.def.name.clone(),
448 old_slug: f.def.slug.clone(),
449 new_slug: f.new_slug.clone(),
450 refused: None,
451 suggestion: None,
452 locations: Vec::new(),
453 running: Vec::new(),
454 }
455}
456
457fn suggest(
460 home: &Home,
461 installs: &[Install],
462 defs: &[Def],
463 taken: &BTreeMap<String, String>,
464 uid: &str,
465 target: &str,
466) -> Result<Option<String>, String> {
467 for n in 2..100 {
468 let next = format!("{target}-{n}");
469 if is_agent_id(&next) && holder_of(home, installs, defs, taken, uid, &next)?.is_none() {
470 return Ok(Some(next));
471 }
472 }
473 Ok(None)
474}
475
476fn summary(candidates: &[ForkSlugCandidate], skipped: &[ForkSlugSkipped], blockers: &[ForkSlugBlocker], duplicates: &[ForkSlugDuplicate]) -> String {
477 let ready = candidates.iter().filter(|c| c.refused.is_none()).count();
478 let mut lines = Vec::new();
479 if candidates.is_empty() {
480 lines.push("No agent has an outdated id.".to_string());
481 } else {
482 lines.push(format!(
483 "{} agent{} {} an outdated id; {ready} can be updated now.",
484 candidates.len(),
485 if candidates.len() == 1 { "" } else { "s" },
486 if candidates.len() == 1 { "has" } else { "have" },
487 ));
488 }
489 for c in candidates {
490 match &c.refused {
491 None => lines.push(format!(" {} : {} -> {}", c.name, c.old_slug, c.new_slug)),
492 Some(why) => lines.push(format!(" {} : {} -> {} refused: {why}", c.name, c.old_slug, c.new_slug)),
493 }
494 }
495 if !skipped.is_empty() {
496 lines.push(format!("{} fork{} left alone (not a pre-fix chain).", skipped.len(), if skipped.len() == 1 { "" } else { "s" }));
497 }
498 for b in blockers {
499 lines.push(format!("Blocked: {}", b.message));
500 }
501 for d in duplicates {
502 lines.push(format!("{} agents share the id {} (an update doesn't change it):", d.holders.len(), d.slug));
503 for (i, h) in d.holders.iter().enumerate() {
504 let what = match (i, &h.proposed) {
505 (0, _) => "keeps it, as the oldest".to_string(),
506 (_, Some(p)) => format!("could be renamed to {p}"),
507 (_, None) => "needs a new id".to_string(),
508 };
509 lines.push(format!(" {} ({}, {}): {what}", h.name, h.uid, h.place));
510 }
511 }
512 lines.join("\n")
513}