Custom Claims are not added after initial sign up

I just noticed an issue with a Rule I have that adds the Roles a user is a member of as a custom claim to the id token. The Rule is pretty basic, it is below.
This Rule works fine on regular User logins. I noticed though on initial User Sign up the claims are not added to the issued id token. The Rule is still running as I can see the console log output in the Rule Debugger, so I know it’s running.

Why doesn’t this work after sign up?

function (user, context, callback) {
  // Custom namespace, can be the same between environments (Tenants)
  var namespace = 'https://exampledomain.com/claims/';

  // Only roles here, permissions are handled in separate Rule and not added to id token payload
  context.idToken[namespace + "roles"] = user.roles;
  console.log('Context obj is: ' + JSON.stringify(context.idToken));
  
  callback(null, user, context);
}

I could not reproduced the situation with a slightly modified version of the rule. For example, when using the following rule:

function (user, context, callback) {
  var namespace = 'https://example.com/claims/';

  context.idToken[namespace + "roles"] = user.roles || ];
  
  callback(null, user, context);
}

I would always obtain a https://example.com/claims/roles claim in the issued ID token independently of the user authenticating being an already existing user or someone who just signed up. This rule defaults the claim to an empty array ] when user.roles is falsy so it may be possible that in your case user.roles is just not set and as such there is no claim to be set.

If the situation persists and you do not trace its source then you should include additional information as a question update; for example, when it does not work what’s the value of user.roles.

Yes, that is the correct logic that I needed. user.roles will be null after first sign up. I had another rule that was assigning a default role to the user. Once I got that rule working (with the similar logic in your answer) things are working on sign up and regular log in.
// code snippet - logic in rule to assign default “User” Role after sign up
var roles = user.roles || ];
roles.push(defaultRole.name);
user.roles = roles;