diff --git a/HealthApp.slnx b/HealthApp.slnx
index e9cd00a..db8a702 100644
--- a/HealthApp.slnx
+++ b/HealthApp.slnx
@@ -1 +1 @@
-
+
diff --git a/ImplementationPlan/clinical-provenance.md b/ImplementationPlan/clinical-provenance.md
new file mode 100644
index 0000000..d7c04ec
--- /dev/null
+++ b/ImplementationPlan/clinical-provenance.md
@@ -0,0 +1,14 @@
+# Preserved clinical behaviour and evidence limits
+
+Approval Q3 requires existing content, thresholds and classifications unchanged for functional comparison. Reference bundle `baseline-2026-10-05` preserves source/update/review dates and numerical operators from pinned source; public guidance preserves its 2026-10-04 review metadata. No new clinical review has been performed or implied.
+
+| Preserved rule/content | Provenance and uncertainty |
+| --- | --- |
+| Home high BP systolic >=135 / diastolic >=85; clinic >=140 / >=90 | Baseline cites Sundhed.dk Lægehåndbogen Højt blodtryk, updated 2024-09-25, reviewed 2026-10-05. Single known Home/Clinic/rest prerequisites and known inadequate preparation gate remain unchanged. General threshold is not personal target |
+| Resting pulse <50 / >100, exclusive limits | Baseline cites Patienthåndbogen Bradykardi (updated 2025-09-02) and Hurtig puls (updated 2025-05-12), reviewed 2026-10-05. Low rate may be physiological; medication/fitness/symptoms unknown |
+| PotentiallyFavourable pressure decrease remaining high; pulse moving from outside towards interval without opposite excursion | Baseline explicitly calls these cautious inferences, not clinical decision rules. Clinical support of every development claim is uncertain; preserved under Q3, no new validation claim |
+| Mixed reversals/outside excursions; PotentiallyConcerning outside levels; CannotInterpret unsupported situations | Exact original branching and explanation preserved. Passing tests verifies equivalence, not clinical validity |
+| Narrative conflicts | Original finite English/Danish phrase detector preserved, including during exercise. Negation/unrecognized wording remain limitations, stated in unchanged explanations; no general-language comprehension claim |
+| Home equipment/rest/repeat/pulse guidance | Original six steps and two source records preserved; clinic/other unavailable and Unknown explicitly labelled. No request-time publisher call or patient write |
+
+Any necessary change to externally visible clinical rules, labels, content or thresholds must be approved before changing it. No unsupported label is silently disabled to make an architecture check pass.
diff --git a/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_11_47_35.trx b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_11_47_35.trx
new file mode 100644
index 0000000..9d466a0
--- /dev/null
+++ b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_11_47_35.trx
@@ -0,0 +1,14496 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ImplementationPlan/implementation-log.md b/ImplementationPlan/implementation-log.md
index 8fdd4a8..b4744f9 100644
--- a/ImplementationPlan/implementation-log.md
+++ b/ImplementationPlan/implementation-log.md
@@ -35,3 +35,7 @@ Profile facade/owned schema/immutable DTOs; account unique/non-null, durable ato
### Stage 3 checkpoint — passed
Observation module owns its private EF context/entities and versioned schema SQL; patient FK restricted, positive/category/rest checks, patient/time/original/UUID index. Typed Profile existence query inside write transaction. API resolves actual observation owner, authorizes, and uses owner-scoped read/locked patch/delete. Original patch application retained; omitted/clear semantics unchanged. Original US-04–09 suites run with one HTTP host/one DB and namespaces updated. Q1 lookup failure test uses DB outage and 503 instead of service stop/502; no-write assertion unchanged. Empty-404 regression fixed in production adapters. 138/138 tests passed including controlled two-patch row-lock barrier and orphan FK rejection; zero build warnings/errors. Private types exposed only to test assembly via InternalsVisibleTo. Stage 2 commit `bfe6ebf`.
+
+### Stage 4 checkpoint — passed
+
+SummaryPolicy, TrendPolicy, ClinicalPolicy and Guidance-owned versioned ReferenceCatalog extracted without changing formulas/rounding/thresholds/labels/explanations. Analytics captures one immutable series and releases the shared snapshot before calculation. All original numerical/trend tests retained, with shared namespaces and explicit catalog constructor injection; HTTP dependency failure expectations alone changed 502→503 under Q1. 207/207 tests passed, zero build warnings/errors. `src/TRENDS.md` preserves reproducible method details; `clinical-provenance.md` records unverified cautious inferences and narrative limits without altering outputs.
diff --git a/ImplementationPlan/test-adaptations.md b/ImplementationPlan/test-adaptations.md
index 99b2d31..e5afd37 100644
--- a/ImplementationPlan/test-adaptations.md
+++ b/ImplementationPlan/test-adaptations.md
@@ -10,3 +10,5 @@ Authority: approval Q1. Unmodified originals remain under Reference/Architecture
| Guidance tests: ApiGateway host | HealthApp host; all original instructions/source/applicability/side-effect assertions and upstream traps unchanged |
| ViewObservationContextTests / filtered access | Empty denied 404 preserved, corrected implementation after tests caught accidental Problem Details |
| New concurrency checks | Hold row lock, prove both patches wait, release, verify both disjoint changes and unchanged owner/time/note; new architecture obligation |
+
+Insight/context/trend/deletion-derived tests: service-stop helpers represent DB outage, expected 503 replaces 502; current data, no-write, no-false-insufficiency assertions unchanged. Pure calculation tests instantiate the identical mathematical implementation through its internal test-compatible entry and explicit Guidance reference catalog. No clinical assertion changed.
diff --git a/src/HealthApp.Contracts/AnalyticsFacades.cs b/src/HealthApp.Contracts/AnalyticsFacades.cs
new file mode 100644
index 0000000..d2ac1a2
--- /dev/null
+++ b/src/HealthApp.Contracts/AnalyticsFacades.cs
@@ -0,0 +1,12 @@
+namespace HealthApp.Contracts;
+public interface ReferenceCatalog
+{
+ ClinicalReference Pulse();
+ ClinicalReference Pressure(string metric,string setting);
+ string Version {get;}
+}
+public interface AnalyticsQueries
+{
+ Task InsightAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
+ Task TrendAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
+}
diff --git a/src/HealthApp.Contracts/HealthInsight.cs b/src/HealthApp.Contracts/HealthInsight.cs
new file mode 100644
index 0000000..b729fda
--- /dev/null
+++ b/src/HealthApp.Contracts/HealthInsight.cs
@@ -0,0 +1,6 @@
+namespace HealthApp.Contracts;
+
+public sealed record HealthInsight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
+ decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
+ int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
+ ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
diff --git a/src/HealthApp.Contracts/TrendAssessment.cs b/src/HealthApp.Contracts/TrendAssessment.cs
new file mode 100644
index 0000000..be3dd26
--- /dev/null
+++ b/src/HealthApp.Contracts/TrendAssessment.cs
@@ -0,0 +1,21 @@
+namespace HealthApp.Contracts;
+
+public sealed record TrendAssessment(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
+ ContextSelection AppliedSelection, int ContributingCount, ComparabilityAssessment Comparability,
+ MeasurementAssessment Systolic, MeasurementAssessment Diastolic, MeasurementAssessment Pulse);
+
+public sealed record ComparabilityAssessment(string Status, IReadOnlyList KnownSimilarities,
+ IReadOnlyList KnownDifferences, IReadOnlyList MissingDetails,
+ IReadOnlyList Conflicts, string Explanation);
+
+public sealed record MeasurementAssessment(string Metric, string Unit, decimal? Mean, int? Minimum,
+ int? Maximum, int? Range, int DistinctTimestampCount, string Direction, string OverallDirection,
+ decimal? SlopePerDay, int ReversalCount, decimal? TotalSuccessiveChange,
+ string NumericalExplanation, ClinicalReference? Reference, string ReferenceComparison,
+ string Interpretation, string Hint);
+
+public sealed record ClinicalReference(string Scope, decimal? LowerBoundary, string? LowerComparison,
+ decimal UpperBoundary, string UpperComparison, IReadOnlyList Sources,
+ string Limitation);
+
+public sealed record ReferenceSource(string Title, string Url, string Updated, string Reviewed);
diff --git a/src/HealthApp/Controllers/InsightsController.cs b/src/HealthApp/Controllers/InsightsController.cs
new file mode 100644
index 0000000..be3775d
--- /dev/null
+++ b/src/HealthApp/Controllers/InsightsController.cs
@@ -0,0 +1,19 @@
+using HealthApp.Contracts;
+using HealthApp.Security;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+namespace HealthApp.Controllers;
+[ApiController]
+public sealed class InsightsController(AnalyticsQueries analytics,AccessPolicy access) : ControllerBase
+{
+ [HttpGet("api/patients/{patientId:guid}/insights")]
+ public Task Insight(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)=>Calculate(patientId,from,to,selection,false,ct);
+ [HttpGet("api/patients/{patientId:guid}/trends")]
+ public Task Trend(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)=>Calculate(patientId,from,to,selection,true,ct);
+ private async Task Calculate(Guid patientId,DateTime from,DateTime to,ContextSelection selection,bool trend,CancellationToken ct)
+ {
+ var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null){Response.StatusCode=404;return new EmptyResult();}
+ try{if(trend)return Ok(await analytics.TrendAsync(scope,from,to,selection,ct));var insight=await analytics.InsightAsync(scope,from,to,selection,ct);return insight is null?Problem(statusCode:404,title:"Insufficient observation data for calculation."):Ok(insight);}
+ catch(ArgumentException){ModelState.AddModelError(nameof(to),"The end time must not be earlier than the start time.");return ValidationProblem(ModelState);}
+ }
+}
diff --git a/src/HealthApp/HealthApp.csproj b/src/HealthApp/HealthApp.csproj
index 27294c6..48a08ab 100644
--- a/src/HealthApp/HealthApp.csproj
+++ b/src/HealthApp/HealthApp.csproj
@@ -1,4 +1,4 @@
net10.0enableenable
-
+
diff --git a/src/HealthApp/Program.cs b/src/HealthApp/Program.cs
index 4a5aaa0..9660fec 100644
--- a/src/HealthApp/Program.cs
+++ b/src/HealthApp/Program.cs
@@ -2,6 +2,8 @@ using HealthApp.Guidance;
using HealthApp.Infrastructure;
using HealthApp.Profile;
using HealthApp.Observations;
+using HealthApp.Analytics;
+using HealthApp.Contracts;
using Npgsql;
using HealthApp.Security;
using Microsoft.AspNetCore.Authorization;
@@ -17,7 +19,7 @@ public class Program
builder.Services.AddProblemDetails();
builder.Services.AddSingleton();
builder.Services.AddSingleton();
- builder.Services.AddSingleton();
+ builder.Services.AddSingleton();builder.Services.AddSingleton();builder.Services.AddAnalytics();
builder.Services.AddSingleton(sp=> {
var c=sp.GetRequiredService();
var text=c.GetConnectionString("HealthDatabase");
diff --git a/src/Modules/Analytics/Analytics.csproj b/src/Modules/Analytics/Analytics.csproj
new file mode 100644
index 0000000..b205ee6
--- /dev/null
+++ b/src/Modules/Analytics/Analytics.csproj
@@ -0,0 +1,4 @@
+
+net10.0enableenable
+
+
diff --git a/src/Modules/Analytics/AnalyticsFacade.cs b/src/Modules/Analytics/AnalyticsFacade.cs
new file mode 100644
index 0000000..68fd70d
--- /dev/null
+++ b/src/Modules/Analytics/AnalyticsFacade.cs
@@ -0,0 +1,25 @@
+using HealthApp.Contracts;
+using HealthApp.Infrastructure;
+using Microsoft.Extensions.DependencyInjection;
+namespace HealthApp.Analytics;
+internal sealed class AnalyticsFacade(ObservationQueries observations,RequestTransaction tx,SummaryPolicy summary,TrendPolicy trend) : AnalyticsQueries
+{
+ public async Task InsightAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
+ {var series=await observations.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);ct.ThrowIfCancellationRequested();return summary.CalculateSummary(scope.PatientId,MeasurementPeriod.Normalize(from),MeasurementPeriod.Normalize(to),series,selection);}
+ public async Task TrendAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
+ {var series=await observations.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);ct.ThrowIfCancellationRequested();return trend.CalculateTrend(scope.PatientId,MeasurementPeriod.Normalize(from),MeasurementPeriod.Normalize(to),series,selection);}
+}
+public static class AnalyticsModule
+{
+ public static IServiceCollection AddAnalytics(this IServiceCollection s)
+ {s.AddSingleton();s.AddSingleton();s.AddSingleton();s.AddScoped();return s;}
+}
+// Test-only-compatible calculation entry, internal to the module; no public repository/SQL access.
+internal sealed class InsightCalculator
+{
+ private readonly SummaryPolicy summary=new();
+ private readonly TrendPolicy trend;
+ internal InsightCalculator(ReferenceCatalog catalog){trend=new(new ClinicalPolicy(catalog));}
+ public HealthInsight? CalculateSummary(Guid patientId,DateTime from,DateTime to,IReadOnlyList observations,ContextSelection selection)=>summary.CalculateSummary(patientId,from,to,observations,selection);
+ public TrendAssessment CalculateTrend(Guid patientId,DateTime from,DateTime to,IReadOnlyList observations,ContextSelection selection)=>trend.CalculateTrend(patientId,from,to,observations,selection);
+}
diff --git a/src/Modules/Analytics/AssemblyInfo.cs b/src/Modules/Analytics/AssemblyInfo.cs
new file mode 100644
index 0000000..f136d84
--- /dev/null
+++ b/src/Modules/Analytics/AssemblyInfo.cs
@@ -0,0 +1,2 @@
+using System.Runtime.CompilerServices;
+[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
diff --git a/src/Modules/Analytics/ClinicalPolicy.cs b/src/Modules/Analytics/ClinicalPolicy.cs
new file mode 100644
index 0000000..ec69f97
--- /dev/null
+++ b/src/Modules/Analytics/ClinicalPolicy.cs
@@ -0,0 +1,92 @@
+using System.Globalization;
+using HealthApp.Contracts;
+namespace HealthApp.Analytics;
+internal sealed class ClinicalPolicy(ReferenceCatalog catalog)
+{
+ internal const string GeneralLimits = "General reference thresholds are not individual treatment targets. " +
+ "This is a descriptive assessment, not a diagnosis or medication recommendation. " +
+ "Symptoms, treatment, training, risk factors and measurement technique are not established by these observations.";
+
+ internal (ClinicalReference? Reference,string Comparison,string Interpretation,string Hint) Apply(string metric,string unit,IReadOnlyList observations,ComparabilityAssessment comparability,(DateTime Time,decimal Value)[] points,string direction,int reversals,decimal mean,Func value)
+ {
+ var reference = SelectReference(metric, observations, comparability);
+ var comparison = "Unavailable: known, non-conflicting resting conditions" +
+ (metric == "Pulse" ? "" : " and a single Home or Clinic setting") + " are required; recorded inadequate preparation also limits applicability.";
+ var interpretation = "CannotInterpret";
+ var hint = "Numerical changes alone do not establish favourable or concerning development.";
+ if (reference is not null)
+ {
+ var above = observations.Count(o => IsHigh(value(o), reference));
+ var below = observations.Count(o => IsLow(value(o), reference));
+ comparison = $"Descriptive mean {Format(mean)} {unit}; {above} observation(s) " +
+ $"{reference.UpperComparison} {Format(reference.UpperBoundary)} {unit}" +
+ (reference.LowerBoundary is { } lower ? $"; {below} observation(s) < {Format(lower)} {unit}." : ".") +
+ " This period does not establish a guideline diagnostic measurement protocol. " + reference.Limitation;
+ if (points.Length >= 2 && comparability.Status == "SupportedRecordedComparability")
+ {
+ var first = points[0].Value;
+ var last = points[^1].Value;
+ if (reversals > 0 && (above > 0 || below > 0))
+ {
+ interpretation = "Mixed";
+ hint = "Reversing movements and excursions outside the cited reference boundaries coexist; " +
+ "an overall slope does not establish consistent improvement or deterioration.";
+ }
+ else if (direction == "Decreasing" && IsHigh(first, reference) &&
+ !IsLow(last, reference) && below == 0 && (metric == "Pulse" || IsHigh(last, reference)))
+ {
+ interpretation = "PotentiallyFavourable";
+ hint = "Movement away from initially high levels towards the cited reference boundary may be favourable. " +
+ "This is a cautious inference from the source's reference comparison, not a clinical decision rule. " +
+ (IsHigh(last, reference) ? "The latest timestamp mean remains above or at the high boundary." :
+ "Reaching the reference interval does not establish an individual treatment target or good health.");
+ }
+ else if (metric == "Pulse" && direction == "Increasing" && IsLow(first, reference) &&
+ !IsHigh(last, reference) && above == 0)
+ {
+ interpretation = "PotentiallyFavourable";
+ hint = "Movement away from initially low resting pulse towards the reference interval may be favourable, " +
+ "but low pulse may be physiological in trained people. This is a cautious inference, not a clinical rule. " +
+ (IsLow(last, reference) ? "The latest timestamp mean remains below the lower boundary." :
+ "Being within these boundaries does not establish good health.");
+ }
+ else if (above > 0 || below > 0)
+ {
+ interpretation = "PotentiallyConcerning";
+ hint = "Observed levels outside the cited reference boundaries may warrant clinical review. " +
+ "Limited variation does not establish healthy levels, and a decrease into low resting pulse " +
+ "is not automatically favourable. The cause and individual significance cannot be determined here.";
+ }
+ }
+ else
+ hint = "The recorded context supports this limited reference comparison, but " +
+ (points.Length < 2 ? "temporal direction is unavailable. " :
+ "missing or differing conditions limit interpretation of the combined trajectory. ") +
+ "An outside-reference value is not dismissed because preparation information is incomplete.";
+ }
+ return (reference,comparison,interpretation,hint);
+ }
+ private ClinicalReference? SelectReference(string metric, IReadOnlyList observations,
+ ComparabilityAssessment comparability)
+ {
+ if (comparability.Conflicts.Count > 0 ||
+ observations.Any(o => o.MeasurementContext?.ActivityCondition != "AtRest")) return null;
+ if (metric == "Pulse") return catalog.Pulse();
+ var settings = observations.Select(o => o.MeasurementContext?.Setting).Distinct().ToArray();
+ if (settings.Length != 1 || settings[0] is not ("Home" or "Clinic")) return null;
+ // Known inadequate rest prevents even a provisional resting-pressure comparison.
+ if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5)) return null;
+ if (observations.Any(o => !string.IsNullOrWhiteSpace(o.MeasurementContext?.BodyPosition) &&
+ !new[] { "seated", "sitting", "siddende" }.Contains(o.MeasurementContext!.BodyPosition!.Trim(), StringComparer.OrdinalIgnoreCase)))
+ return null;
+ return catalog.Pressure(metric,settings[0]!);
+ }
+
+ private static bool IsHigh(decimal value, ClinicalReference reference) =>
+ reference.UpperComparison == ">=" ? value >= reference.UpperBoundary : value > reference.UpperBoundary;
+ private static bool IsLow(decimal value, ClinicalReference reference) =>
+ reference.LowerBoundary is { } lower && value < lower;
+ private static decimal Round(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero);
+ private static string Format(decimal value) => Round(value).ToString("0.##", CultureInfo.InvariantCulture);
+
+}
diff --git a/src/Modules/Analytics/SummaryPolicy.cs b/src/Modules/Analytics/SummaryPolicy.cs
new file mode 100644
index 0000000..6b2e42f
--- /dev/null
+++ b/src/Modules/Analytics/SummaryPolicy.cs
@@ -0,0 +1,50 @@
+using System.Globalization;
+using HealthApp.Contracts;
+
+namespace HealthApp.Analytics;
+
+internal sealed class SummaryPolicy
+{
+ public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
+ IReadOnlyList observations, ContextSelection selection)
+ {
+ if (observations.Count == 0)
+ return null;
+ return new HealthInsight(patientId, from, to,
+ Math.Round(observations.Average(o => (decimal)o.Systolic), 2, MidpointRounding.AwayFromZero),
+ Math.Round(observations.Average(o => (decimal)o.Diastolic), 2, MidpointRounding.AwayFromZero),
+ Math.Round(observations.Average(o => (decimal)o.Pulse), 2, MidpointRounding.AwayFromZero),
+ observations.Min(o => o.Systolic), observations.Max(o => o.Systolic),
+ observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic),
+ selection, observations.Count, DescribeContext(observations));
+ }
+
+ private static string DescribeContext(IReadOnlyList observations)
+ {
+ var settings = observations.Select(o => o.MeasurementContext?.Setting ?? "Unknown").ToArray();
+ var activities = observations.Select(o => o.MeasurementContext?.ActivityCondition ?? "Unknown").ToArray();
+ var explanation = $"Recorded settings: {Counts(settings)}. Recorded activity conditions: {Counts(activities)}.";
+ if (settings.Distinct().Count() > 1 || activities.Distinct().Count() > 1)
+ explanation += " This numerical summary pools mixed settings or activity conditions.";
+ if (settings.Contains("Unknown") || activities.Contains("Unknown"))
+ explanation += " Some setting or activity information is unknown.";
+ var details = new (string Name, string?[] Values)[]
+ {
+ ("rest duration", observations.Select(o => o.MeasurementContext?.RestDurationMinutes?.ToString("G29", CultureInfo.InvariantCulture)).ToArray()),
+ ("body position", observations.Select(o => o.MeasurementContext?.BodyPosition).ToArray()),
+ ("measured arm", observations.Select(o => o.MeasurementContext?.MeasuredArm).ToArray()),
+ ("device", observations.Select(o => o.MeasurementContext?.DeviceDetails).ToArray()),
+ ("cuff", observations.Select(o => o.MeasurementContext?.CuffDetails).ToArray()),
+ ("additional circumstances", observations.Select(o => o.MeasurementContext?.AdditionalCircumstances).ToArray())
+ };
+ var missing = details.Where(d => d.Values.Any(string.IsNullOrWhiteSpace)).Select(d => d.Name).ToArray();
+ var differing = details.Where(d => d.Values.Where(v => !string.IsNullOrWhiteSpace(v)).Distinct().Count() > 1)
+ .Select(d => d.Name).ToArray();
+ if (missing.Length > 0) explanation += $" Optional details are unrecorded for some observations: {string.Join(", ", missing)}.";
+ if (differing.Length > 0) explanation += $" Recorded detail values differ: {string.Join(", ", differing)}.";
+ return explanation + " These are descriptive statistics, not a diagnostic monitoring protocol; recorded categories alone do not establish clinically comparable conditions. Legacy narrative text does not establish a category.";
+ }
+
+ private static string Counts(IEnumerable values) => string.Join(", ", values.GroupBy(v => v)
+ .OrderBy(g => g.Key, StringComparer.Ordinal).Select(g => $"{g.Key} ({g.Count()})"));
+}
diff --git a/src/Modules/Analytics/TrendPolicy.cs b/src/Modules/Analytics/TrendPolicy.cs
new file mode 100644
index 0000000..2c68fd3
--- /dev/null
+++ b/src/Modules/Analytics/TrendPolicy.cs
@@ -0,0 +1,131 @@
+using System.Globalization;
+using HealthApp.Contracts;
+
+namespace HealthApp.Analytics;
+
+internal sealed class TrendPolicy(ClinicalPolicy clinical)
+{
+ private const string GeneralLimits=ClinicalPolicy.GeneralLimits;
+
+ public TrendAssessment CalculateTrend(Guid patientId, DateTime from, DateTime to,
+ IReadOnlyList observations, ContextSelection selection)
+ {
+ var comparability = AssessComparability(observations);
+ return new(patientId, from, to, selection, observations.Count, comparability,
+ AssessMeasurement("Systolic", "mmHg", observations, o => o.Systolic, comparability),
+ AssessMeasurement("Diastolic", "mmHg", observations, o => o.Diastolic, comparability),
+ AssessMeasurement("Pulse", "beats/min", observations, o => o.Pulse, comparability));
+ }
+
+ private MeasurementAssessment AssessMeasurement(string metric, string unit,
+ IReadOnlyList observations, Func value,
+ ComparabilityAssessment comparability)
+ {
+ if (observations.Count == 0)
+ return new(metric, unit, null, null, null, null, 0, "Unavailable", "Unavailable", null, 0,
+ null, "No matching observations; insufficient observation data for trend calculation.",
+ null, "Unavailable: no matching observations.", "CannotInterpret", GeneralLimits);
+
+ // Collapse timestamp ties for temporal calculations only; descriptive levels retain every observation.
+ var points = observations.GroupBy(o => o.MeasuredAt).OrderBy(g => g.Key)
+ .Select(g => (Time: g.Key, Value: g.Average(o => (decimal)value(o)))).ToArray();
+ var minimum = observations.Min(value);
+ var maximum = observations.Max(value);
+ var mean = observations.Average(o => (decimal)value(o));
+ var signs = points.Zip(points.Skip(1), (a, b) => Math.Sign(b.Value - a.Value))
+ .Where(s => s != 0).ToArray();
+ var reversals = signs.Zip(signs.Skip(1), (a, b) => a != b ? 1 : 0).Sum();
+ var direction = points.Length < 2 ? "Unavailable" : signs.Length == 0 ? "NoClearDirection" :
+ reversals > 0 ? "Mixed" : signs[0] > 0 ? "Increasing" : "Decreasing";
+ decimal? slope = null;
+ var overall = "Unavailable";
+ decimal? totalChange = null;
+ if (points.Length >= 2)
+ {
+ // Scale time to [0,1] before OLS, avoiding extreme timestamp magnitudes.
+ var span = (decimal)(points[^1].Time.Ticks - points[0].Time.Ticks);
+ var xs = points.Select(p => (p.Time.Ticks - points[0].Time.Ticks) / span).ToArray();
+ var xMean = xs.Average();
+ var yMean = points.Average(p => p.Value);
+ var numerator = points.Select((p, i) => (xs[i] - xMean) * (p.Value - yMean)).Sum();
+ var denominator = xs.Sum(x => (x - xMean) * (x - xMean));
+ var scaledSlope = numerator / denominator;
+ slope = scaledSlope / (span / TimeSpan.TicksPerDay);
+ overall = scaledSlope > 0 ? "Increasing" : scaledSlope < 0 ? "Decreasing" : "NoClearDirection";
+ totalChange = points.Zip(points.Skip(1), (a, b) => Math.Abs(b.Value - a.Value)).Sum();
+ }
+ var numerical = $"All {observations.Count} observations: mean {Format(mean)}, minimum {minimum}, maximum {maximum}, " +
+ $"range {maximum - minimum} {unit}. " + (points.Length < 2
+ ? "Direction is unavailable: at least two distinct measurement timestamps are required."
+ : $"Temporal direction: {direction}; full-period least-squares direction: {overall}; " +
+ $"{reversals} reversal(s). Timestamp ties use arithmetic means. " +
+ $"Total successive change is {Format(totalChange!.Value)} {unit}.") +
+ " Range and successive change describe observed variation; no clinical stability classification is made.";
+
+ var result = clinical.Apply(metric,unit,observations,comparability,points,direction,reversals,mean,value);
+ var reference=result.Reference;var comparison=result.Comparison;var interpretation=result.Interpretation;var hint=result.Hint;
+ return new(metric, unit, Round(mean), minimum, maximum, maximum - minimum, points.Length,
+ direction, overall, slope is { } s ? Math.Round(s, 6, MidpointRounding.AwayFromZero) : null,
+ reversals, totalChange is { } change ? Round(change) : null, numerical, reference,
+ comparison, interpretation, hint + " " + comparability.Explanation + " " + GeneralLimits);
+ }
+
+ private static decimal Round(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero);
+ private static string Format(decimal value) => Round(value).ToString("0.##", CultureInfo.InvariantCulture);
+
+ private static ComparabilityAssessment AssessComparability(IReadOnlyList observations)
+ {
+ List similarities = [], differences = [], missing = [], conflicts = [];
+ if (observations.Count == 0)
+ return new("InsufficientContext", similarities, differences, missing, conflicts,
+ "No matching observations are available to assess comparability.");
+ var details = new (string Name, string?[] Values)[]
+ {
+ ("setting", observations.Select(o => o.MeasurementContext?.Setting).ToArray()),
+ ("activity condition", observations.Select(o => o.MeasurementContext?.ActivityCondition).ToArray()),
+ ("rest duration", observations.Select(o => o.MeasurementContext?.RestDurationMinutes?.ToString("G29", CultureInfo.InvariantCulture)).ToArray()),
+ ("body position", observations.Select(o => o.MeasurementContext?.BodyPosition).ToArray()),
+ ("measured arm", observations.Select(o => o.MeasurementContext?.MeasuredArm).ToArray()),
+ ("device", observations.Select(o => o.MeasurementContext?.DeviceDetails).ToArray()),
+ ("cuff", observations.Select(o => o.MeasurementContext?.CuffDetails).ToArray())
+ };
+ foreach (var (name, values) in details)
+ {
+ var known = values.Where(v => !string.IsNullOrWhiteSpace(v) && v != "Unknown")
+ .Select(v => v!.Trim()).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
+ if (values.Any(v => string.IsNullOrWhiteSpace(v) || v == "Unknown")) missing.Add(name);
+ if (known.Length > 1) differences.Add($"{name}: {string.Join(" / ", known)}");
+ else if (known.Length == 1 && !missing.Contains(name)) similarities.Add($"{name}: {known[0]}");
+ }
+ var circumstances = observations.Select(o => o.MeasurementContext?.AdditionalCircumstances)
+ .Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s!.Trim())
+ .Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
+ if (circumstances.Length > 1) differences.Add("additional circumstances differ");
+ if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5))
+ differences.Add("recorded rest duration is below the five-minute blood-pressure preparation recommendation");
+ foreach (var observation in observations)
+ {
+ var context = observation.MeasurementContext;
+ var narrative = string.Join(" ", observation.Context, observation.Note, context?.AdditionalCircumstances,
+ context?.BodyPosition, context?.DeviceDetails, context?.CuffDetails).ToLowerInvariant();
+ if (context?.ActivityCondition == "AtRest" && new[]
+ { "during exercise", "during activity", "after exercise", "after activity", "under motion", "under træning", "efter motion", "efter træning" }
+ .Any(narrative.Contains)) conflicts.Add("AtRest conflicts with an activity description in recorded text.");
+ if (context?.Setting == "Home" && new[] { "at clinic", "in clinic", "at the clinic", "på klinik", "hos lægen" }.Any(narrative.Contains))
+ conflicts.Add("Home conflicts with a clinic description in recorded text.");
+ if (context?.Setting == "Clinic" && new[] { "at home", "hjemme" }.Any(narrative.Contains))
+ conflicts.Add("Clinic conflicts with a home description in recorded text.");
+ }
+ var status = conflicts.Count > 0 ? "ConflictingContext" : differences.Count > 0 ? "KnownDifferences" :
+ missing.Count > 0 ? "InsufficientContext" : "SupportedRecordedComparability";
+ var explanation = $"Recorded comparability: {status}. " +
+ (missing.Count > 0 ? $"Unknown or missing: {string.Join(", ", missing)}. " : "") +
+ (differences.Count > 0 ? $"Known differences: {string.Join("; ", differences)}. " : "") +
+ (conflicts.Count > 0 ? $"Conflicts: {string.Join("; ", conflicts.Distinct())} " : "") +
+ "Matching recorded details support comparability only of those details; they do not certify identical " +
+ "conditions, validated equipment or guideline-compliant technique. Narrative conflict detection is limited " +
+ "to documented phrases; other text is not proof of comparability. A difference between Home and Clinic " +
+ "selections alone is not improvement or deterioration over time.";
+ return new(status, similarities, differences, missing, conflicts.Distinct().Order(StringComparer.Ordinal).ToArray(), explanation);
+ }
+}
diff --git a/src/Modules/Guidance/ReviewedReferenceCatalog.cs b/src/Modules/Guidance/ReviewedReferenceCatalog.cs
new file mode 100644
index 0000000..daa1aa8
--- /dev/null
+++ b/src/Modules/Guidance/ReviewedReferenceCatalog.cs
@@ -0,0 +1,31 @@
+using HealthApp.Contracts;
+namespace HealthApp.Guidance;
+// Pinned content and thresholds; this relocation does not imply a new clinical review.
+public sealed class ReviewedReferenceCatalog : ReferenceCatalog
+{
+ public string Version=>"baseline-2026-10-05";
+ public ClinicalReference Pulse()
+ {
+ return new("Recorded resting pulse", 50, "<", 100, ">",
+ [new("Patienthåndbogen: Bradykardi (langsom puls)",
+ "https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/",
+ "2025-09-02", "2026-10-05"),
+ new("Patienthåndbogen: Hurtig puls (takykardi)",
+ "https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/",
+ "2025-05-12", "2026-10-05")],
+ "These are resting-rate reference boundaries, not a diagnosis, a universal normal range or a treatment target. " +
+ "Low pulse can be physiological in trained people; age, fitness, symptoms and medicines affect applicability.");
+ }
+ public ClinicalReference Pressure(string metric,string setting)
+ {
+ var threshold = metric == "Systolic" ? (setting == "Home" ? 135 : 140) :
+ (setting == "Home" ? 85 : 90);
+ return new($"Recorded {setting} resting blood pressure", null, null, threshold, ">=",
+ [new("Lægehåndbogen: Højt blodtryk",
+ "https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/",
+ "2024-09-25", "2026-10-05")],
+ "Setting-specific high-pressure reference threshold. Missing preparation details make this comparison provisional; " +
+ "five minutes of rest, appropriate technique and repeated measurements are not inferred. " +
+ "Being below a high-pressure threshold does not establish an appropriate lower level or a personalised goal.");
+ }
+}
diff --git a/src/TRENDS.md b/src/TRENDS.md
new file mode 100644
index 0000000..6ced659
--- /dev/null
+++ b/src/TRENDS.md
@@ -0,0 +1,85 @@
+# US-11 trend API and methods
+
+`GET /api/patients/{patientId}/trends?from=...&to=...&setting=Home&activityCondition=AtRest`
+uses the same inclusive UTC measurement-instant semantics and optional context selections as history and
+numerical insight. Offset-free timestamps mean UTC. Both selected dimensions must match; `Unknown`
+is an explicit category. Patient ownership or professional assignment is required. Each selection is a
+separate labelled result for the same requested period. No cross-setting difference is interpreted as
+improvement. Analytics obtains current immutable observations through the typed ObservationQueries interface inside the authorized request snapshot, without result persistence.
+
+A valid request returns 200 even for an empty selection. Count zero, null descriptive values and explicit
+`Unavailable` direction distinguish empty data from dependency/deadline failures (503/504). One observation or
+all observations at a single instant retain descriptive values, but temporal direction is unavailable.
+Invalid/missing period or unsupported selections return 400. The algorithm is unchanged; method version is baseline-2026-10-05.
+
+## Numerical method
+
+Each metric has its own unit, mean, minimum, maximum and range over every eligible observation. Decimal
+means are rounded only for output, to two decimals with midpoint rounding away from zero. No numerical
+range threshold is used to declare clinical stability or instability.
+
+Temporal calculations group equal measurement instants using the arithmetic mean for each metric,
+then order those groups by measurement instant. Identifier and storage order play no part. Direction
+uses every adjacent nonzero change: all positive means Increasing, all negative Decreasing, both signs
+Mixed, all zero NoClearDirection. Reversal count counts sign changes after excluding zero steps.
+TotalSuccessiveChange sums absolute changes between consecutive timestamp means. This retains intermediate
+excursions, while raw min/max retain differences within timestamp ties. No temporal change is assigned
+between measurements at the same instant.
+
+OverallDirection additionally reports the sign of an ordinary least-squares line over all timestamp
+means. Time is scaled from zero to one over the observed span; each distinct timestamp has equal weight.
+SlopePerDay converts that fitted slope to metric units per day and rounds to six decimals. Classification
+uses the unrounded slope. An extremely small nonzero slope may round to zero; its sign is a mathematical
+result, not evidence of clinical significance. The fit describes a linear tendency, not a prediction,
+causal effect or a monotonic trajectory. Mixed direction and reversal count remain visible even when
+an overall slope exists. Irregular sampling and repeated observations can affect the description;
+there is no significance test, smoothing, diagnostic protocol or clinical variability classification.
+
+## Context and interpretation
+
+Comparability lists known similarities, differences and missing information for setting, activity,
+rest duration, body position, measured arm, device and cuff. Differing recorded additional circumstances
+also limit comparability. Matching complete recorded fields support comparability of recorded details
+only, without certifying clinical technique or equipment. Missing optional additional circumstances do
+not block a supported reference comparison. Known inadequate rest is reported separately.
+
+Limited deterministic conflict detection recognises case-insensitive `during exercise`, `during activity`,
+`after exercise`, `after activity`, `under motion`, `under træning`, `efter motion`, `efter træning` against
+AtRest; `at clinic`, `in clinic`, `at the clinic`, `på klinik`, `hos lægen` against Home; and `at home`,
+`hjemme` against Clinic. It examines preserved context, notes and recorded preparation text, without
+recategorising observations. This is conservative phrase detection, not general language understanding;
+negated phrases can still withhold interpretation. Arbitrary narrative is not proof of correct technique.
+Detected conflicts withhold resting-reference interpretation while preserving numerical information.
+
+Sources reviewed 2026-10-05:
+
+- [Lægehåndbogen: Højt blodtryk](https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/)
+ (updated 2024-09-25): separate high-pressure boundaries of home 135/85 and clinic 140/90 mmHg,
+ inclusive. The reference comparison requires a single known setting and recorded AtRest; known rest
+ below five minutes or a non-seated recorded position prevents it. Missing optional preparation
+ details permit only a provisional comparison, explicitly identifying unknown technique. Arbitrary
+ period means do not establish the source's diagnostic protocol. No lower BP boundary is inferred.
+- [Patienthåndbogen: Bradykardi](https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/)
+ (updated 2025-09-02) and [Hurtig puls](https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/)
+ (updated 2025-05-12): resting pulse below 50 or above 100 beats/min provides limited rate-reference
+ comparisons. Low pulse can be physiological in trained people. Rate alone does not diagnose rhythm
+ abnormalities; age, fitness, medicines and symptoms remain unknown. These boundaries are not a
+ universal healthy range or a patient-specific target.
+
+Every metric returns its reference scope, exact comparison operators, source URLs, update/review dates,
+counts outside the boundaries and limitations. Comparisons remain available despite missing preparation
+information when the known context supports that limited comparison. Mixed or unknown activity,
+conflicting narrative, mixed BP settings, or unsupported BP setting make the affected comparison unavailable.
+
+Interpretation of development requires temporal separation, applicable references and supported recorded
+comparability. The following are deliberately cautious inferences from the cited references, not new
+clinical decision rules: a consistent fall from high BP that remains high may be PotentiallyFavourable,
+while explicitly still high; resting pulse moving from outside towards the reference interval may be
+PotentiallyFavourable unless any contributing observation crosses the opposite boundary, including values within timestamp ties. Excursions outside a boundary with reversals
+are Mixed. Other outside-reference levels may be PotentiallyConcerning, including falling low pulse
+or unchanging high BP. Remaining cases are CannotInterpret. No BP fall below the high threshold is
+automatically called favourable, because an applicable lower limit or personalised goal is unavailable.
+
+Each hint distinguishes numerical variation from clinical meaning, explains incomplete/differing context,
+and disclaims diagnosis and medication advice. There is no combined good/bad classification across metrics.
+Reference comparisons and hints are for review, not a replacement for individual clinical assessment.
diff --git a/tests/HealthApp.AcceptanceTests/ContextSelectedInsightTests.cs b/tests/HealthApp.AcceptanceTests/ContextSelectedInsightTests.cs
new file mode 100644
index 0000000..fba1f83
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/ContextSelectedInsightTests.cs
@@ -0,0 +1,205 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text.Json;
+using HealthApp.TestSupport;
+using Xunit;
+
+namespace Observation.AcceptanceTests;
+
+public sealed class ContextSelectedInsightTests(ObservationApiFixture fixture) : IClassFixture
+{
+ private sealed record Profile(Guid PatientId);
+ private sealed record Observation(Guid ObservationId);
+ private sealed record Selection(string? Setting, string? ActivityCondition);
+ private sealed record Insight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
+ decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse, int MinSystolic, int MaxSystolic,
+ int MinDiastolic, int MaxDiastolic, Selection AppliedSelection, int ContributingCount, string ContextExplanation);
+ private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
+
+ private async Task Patient()
+ {
+ using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Selected insight", dateOfBirth = "1980-01-01" });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!.PatientId;
+ }
+
+ private async Task Record(Guid patient, int systolic, int diastolic, int pulse, string? setting = "Home",
+ string? activity = "AtRest", string time = "2026-09-05T08:00:00", string? position = null)
+ {
+ using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
+ {
+ measuredAt = time, systolic, diastolic, pulse, context = "Home resting?",
+ measurementContext = new { setting, activityCondition = activity, bodyPosition = position }
+ });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!.ObservationId;
+ }
+
+ private string PathFor(Guid patient, string selection = "", string period = Period) =>
+ $"/api/patients/{patient}/insights?{period}{selection}";
+ private Task Summary(Guid patient, string selection = "") => fixture.Client.GetFromJsonAsync(PathFor(patient, selection));
+
+ [Theory]
+ [InlineData("&setting=Home&activityCondition=AtRest", "Home", "AtRest", 2, 125)]
+ [InlineData("&setting=Home", "Home", null, 3, 130)]
+ [InlineData("&activityCondition=AtRest", null, "AtRest", 3, 136.67)]
+ public async Task Independent_and_combined_selections_use_only_matching_observations_and_report_their_basis(
+ string query, string? setting, string? activity, int count, double average)
+ {
+ var patient = await Patient();
+ await Record(patient, 120, 80, 60);
+ await Record(patient, 130, 84, 70);
+ await Record(patient, 140, 88, 80, activity: "AfterActivity");
+ await Record(patient, 160, 90, 90, setting: "Clinic");
+ var result = (await Summary(patient, query))!;
+ Assert.Equal((decimal)average, result.AverageSystolic);
+ Assert.Equal(count, result.ContributingCount);
+ Assert.Equal(new Selection(setting, activity), result.AppliedSelection);
+ Assert.Equal(patient, result.PatientId);
+ if (count == 2)
+ {
+ Assert.Equal(82m, result.AverageDiastolic);
+ Assert.Equal(65m, result.AveragePulse);
+ Assert.Equal(120, result.MinSystolic);
+ Assert.Equal(130, result.MaxSystolic);
+ Assert.Equal(80, result.MinDiastolic);
+ Assert.Equal(84, result.MaxDiastolic);
+ }
+ }
+
+ [Fact]
+ public async Task Unfiltered_insight_includes_unknown_context_and_explains_mixed_and_missing_conditions()
+ {
+ var patient = await Patient();
+ await Record(patient, 120, 80, 60, position: "Seated");
+ await Record(patient, 130, 84, 70, setting: "Clinic", activity: "AfterActivity", position: "Standing");
+ await Record(patient, 140, 88, 80, setting: null, activity: null);
+ var result = (await Summary(patient))!;
+ Assert.Equal(130m, result.AverageSystolic);
+ Assert.Equal(3, result.ContributingCount);
+ Assert.Equal(new Selection(null, null), result.AppliedSelection);
+ Assert.Contains("mixed settings or activity conditions", result.ContextExplanation);
+ Assert.Contains("unknown", result.ContextExplanation);
+ Assert.Contains("Optional details are unrecorded", result.ContextExplanation);
+ Assert.Contains("Recorded detail values differ: body position", result.ContextExplanation);
+ Assert.Contains("do not establish clinically comparable conditions", result.ContextExplanation);
+ }
+
+ [Theory]
+ [InlineData("&setting=Unknown", "Unknown", null)]
+ [InlineData("&activityCondition=Unknown", null, "Unknown")]
+ [InlineData("&setting=Unknown&activityCondition=Unknown", "Unknown", "Unknown")]
+ public async Task Unknown_selection_is_explicit_and_legacy_narrative_does_not_create_known_membership(string query,
+ string? setting, string? activity)
+ {
+ var patient = await Patient();
+ await Record(patient, 120, 80, 60, setting: null, activity: null);
+ await Record(patient, 180, 100, 90);
+ var result = (await Summary(patient, query))!;
+ Assert.Equal(1, result.ContributingCount);
+ Assert.Equal(120m, result.AverageSystolic);
+ Assert.Equal(80m, result.AverageDiastolic);
+ Assert.Equal(60m, result.AveragePulse);
+ Assert.Equal(result.MinSystolic, result.MaxSystolic);
+ Assert.Equal(result.MinDiastolic, result.MaxDiastolic);
+ Assert.Equal(new Selection(setting, activity), result.AppliedSelection);
+ }
+
+ [Theory]
+ [InlineData(8, 120.13, 80.13, 60.13)]
+ [InlineData(3, 120.33, 80.33, 60.33)]
+ public async Task Means_round_only_the_final_value_to_two_decimals_with_half_up_rounding(int count,
+ double systolic, double diastolic, double pulse)
+ {
+ var patient = await Patient();
+ for (var i = 0; i < count; i++)
+ await Record(patient, 120 + (i == count - 1 ? 1 : 0), 80 + (i == count - 1 ? 1 : 0), 60 + (i == count - 1 ? 1 : 0));
+ var result = (await Summary(patient))!;
+ Assert.Equal((decimal)systolic, result.AverageSystolic);
+ Assert.Equal((decimal)diastolic, result.AverageDiastolic);
+ Assert.Equal((decimal)pulse, result.AveragePulse);
+ Assert.Equal(count, result.ContributingCount);
+ Assert.Equal(120, result.MinSystolic);
+ Assert.Equal(121, result.MaxSystolic);
+ }
+
+ [Fact]
+ public async Task Corrections_clearing_and_deletion_change_membership_and_fresh_summary_results_after_restart()
+ {
+ var patient = await Patient();
+ var first = await Record(patient, 120, 80, 60);
+ var second = await Record(patient, 130, 84, 70);
+ Assert.Equal(125m, (await Summary(patient, "&setting=Home"))!.AverageSystolic);
+ using var corrected = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}", new { measurementContext = new { setting = "Clinic" } });
+ Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
+ Assert.Equal(120m, (await Summary(patient, "&setting=Home"))!.AverageSystolic);
+ using var cleared = await fixture.Client.PatchAsJsonAsync($"/api/observations/{first}", new { measurementContext = new { activityCondition = (string?)null } });
+ Assert.Equal(HttpStatusCode.OK, cleared.StatusCode);
+ var selected = (await Summary(patient, "&setting=Home&activityCondition=Unknown"))!;
+ Assert.Equal(1, selected.ContributingCount);
+ using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{first}");
+ Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
+ await fixture.RestartHostsAsync();
+ using var empty = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home"));
+ Assert.Equal(HttpStatusCode.NotFound, empty.StatusCode);
+ Assert.Contains("Insufficient observation data", await empty.Content.ReadAsStringAsync());
+ var remaining = (await Summary(patient, "&setting=Clinic"))!;
+ Assert.Equal(1, remaining.ContributingCount);
+ Assert.Equal(130m, remaining.AverageSystolic);
+ }
+
+ [Fact]
+ public async Task Filtered_insight_preserves_patient_scope_inclusive_bounds_and_equal_instants()
+ {
+ var patient = await Patient();
+ await Record(patient, 120, 80, 60, time: "2026-09-01T08:00:00");
+ await Record(patient, 130, 84, 70, time: "2026-09-10T08:00:00");
+ await Record(patient, 200, 100, 90, time: "2026-09-01T07:59:59");
+ await Record(patient, 210, 110, 95, time: "2026-09-10T08:00:01");
+ await Record(await Patient(), 220, 120, 100);
+ var summary = (await Summary(patient, "&setting=Home&activityCondition=AtRest"))!;
+ Assert.Equal(2, summary.ContributingCount);
+ Assert.Equal(125m, summary.AverageSystolic);
+ using var equal = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home", "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z"));
+ Assert.Equal(HttpStatusCode.OK, equal.StatusCode);
+ Assert.Equal(120m, (await equal.Content.ReadFromJsonAsync())!.AverageSystolic);
+ }
+
+ [Theory]
+ [InlineData("&setting=Unsupported")]
+ [InlineData("&activityCondition=Unsupported")]
+ public async Task Unsupported_selection_is_rejected_with_validation_details(string query)
+ {
+ var patient = await Patient();
+ await Record(patient, 120, 80, 60);
+ using var response = await fixture.Client.GetAsync(PathFor(patient, query));
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ Assert.True(problem.RootElement.TryGetProperty("errors", out _));
+ Assert.Equal(1, (await Summary(patient))!.ContributingCount);
+ }
+
+ [Fact]
+ public async Task Professional_selection_requires_assignment_and_other_patient_access_is_rejected()
+ {
+ var patient = await Patient();
+ await Record(patient, 120, 80, 60);
+ var other = await Patient();
+ fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
+ await fixture.RestartHostsAsync();
+ foreach (var (account, status) in new[]
+ {
+ ("professional", HttpStatusCode.OK), ("professional-empty", HttpStatusCode.NotFound),
+ (fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound)
+ })
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient, "&setting=Home&activityCondition=AtRest"));
+ request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
+ using var response = await fixture.RawClient.SendAsync(request);
+ Assert.Equal(status, response.StatusCode);
+ if (status == HttpStatusCode.OK) Assert.Equal(1, (await response.Content.ReadFromJsonAsync())!.ContributingCount);
+ else Assert.Empty(await response.Content.ReadAsStringAsync());
+ }
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/DeleteContextualisedObservationTests.cs b/tests/HealthApp.AcceptanceTests/DeleteContextualisedObservationTests.cs
new file mode 100644
index 0000000..fb1636d
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/DeleteContextualisedObservationTests.cs
@@ -0,0 +1,129 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using HealthApp.TestSupport;
+using Microsoft.EntityFrameworkCore;
+using Xunit;
+
+namespace Observation.AcceptanceTests;
+
+public sealed class DeleteContextualisedObservationTests(ObservationApiFixture fixture) : IClassFixture
+{
+ private sealed record Profile(Guid PatientId);
+ private sealed record ContextData(string Setting, string ActivityCondition, decimal? RestDurationMinutes,
+ string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
+ private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
+ int Systolic, int Diastolic, int Pulse, string? Context, string? Note, ContextData MeasurementContext);
+ private sealed record Insight(decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
+ int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
+ private const string Period = "from=2026-09-01&to=2026-10-01";
+
+ private async Task Patient()
+ {
+ using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Context deletion", dateOfBirth = "1980-01-01" });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!.PatientId;
+ }
+
+ private async Task Record(Guid patient, string time, int systolic, int diastolic, int pulse)
+ {
+ using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
+ {
+ measuredAt = time, systolic, diastolic, pulse, context = "Original context", note = "Original note",
+ measurementContext = new { setting = "Home", activityCondition = "AtRest", restDurationMinutes = 5.5m,
+ bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device", cuffDetails = "Cuff", additionalCircumstances = "Actual circumstances" }
+ });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!;
+ }
+
+ private Task History(Guid patient) => fixture.Client.GetFromJsonAsync(
+ $"/api/patients/{patient}/observations?{Period}&setting=Home&activityCondition=AtRest");
+ private Task Summary(Guid patient) => fixture.Client.GetFromJsonAsync($"/api/patients/{patient}/insights?{Period}");
+
+ [Fact]
+ public async Task Deleted_context_stays_absent_from_retrieval_filtered_history_and_latest_after_restart()
+ {
+ var patient = await Patient();
+ var retained = await Record(patient, "2026-09-10T08:00:00", 120, 80, 60);
+ var deleted = await Record(patient, "2026-09-12T08:00:00", 200, 110, 100);
+ var other = await Record(await Patient(), "2026-09-13T08:00:00", 130, 84, 70);
+ using var response = await fixture.Client.DeleteAsync($"/api/observations/{deleted.ObservationId}");
+ Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
+ Assert.Empty(await response.Content.ReadAsStringAsync());
+ await fixture.RestartHostsAsync();
+ using var missing = await fixture.Client.GetAsync($"/api/observations/{deleted.ObservationId}");
+ Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode);
+ Assert.Empty(await missing.Content.ReadAsStringAsync());
+ Assert.Equal(retained, Assert.Single((await History(patient))!));
+ Assert.Equal(retained, await fixture.Client.GetFromJsonAsync($"/api/patients/{patient}/observations/latest"));
+ Assert.Equal(other, Assert.Single((await History(other.PatientId))!));
+ Assert.Equal(other, await fixture.Client.GetFromJsonAsync($"/api/observations/{other.ObservationId}"));
+ await using var db = fixture.CreateObservationDbContext();
+ Assert.False(await db.Observations.AnyAsync(o => o.ObservationId == deleted.ObservationId));
+ Assert.Equal("Device", (await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == retained.ObservationId)).MeasurementContext.DeviceDetails);
+ }
+
+ [Fact]
+ public async Task New_numerical_summary_excludes_deleted_values_and_retains_current_remaining_observations()
+ {
+ var patient = await Patient();
+ var first = await Record(patient, "2026-09-10T08:00:00", 120, 80, 60);
+ var second = await Record(patient, "2026-09-11T08:00:00", 130, 84, 70);
+ var outlier = await Record(patient, "2026-09-12T08:00:00", 200, 110, 100);
+ Assert.Equal(150m, (await Summary(patient))!.AverageSystolic);
+ using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{outlier.ObservationId}");
+ Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
+ var expected = new Insight(125m, 82m, 65m, 120, 130, 80, 84);
+ Assert.Equal(expected, await Summary(patient));
+ Assert.Equal(new[] { first, second }, await History(patient));
+ await fixture.RestartHostsAsync();
+ Assert.Equal(expected, await Summary(patient));
+ Assert.Equal(new[] { first, second }, await History(patient));
+ }
+
+ [Fact]
+ public async Task Deleting_only_contextualised_observation_leaves_empty_filtered_history_and_no_summary()
+ {
+ var patient = await Patient();
+ var observation = await Record(patient, "2026-09-12T08:00:00", 128, 82, 68);
+ using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
+ Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
+ using var history = await fixture.Client.GetAsync($"/api/patients/{patient}/observations?{Period}&setting=Home&activityCondition=AtRest");
+ Assert.Equal(HttpStatusCode.OK, history.StatusCode);
+ Assert.Equal("[]", await history.Content.ReadAsStringAsync());
+ Assert.Equal("Home", Assert.Single(history.Headers.GetValues("X-Measurement-Setting")));
+ Assert.Equal("AtRest", Assert.Single(history.Headers.GetValues("X-Activity-Condition")));
+ using var latest = await fixture.Client.GetAsync($"/api/patients/{patient}/observations/latest");
+ using var summary = await fixture.Client.GetAsync($"/api/patients/{patient}/insights?{Period}");
+ using var repeated = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
+ Assert.Equal(HttpStatusCode.NotFound, latest.StatusCode);
+ Assert.Equal(HttpStatusCode.NotFound, summary.StatusCode);
+ Assert.Equal(HttpStatusCode.NotFound, repeated.StatusCode);
+ }
+
+ [Fact]
+ public async Task Unauthorised_deletions_preserve_the_observation_and_all_context()
+ {
+ var patient = await Patient();
+ var original = await Record(patient, "2026-09-12T08:00:00", 128, 82, 68);
+ var otherPatient = await Patient();
+ fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
+ await fixture.RestartHostsAsync();
+ var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, fixture.Authentication.PatientAccounts[otherPatient]);
+ var professional = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
+ foreach (var (token, status) in new[]
+ {
+ ((string?)null, HttpStatusCode.Unauthorized), ((string?)"invalid", HttpStatusCode.Unauthorized),
+ ((string?)otherToken, HttpStatusCode.NotFound), ((string?)professional, HttpStatusCode.Forbidden)
+ })
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Delete, $"/api/observations/{original.ObservationId}");
+ if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
+ using var rejected = await fixture.RawClient.SendAsync(request);
+ Assert.Equal(status, rejected.StatusCode);
+ Assert.Equal(original, await fixture.Client.GetFromJsonAsync($"/api/observations/{original.ObservationId}"));
+ }
+ Assert.Equal(original, Assert.Single((await History(patient))!));
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/HealthInsightTests.cs b/tests/HealthApp.AcceptanceTests/HealthInsightTests.cs
new file mode 100644
index 0000000..efe2d8d
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/HealthInsightTests.cs
@@ -0,0 +1,158 @@
+using System.Net;
+using System.Net.Http.Json;
+using System.Text.Json;
+using Xunit;
+
+namespace Observation.AcceptanceTests;
+
+public sealed class HealthInsightTests(ObservationApiFixture fixture) : IClassFixture
+{
+ private sealed record Profile(Guid PatientId);
+ private sealed record Observation(Guid ObservationId);
+ private sealed record Insight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
+ decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
+ int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
+
+ private async Task PatientAsync()
+ {
+ using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
+ { name = "Insight Example", dateOfBirth = "1980-01-01" });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!.PatientId;
+ }
+
+ private async Task RecordAsync(Guid patientId, string time, int systolic, int diastolic, int pulse)
+ {
+ using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
+ { measuredAt = time, systolic, diastolic, pulse });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!.ObservationId;
+ }
+
+ private string PathFor(Guid patientId, string from = "2026-09-03T00:00:00", string to = "2026-09-08T23:59:59") =>
+ $"/api/patients/{patientId}/insights?from={Uri.EscapeDataString(from)}&to={Uri.EscapeDataString(to)}";
+
+ private async Task SummaryAsync(Guid patientId)
+ {
+ using var response = await fixture.Client.GetAsync(PathFor(patientId));
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!;
+ }
+
+ [Fact]
+ public async Task Averages_use_only_the_requested_patient_and_period_after_restart()
+ {
+ var patientId = await PatientAsync();
+ await RecordAsync(patientId, "2026-09-03T00:00:00", 120, 80, 60);
+ await RecordAsync(patientId, "2026-09-08T23:59:59", 130, 84, 70);
+ await RecordAsync(patientId, "2026-09-01T08:00:00", 200, 100, 90);
+ await RecordAsync(patientId, "2026-09-10T08:00:00", 210, 110, 95);
+ await RecordAsync(await PatientAsync(), "2026-09-05T08:00:00", 220, 120, 100);
+ await fixture.RestartHostsAsync();
+ var insight = await SummaryAsync(patientId);
+ Assert.Equal(patientId, insight.PatientId);
+ Assert.Equal(new DateTime(2026, 9, 3), insight.PeriodStart);
+ Assert.Equal(new DateTime(2026, 9, 8, 23, 59, 59), insight.PeriodEnd);
+ Assert.Equal(125m, insight.AverageSystolic);
+ Assert.Equal(82m, insight.AverageDiastolic);
+ Assert.Equal(65m, insight.AveragePulse);
+ }
+
+ [Fact]
+ public async Task Minimum_and_maximum_values_are_calculated()
+ {
+ var patientId = await PatientAsync();
+ await RecordAsync(patientId, "2026-09-04T08:00:00", 118, 76, 61);
+ await RecordAsync(patientId, "2026-09-05T08:00:00", 130, 84, 70);
+ await RecordAsync(patientId, "2026-09-06T08:00:00", 124, 80, 66);
+ var insight = await SummaryAsync(patientId);
+ Assert.Equal(118, insight.MinSystolic);
+ Assert.Equal(130, insight.MaxSystolic);
+ Assert.Equal(76, insight.MinDiastolic);
+ Assert.Equal(84, insight.MaxDiastolic);
+ }
+
+ [Fact]
+ public async Task Fractional_averages_are_preserved_and_recalculated_after_correction_and_deletion()
+ {
+ var patientId = await PatientAsync();
+ var first = await RecordAsync(patientId, "2026-09-04T08:00:00", 120, 80, 60);
+ var second = await RecordAsync(patientId, "2026-09-05T08:00:00", 121, 81, 61);
+ var initial = await SummaryAsync(patientId);
+ Assert.Equal(120.5m, initial.AverageSystolic);
+ Assert.Equal(80.5m, initial.AverageDiastolic);
+ Assert.Equal(60.5m, initial.AveragePulse);
+ using var updated = await fixture.Client.PutAsJsonAsync($"/api/observations/{second}",
+ new { systolic = 130, diastolic = 84, pulse = 70 });
+ Assert.Equal(HttpStatusCode.OK, updated.StatusCode);
+ Assert.Equal(125m, (await SummaryAsync(patientId)).AverageSystolic);
+ using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
+ Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
+ var single = await SummaryAsync(patientId);
+ Assert.Equal(120m, single.AverageSystolic);
+ Assert.Equal(single.MinSystolic, single.MaxSystolic);
+ using var last = await fixture.Client.DeleteAsync($"/api/observations/{first}");
+ Assert.Equal(HttpStatusCode.NoContent, last.StatusCode);
+ using var empty = await fixture.Client.GetAsync(PathFor(patientId));
+ Assert.Equal(HttpStatusCode.NotFound, empty.StatusCode);
+ }
+
+ [Fact]
+ public async Task No_matching_observations_reports_insufficient_data()
+ {
+ var patientId = await PatientAsync();
+ await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
+ await RecordAsync(await PatientAsync(), "2026-09-05T08:00:00", 130, 84, 70);
+ using var response = await fixture.Client.GetAsync(PathFor(patientId));
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ Assert.Equal("Insufficient observation data for calculation.", problem.RootElement.GetProperty("title").GetString());
+ }
+
+ [Theory]
+ [InlineData("from=2026-09-08T00:00:00&to=2026-09-03T00:00:00")]
+ [InlineData("from=invalid&to=2026-09-08T00:00:00")]
+ [InlineData("from=2026-09-03T00:00:00&to=invalid")]
+ [InlineData("from=2026-09-03T00:00:00")]
+ [InlineData("to=2026-09-08T00:00:00")]
+ [InlineData("")]
+ public async Task Invalid_or_missing_period_is_rejected(string query)
+ {
+ var patientId = await PatientAsync();
+ using var response = await fixture.Client.GetAsync($"/api/patients/{patientId}/insights?{query}");
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ Assert.True(problem.RootElement.TryGetProperty("errors", out _));
+ }
+
+ [Fact]
+ public async Task Equal_bounds_and_offsets_match_recording_timestamp_semantics()
+ {
+ var patientId = await PatientAsync();
+ await RecordAsync(patientId, "2026-09-05T10:00:00+02:00", 120, 80, 60);
+ using var response = await fixture.Client.GetAsync(PathFor(patientId,
+ "2026-09-05T10:00:00+02:00", "2026-09-05T08:00:00Z"));
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var insight = (await response.Content.ReadFromJsonAsync())!;
+ Assert.Equal(120m, insight.AverageSystolic);
+ Assert.Equal(insight.PeriodStart, insight.PeriodEnd);
+ }
+
+ [Fact]
+ public async Task Unavailable_observations_report_failure_instead_of_insufficient_data()
+ {
+ var patientId = await PatientAsync();
+ await RecordAsync(patientId, "2026-09-05T08:00:00", 120, 80, 60);
+ await fixture.StopObservationServiceAsync();
+ try
+ {
+ using var response = await fixture.Client.GetAsync(PathFor(patientId));
+ Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
+ }
+ finally
+ {
+ await fixture.RestartHostsAsync();
+ }
+ Assert.Equal(120m, (await SummaryAsync(patientId)).AverageSystolic);
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/HealthTrendTests.cs b/tests/HealthApp.AcceptanceTests/HealthTrendTests.cs
new file mode 100644
index 0000000..2990446
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/HealthTrendTests.cs
@@ -0,0 +1,415 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text.Json;
+using HealthApp.TestSupport;
+using HealthApp.Contracts;
+using HealthApp.Analytics;
+using Xunit;
+
+namespace Observation.AcceptanceTests;
+
+public sealed class HealthTrendCalculationTests
+{
+ private static readonly Guid PatientId = Guid.NewGuid();
+ private static readonly DateTime Start = new(2026, 9, 1);
+ private static readonly MeasurementContextDto Prepared = new("Home", "AtRest", 5, "Seated", "Left", "Device A", "Adult cuff", null);
+ private static ObservationDto Observation(int day, int systolic, int diastolic = 90, int pulse = 70,
+ MeasurementContextDto? context = null, string? text = null) =>
+ new(Guid.NewGuid(), PatientId, Start.AddDays(day), systolic, diastolic, pulse, context ?? Prepared, text);
+ private static TrendAssessment Calculate(params ObservationDto[] observations) =>
+ new InsightCalculator(new HealthApp.Guidance.ReviewedReferenceCatalog()).CalculateTrend(PatientId, Start, Start.AddDays(10), observations, new() { Setting = "Home", ActivityCondition = "AtRest" });
+
+ [Theory]
+ [InlineData(140, 150, 160, "Increasing")]
+ [InlineData(160, 150, 140, "Decreasing")]
+ [InlineData(150, 150, 150, "NoClearDirection")]
+ public void Full_period_direction_and_separate_units_and_levels(int first, int middle, int last, string direction)
+ {
+ var result = Calculate(Observation(0, first, 95, 65), Observation(1, middle, 90, 70), Observation(2, last, 85, 75));
+ Assert.Equal(direction, result.Systolic.Direction);
+ Assert.Equal(direction, result.Systolic.OverallDirection);
+ Assert.Equal("Decreasing", result.Diastolic.Direction);
+ Assert.Equal("Increasing", result.Pulse.Direction);
+ Assert.Equal("mmHg", result.Systolic.Unit);
+ Assert.Equal("mmHg", result.Diastolic.Unit);
+ Assert.Equal("beats/min", result.Pulse.Unit);
+ Assert.Equal(150m, result.Systolic.Mean);
+ Assert.Equal(90m, result.Diastolic.Mean);
+ Assert.Equal(70m, result.Pulse.Mean);
+ Assert.Equal("SupportedRecordedComparability", result.Comparability.Status);
+ Assert.Contains("rest duration: 5", result.Comparability.KnownSimilarities);
+ }
+
+ [Fact]
+ public void Equal_endpoints_do_not_hide_intermediate_excursion_or_reversal()
+ {
+ var result = Calculate(Observation(0, 140), Observation(1, 190), Observation(2, 140));
+ Assert.Equal("Mixed", result.Systolic.Direction);
+ Assert.Equal("NoClearDirection", result.Systolic.OverallDirection);
+ Assert.Equal(1, result.Systolic.ReversalCount);
+ Assert.Equal(50, result.Systolic.Range);
+ Assert.Equal(100m, result.Systolic.TotalSuccessiveChange);
+ Assert.Equal("Mixed", result.Systolic.Interpretation);
+ Assert.Contains("no clinical stability classification", result.Systolic.NumericalExplanation);
+ }
+
+ [Fact]
+ public void Overall_decrease_can_coexist_with_reversals_and_large_variation()
+ {
+ var result = Calculate(Observation(0, 180), Observation(1, 160), Observation(2, 170), Observation(3, 140));
+ Assert.Equal("Mixed", result.Systolic.Direction);
+ Assert.Equal("Decreasing", result.Systolic.OverallDirection);
+ Assert.Equal(2, result.Systolic.ReversalCount);
+ Assert.Equal(60m, result.Systolic.TotalSuccessiveChange);
+ Assert.True(result.Systolic.SlopePerDay < 0);
+ }
+
+ [Fact]
+ public void Low_variation_outside_reference_is_not_healthy()
+ {
+ var result = Calculate(Observation(0, 155), Observation(1, 155), Observation(2, 155));
+ Assert.Equal(0, result.Systolic.Range);
+ Assert.Equal("PotentiallyConcerning", result.Systolic.Interpretation);
+ Assert.Contains("3 observation(s) >= 135", result.Systolic.ReferenceComparison);
+ Assert.Contains("Limited variation does not establish healthy", result.Systolic.Hint);
+ }
+
+ [Fact]
+ public void Favourable_pressure_decrease_can_still_be_high_while_falling_pulse_is_concerning()
+ {
+ var result = Calculate(Observation(0, 160, 85, 70), Observation(1, 150, 90, 55), Observation(2, 140, 95, 40));
+ Assert.Equal("PotentiallyFavourable", result.Systolic.Interpretation);
+ Assert.Contains("remains above or at", result.Systolic.Hint);
+ Assert.Equal("PotentiallyConcerning", result.Diastolic.Interpretation);
+ Assert.Equal("PotentiallyConcerning", result.Pulse.Interpretation);
+ Assert.Contains("not automatically favourable", result.Pulse.Hint);
+ Assert.Equal(50m, result.Pulse.Reference!.LowerBoundary);
+ Assert.Equal(100m, result.Pulse.Reference.UpperBoundary);
+ }
+
+ [Fact]
+ public void Moving_low_pulse_up_or_high_pulse_down_is_not_automatically_concerning()
+ {
+ Assert.Equal("PotentiallyFavourable", Calculate(Observation(0, 120, pulse: 40), Observation(1, 120, pulse: 55)).Pulse.Interpretation);
+ Assert.Equal("PotentiallyFavourable", Calculate(Observation(0, 120, pulse: 120), Observation(1, 120, pulse: 105)).Pulse.Interpretation);
+ Assert.Equal("CannotInterpret", Calculate(Observation(0, 120), Observation(1, 110)).Systolic.Interpretation);
+ }
+
+ [Fact]
+ public void Opposite_pulse_excursions_within_timestamp_ties_are_not_hidden_by_their_mean()
+ {
+ var result = Calculate(Observation(0, 120, pulse: 30), Observation(0, 120, pulse: 210),
+ Observation(1, 120, pulse: 105));
+ Assert.Equal("Decreasing", result.Pulse.Direction);
+ Assert.Equal(180, result.Pulse.Range);
+ Assert.Equal("PotentiallyConcerning", result.Pulse.Interpretation);
+ Assert.Contains("1 observation(s) < 50", result.Pulse.ReferenceComparison);
+ }
+
+ [Theory]
+ [InlineData("Home", 135, 85)]
+ [InlineData("Clinic", 140, 90)]
+ public void References_are_setting_specific_sourced_and_not_treatment_targets(string setting, int systolic, int diastolic)
+ {
+ var context = Prepared with { Setting = setting };
+ var result = Calculate(Observation(0, 138, context: context), Observation(1, 138, context: context));
+ Assert.Equal(systolic, result.Systolic.Reference!.UpperBoundary);
+ Assert.Equal(diastolic, result.Diastolic.Reference!.UpperBoundary);
+ Assert.Equal(">=", result.Systolic.Reference.UpperComparison);
+ Assert.Contains("sundhed.dk", result.Systolic.Reference.Sources.Single().Url);
+ Assert.Contains("not individual treatment targets", result.Systolic.Hint);
+ }
+
+ [Theory]
+ [InlineData(50, 0)]
+ [InlineData(100, 0)]
+ [InlineData(49, 2)]
+ [InlineData(101, 2)]
+ public void Pulse_reference_boundaries_are_exclusive(int pulse, int outsideCount)
+ {
+ var result = Calculate(Observation(0, 120, pulse: pulse), Observation(1, 120, pulse: pulse));
+ Assert.Contains($"{(pulse > 100 ? outsideCount : 0)} observation(s) > 100", result.Pulse.ReferenceComparison);
+ Assert.Contains($"{(pulse < 50 ? outsideCount : 0)} observation(s) < 50", result.Pulse.ReferenceComparison);
+ }
+
+ [Fact]
+ public void Missing_context_preserves_numerical_direction_but_not_resting_interpretation()
+ {
+ var unknown = new MeasurementContextDto("Unknown", "Unknown", null, null, null, null, null, null);
+ var result = Calculate(Observation(0, 150, context: unknown), Observation(1, 160, context: unknown));
+ Assert.Equal("Increasing", result.Systolic.Direction);
+ Assert.Equal(10, result.Systolic.Range);
+ Assert.Null(result.Systolic.Reference);
+ Assert.Null(result.Pulse.Reference);
+ Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
+ Assert.Contains("setting", result.Comparability.MissingDetails);
+ }
+
+ [Fact]
+ public void Known_categories_with_missing_preparation_support_limited_reference_comparison()
+ {
+ var limited = new MeasurementContextDto("Home", "AtRest", null, null, null, null, null, null);
+ var result = Calculate(Observation(0, 150, context: limited), Observation(1, 160, context: limited));
+ Assert.Equal("InsufficientContext", result.Comparability.Status);
+ Assert.Contains("setting: Home", result.Comparability.KnownSimilarities);
+ Assert.Contains("rest duration", result.Comparability.MissingDetails);
+ Assert.NotNull(result.Systolic.Reference);
+ Assert.Contains("provisional", result.Systolic.ReferenceComparison);
+ Assert.Contains("limited reference comparison", result.Systolic.Hint);
+ Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
+ }
+
+ [Fact]
+ public void Missing_optional_circumstances_do_not_block_supported_comparison()
+ {
+ var result = Calculate(Observation(0, 150), Observation(1, 160));
+ Assert.NotNull(result.Systolic.Reference);
+ Assert.Equal("PotentiallyConcerning", result.Systolic.Interpretation);
+ Assert.Equal("SupportedRecordedComparability", result.Comparability.Status);
+ }
+
+ [Theory]
+ [InlineData("during exercise")]
+ [InlineData("after activity")]
+ [InlineData("under træning")]
+ public void Conflicting_rest_narrative_withholds_resting_interpretation(string narrative)
+ {
+ var result = Calculate(Observation(0, 150, text: narrative), Observation(1, 160));
+ Assert.Equal("ConflictingContext", result.Comparability.Status);
+ Assert.Contains(result.Comparability.Conflicts, s => s.Contains("AtRest"));
+ Assert.Null(result.Systolic.Reference);
+ Assert.Null(result.Pulse.Reference);
+ Assert.Equal("Increasing", result.Systolic.Direction);
+ }
+
+ [Fact]
+ public void Different_conditions_and_preparation_are_visible_and_limit_combined_trajectory()
+ {
+ var result = Calculate(Observation(0, 150), Observation(1, 160, context: Prepared with
+ { ActivityCondition = "AfterActivity", BodyPosition = "Standing" }));
+ Assert.Equal("KnownDifferences", result.Comparability.Status);
+ Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("activity condition"));
+ Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("body position"));
+ Assert.Null(result.Systolic.Reference);
+ Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
+ }
+
+ [Fact]
+ public void Known_inadequate_pressure_preparation_does_not_block_resting_pulse_reference()
+ {
+ var result = Calculate(Observation(0, 150, context: Prepared with { RestDurationMinutes = 1 }), Observation(1, 160));
+ Assert.Null(result.Systolic.Reference);
+ Assert.NotNull(result.Pulse.Reference);
+ Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("five-minute"));
+ var standing = Calculate(Observation(0, 150, context: Prepared with { BodyPosition = "Standing" }),
+ Observation(1, 160, context: Prepared with { BodyPosition = "Standing" }));
+ Assert.Null(standing.Systolic.Reference);
+ }
+
+ [Fact]
+ public void Timestamp_ties_do_not_manufacture_direction_or_hide_descriptive_range()
+ {
+ var result = Calculate(Observation(1, 140), Observation(1, 180));
+ Assert.Equal("Unavailable", result.Systolic.Direction);
+ Assert.Null(result.Systolic.SlopePerDay);
+ Assert.Equal(160m, result.Systolic.Mean);
+ Assert.Equal(40, result.Systolic.Range);
+ Assert.NotNull(result.Systolic.Reference);
+ Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
+ }
+
+ [Fact]
+ public void Empty_and_single_series_report_each_unavailable_part()
+ {
+ var empty = Calculate();
+ Assert.Equal(0, empty.ContributingCount);
+ Assert.Null(empty.Systolic.Mean);
+ Assert.Equal("Unavailable", empty.Systolic.Direction);
+ Assert.Contains("No matching observations", empty.Systolic.NumericalExplanation);
+ var single = Calculate(Observation(0, 140));
+ Assert.Equal(140m, single.Systolic.Mean);
+ Assert.Equal("Unavailable", single.Systolic.Direction);
+ Assert.Equal("Unavailable", single.Systolic.OverallDirection);
+ }
+
+ [Fact]
+ public void Retrieval_and_identifier_order_do_not_change_results_including_ties()
+ {
+ var series = new[] { Observation(0, 140), Observation(0, 180), Observation(1, 150), Observation(2, 140) };
+ Assert.Equal(JsonSerializer.Serialize(Calculate(series)), JsonSerializer.Serialize(Calculate(series.Reverse()
+ .Select(o => o with { ObservationId = Guid.NewGuid() }).ToArray())));
+ Assert.Equal("Decreasing", Calculate(series).Systolic.Direction);
+ }
+}
+
+public sealed class HealthTrendTests(ObservationApiFixture fixture) : IClassFixture
+{
+ private sealed record Profile(Guid PatientId);
+ private sealed record Recorded(Guid ObservationId);
+ private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
+ private static string PathFor(Guid patient, string selection = "", string period = Period) =>
+ $"/api/patients/{patient}/trends?{period}{selection}";
+ private async Task Patient()
+ {
+ using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Health trend", dateOfBirth = "1980-01-01" });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!.PatientId;
+ }
+ private async Task Record(Guid patient, int systolic, string time = "2026-09-05T08:00:00",
+ string? setting = "Home", string? activity = "AtRest")
+ {
+ using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
+ {
+ measuredAt = time, systolic, diastolic = 85, pulse = 70,
+ measurementContext = new { setting, activityCondition = activity, restDurationMinutes = 5,
+ bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device A", cuffDetails = "Adult cuff" }
+ });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!.ObservationId;
+ }
+ private async Task Trend(Guid patient, string selection = "", string period = Period)
+ {
+ using var response = await fixture.Client.GetAsync(PathFor(patient, selection, period));
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!;
+ }
+
+ [Fact]
+ public async Task Inclusive_patient_period_and_equal_offset_instants_apply_before_sufficiency()
+ {
+ var patient = await Patient();
+ await Record(patient, 150, "2026-09-01T08:00:00");
+ await Record(patient, 160, "2026-09-10T08:00:00");
+ await Record(patient, 250, "2026-09-01T07:59:59");
+ await Record(patient, 250, "2026-09-10T08:00:01");
+ await Record(await Patient(), 250);
+ var result = await Trend(patient);
+ Assert.Equal(patient, result.PatientId);
+ Assert.Equal(new DateTime(2026, 9, 1, 8, 0, 0), result.PeriodStart);
+ Assert.Equal(new DateTime(2026, 9, 10, 8, 0, 0), result.PeriodEnd);
+ Assert.Equal(2, result.ContributingCount);
+ Assert.Equal(155m, result.Systolic.Mean);
+ Assert.Equal("Increasing", result.Systolic.Direction);
+ var equal = await Trend(patient, period: "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z");
+ Assert.Equal(equal.PeriodStart, equal.PeriodEnd);
+ Assert.Equal(1, equal.ContributingCount);
+ Assert.Equal("Unavailable", equal.Systolic.Direction);
+ }
+
+ [Fact]
+ public async Task Labelled_home_and_clinic_selections_and_independent_dimensions_use_only_matches()
+ {
+ var patient = await Patient();
+ await Record(patient, 150, "2026-09-02T08:00:00");
+ await Record(patient, 145, "2026-09-03T08:00:00");
+ await Record(patient, 160, "2026-09-02T08:00:00", "Clinic");
+ await Record(patient, 155, "2026-09-03T08:00:00", "Clinic");
+ await Record(patient, 200, activity: "AfterActivity");
+ var home = await Trend(patient, "&setting=Home&activityCondition=AtRest");
+ var clinic = await Trend(patient, "&setting=Clinic&activityCondition=AtRest");
+ Assert.Equal(new ContextSelection { Setting = "Home", ActivityCondition = "AtRest" }, home.AppliedSelection);
+ Assert.Equal(new ContextSelection { Setting = "Clinic", ActivityCondition = "AtRest" }, clinic.AppliedSelection);
+ Assert.Equal(2, home.ContributingCount);
+ Assert.Equal(2, clinic.ContributingCount);
+ Assert.Equal(135m, home.Systolic.Reference!.UpperBoundary);
+ Assert.Equal(140m, clinic.Systolic.Reference!.UpperBoundary);
+ Assert.Contains("alone is not improvement or deterioration", home.Comparability.Explanation);
+ Assert.Equal(3, (await Trend(patient, "&setting=Home")).ContributingCount);
+ Assert.Equal(4, (await Trend(patient, "&activityCondition=AtRest")).ContributingCount);
+ Assert.Equal("KnownDifferences", (await Trend(patient)).Comparability.Status);
+ }
+
+ [Fact]
+ public async Task Unknown_empty_and_one_selected_observation_do_not_borrow_excluded_data()
+ {
+ var patient = await Patient();
+ await Record(patient, 150, "2026-09-02T08:00:00");
+ await Record(patient, 160, "2026-09-03T08:00:00");
+ await Record(patient, 180, setting: null, activity: null);
+ var unknown = await Trend(patient, "&setting=Unknown&activityCondition=Unknown");
+ Assert.Equal(1, unknown.ContributingCount);
+ Assert.Equal("Unavailable", unknown.Systolic.Direction);
+ Assert.Equal(180m, unknown.Systolic.Mean);
+ Assert.Null(unknown.Systolic.Reference);
+ var empty = await Trend(patient, "&setting=Clinic");
+ Assert.Equal(0, empty.ContributingCount);
+ Assert.Contains("No matching observations", empty.Pulse.NumericalExplanation);
+ }
+
+ [Fact]
+ public async Task Corrected_values_context_and_deletions_are_used_on_every_request_after_restart()
+ {
+ var patient = await Patient();
+ var first = await Record(patient, 150, "2026-09-02T08:00:00");
+ var second = await Record(patient, 160, "2026-09-03T08:00:00");
+ Assert.Equal("Increasing", (await Trend(patient)).Systolic.Direction);
+ using var corrected = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}", new { systolic = 140 });
+ Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
+ Assert.Equal("Decreasing", (await Trend(patient)).Systolic.Direction);
+ using var context = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}",
+ new { measurementContext = new { activityCondition = "AfterActivity" } });
+ Assert.Equal(HttpStatusCode.OK, context.StatusCode);
+ var selected = await Trend(patient, "&activityCondition=AtRest");
+ Assert.Equal(1, selected.ContributingCount);
+ Assert.Equal("Unavailable", selected.Systolic.Direction);
+ Assert.Null((await Trend(patient)).Systolic.Reference);
+ using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
+ Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
+ await fixture.RestartHostsAsync();
+ Assert.Equal(150m, (await Trend(patient)).Systolic.Mean);
+ using var last = await fixture.Client.DeleteAsync($"/api/observations/{first}");
+ Assert.Equal(HttpStatusCode.NoContent, last.StatusCode);
+ Assert.Equal(0, (await Trend(patient)).ContributingCount);
+ }
+
+ [Theory]
+ [InlineData("from=2026-09-10&to=2026-09-01")]
+ [InlineData("from=bad&to=2026-09-10")]
+ [InlineData("from=2026-09-01")]
+ [InlineData("to=2026-09-10")]
+ [InlineData("")]
+ [InlineData(Period + "&setting=Invalid")]
+ [InlineData(Period + "&activityCondition=Invalid")]
+ public async Task Invalid_period_or_selection_is_rejected_with_explanation(string period)
+ {
+ using var response = await fixture.Client.GetAsync(PathFor(await Patient(), period: period));
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ Assert.True(problem.RootElement.TryGetProperty("errors", out _));
+ }
+
+ [Fact]
+ public async Task Trend_access_requires_authentication_ownership_or_professional_assignment()
+ {
+ var patient = await Patient();
+ await Record(patient, 150);
+ var other = await Patient();
+ fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
+ await fixture.RestartHostsAsync();
+ using var anonymous = await fixture.RawClient.GetAsync(PathFor(patient));
+ Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
+ foreach (var (account, status) in new[] { ("professional", HttpStatusCode.OK),
+ ("professional-empty", HttpStatusCode.NotFound), (fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound) })
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient));
+ request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
+ using var response = await fixture.RawClient.SendAsync(request);
+ Assert.Equal(status, response.StatusCode);
+ if (status != HttpStatusCode.OK) Assert.Empty(await response.Content.ReadAsStringAsync());
+ }
+ }
+
+ [Fact]
+ public async Task Upstream_failure_is_not_misreported_as_empty_data()
+ {
+ var patient = await Patient();
+ await fixture.StopObservationServiceAsync();
+ try
+ {
+ using var response = await fixture.Client.GetAsync(PathFor(patient));
+ Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
+ }
+ finally { await fixture.RestartHostsAsync(); }
+ }
+}