Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@
<AdditionalFiles Include="$(MSBuildThisFileDirectory)CodeMetricsConfig.txt" />
</ItemGroup>

<ItemGroup Condition="'$(MSBuildProjectName)' != 'Orbit.Analyzers'">
<ItemGroup Condition="'$(MSBuildProjectName)' != 'Orbit.Analyzers' And '$(MSBuildProjectName)' != 'Orbit.Analyzers.CodeFixes'">
<ProjectReference Include="$(MSBuildThisFileDirectory)src/Orbit.Analyzers/Orbit.Analyzers.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false"
PrivateAssets="all" />
<ProjectReference Include="$(MSBuildThisFileDirectory)src/Orbit.Analyzers.CodeFixes/Orbit.Analyzers.CodeFixes.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false"
PrivateAssets="all" />
</ItemGroup>

</Project>
1 change: 1 addition & 0 deletions Orbit.slnx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/Orbit.Analyzers/Orbit.Analyzers.csproj" />
<Project Path="src/Orbit.Analyzers.CodeFixes/Orbit.Analyzers.CodeFixes.csproj" />
<Project Path="src/Orbit.Api/Orbit.Api.csproj" />
<Project Path="src/Orbit.Application/Orbit.Application.csproj" />
<Project Path="src/Orbit.Domain/Orbit.Domain.csproj" />
Expand Down
22 changes: 22 additions & 0 deletions src/Orbit.Analyzers.CodeFixes/Orbit.Analyzers.CodeFixes.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<ImplicitUsings>disable</ImplicitUsings>
<IncludeBuildOutput>false</IncludeBuildOutput>
<EnforceExtendedAnalyzerRules>false</EnforceExtendedAnalyzerRules>
<IsPackable>false</IsPackable>
<NoWarn>$(NoWarn);RS2008</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="5.6.0" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Orbit.Analyzers\Orbit.Analyzers.csproj" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion src/Orbit.Analyzers/Orbit.Analyzers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.6.0" PrivateAssets="all" />
</ItemGroup>

</Project>
6 changes: 5 additions & 1 deletion src/Orbit.Api/Controllers/AdminController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ public async Task<IActionResult> SendMarketingBroadcast(
if (result.IsFailure)
return result.ToErrorResult();

LogBroadcastRequested(logger, HttpContext.GetUserId(), result.Value.RecipientCount, result.Value.WasTest);
if (logger.IsEnabled(LogLevel.Information))
{
var adminUserId = HttpContext.GetUserId();
LogBroadcastRequested(logger, adminUserId, result.Value.RecipientCount, result.Value.WasTest);
}
return Accepted(new { recipientCount = result.Value.RecipientCount, test = result.Value.WasTest });
}

Expand Down
2 changes: 1 addition & 1 deletion src/Orbit.Api/Controllers/SyncControllerMutations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ private static async Task ApplyEntityMutationAsync<TEntity>(
Action<TEntity> mutate,
CancellationToken ct) where TEntity : class
{
if (mutation.Action.ToLowerInvariant() != supportedAction)
if (!string.Equals(mutation.Action, supportedAction, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"Unsupported action: {mutation.Action} for {entityNoun}.");

if (mutation.Id is null)
Expand Down
6 changes: 5 additions & 1 deletion src/Orbit.Api/Controllers/WaitlistController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ public async Task<IActionResult> Join(
{
await mediator.Send(new JoinWaitlistCommand(request.Email, request.Language), cancellationToken);

LogWaitlistJoinRequested(logger, HttpContext.GetRequestId());
if (logger.IsEnabled(LogLevel.Information))
{
var requestId = HttpContext.GetRequestId();
LogWaitlistJoinRequested(logger, requestId);
}
return Ok(new { message = "Check your inbox to confirm your spot." });
}

Expand Down
6 changes: 2 additions & 4 deletions src/Orbit.Api/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,9 @@ public static WebApplicationBuilder AddOrbitAuthentication(this WebApplicationBu
};
});

builder.Services.AddAuthorization(options =>
{
options.AddPolicy(AdminPolicy.Name, policy =>
builder.Services.AddAuthorizationBuilder()
.AddPolicy(AdminPolicy.Name, policy =>
policy.Requirements.Add(new AdminRequirement()));
});
builder.Services.AddScoped<IAuthorizationHandler, AdminAuthorizationHandler>();

return builder;
Expand Down
6 changes: 5 additions & 1 deletion src/Orbit.Api/Middleware/MinimumVersionMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ public async Task InvokeAsync(HttpContext context, IAppConfigService configServi
return;
}

LogUpgradeRequired(logger, clientVersion, minimumVersion, context.GetRequestId());
if (logger.IsEnabled(LogLevel.Information))
{
var requestId = context.GetRequestId();
LogUpgradeRequired(logger, clientVersion, minimumVersion, requestId);
}

context.Response.StatusCode = StatusCodes.Status426UpgradeRequired;
context.Response.ContentType = "application/json";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ private async Task PersistExecutionResultsAsync(
{
await ConcurrencyRetry.SaveWithRetryAsync(
execution.UnitOfWork,
ct => execution.UserStreakService.RecalculateAsync(userId, ct),
ct => execution.UserStreakService.RecalculateAsync(userId, cancellationToken: ct),
cancellationToken);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ public async Task<Result<ChatResponse>> Handle(
goalList));
}

private (string? AiMessage, HabitListCard? HabitList, GoalListCard? GoalList) BuildResponseCards(
private static (string? AiMessage, HabitListCard? HabitList, GoalListCard? GoalList) BuildResponseCards(
string? aiMessage, ProcessUserChatCommand request, ChatContext context)
{
HabitListCard? habitList = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public async Task<Result<RecapResponse>> Handle(GetRecapQuery request, Cancellat
cancellationToken);

var streakState = await userStreakService.RecalculateAsync(
request.UserId, cancellationToken, awardFreezeIfEligible: false);
request.UserId, awardFreezeIfEligible: false, cancellationToken);

var metrics = RetrospectiveMetricsCalculator.Compute(
habits.ToList(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public async Task<Result<StreakInfoResponse>> Handle(GetStreakInfoQuery request,
return Result.PayGateFailure<StreakInfoResponse>("Streak insights are a Pro feature. Upgrade to unlock!");

var recalculatedStreak = await userStreakService.RecalculateAsync(
request.UserId, cancellationToken, awardFreezeIfEligible: false);
request.UserId, awardFreezeIfEligible: false, cancellationToken);
if (recalculatedStreak is not null)
await unitOfWork.SaveChangesAsync(cancellationToken);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ await unitOfWork.ExecuteInTransactionAsync(async ct =>
{
await ConcurrencyRetry.SaveWithRetryAsync(
unitOfWork,
c => userStreakService.RecalculateAsync(request.UserId, c),
c => userStreakService.RecalculateAsync(request.UserId, cancellationToken: c),
ct);
}
}, cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ await unitOfWork.ExecuteInTransactionAsync(async ct =>

await ConcurrencyRetry.SaveWithRetryAsync(
unitOfWork,
c => services.UserStreakService.RecalculateAsync(request.UserId, c),
c => services.UserStreakService.RecalculateAsync(request.UserId, cancellationToken: c),
ct);
}
}, cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public async Task<Result> Handle(DeleteHabitCommand request, CancellationToken c
await unitOfWork.SaveChangesAsync(cancellationToken);
await ConcurrencyRetry.SaveWithRetryAsync(
unitOfWork,
ct => userStreakService.RecalculateAsync(request.UserId, ct),
ct => userStreakService.RecalculateAsync(request.UserId, cancellationToken: ct),
cancellationToken);

var today = await userDateService.GetUserTodayAsync(request.UserId, cancellationToken);
Expand Down
6 changes: 3 additions & 3 deletions src/Orbit.Application/Habits/Commands/LogHabitCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ private async Task<Result<LogHabitResponse>> HandleUnlogAsync(
await ConcurrencyRetry.SaveWithRetryAsync(
unitOfWork,
async ct => streakState = await services.UserStreakService.RecalculateAsync(
habit.UserId, ct, awardFreezeIfEligible: false),
habit.UserId, awardFreezeIfEligible: false, ct),
cancellationToken);
CacheInvalidationHelper.InvalidateUserAiCaches(cache, habit.UserId, today);

Expand Down Expand Up @@ -197,7 +197,7 @@ private async Task<Result<LogHabitResponse>> HandleLogAsync(
attempt++;
}

var streakState = await services.UserStreakService.RecalculateAsync(request.UserId, cancellationToken);
var streakState = await services.UserStreakService.RecalculateAsync(request.UserId, cancellationToken: cancellationToken);
var gamificationResult = await ProcessGamificationSafeAsync(request.UserId, request.HabitId, cancellationToken);
await ProcessChallengeProgressSafeAsync(request.UserId, request.HabitId, cancellationToken);
await ProcessOnboardingChecklistSafeAsync(request.UserId, OnboardingChecklistSignal.HabitLogged, cancellationToken);
Expand Down Expand Up @@ -243,7 +243,7 @@ private async Task PersistStreakRecalcAsync(Guid userId, CancellationToken cance
catch (DbUpdateConcurrencyException) when (attempt < MaxLogAttempts)
{
unitOfWork.ResetTracking();
await services.UserStreakService.RecalculateAsync(userId, cancellationToken);
await services.UserStreakService.RecalculateAsync(userId, cancellationToken: cancellationToken);
}

attempt++;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public async Task<Result> Handle(RestoreHabitCommand request, CancellationToken
await unitOfWork.SaveChangesAsync(cancellationToken);
await ConcurrencyRetry.SaveWithRetryAsync(
unitOfWork,
ct => userStreakService.RecalculateAsync(request.UserId, ct),
ct => userStreakService.RecalculateAsync(request.UserId, cancellationToken: ct),
cancellationToken);

var today = await userDateService.GetUserTodayAsync(request.UserId, cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public async Task<Result<RetrospectiveResponse>> Handle(
return Result.Failure<RetrospectiveResponse>(ErrorMessages.NoHabitsForPeriod);

var streakState = await userStreakService.RecalculateAsync(
request.UserId, cancellationToken, awardFreezeIfEligible: false);
request.UserId, awardFreezeIfEligible: false, cancellationToken);

var metrics = RetrospectiveMetricsCalculator.Compute(
habitList,
Expand Down
3 changes: 3 additions & 0 deletions src/Orbit.Application/Profile/Commands/SetHandleCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@ public async Task<Result> Handle(SetHandleCommand request, CancellationToken can
var normalized = request.Handle.Trim();
var lowered = normalized.ToLowerInvariant();

// EF Core cannot translate string.Equals(StringComparison) to SQL; the case-insensitive handle match stays as ToLower(). https://github.com/dotnet/efcore/issues/1222
#pragma warning disable CA1862
var taken = await userRepository.AnyAsync(
u => u.Id != request.UserId && u.Handle != null && u.Handle.ToLower() == lowered,
cancellationToken);
#pragma warning restore CA1862
if (taken)
return Result.Failure(ErrorMessages.HandleTaken);

Expand Down
3 changes: 3 additions & 0 deletions src/Orbit.Application/Social/Services/FriendGraphService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@ public class FriendGraphService(
if (!string.IsNullOrWhiteSpace(handle))
{
var normalized = handle.Trim().ToLowerInvariant();
// EF Core cannot translate string.Equals(StringComparison) to SQL; the case-insensitive handle match stays as ToLower(). https://github.com/dotnet/efcore/issues/1222
#pragma warning disable CA1862
var matches = await userRepository.FindAsync(
u => u.Handle != null && u.Handle.ToLower() == normalized,
cancellationToken);
#pragma warning restore CA1862
return matches.Count > 0 ? matches[0] : null;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Orbit.Domain/Interfaces/IUserStreakService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ public interface IUserStreakService
/// <param name="cancellationToken">Cancellation.</param>
Task<UserStreakState?> RecalculateAsync(
Guid userId,
CancellationToken cancellationToken = default,
bool awardFreezeIfEligible = true);
bool awardFreezeIfEligible = true,
CancellationToken cancellationToken = default);
}
8 changes: 4 additions & 4 deletions src/Orbit.Infrastructure/AI/AiCompletionClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,10 @@ internal AiCompletionClient(
string systemPrompt,
string userPrompt,
double temperature = 0.7,
CancellationToken cancellationToken = default,
int? maxOutputTokens = null,
string purpose = "text",
AiModelTier tier = AiModelTier.Primary)
AiModelTier tier = AiModelTier.Primary,
CancellationToken cancellationToken = default)
{
var messages = new List<ChatMessage>
{
Expand Down Expand Up @@ -136,10 +136,10 @@ internal AiCompletionClient(
string systemPrompt,
string userPrompt,
double temperature = 0.1,
CancellationToken cancellationToken = default,
int? maxOutputTokens = null,
string purpose = "json",
AiModelTier tier = AiModelTier.Primary)
AiModelTier tier = AiModelTier.Primary,
CancellationToken cancellationToken = default)
{
var messages = new List<ChatMessage>
{
Expand Down
2 changes: 1 addition & 1 deletion src/Orbit.Infrastructure/Services/AiGoalReviewService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public async Task<Result<string>> GenerateReviewAsync(
"You are a goal progress coach. Review the user's active goals and provide a concise summary.",
prompt,
temperature: 0.7,
cancellationToken,
cancellationToken: cancellationToken,
purpose: "goal_review");

if (string.IsNullOrWhiteSpace(text))
Expand Down
2 changes: 1 addition & 1 deletion src/Orbit.Infrastructure/Services/AiIntentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@
System.Diagnostics.Stopwatch stopwatch,
bool firstTokenLogged)
{
foreach (var part in update.ContentUpdate.Where(part => !string.IsNullOrEmpty(part.Text)))

Check warning on line 239 in src/Orbit.Infrastructure/Services/AiIntentService.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

Loop should be simplified by calling Select(part => part.Text))

Check warning on line 239 in src/Orbit.Infrastructure/Services/AiIntentService.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

Loop should be simplified by calling Select(part => part.Text))
{
if (!firstTokenLogged)
{
Expand Down Expand Up @@ -384,7 +384,7 @@
HistorySummarySystemPrompt,
transcript,
temperature: 0.2,
cancellationToken,
cancellationToken: cancellationToken,
maxOutputTokens: 320,
purpose: "history_summary");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public sealed partial class AiProactiveCheckinMessageService(
"You are Astra, a supportive habit coach sending a proactive check-in push notification to help someone get back on track with the habits they fell behind on today.",
prompt,
temperature: 0.9,
cancellationToken,
cancellationToken: cancellationToken,
purpose: "proactive_checkin");

if (string.IsNullOrWhiteSpace(text))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public async Task<Result<RetrospectiveNarrative>> GenerateRetrospectiveAsync(
"You are a thoughtful habit coach writing retrospective reviews.",
prompt,
temperature: 0.7,
cancellationToken,
cancellationToken: cancellationToken,
purpose: "retrospective");

if (string.IsNullOrWhiteSpace(text))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public sealed partial class AiSlipAlertMessageService(
"You are a supportive habit coach sending a push notification to help someone avoid a bad habit slip-up.",
prompt,
temperature: 0.9,
cancellationToken,
cancellationToken: cancellationToken,
purpose: "slip_alert");

if (string.IsNullOrWhiteSpace(text))
Expand Down
2 changes: 1 addition & 1 deletion src/Orbit.Infrastructure/Services/AiSummaryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public async Task<Result<DailySummaryContent>> GenerateSummaryAsync(
"You are Astra, a perceptive, warm close friend who knows the person well. You notice and celebrate the good things they have already done, you treat a slip on a habit they are trying to quit as a gentle, judgment-free moment rather than something to praise, and you stay easy and unpushy about what is left. You never sound corporate, clinical, or like a coach reading a checklist. You reply with a single JSON object as instructed; the wording inside every field is plain language -- no markdown, bullets, headings, or emoji -- with no greeting and no sign-off, only in the language you are told to use.",
prompt,
temperature: 0.7,
cancellationToken,
cancellationToken: cancellationToken,
maxOutputTokens: 240,
purpose: "daily_summary");

Expand Down
6 changes: 5 additions & 1 deletion src/Orbit.Infrastructure/Services/AiUsageSummaryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,11 @@ internal async Task SummarizeYesterdayAsync(CancellationToken cancellationToken)
.Where(usage => usage.Date == yesterday)
.ToListAsync(cancellationToken);

LogAiUsageSummary(logger, BuildSummaryLine(yesterday, rows, _pricing));
if (logger.IsEnabled(LogLevel.Information))
{
var summaryLine = BuildSummaryLine(yesterday, rows, _pricing);
LogAiUsageSummary(logger, summaryLine);
}
_lastSummarizedDate = yesterday;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Orbit.Infrastructure/Services/UserStreakService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public partial class UserStreakService(
{
public async Task<UserStreakState?> RecalculateAsync(
Guid userId,
CancellationToken cancellationToken = default,
bool awardFreezeIfEligible = true)
bool awardFreezeIfEligible = true,
CancellationToken cancellationToken = default)
{
var user = await repos.Users.FindOneTrackedAsync(
u => u.Id == userId,
Expand Down
1 change: 1 addition & 0 deletions tests/Orbit.Analyzers.Tests/Orbit.Analyzers.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

<ItemGroup>
<ProjectReference Include="..\..\src\Orbit.Analyzers\Orbit.Analyzers.csproj" />
<ProjectReference Include="..\..\src\Orbit.Analyzers.CodeFixes\Orbit.Analyzers.CodeFixes.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ private void AssertEnqueuedVerificationEmail(string expectedEmail, string expect
_backgroundJobClient.Received(1).Create(
Arg.Any<Job>(), Arg.Is<IState>(state => state is EnqueuedState));
_enqueuedJob.Should().NotBeNull();
_enqueuedJob!.Type.Should().Be(typeof(SendVerificationCodeEmailJob));
_enqueuedJob!.Type.Should().Be<SendVerificationCodeEmailJob>();
_enqueuedJob.Method.Name.Should().Be(nameof(SendVerificationCodeEmailJob.ExecuteAsync));
_enqueuedJob.Args.Should().Equal(expectedEmail, expectedCode, expectedLanguage);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public ProcessUserChatCommandHandlerTests()
_catalogService.BuildDynamicSupplement(Arg.Any<AgentContextSnapshot>()).Returns("dynamic supplement");

_userDateService.GetUserTodayAsync(UserId, Arg.Any<CancellationToken>()).Returns(Today);
_userStreakService.RecalculateAsync(UserId, Arg.Any<CancellationToken>())
_userStreakService.RecalculateAsync(UserId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(new UserStreakState(1, 1, Today));
_streakGoalReadSyncer.ComputeFreshValuesAsync(Arg.Any<Guid>(), Arg.Any<DateOnly>(), Arg.Any<CancellationToken>())
.Returns(new Dictionary<Guid, int>());
Expand Down
Loading
Loading