Merge pull request #723 from MBombeck/fix/cycle-correctness

Cycle correctness: overdue verdicts, backfills, deletes that leave no torso
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-08-07 19:58:39 +02:00
commit 8a1585a391
37 files changed
+2385 -180

No files matched your search

@@ -103,6 +103,16 @@ const LONG_CYCLE_STARTS = [
"2026-04-30",
];
/**
* Four period starts exactly 28 days apart — the textbook regular record. The
* last start is open, so where "today" sits relative to `lastStart + 28`
* decides what the verdict may claim. Built from a supplied last start so a
* test can place today a chosen number of days past the predicted one.
*/
function regularStarts(lastStart: string): string[] {
return [-84, -56, -28, 0].map((offset) => addDays(lastStart, offset));
}
function cycleRows(starts: readonly string[]) {
return starts.map((startDate, i) => ({
id: `cyc-${i}`,
@@ -249,6 +259,7 @@ describe("GET /api/cycle/calendar carries the resolved verdict", () => {
cycleRows(LONG_CYCLE_STARTS) as never,
prediction?.nextPeriodStart ?? null,
resolveLuteal(profile() as never),
"2026-05-20",
);
expect(verdict.dayOfCycle).toBe(fromEngine.dayOfCycle);
expect(verdict.phase).toBe(fromEngine.phase);
@@ -276,6 +287,259 @@ describe("GET /api/cycle/calendar carries the resolved verdict", () => {
expect(prediction!.nextPeriodStart).toBe(addDays("2026-05-20", expected));
});
/**
* D-list edge 1 — the verdict at and after the predicted start day, driven
* through the real route.
*
* A regular 28-day record whose period has not arrived is the ORDINARY way
* to be late, and it is the case the ring was silent about: the engine ends
* the open cycle's phase window at the predicted start, so the day after it
* carried no phase, and the verdict resolver read "no phase today" as "no
* data at all". The person saw an empty ring and the words insufficient data
* on the third day of a late period. `OVERDUE` was only ever reachable when
* the engine itself forecast a cycle longer than the grace window.
*/
describe("a period that has not arrived", () => {
/** Place today N days past `lastStart + 28`, the predicted next start. */
function overdueBy(days: number): { today: string; lastStart: string } {
const today = "2026-06-11";
return { today, lastStart: addDays(today, -(28 + days)) };
}
function seedRegular(lastStart: string): void {
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
cycleRows(regularStarts(lastStart)) as never,
);
}
it("keeps counting the open cycle past the predicted start", async () => {
const { today, lastStart } = overdueBy(3);
seedRegular(lastStart);
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
vi.useFakeTimers();
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
const { body } = await callCalendar();
const data = body.data as Record<string, unknown>;
const verdict = data.verdict as Record<string, unknown>;
const prediction = data.prediction as { nextPeriodStart: string } | null;
// The predicted start really is behind us — otherwise this asserts nothing.
expect(prediction?.nextPeriodStart).toBe(addDays(today, -3));
expect(verdict.state).toBe("IN_CYCLE");
expect(verdict.dayOfCycle).toBe(32);
expect(verdict.phase).toBe("LUTEAL");
expect(verdict.cycleStartDate).toBe(lastStart);
// There is no "until" once the predicted start is behind us.
expect(verdict.daysUntilNext).toBeNull();
});
it("says OVERDUE, with the day count, once the grace window is spent", async () => {
// Typical 28 + 14 days of grace = 42. Day 44 is past it.
const { today, lastStart } = overdueBy(15);
seedRegular(lastStart);
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
vi.useFakeTimers();
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
const { body } = await callCalendar();
const verdict = (body.data as Record<string, unknown>).verdict as Record<
string,
unknown
>;
expect(verdict.state).toBe("OVERDUE");
expect(verdict.dayOfCycle).toBeNull();
expect(verdict.phase).toBeNull();
expect(verdict.overdueDays).toBe(16);
expect(verdict.cycleStartDate).toBe(lastStart);
expect(verdict.spans).toHaveLength(4);
});
it("holds the count on the predicted start day itself", async () => {
const { today, lastStart } = overdueBy(0);
seedRegular(lastStart);
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
vi.useFakeTimers();
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
const { body } = await callCalendar();
const verdict = (body.data as Record<string, unknown>).verdict as Record<
string,
unknown
>;
// Day 29 of a 28-day cycle: the period is due today and has not been
// logged, which is a cycle day, not an absence of data.
expect(verdict.state).toBe("IN_CYCLE");
expect(verdict.dayOfCycle).toBe(29);
expect(verdict.daysUntilNext).toBe(0);
});
it("stops extending the open window once the next period is logged", async () => {
// The same record with one more start logged four days ago: the earlier
// cycle closes at that start and today is day 5 of the new one.
const { today, lastStart } = overdueBy(3);
const withNewStart = [...regularStarts(lastStart), addDays(today, -4)];
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
cycleRows(withNewStart) as never,
);
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
vi.useFakeTimers();
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
const { body } = await callCalendar();
const verdict = (body.data as Record<string, unknown>).verdict as Record<
string,
unknown
>;
expect(verdict.state).toBe("IN_CYCLE");
expect(verdict.dayOfCycle).toBe(5);
expect(verdict.cycleStartDate).toBe(addDays(today, -4));
});
});
/**
* The cold-start gate suppresses the PHASE band while the engine is still
* learning — a population-framed phase word off one or two cycles is not
* earned. The day count is not a guess: it is the number of days since a
* start the person logged themselves. Reading it off the phase labels meant
* the gate took both, so a record with three logged periods rendered an
* empty ring and offered to log a first period.
*/
describe("while the engine is still learning", () => {
it("still counts the cycle day off the logged start", async () => {
const today = "2026-06-11";
const lastStart = addDays(today, -10);
// Three starts → two observed lengths → under the three-cycle gate.
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
cycleRows([
addDays(lastStart, -56),
addDays(lastStart, -28),
lastStart,
]) as never,
);
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
vi.useFakeTimers();
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
const { body } = await callCalendar();
const data = body.data as Record<string, unknown>;
// The gate really is on, so the phase below is suppressed rather than absent.
expect(data.stillLearning).toBe(true);
const verdict = data.verdict as Record<string, unknown>;
expect(verdict.state).toBe("IN_CYCLE");
expect(verdict.dayOfCycle).toBe(11);
expect(verdict.cycleStartDate).toBe(lastStart);
// No phase claim — that part of the gate stands.
expect(verdict.phase).toBeNull();
// The ring still draws a full wheel rather than an empty circle.
expect(verdict.spans).toHaveLength(4);
});
it("still says how late a period is", async () => {
const today = "2026-06-11";
const lastStart = addDays(today, -50);
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
cycleRows([
addDays(lastStart, -56),
addDays(lastStart, -28),
lastStart,
]) as never,
);
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
vi.useFakeTimers();
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
const { body } = await callCalendar();
const verdict = (body.data as Record<string, unknown>).verdict as Record<
string,
unknown
>;
// Day 51 against a stated 28-day typical plus 14 days of grace.
expect(verdict.state).toBe("OVERDUE");
expect(verdict.overdueDays).toBe(23);
expect(verdict.cycleStartDate).toBe(lastStart);
});
});
/**
* D-list edge 15 — the day count under a narrowed `from` window.
*
* The count used to be the length of the labelled run inside the grid, so a
* caller that asked for a shorter span got a smaller number for the same day:
* the run was cut off at the window's edge, not at the cycle's start. That was
* a latent contract question while every caller asked for the same ninety
* days. It stopped being latent when the month grid started reading its own
* month, which is a thirty-day window by construction.
*/
describe("under a narrowed window", () => {
async function callWindow(
from: string,
to: string,
): Promise<Record<string, unknown>> {
const res = await GET(
new NextRequest(
`http://localhost/api/cycle/calendar?from=${from}&to=${to}`,
),
);
const body = JSON.parse(await res.text());
return (body.data as Record<string, unknown>).verdict as Record<
string,
unknown
>;
}
it("counts from the logged start, not from the window's edge", async () => {
const today = "2026-06-11";
const lastStart = "2026-05-20"; // day 23 of the open cycle
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
cycleRows([
addDays(lastStart, -84),
addDays(lastStart, -56),
addDays(lastStart, -28),
lastStart,
]) as never,
);
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
vi.useFakeTimers();
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
const wide = await callWindow(addDays(today, -90), addDays(today, 180));
expect(wide.dayOfCycle).toBe(23);
// The month the grid would be showing: the cycle start is inside it, but
// the window begins after several earlier cycles.
const narrow = await callWindow("2026-06-01", "2026-06-30");
expect(narrow.dayOfCycle).toBe(23);
expect(narrow.cycleStartDate).toBe(lastStart);
});
it("counts correctly when the window excludes the start entirely", async () => {
const today = "2026-06-25";
const lastStart = "2026-05-20";
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
cycleRows([
addDays(lastStart, -56),
addDays(lastStart, -28),
lastStart,
]) as never,
);
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
vi.useFakeTimers();
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
// June only: the cycle opened in May, outside the window entirely.
const narrow = await callWindow("2026-06-01", "2026-06-30");
expect(narrow.cycleStartDate).toBe(lastStart);
expect(narrow.dayOfCycle).toBe(37);
});
});
it("says INSUFFICIENT_DATA when nothing has been logged", async () => {
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue([] as never);
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
+6
View File
@@ -195,6 +195,12 @@ export const GET = apiHandler(async (request: NextRequest) => {
nextPeriodStart: predictionDto?.nextPeriodStart ?? null,
fertileWindowStart: predictionDto?.fertileWindowStart ?? null,
fertileWindowEnd: predictionDto?.fertileWindowEnd ?? null,
// The latest start the person logged, read off the cycle rows rather than
// the grid. The grid's phase band is withheld while the engine is still
// learning, and the day count must not go with it — `cycles` is ordered by
// startDate ascending, so the last one at or before today is the anchor.
lastPeriodStart:
cycles.filter((c) => c.startDate <= today).at(-1)?.startDate ?? null,
});
annotate({
+39 -5
View File
@@ -2,6 +2,12 @@
* `DELETE /api/cycle/cycles/{id}` — soft-delete a cycle
* (ios-contract §2.F): set `deletedAt` + bump `syncVersion`, emit a
* tombstone on the next sync page. 204. Idempotent. Owner-scoped + gated.
*
* The delete also hands the span back to the preceding cycle. Opening a cycle
* closes the one before it, so removing it without re-deriving that boundary
* left the previous cycle standing as a closed torso with an end date taken
* from a cycle that no longer exists — and a record whose last cycle is closed
* has no open cycle to forecast from.
*/
import { NextRequest } from "next/server";
@@ -9,8 +15,10 @@ import { prisma } from "@/lib/db";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { overwriteDetails } from "@/lib/sharing/audit-details";
import { apiError, getClientIp } from "@/lib/api-response";
import { requireCycleEnabled } from "@/lib/cycle/gate";
import { reanchorAfterRemovedStart } from "@/lib/cycle/cycle-boundaries";
type RouteParams = { params: Promise<{ id: string }> };
@@ -28,21 +36,46 @@ export const DELETE = apiHandler(
const existing = await prisma.menstrualCycle.findUnique({
where: { id },
select: { id: true, userId: true },
select: { id: true, userId: true, startDate: true },
});
if (!existing || existing.userId !== user.id) {
return apiError("Cycle not found", 404);
}
await prisma.menstrualCycle.update({
where: { id },
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
// Tombstone + re-anchor as one unit: a neighbour re-derived against a
// half-applied delete would read the row being removed as still live.
const reanchored = await prisma.$transaction(async (db) => {
await db.menstrualCycle.update({
where: { id },
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
});
return reanchorAfterRemovedStart(db, user.id, existing.startDate);
});
await auditLog("cycle.cycle.delete", {
userId: user.id,
ipAddress: getClientIp(request),
details: { cycleId: id },
// The tombstone carries the deleted cycle's own columns, so the only
// unrecoverable part of this write is what it moved on the NEIGHBOUR.
details: {
cycleId: id,
startDate: existing.startDate,
...(reanchored
? {
reanchoredCycleId: reanchored.cycleId,
...overwriteDetails({
before: {
endDate: reanchored.endDateBefore,
lengthDays: reanchored.lengthDaysBefore,
},
after: {
endDate: reanchored.endDateAfter,
lengthDays: reanchored.lengthDaysAfter,
},
}),
}
: {}),
},
});
annotate({
@@ -51,6 +84,7 @@ export const DELETE = apiHandler(
entity_type: "menstrual_cycle",
entity_id: id,
},
meta: { reanchored_prior: reanchored !== null },
});
return new Response(null, { status: 204 });
+81 -5
View File
@@ -23,6 +23,11 @@ import {
safeJson,
} from "@/lib/api-response";
import { requireCycleEnabled } from "@/lib/cycle/gate";
import {
ensureCycleForBleedingDay,
removeCycleStartedOn,
} from "@/lib/cycle/cycle-boundaries";
import { DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
import { encrypt, decrypt } from "@/lib/crypto";
import { getOrCreateCycleProfile } from "@/lib/cycle/profile";
import { replaceSymptomLinks } from "@/lib/cycle/day-log-write";
@@ -157,6 +162,26 @@ export const PATCH = apiHandler(
include: dayLogSymptomInclude,
});
// An edit that turns a day into a first bleeding day opens the cycle it
// starts, and an edit that takes the bleeding back off it removes the
// cycle that day opened. Both directions go through the same shared
// boundary work the capture route and the one-tap start use — a cycle that
// could be created here but not undone here is how the record ends up
// holding a period nothing on the day says happened.
const openedCycleId = await ensureCycleForBleedingDay(
user.id,
existing.date,
user.timezone ?? DEFAULT_TIMEZONE,
row,
);
let removedCycleId: string | null = null;
if (!openedCycleId && !stillBleeds(row)) {
const removed = await prisma.$transaction((db) =>
removeCycleStartedOn(db, user.id, existing.date),
);
removedCycleId = removed?.cycleId ?? null;
}
await auditLog("cycle.day-log.update", {
userId: user.id,
ipAddress: getClientIp(request),
@@ -166,6 +191,8 @@ export const PATCH = apiHandler(
details: {
dayLogId: id,
date: existing.date,
...(openedCycleId ? { openedCycleId } : {}),
...(removedCycleId ? { removedCycleId } : {}),
...overwriteDetails({
before: {},
after: {},
@@ -183,6 +210,10 @@ export const PATCH = apiHandler(
entity_type: "cycle_day_log",
entity_id: id,
},
meta: {
opened_cycle: openedCycleId !== null,
removed_cycle: removedCycleId !== null,
},
});
return apiSuccess(toCycleDayLogDTO(row));
@@ -202,7 +233,7 @@ export const DELETE = apiHandler(
const existing = await prisma.cycleDayLog.findUnique({
where: { id },
select: { id: true, userId: true },
select: { id: true, userId: true, date: true },
});
if (!existing || existing.userId !== user.id) {
return apiError("Day-log not found", 404);
@@ -211,15 +242,44 @@ export const DELETE = apiHandler(
// Soft-delete: leave the row in place so the `/api/sync/changes`
// delta feed surfaces it as a tombstone. A re-delete re-bumps
// `syncVersion` harmlessly (idempotent).
await prisma.cycleDayLog.update({
where: { id },
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
//
// A day that OPENS a cycle takes that cycle with it. The one-tap "started
// my period" writes both rows, and this delete is the only way the web
// offers to take it back — leaving the cycle behind meant the previous one
// stayed closed against a start whose last trace had just been removed, and
// the forecast never came back. The cycle boundary is then re-derived for
// the preceding cycle, the same repair the cycle delete does.
const removed = await prisma.$transaction(async (db) => {
await db.cycleDayLog.update({
where: { id },
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
});
return removeCycleStartedOn(db, user.id, existing.date);
});
await auditLog("cycle.day-log.delete", {
userId: user.id,
ipAddress: getClientIp(request),
details: { dayLogId: id },
details: {
dayLogId: id,
date: existing.date,
...(removed ? { removedCycleId: removed.cycleId } : {}),
...(removed?.reanchored
? {
reanchoredCycleId: removed.reanchored.cycleId,
...overwriteDetails({
before: {
endDate: removed.reanchored.endDateBefore,
lengthDays: removed.reanchored.lengthDaysBefore,
},
after: {
endDate: removed.reanchored.endDateAfter,
lengthDays: removed.reanchored.lengthDaysAfter,
},
}),
}
: {}),
},
});
annotate({
@@ -228,6 +288,10 @@ export const DELETE = apiHandler(
entity_type: "cycle_day_log",
entity_id: id,
},
meta: {
removed_cycle: removed !== null,
reanchored_prior: removed?.reanchored != null,
},
});
return new Response(null, { status: 204 });
@@ -281,3 +345,15 @@ function readStoredSensitive(row: {
contraceptive: row.contraceptive,
};
}
/**
* Whether the edited day still records a period. A cleared or downgraded flow,
* or one re-flagged as bleeding between periods, no longer anchors a cycle.
*/
function stillBleeds(row: {
flow: string | null;
intermenstrualBleeding: boolean;
}): boolean {
if (row.intermenstrualBleeding) return false;
return row.flow !== null && row.flow !== "NONE" && row.flow !== "SPOTTING";
}
+1
View File
@@ -176,6 +176,7 @@ export const GET = apiHandler(async () => {
profile.lutealPhaseLength ?? LUTEAL_DEFAULT,
from,
today,
today,
);
const measurements: CrossMetricMeasurement[] = measurementRows.map((m) => ({
+17 -81
View File
@@ -37,26 +37,20 @@ import {
dayLogSymptomInclude,
} from "@/lib/cycle/dto";
import { DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
import { addDays, dayDiff } from "@/lib/cycle/day-math";
import { openCycleAt, type MovedAnchors } from "@/lib/cycle/cycle-boundaries";
export const POST = apiHandler(withIdempotency<[NextRequest]>(postPeriod));
/**
* v1.37.0 — the anchors a boundary write moves, carried out of the
* transaction so the audit row can name them (C4).
* transaction so the audit row can name them (C4). The `start` arm's own
* anchors live with the shared boundary helper; the `end` arm adds the one
* column it overwrites.
*/
interface MovedAnchors {
priorCycleId?: string;
/** Day keys, the shape this domain stores its dates in. */
priorEndDateBefore?: string | null;
priorEndDateAfter?: string | null;
priorLengthBefore?: number | null;
priorLengthAfter?: number | null;
openedEndDateBefore?: string | null;
openedEndDateAfter?: string | null;
type PeriodMovedAnchors = MovedAnchors & {
periodEndDateBefore?: string | null;
periodEndDateAfter?: string | null;
}
};
async function postPeriod(request: NextRequest): Promise<Response> {
// v1.37.0 — MANAGE. Setting a boundary re-anchors the neighbouring cycles,
@@ -97,73 +91,15 @@ async function postPeriod(request: NextRequest): Promise<Response> {
// exact-key replay; the transaction guards the interleaving case.
const txResult = await prisma.$transaction(async (db) => {
if (action === "start") {
// Close the prior open cycle (its end is the day before this start)
// and record its observed length.
const prior = await db.menstrualCycle.findFirst({
where: { userId: user.id, deletedAt: null, startDate: { lt: date } },
orderBy: { startDate: "desc" },
// v1.37.0 — `endDate` and `lengthDays` are read for the audit row:
// this write overwrites both on the prior cycle and they are the
// dates C4 exists to name.
select: {
id: true,
startDate: true,
endDate: true,
lengthDays: true,
},
});
const moved: MovedAnchors = {};
if (prior) {
moved.priorCycleId = prior.id;
moved.priorEndDateBefore = prior.endDate;
moved.priorEndDateAfter = addDays(date, -1);
moved.priorLengthBefore = prior.lengthDays;
moved.priorLengthAfter = dayDiff(date, prior.startDate);
await db.menstrualCycle.update({
where: { id: prior.id },
data: {
endDate: addDays(date, -1),
lengthDays: dayDiff(date, prior.startDate),
syncVersion: { increment: 1 },
},
});
}
// Upsert the new cycle on the `(userId, startDate)` unique so a
// re-tap on the same day is idempotent.
const cycle = await db.menstrualCycle.upsert({
where: { userId_startDate: { userId: user.id, startDate: date } },
create: { userId: user.id, startDate: date, tz, isPredicted: false },
update: {
deletedAt: null,
isPredicted: false,
syncVersion: { increment: 1 },
},
});
// Re-anchor the FOLLOWING neighbour: when this start is back-filled
// between two existing cycles, the new cycle's end + length are already
// known from its successor's start. Without this the inserted cycle keeps
// endDate/lengthDays = null even though the next start exists, and the
// iOS mirror + history surfaces read a stale open cycle (QA M-1).
const next = await db.menstrualCycle.findFirst({
where: { userId: user.id, deletedAt: null, startDate: { gt: date } },
orderBy: { startDate: "asc" },
select: { startDate: true },
});
if (next) {
moved.openedEndDateBefore = cycle.endDate;
moved.openedEndDateAfter = addDays(next.startDate, -1);
await db.menstrualCycle.update({
where: { id: cycle.id },
data: {
endDate: addDays(next.startDate, -1),
lengthDays: dayDiff(next.startDate, date),
syncVersion: { increment: 1 },
},
});
}
return { cycleId: cycle.id as string | null, moved };
// Close the prior open cycle, open this one, and re-anchor the following
// neighbour when the start is back-filled between two existing cycles.
// The same helper runs when a first bleeding day is captured as flow, so
// a period start means one thing however it was entered.
const { cycleId, moved } = await openCycleAt(db, user.id, date, tz);
return {
cycleId: cycleId as string | null,
moved: moved as PeriodMovedAnchors,
};
}
// `end`: stamp the current cycle's periodEndDate.
@@ -174,7 +110,7 @@ async function postPeriod(request: NextRequest): Promise<Response> {
select: { id: true, periodEndDate: true },
});
if (!current) {
return { cycleId: null, moved: {} satisfies MovedAnchors };
return { cycleId: null, moved: {} satisfies PeriodMovedAnchors };
}
await db.menstrualCycle.update({
where: { id: current.id },
@@ -185,7 +121,7 @@ async function postPeriod(request: NextRequest): Promise<Response> {
moved: {
periodEndDateBefore: current.periodEndDate,
periodEndDateAfter: date,
} satisfies MovedAnchors,
} satisfies PeriodMovedAnchors,
};
});