isSubagentDescendant reports whether targetChatID is a descendant of ancestorChatID by walking up the parent chain from the target. This is O(depth) DB queries instead of O(nodes) BFS.
( ctx context.Context, store database.Store, ancestorChatID uuid.UUID, targetChatID uuid.UUID, )
| 1474 | // of ancestorChatID by walking up the parent chain from the target. |
| 1475 | // This is O(depth) DB queries instead of O(nodes) BFS. |
| 1476 | func isSubagentDescendant( |
| 1477 | ctx context.Context, |
| 1478 | store database.Store, |
| 1479 | ancestorChatID uuid.UUID, |
| 1480 | targetChatID uuid.UUID, |
| 1481 | ) (bool, error) { |
| 1482 | if ancestorChatID == targetChatID { |
| 1483 | return false, nil |
| 1484 | } |
| 1485 | |
| 1486 | currentID := targetChatID |
| 1487 | visited := map[uuid.UUID]struct{}{} // cycle protection |
| 1488 | for { |
| 1489 | if _, seen := visited[currentID]; seen { |
| 1490 | return false, nil |
| 1491 | } |
| 1492 | visited[currentID] = struct{}{} |
| 1493 | |
| 1494 | chat, err := store.GetChatByID(ctx, currentID) |
| 1495 | if err != nil { |
| 1496 | if xerrors.Is(err, sql.ErrNoRows) { |
| 1497 | return false, nil // chain broken; not a confirmed descendant |
| 1498 | } |
| 1499 | return false, xerrors.Errorf("get chat %s: %w", currentID, err) |
| 1500 | } |
| 1501 | if !chat.ParentChatID.Valid { |
| 1502 | return false, nil // reached root without finding ancestor |
| 1503 | } |
| 1504 | if chat.ParentChatID.UUID == ancestorChatID { |
| 1505 | return true, nil |
| 1506 | } |
| 1507 | currentID = chat.ParentChatID.UUID |
| 1508 | } |
| 1509 | } |
| 1510 | |
| 1511 | func subagentFallbackChatTitle(message string) string { |
| 1512 | const maxWords = 6 |