Merge branch 'fix/v1475-cleanup' into release/v1.47.5

# Conflicts:
#	src/__tests__/baselines/source-file-lines.json
#	src/__tests__/baselines/source-function-lines.json
#	src/__tests__/baselines/version-stamp-comments.json
This commit is contained in:
Marc-André Bombeck committed 2026-11-11 22:51:42 +01:00
commit d5dd05b5ac
164 files changed
+1109 -15288

No files matched your search

+1 -1
View File
@@ -30,4 +30,4 @@ The server and runtime toolkit. Everything that is not a page, component, or rou
## Conventions
Kebab-case filenames. See [`../../CLAUDE.md`](../../CLAUDE.md) "Code conventions" and "Security-relevant patterns"; the critical-files map there cites the exact entry points. Most modules carry tests in a sibling `__tests__/`.
Kebab-case filenames. Most modules carry tests in a sibling `__tests__/`.
+5 -4
View File
@@ -242,10 +242,11 @@ export function invalidateUserHealthScore(userId: string): void {
* on the very next read.
*
* Callers: `/api/user/thresholds` PUT + DELETE, `applyProfileUpdate`
* (only when heightCm / dateOfBirth / gender is in the update set), and
* `/api/auth/me/source-priority` PUT. The unit-preference toggle is NOT
* wired in: it only drives the client-side display transform, no
* server-cached payload reads it.
* (only when heightCm / dateOfBirth / gender is in the update set),
* `/api/auth/me/source-priority` PUT, and `/api/auth/me/glucose-unit` PATCH
* (the targets payload states glucose in the account's unit). The
* unit-preference toggle is NOT wired in: it only drives the client-side
* display transform, no server-cached payload reads it.
*/
export function invalidateUserProfile(userId: string): void {
caches.insightsTargets.deleteByPrefix(userId);
+4 -4
View File
@@ -171,17 +171,17 @@ export const SETTINGS_CARDS: ReadonlyArray<SettingsCardEntry> = [
{ section: "integrations", anchor: "webhook", titleKey: "settings.webhook" },
// ── Health record ──
{
section: "gesundheitsakte",
section: "health-record",
anchor: "health-record",
titleKey: "settings.healthRecord.title",
},
{
section: "gesundheitsakte",
section: "health-record",
anchor: "share-link-create",
titleKey: "settings.sharing.createTitle",
},
{
section: "gesundheitsakte",
section: "health-record",
anchor: "share-links-active",
titleKey: "settings.sharing.activeTitle",
},
@@ -459,7 +459,7 @@ export const SETTINGS_LAYOUT_PAGES: ReadonlyArray<{
titleKey: "settings.sections.layout.documents.title",
module: "inboundDocuments",
},
{ slug: "vorsorge", titleKey: "settings.sections.layout.vorsorge.title" },
{ slug: "checkups", titleKey: "settings.sections.layout.checkups.title" },
];
/**
-28
View File
@@ -1,28 +0,0 @@
/**
* The backup verdict for one schema model, read off the lists in
* `./backup-plan.ts`. Kept beside it rather than in it so the plan stays the
* lists and their reasons, and the one question asked of them lives here.
*/
import {
AUTH_MODELS_OUT_OF_SCOPE,
BACKED_UP_MODELS,
DERIVED_MODELS,
NOT_IN_BACKUP_MODELS,
} from "./backup-plan";
export type BackupVerdict = "BACKED_UP" | "DERIVED" | "NOT_IN_BACKUP" | "AUTH";
/**
* The verdict for a model, or `null` when the schema carries a model this file
* has never ruled on. The guard turns that `null` into a failing test, which
* is the whole point: a new model gets a decision, not a default.
*/
export function backupVerdict(model: string): BackupVerdict | null {
if ((BACKED_UP_MODELS as readonly string[]).includes(model)) {
return "BACKED_UP";
}
if (model in DERIVED_MODELS) return "DERIVED";
if (model in NOT_IN_BACKUP_MODELS) return "NOT_IN_BACKUP";
if (AUTH_MODELS_OUT_OF_SCOPE.includes(model)) return "AUTH";
return null;
}
+1 -2
View File
@@ -62,8 +62,7 @@
* other twenty-two are admin-console routes, operator diagnostics, aggregators
* superseded in place, and the moodLog bridge — surfaces reachable only from
* the operator's own browser, which ships with the server and reads no
* contract to find out what it talks to. `moodlog-removal-guard.test.ts`
* separately holds that bridge removed. Every entry after those five was
* contract to find out what it talks to. Every entry after those five was
* written by the release that removed the path, which is where a tombstone
* belongs.
*
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { METRIC_CATALOG_ENTRIES } from "../metric-catalog";
/**
* The metric catalog offers "Connect a source" for a metric without readings
* and the metric's own entry action for one only a person can log. Ketones
* shipped without joining the manual list, so their row sent people to the
* integrations page, where nothing delivers ketones.
*/
describe("metric catalog", () => {
it("offers ketones as a manual entry, not a source to connect", () => {
const ketones = METRIC_CATALOG_ENTRIES.find((e) => e.id === "ketones");
expect(ketones).toBeDefined();
expect(ketones?.connectable).toBe(false);
expect(ketones?.manualHref).toBe("/measurements?add=BLOOD_KETONES");
expect(ketones?.manualCtaKey).toBe("insights.bloodKetones.emptyState.cta");
});
it("gives every metric that cannot be connected a way to log it", () => {
const manualOnly = METRIC_CATALOG_ENTRIES.filter(
(e) => e.kind === "metric" && !e.connectable,
);
expect(manualOnly.length).toBeGreaterThan(0);
for (const entry of manualOnly) {
expect(entry.manualHref, entry.id).toBeTruthy();
expect(entry.manualCtaKey, entry.id).toBeTruthy();
}
});
});
+11 -5
View File
@@ -109,12 +109,13 @@ const SOURCE_KEY_OVERRIDES: Partial<Record<SubPageSlug, string>> = {
/**
* Metrics with no device path at all — manual entry is the only source.
* Mood and medications are inherently self-report (no sensor produces a
* mood score or an adherence event). Pain, grip strength, and waist-to-
* height ratio are ALSO manual-only despite sitting beside device-fed
* siblings in their group: none carries an Apple Health mapping
* mood score or an adherence event). Pain, grip strength, waist-to-height
* ratio and blood ketones are ALSO manual-only despite sitting beside
* device-fed siblings in their group: none carries an Apple Health mapping
* (`apple-health-mapping.ts`) or a Withings/wearable source — pain is a
* 0–10 self-rating, grip strength is read off a hand dynamometer, and
* waist-to-height is logged directly (not derived like BMI). Cross-
* 0–10 self-rating, grip strength is read off a hand dynamometer,
* waist-to-height is logged directly (not derived like BMI), and ketones
* come off a fingerstick meter that no integration reads. Cross-
* checked against every routed sub-page's `emptyStateCtaType` +
* `emptyState.description` copy so this list can't silently drift from
* what the metric's own empty state actually offers.
@@ -125,6 +126,7 @@ const MANUAL_ONLY_SLUGS: ReadonlySet<SubPageSlug> = new Set([
"pain",
"grip-strength",
"waist-to-height",
"ketones",
]);
const MANUAL_CTA: Partial<
@@ -147,6 +149,10 @@ const MANUAL_CTA: Partial<
href: "/measurements?add=WAIST_TO_HEIGHT",
ctaKey: "insights.waistToHeight.emptyState.cta",
},
ketones: {
href: "/measurements?add=BLOOD_KETONES",
ctaKey: "insights.bloodKetones.emptyState.cta",
},
};
/**
@@ -310,7 +310,7 @@ describe("runMedicationLowStockTick", () => {
thresholdDays: 7,
unitsRemaining: 5,
// Deep link lands on the detail page's Bestand (supply) tab.
url: "/medications/med-1?tab=bestand",
url: "/medications/med-1?tab=supply",
}),
}),
);
@@ -6,7 +6,7 @@ import {
COMPREHENSIVE_WARM_CEILING_MS,
comprehensiveWarmBudgetMs,
} from "../model-time";
import { QUEUE_RUNTIME } from "../queue-runtime";
import { QUEUE_RUNTIME } from "@/__tests__/helpers/queue-runtime";
import { COMPREHENSIVE_MODEL_CALLS } from "@/lib/ai/ai-budgets";
import { AI_RESPONSE_TIMEOUT_MAX_SECONDS } from "@/lib/ai/effective-timeout";
import type { GenerateOutcome } from "@/lib/insights/comprehensive-generate";
+1 -1
View File
@@ -8,7 +8,7 @@ import {
RESTORE_DRILL_QUEUE,
RESTORE_DRILL_SEND_OPTIONS,
} from "@/lib/jobs/restore-drill-queue";
import { QUEUE_RUNTIME } from "../queue-runtime";
import { QUEUE_RUNTIME } from "@/__tests__/helpers/queue-runtime";
vi.mock("../report-worker-error", () => ({
reportWorkerError: vi.fn().mockResolvedValue(undefined),
@@ -1,238 +0,0 @@
/**
* Round-trip + paging contract for the backup measurement reader.
*
* Runs without a database: the keyset pager takes a `fetchPage` callback,
* so an in-memory fixture stands in for Prisma. This pins the two things
* the heap-bounding refactor must not break:
* 1. the keyset scan visits every row exactly once, in id order,
* across page boundaries and the exact-multiple edge case;
* 2. a measurement survives the full serialize → encrypt-blob shape →
* `parseBackupPayload` → restore-mapping round-trip unchanged,
* including a soft-deleted (tombstoned) row, which both writers keep.
*/
import { describe, it, expect } from "vitest";
import {
collectPagedMeasurements,
toWeeklyBackupMeasurement,
sortWeeklyMeasurementsDesc,
type WeeklyMeasurementRow,
} from "@/lib/jobs/backup/measurement-page";
import { parseBackupPayload } from "@/lib/validations/backup";
/** Build an id-ascending fixture; `id` is zero-padded so string order == insert order. */
function makeRows(n: number): WeeklyMeasurementRow[] {
return Array.from({ length: n }, (_, i) => ({
id: `m${String(i).padStart(4, "0")}`,
type: "WEIGHT",
value: 70 + i,
unit: "kg",
source: "MANUAL",
measuredAt: new Date(Date.UTC(2026, 0, 1 + i, 8, 0, 0)),
notes: i % 2 === 0 ? `note ${i}` : null,
// notesEncrypted left null so readNote returns the plaintext fallback
// and the pure test needs no encryption key.
notesEncrypted: null,
}));
}
/** In-memory keyset fetcher over an id-sorted fixture. */
function fakeFetcher(rows: WeeklyMeasurementRow[]) {
const sorted = [...rows].sort((a, b) =>
a.id < b.id ? -1 : a.id > b.id ? 1 : 0,
);
return (afterId: string | null, take: number) => {
const start = afterId ? sorted.findIndex((r) => r.id === afterId) + 1 : 0;
return Promise.resolve(sorted.slice(start, start + take));
};
}
describe("collectPagedMeasurements", () => {
it("visits every row exactly once, in id order, across pages", async () => {
const rows = makeRows(25);
const out = await collectPagedMeasurements({
fetchPage: fakeFetcher(rows),
project: (r) => r.id,
pageSize: 10,
});
expect(out).toEqual(rows.map((r) => r.id));
expect(new Set(out).size).toBe(out.length);
});
it("terminates on the exact-multiple boundary without dropping rows", async () => {
const rows = makeRows(20);
const out = await collectPagedMeasurements({
fetchPage: fakeFetcher(rows),
project: (r) => r.id,
pageSize: 10,
});
expect(out).toHaveLength(20);
expect(out[out.length - 1]).toBe("m0019");
});
it("handles an empty set", async () => {
const out = await collectPagedMeasurements({
fetchPage: fakeFetcher([]),
project: (r) => r.id,
pageSize: 10,
});
expect(out).toEqual([]);
});
});
describe("weekly backup measurement round-trip", () => {
it("serialize → parseBackupPayload → restore-map equals originals", async () => {
const rows: WeeklyMeasurementRow[] = [
{
id: "m0001",
type: "WEIGHT",
value: 82.4,
unit: "kg",
source: "MANUAL",
measuredAt: new Date("2026-02-10T07:30:00.000Z"),
notes: "morning",
notesEncrypted: null,
},
{
id: "m0002",
type: "PULSE",
value: 58,
unit: "bpm",
source: "WITHINGS",
measuredAt: new Date("2026-02-11T06:00:00.000Z"),
notes: null,
notesEncrypted: null,
},
{
// A tombstoned row: the weekly writer applies no deletedAt filter,
// so a soft-deleted measurement is still backed up. The narrow
// weekly projection does not carry deletedAt (the restore does not
// recreate it), but the row must still appear in the payload.
id: "m0003",
type: "BLOOD_GLUCOSE",
value: 95,
unit: "mg/dL",
source: "IMPORT",
measuredAt: new Date("2026-02-12T12:00:00.000Z"),
notes: "fasting",
notesEncrypted: null,
},
];
const measurements = sortWeeklyMeasurementsDesc(
await collectPagedMeasurements({
fetchPage: fakeFetcher(rows),
project: toWeeklyBackupMeasurement,
pageSize: 2,
}),
);
// Same envelope the writer produces, then parse it back exactly as the
// admin restore route does.
const backupJson = JSON.stringify({
schemaVersion: "1",
exportedAt: new Date("2026-02-13T00:00:00.000Z").toISOString(),
userId: "user-1",
measurements,
medications: [],
intakeEvents: [],
moodEntries: [],
});
const payload = parseBackupPayload(backupJson);
expect(payload.measurements).toHaveLength(rows.length);
// measuredAt-desc ordering preserved (newest first).
expect(payload.measurements.map((m) => m.measuredAt)).toEqual([
"2026-02-12T12:00:00.000Z",
"2026-02-11T06:00:00.000Z",
"2026-02-10T07:30:00.000Z",
]);
// Every original row survives the round-trip by value (the tombstoned
// m0003 included).
for (const original of rows) {
const restored = payload.measurements.find(
(m) => m.measuredAt === original.measuredAt.toISOString(),
);
expect(restored, `row ${original.id} missing from payload`).toBeDefined();
expect(restored!.type).toBe(original.type);
expect(restored!.value).toBe(original.value);
expect(restored!.unit).toBe(original.unit);
expect(restored!.source).toBe(original.source);
expect(restored!.notes ?? null).toBe(original.notes ?? null);
}
});
});
describe("offhost backup measurement round-trip", () => {
it("full-row JSON dump → parse preserves all columns incl. soft-deleted", async () => {
// The off-host DR dump keeps the full row shape (identity projection).
// Mirror the writer's select output for a live row and a tombstoned row.
const liveRow = {
id: "m0001",
userId: "user-1",
type: "WEIGHT",
value: 80.1,
valueMin: null,
valueMax: null,
unit: "kg",
source: "MANUAL",
measuredAt: new Date("2026-03-01T07:00:00.000Z"),
notes: null,
notesEncrypted: null,
externalId: null,
externalSourceVersion: null,
glucoseContext: null,
sleepStage: null,
rhythmClassification: null,
deviceType: "scale",
syncVersion: 1,
deletedAt: null,
createdAt: new Date("2026-03-01T07:00:01.000Z"),
updatedAt: new Date("2026-03-01T07:00:01.000Z"),
};
const tombstonedRow = {
...liveRow,
id: "m0002",
value: 81.2,
measuredAt: new Date("2026-03-02T07:00:00.000Z"),
deletedAt: new Date("2026-03-03T09:00:00.000Z"),
};
const measurements = await collectPagedMeasurements({
fetchPage: fakeFetcher([
liveRow,
tombstonedRow,
] as unknown as WeeklyMeasurementRow[]),
project: (row) => row,
pageSize: 1,
});
const payload = JSON.parse(
JSON.stringify({
exportedAt: new Date("2026-03-04T00:00:00.000Z").toISOString(),
userId: "user-1",
measurements,
medications: [],
intakeEvents: [],
moodEntries: [],
cycleProfile: null,
cycles: [],
cycleDayLogs: [],
}),
) as { measurements: Array<Record<string, unknown>> };
expect(payload.measurements).toHaveLength(2);
// The soft-deleted row survives with its tombstone instant intact —
// the DR snapshot must include it.
const restoredTombstone = payload.measurements.find(
(m) => m.id === "m0002",
)!;
expect(restoredTombstone.deletedAt).toBe("2026-03-03T09:00:00.000Z");
// Every scalar column the writer selected is present on the dump.
const expectedKeys = Object.keys(liveRow).sort();
expect(Object.keys(payload.measurements[0]).sort()).toEqual(expectedKeys);
});
});
-126
View File
@@ -1,126 +0,0 @@
/**
* Keyset-paged measurement reader shared by the two backup writers.
*
* Both writers — the weekly on-host `DataBackup` snapshot
* (`reminder/backup-handlers.ts`) and the nightly off-host DR dump
* (`offhost-backup.ts`) — used to load a user's ENTIRE measurement set
* as full ORM rows into one array and then run a single
* `JSON.stringify` over the whole payload. On a heavy multi-year tenant
* that holds every measurement row plus the giant serialized string in
* memory at the same instant, which is the dominant heap spike of either
* job and scales linearly with history depth.
*
* This reader walks the set in id-ascending keyset pages: at most one
* page of rows is resident at a time, and each page is projected to its
* compact backup shape before the next page is fetched. Transient peak
* heap is bounded by the page size, not by the size of the user's
* history. The accumulated output is the compact projection the payload
* needs anyway — not the wide ORM rows.
*
* Keyset (cursor on `id`) rather than `skip`/`take` offset paging so the
* scan stays O(rows) instead of O(rows^2) as the offset grows, and so a
* concurrent insert can't shift rows across a page boundary.
*/
import { readNote } from "@/lib/crypto/note-cipher";
/**
* Page size for the backup keyset scan. Large enough that the per-page
* round-trip overhead stays negligible, small enough that a single page
* of rows is a bounded slice of any tenant's history.
*/
export const MEASUREMENT_BACKUP_PAGE_SIZE = 2000;
/**
* Walk a keyset-paged result set, projecting each row to its compact
* backup shape as it arrives. `fetchPage` returns the next page of rows
* after `afterId` (exclusive, id-ascending), bounded to `take` rows;
* returning fewer than `take` rows signals the final page. The generic
* stays free of any Prisma dependency so the paging contract is unit
* testable without a database.
*/
export async function collectPagedMeasurements<
Row extends { id: string },
Out,
>(args: {
fetchPage: (afterId: string | null, take: number) => Promise<Row[]>;
project: (row: Row) => Out;
pageSize?: number;
}): Promise<Out[]> {
const { fetchPage, project } = args;
const pageSize = args.pageSize ?? MEASUREMENT_BACKUP_PAGE_SIZE;
const out: Out[] = [];
let afterId: string | null = null;
for (;;) {
const page = await fetchPage(afterId, pageSize);
if (page.length === 0) break;
for (const row of page) out.push(project(row));
if (page.length < pageSize) break;
afterId = page[page.length - 1].id;
}
return out;
}
/**
* Narrow row shape the weekly snapshot reads — exactly the columns the
* admin restore path recreates a measurement from
* (`api/admin/backups/[id]/restore`): `type`, `value`, `unit`, `source`,
* `measuredAt`, plus the note pair so the decrypted note rides into the
* (whole-blob-encrypted) payload. `id` rides along only as the keyset
* cursor.
*/
export interface WeeklyMeasurementRow {
id: string;
type: string;
value: number;
unit: string;
source: string;
measuredAt: Date;
notes: string | null;
notesEncrypted: Uint8Array | null;
}
/** Compact measurement shape the weekly `DataBackup` JSON carries. */
export interface WeeklyBackupMeasurement {
type: string;
value: number;
unit: string;
measuredAt: string;
source: string;
notes: string | null;
}
/**
* Project a narrow measurement row into the weekly backup shape. The
* note is decrypted here so the restore re-encrypts on re-insert — the
* same contract the previous inline writer used. Shared with the writer
* so the round-trip test exercises the real projection.
*/
export function toWeeklyBackupMeasurement(
row: WeeklyMeasurementRow,
): WeeklyBackupMeasurement {
return {
type: row.type,
value: row.value,
unit: row.unit,
measuredAt: row.measuredAt.toISOString(),
source: row.source,
notes: readNote(row.notesEncrypted, row.notes),
};
}
/**
* Order the collected weekly measurements newest-first to match the
* pre-paging `orderBy: { measuredAt: "desc" }` output. The keyset scan
* reads id-ascending for a stable cursor; this restores the historical
* array order. Operates on the compact projections, so it does not
* reintroduce the wide-row heap spike. ISO-8601 strings sort
* lexicographically in chronological order, so a string compare is the
* chronological compare.
*/
export function sortWeeklyMeasurementsDesc(
measurements: WeeklyBackupMeasurement[],
): WeeklyBackupMeasurement[] {
return measurements.sort((a, b) =>
a.measuredAt < b.measuredAt ? 1 : a.measuredAt > b.measuredAt ? -1 : 0,
);
}
+1 -1
View File
@@ -46,7 +46,7 @@
* provider-less account costs one cheap chain-resolve and no LLM call.
*
* Recurring pg-boss task — never runs inside an HTTP request and never
* shells out to `tsx` (CLAUDE.md DO-NOTs).
* shells out to `tsx` (the production image has none).
*/
import { activeAccount } from "@/lib/account-deletion/active-account";
import { createHash, randomUUID } from "node:crypto";
+1 -1
View File
@@ -16,7 +16,7 @@
* polls the read-only GET until it lands.
*
* Recurring/event pg-boss task — never runs inside an HTTP request and
* never shells out to `tsx` (CLAUDE.md DO-NOTs). Registered in the
* never shells out to `tsx` (the production image has none). Registered in the
* reminder-worker `allQueues` loop + a `boss.work` handler; a queue built
* but never registered silently never drains (the v1.4.37 W10 incident),
* so a guard test pins the registration.
+1 -1
View File
@@ -621,7 +621,7 @@ export async function runMedicationLowStockTick(
// the service-worker payload's click target. Lands on
// the detail page's Bestand (supply) tab, the surface
// the alert is about.
url: `/medications/${med.id}?tab=bestand`,
url: `/medications/${med.id}?tab=supply`,
},
});
if (!outcome.dispatched) {
+1 -1
View File
@@ -17,7 +17,7 @@
* so a provider-less / sparse account costs only the context build.
*
* Recurring pg-boss task — never runs inside an HTTP request, never shells out
* to `tsx` (CLAUDE.md DO-NOTs).
* to `tsx` (the production image has none).
*/
import { ACTIVE_ACCOUNT } from "@/lib/account-deletion/active-account";
import type { PrismaClient } from "@/generated/prisma/client";
-626
View File
@@ -1,626 +0,0 @@
/**
* How long one job of each queue can run, and what keeps a long one safe.
*
* pg-boss gives every job an expiry, fifteen minutes unless the send says
* otherwise. Past it pg-boss fails the job, fires its abort signal and retries
* it, and it does not stop the handler, so a job that legitimately needs longer
* ends up running twice beside itself. No queue policy prevents that: the
* policies constrain job rows, and an expired row is no longer active. Every
* queue the worker registry declares is therefore declared here as one of:
*
* - `short`: a job cannot come near fifteen minutes (one account's bounded
* window, one document, a forwarder, a bounded delete). It relies on the
* default expiry, and the reason says why that is enough.
* - `budgeted`: a pass over a long history that stops itself at three
* quarters of the default expiry (`jobBudget`) and hands the rest to its
* next run, so it ends before fifteen minutes by construction.
* - `bounded`: one unit of model work (one account's note, refresh or
* memory pass, a document summary) whose calls wait the person's
* response timeout each, up to ten minutes, which can outlast fifteen
* minutes. Every call carries its own abort and most sit behind an outer
* bound, so the job's longest run is known (`modelSeconds`, from
* `model-time.ts`); it carries an explicit
* `expireInSeconds` above that on every send, and no retry can start
* beside a run that is still going (#1274).
* - `long`: a job that may run for hours. It carries an explicit
* `expireInSeconds` on every send and schedule, stops itself before that
* expiry (`jobBudget` / `jobDeadline`), and holds something per identity
* that keeps a second run from working beside it: the lock `lockedPass`
* takes, a lock of its own, or a row it claims. The one exception is a
* one-shot job with `retryLimit: 0`, which pg-boss never retries and which
* cannot stop half-way without losing its input.
*
* `src/__tests__/job-queue-runtime-guard.test.ts` holds every binding, send
* and schedule in the tree to this table.
*/
import { INTEGRATION_BACKFILL_EXPIRE_SECONDS } from "@/lib/jobs/integration-backfill-admission";
import { NIGHTLY_INSIGHT_PASS_EXPIRE_SECONDS } from "@/lib/jobs/reminder/registrar-shared";
import { INSIGHT_PREGENERATE_EXPIRE_SECONDS } from "@/lib/jobs/insight-pregenerate-shared";
import { PERIOD_NARRATIVE_EXPIRE_SECONDS } from "@/lib/jobs/period-narrative-queue";
import { PR_DETECTION_EXPIRE_SECONDS } from "@/lib/jobs/pr-detection";
import { ENCRYPTION_KEY_ROTATE_EXPIRE_SECONDS } from "@/lib/jobs/encryption-key-rotate";
import { CONTENT_INDEX_BACKFILL_EXPIRE_SECONDS } from "@/lib/jobs/document-content-index-backfill";
import { DOCUMENT_AI_RUN_EXPIRE_SECONDS } from "@/lib/jobs/document-ai-run";
import { DATA_BACKUP_SEND_OPTIONS } from "@/lib/jobs/data-backup-policy";
import { DATABASE_BACKUP_EXPIRE_SECONDS } from "@/lib/jobs/database-backup-queue";
import { OFFHOST_BACKUP_EXPIRE_SECONDS } from "@/lib/jobs/offhost-backup-queue";
import { BACKUP_RESTORE_EXPIRE_SECONDS } from "@/lib/jobs/backup-restore";
import { RESTORE_DRILL_EXPIRE_SECONDS } from "@/lib/jobs/restore-drill-queue";
import { APPLE_HEALTH_IMPORT_SEND_OPTIONS } from "@/lib/jobs/apple-health-import-worker";
import { MEDICATION_INTAKE_IMPORT_SEND_OPTIONS } from "@/lib/jobs/medication-intake-import";
import { HEALTH_CONNECT_IMPORT_SEND_OPTIONS } from "@/lib/jobs/health-connect-import-worker";
import { MEASUREMENT_MAINTENANCE_SEND_OPTIONS } from "@/lib/jobs/measurement-maintenance";
import { PULSE_DAY_MEAN_SEND_OPTIONS } from "@/lib/jobs/pulse-day-mean";
import { ROLLUP_FULL_BACKFILL_EXPIRE_SECONDS } from "@/lib/rollups/full-backfill";
import { MORNING_DIGEST_REFRESH_EXPIRE_SECONDS } from "@/lib/jobs/morning-digest-refresh-shared";
import { INSIGHT_STATUS_GENERATE_EXPIRE_SECONDS } from "@/lib/jobs/insight-status-generate-queue";
import { WORKOUT_INSIGHT_GENERATE_EXPIRE_SECONDS } from "@/lib/jobs/workout-insight-generate-shared";
import {
COACH_MEMORY_MODEL_RUNS,
COACH_MEMORY_REFRESH_EXPIRE_SECONDS,
} from "@/lib/ai/coach/coach-memory-shared";
import {
COMPLETION_CEILING_MS,
COMPREHENSIVE_WARM_CEILING_MS,
} from "@/lib/jobs/model-time";
import { DOCUMENT_INDEX_EXPIRE_SECONDS } from "@/lib/jobs/document-index-queue";
import { DOCUMENT_SUMMARY_EXPIRE_SECONDS } from "@/lib/jobs/document-summary-queue";
/** pg-boss's default job expiry, in seconds. */
export const DEFAULT_JOB_EXPIRE_SECONDS = 15 * 60;
/** Where a check lives: a function (or const) in a file under `src/`. */
export type SourceSite = { file: string; fn: string };
export type QueueRuntime =
| { runtime: "short"; why: string }
| { runtime: "budgeted"; budget: SourceSite; why: string }
| {
runtime: "bounded";
/**
* The longest the job's model work runs at the largest response-timeout
* setting, in seconds: the outer bounds in the code, not an estimate.
*/
modelSeconds: number;
expireInSeconds: number;
/** As for `long`: identifiers that carry the expiry into a send. */
expiryVia: readonly string[];
why: string;
}
| {
runtime: "long";
expireInSeconds: number;
/**
* Identifiers that carry the expiry into a send or a schedule. A site
* that names none of them must set `expireInSeconds` itself.
*/
expiryVia: readonly string[];
/** Where the handler stops on the job's budget, or `oneShot`. */
stop: SourceSite | { oneShot: string };
/**
* What keeps a second run from working beside this one: the `lock`
* its registry definition declares (`lockedPass`), or a marker in the
* named function.
*/
exclusive: "lockedPass" | { marker: string; at: SourceSite };
why: string;
};
const short = (why: string): QueueRuntime => ({ runtime: "short", why });
const cohortSync = (provider: string): QueueRuntime =>
short(
`${provider} sync: a recent window per connection (incremental since the last sync); a webhook job is one connection.`,
);
const oauthStateCleanup = short("One DELETE of expired OAuth state rows.");
const forwarder = short(
"Forwards each job to integration-backfill-admission; the import itself runs there.",
);
export const QUEUE_RUNTIME: Readonly<Record<string, QueueRuntime>> = {
// ── Integration sync ───────────────────────────────────────────────
"integration-backfill-admission": {
runtime: "long",
expireInSeconds: INTEGRATION_BACKFILL_EXPIRE_SECONDS,
expiryVia: ["integrationBackfillAdmissionSendOptions"],
stop: {
file: "lib/jobs/integration-backfill-drain.ts",
fn: "drainIntegrationBackfillAdmission",
},
exclusive: {
marker: "withIntegrationBackfillLock",
at: {
file: "lib/jobs/integration-backfill-drain.ts",
fn: "drainIntegrationBackfillAdmission",
},
},
why: "Full-history provider imports: thousands of pages on a dense account.",
},
"withings-fallback-sync": cohortSync("Withings"),
"withings-activity-sync": cohortSync("Withings activity"),
"withings-sleep-sync": cohortSync("Withings sleep"),
"withings-ecg-sync": cohortSync("Withings ECG"),
"withings-oauth-state-cleanup": oauthStateCleanup,
"whoop-recovery-sync": cohortSync("WHOOP recovery"),
"whoop-sleep-sync": cohortSync("WHOOP sleep"),
"whoop-workout-sync": cohortSync("WHOOP workout"),
"whoop-cycle-sync": cohortSync("WHOOP cycle"),
"whoop-backfill": forwarder,
"whoop-oauth-state-cleanup": oauthStateCleanup,
"oidc-native-handoff-cleanup": short("One DELETE of expired handoff rows."),
"fitbit-sync": cohortSync("Fitbit"),
"fitbit-backfill": forwarder,
"fitbit-sleep-repair": forwarder,
"fitbit-oauth-state-cleanup": oauthStateCleanup,
"google-health-sync": cohortSync("Google Health"),
"google-health-backfill": forwarder,
"google-health-sleep-repair": forwarder,
"google-health-oauth-state-cleanup": oauthStateCleanup,
"sleep-timeline-backfill": forwarder,
"lab-biomarker-backfill": forwarder,
"nightscout-sync": cohortSync("Nightscout"),
"polar-sync": cohortSync("Polar"),
"oura-sync": cohortSync("Oura"),
"strava-sync": cohortSync("Strava"),
"strava-backfill": forwarder,
"oura-backfill": forwarder,
"garmin-sync": cohortSync("Garmin"),
"garmin-backfill": forwarder,
// ── Status and insights ────────────────────────────────────────────
"insights-general-status": {
runtime: "long",
expireInSeconds: NIGHTLY_INSIGHT_PASS_EXPIRE_SECONDS,
expiryVia: ["nightlyInsightPassOptions"],
stop: {
file: "lib/jobs/reminder/insights-handlers.ts",
fn: "handleGeneralStatusGenerate",
},
exclusive: "lockedPass",
why: "Nightly status batch: one provider call per candidate account, serially, over the whole instance.",
},
"insight-pregenerate": {
runtime: "long",
expireInSeconds: INSIGHT_PREGENERATE_EXPIRE_SECONDS,
expiryVia: ["INSIGHT_PREGENERATE_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/insights-handlers.ts",
fn: "handleInsightPregenerateJob",
},
exclusive: "lockedPass",
why: "Up to 200 accounts, a comprehensive generation each (up to five provider calls in a row, each bounded by the account's timeout of at most ten minutes) plus the status warm.",
},
"morning-digest-refresh": {
runtime: "bounded",
modelSeconds: COMPREHENSIVE_WARM_CEILING_MS / 1000,
expireInSeconds: MORNING_DIGEST_REFRESH_EXPIRE_SECONDS,
expiryVia: ["MORNING_DIGEST_REFRESH_EXPIRE_SECONDS"],
why: "One account, one forced comprehensive generation: up to five calls in a row at the account's timeout, behind the warm's own bound.",
},
"insight-status-generate": {
runtime: "bounded",
modelSeconds: COMPLETION_CEILING_MS / 1000,
expireInSeconds: INSIGHT_STATUS_GENERATE_EXPIRE_SECONDS,
expiryVia: ["INSIGHT_STATUS_GENERATE_EXPIRE_SECONDS"],
why: "One account, one note: one status run, the call and its one reasoning repeat at the account's timeout.",
},
"data-arrival": short("One arrival's reactions."),
"reaction-line-generate": short("One provider call for one reaction line."),
"workout-insight-generate": {
runtime: "bounded",
modelSeconds: COMPLETION_CEILING_MS / 1000,
expireInSeconds: WORKOUT_INSIGHT_GENERATE_EXPIRE_SECONDS,
expiryVia: ["WORKOUT_INSIGHT_GENERATE_EXPIRE_SECONDS"],
why: "One workout's line: one status run at the account's timeout.",
},
"recovery-score-compute": short(
"Arithmetic over a recent window, capped at 500 accounts; no provider call.",
),
"stress-score-compute": short(
"Arithmetic over a recent window, capped at 500 accounts; no provider call.",
),
"strain-score-compute": short(
"Arithmetic over a recent window, capped at 500 accounts; no provider call.",
),
"period-narrative-warm": {
runtime: "long",
expireInSeconds: PERIOD_NARRATIVE_EXPIRE_SECONDS,
expiryVia: ["PERIOD_NARRATIVE_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/status-handlers.ts",
fn: "handlePeriodNarrative",
},
exclusive: "lockedPass",
why: "On a boundary night up to 200 accounts with a provider call per period each; a single-account warm is short.",
},
"coach-memory-refresh": {
runtime: "bounded",
modelSeconds: (COACH_MEMORY_MODEL_RUNS * COMPLETION_CEILING_MS) / 1000,
expireInSeconds: COACH_MEMORY_REFRESH_EXPIRE_SECONDS,
expiryVia: ["COACH_MEMORY_REFRESH_EXPIRE_SECONDS"],
why: "One conversation's summary, facts and plan proposals: three status runs in a row at the account's timeout.",
},
"coach-nudge": short(
"Light deterministic checks per account; the provider part is capped at 25 calls and 90 seconds a tick.",
),
"coach-reminder-sweep": short("Batches of 200 to 500 rows, no provider."),
"coach-plan-review": short("A batch of 100 plans, folded in SQL."),
"medication-low-stock": short("A light inventory check per account."),
"daily-briefing": short("A light cohort scan every fifteen minutes."),
// ── Rollups ────────────────────────────────────────────────────────
"rollup-recompute": short(
"One type at one granularity over one bucket or a run of adjacent buckets, inside the five-year fold window.",
),
"rollup-full-backfill": {
runtime: "long",
expireInSeconds: ROLLUP_FULL_BACKFILL_EXPIRE_SECONDS,
expiryVia: ["ROLLUP_FULL_BACKFILL_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/rollup-handlers.ts",
fn: "handleRollupFullBackfill",
},
exclusive: "lockedPass",
why: "One account's five-year fold, a calendar year at a time with every statement under its own five-minute limit; the run stops at its budget between windows and hands the remaining years to a follow-up.",
},
"mood-rollup-recompute": short("One bucket."),
"mood-rollup-full-backfill": short(
"One account's mood entries, a few a day.",
),
"step-consolidation": short(
"One account's legacy step rows, one transaction per day.",
),
"step-consolidation-repair": short(
"One account's tombstoned step rows inside the retention window.",
),
"supplement-nutrient-recompute": short(
"One account's taken doses of medications with a composition: a few thousand rows for years of a daily supplement.",
),
"cumulative-pr-rederive": short(
"One account's record detection; measured at 20 seconds for 1.25 million rows.",
),
"mean-consolidation": {
runtime: "budgeted",
budget: {
file: "lib/jobs/reminder/rollup-handlers.ts",
fn: "handleMeanConsolidation",
},
why: "One account's whole history, a day at a time; stops at three quarters of the default expiry and resumes.",
},
"dense-intraday-retention": {
runtime: "budgeted",
budget: {
file: "lib/jobs/reminder/rollup-handlers.ts",
fn: "handleDenseIntradayRetention",
},
why: "A dense account's history, a day at a time; stops at three quarters of the default expiry and resumes.",
},
"dense-intraday-hourly-rebuild": {
runtime: "budgeted",
budget: {
file: "lib/jobs/reminder/rollup-handlers.ts",
fn: "handleDenseIntradayHourlyRebuild",
},
why: "A dense account's hourly rows, a day at a time; stops at three quarters of the default expiry and resumes.",
},
"drain-per-sample-cumulative": {
runtime: "budgeted",
budget: {
file: "lib/jobs/reminder/rollup-handlers.ts",
fn: "drainCumulativeHandler",
},
why: "Every account's per-sample drains; stops at three quarters of the default expiry and hands the rest to a continuation job.",
},
// ── Reminders ──────────────────────────────────────────────────────
"medication-reminder-check": short("The due slots of the current minute."),
"mood-reminder-check": short("Accounts whose local reminder hour is now."),
"cycle-reminder-check": short("Accounts whose local reminder hour is now."),
"measurement-reminder-check": short(
"Accounts whose local reminder hour is now.",
),
"reminder-satisfy": short("One account's open reminders."),
// ── Maintenance ────────────────────────────────────────────────────
"data-backup": {
runtime: "long",
expireInSeconds: DATA_BACKUP_SEND_OPTIONS.expireInSeconds,
expiryVia: ["DATA_BACKUP_SEND_OPTIONS"],
stop: {
file: "lib/jobs/reminder/backup-handlers.ts",
fn: "handleDataBackup",
},
exclusive: "lockedPass",
why: "Serialises every account's whole record.",
},
"database-backup": {
runtime: "long",
expireInSeconds: DATABASE_BACKUP_EXPIRE_SECONDS,
expiryVia: ["DATABASE_BACKUP_SEND_OPTIONS"],
stop: {
file: "lib/jobs/reminder/backup-handlers.ts",
fn: "handleDatabaseBackup",
},
exclusive: "lockedPass",
why: "Runs pg_dump over the whole database and uploads the dump off-host.",
},
"data-backup-offhost": {
runtime: "long",
expireInSeconds: OFFHOST_BACKUP_EXPIRE_SECONDS,
expiryVia: ["OFFHOST_BACKUP_SEND_OPTIONS"],
stop: {
file: "lib/jobs/reminder/backup-handlers.ts",
fn: "handleOffhostBackup",
},
exclusive: "lockedPass",
why: "Uploads every account's record off-host.",
},
"data-restore-drill": {
runtime: "long",
expireInSeconds: RESTORE_DRILL_EXPIRE_SECONDS,
expiryVia: ["RESTORE_DRILL_SEND_OPTIONS"],
stop: { file: "lib/jobs/restore-drill.ts", fn: "handleRestoreDrill" },
exclusive: "lockedPass",
why: "Fetches and stream-parses every account's newest off-host object.",
},
"offhost-backup-purge": short("At most 200 delete requests per run."),
"account-deletion-purge": short(
"At most 50 account erasures per run, plus one DELETE of expired pre-wipe copies.",
),
"backup-restore": {
runtime: "long",
expireInSeconds: BACKUP_RESTORE_EXPIRE_SECONDS,
expiryVia: ["BACKUP_RESTORE_SEND_OPTIONS", "BACKUP_RESTORE_EXPIRE_SECONDS"],
stop: { file: "lib/jobs/backup-restore.ts", fn: "handleBackupRestore" },
exclusive: {
marker: "restore_claimed",
at: { file: "lib/jobs/backup-restore.ts", fn: "runBackupRestoreJob" },
},
why: "Restores a whole account in one transaction.",
},
"host-metric-sample": short("One host sample."),
"feedback-aggregator": short("One aggregate over the feedback table."),
"geo-backfill": short("At most 500 audit rows per pass."),
"geolite2-fetch": short("One database download."),
"tls-pin-monitor": short("One TLS handshake."),
"recovery-readiness": short(
"A few indexed reads, one row per account from two backup ledgers, and at most one notice per signal.",
),
"system-job-alert": short(
"The newest fifty terminal runs of each system queue over pg-boss's completion index, and at most one notice per queue.",
),
"integration-watchdog-hourly": short(
"A few indexed reads per account with a connection and no provider call; a 14-day history count only for a silent source.",
),
"integration-watchdog-daily": short(
"The hourly pass plus one 14-day history count per standing silence flag.",
),
"mood-reminder-cleanup": short("One retention DELETE."),
"push-attempt-cleanup": short("One retention DELETE."),
"arrival-reaction-cleanup": short("One retention DELETE."),
"rate-limit-cleanup": short("One retention DELETE."),
"idempotency-cleanup": short("One retention DELETE."),
"step-up-elevation-cleanup": short("One retention DELETE."),
"coach-message-cleanup": short("One retention DELETE."),
"workout-insight-claim-cleanup": short("One retention DELETE."),
"mcp-token-cleanup": short("One retention DELETE."),
"audit-log-cleanup": short("At most 40 batches of 5 000 rows per leg."),
"measurement-tombstone-cleanup": short(
"At most 40 batches of 5 000 rows per leg.",
),
"document-tombstone-purge": short("One deleteMany."),
"soft-delete-purge": short(
"At most 40 batches of 5 000 rows per table, over a few small tables.",
),
"auth-ledger-cleanup": short("At most 40 batches of 5 000 rows per table."),
"document-summary-reaper": short("One updateMany."),
"cycle-prediction-refresh": short(
"Arithmetic per eligible account, no provider call.",
),
"mood-prognosis-refresh": short(
"Arithmetic per eligible account, no provider call.",
),
"achievement-unlock-sweep": short(
"A bounded achievement read per account, no provider call.",
),
"pr-detection": {
runtime: "long",
expireInSeconds: PR_DETECTION_EXPIRE_SECONDS,
expiryVia: ["PR_DETECTION_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/ops-handlers.ts",
fn: "handlePrDetection",
},
exclusive: "lockedPass",
why: "The fallback cron scans every account's all-time history every thirty minutes; an ingest job is one account.",
},
"medication-inventory-expire": short("One updateMany."),
"intake-auto-skip": short("One updateMany."),
"intake-auto-take": short(
"At most seven days of slots per opted-in medication, a few rows each.",
),
"apple-health-import-v2": {
runtime: "long",
expireInSeconds: APPLE_HEALTH_IMPORT_SEND_OPTIONS.expireInSeconds,
expiryVia: ["APPLE_HEALTH_IMPORT_SEND_OPTIONS"],
stop: {
oneShot:
"The run consumes and unlinks its staged upload, so it can neither stop half-way nor be retried; the send sets retryLimit 0.",
},
exclusive: {
marker: "retryLimit: 0",
at: {
file: "lib/jobs/apple-health-import-worker.ts",
fn: "APPLE_HEALTH_IMPORT_SEND_OPTIONS",
},
},
why: "Parses an export that can be several gigabytes.",
},
"apple-health-import": short(
"The legacy queue: moves each job onto apple-health-import-v2.",
),
"apple-health-import-reconcile": short("One updateMany."),
"health-connect-import": {
runtime: "long",
expireInSeconds: HEALTH_CONNECT_IMPORT_SEND_OPTIONS.expireInSeconds,
expiryVia: ["HEALTH_CONNECT_IMPORT_SEND_OPTIONS"],
stop: {
oneShot:
"The run consumes and unlinks its staged upload, so it can neither stop half-way nor be retried; the send sets retryLimit 0.",
},
exclusive: {
marker: "retryLimit: 0",
at: {
file: "lib/jobs/health-connect-import-worker.ts",
fn: "HEALTH_CONNECT_IMPORT_SEND_OPTIONS",
},
},
why: "Reads a Health Connect export database that can hold years of minute-level samples.",
},
"compaction-tombstone-purge": short(
"At most 40 batches of 5 000 rows per run; the predicate is idempotent, so the next run resumes.",
),
"measurement-fold-repair": {
runtime: "budgeted",
budget: {
file: "lib/jobs/measurement-fold-repair.ts",
fn: "handleMeasurementFoldRepair",
},
why: "One account's folded means, a day at a time; stops at three quarters of the default expiry and sends a follow-up that resumes at the next day.",
},
"lab-document-date-repair": short(
"Reads the document lab values still filed at their confirmation moment, a handful per account, and moves each with one update.",
),
"wearable-cycle-repair": short(
"Reads the wearable period days still without a cycle, a few hundred per account at most, and opens or attributes each with a short transaction.",
),
"measurement-maintenance": {
runtime: "long",
expireInSeconds: MEASUREMENT_MAINTENANCE_SEND_OPTIONS.expireInSeconds,
expiryVia: ["MEASUREMENT_MAINTENANCE_SEND_OPTIONS"],
stop: {
oneShot:
"VACUUM and REINDEX CONCURRENTLY cannot be resumed mid-statement; the send and the nightly tick set retryLimit 0, and the next night or the operator runs it again.",
},
exclusive: {
marker: "retryLimit: 0",
at: {
file: "lib/jobs/measurement-maintenance.ts",
fn: "MEASUREMENT_MAINTENANCE_SEND_OPTIONS",
},
},
why: "The operator's run rebuilds every index of the largest table, one at a time; the nightly check is one VACUUM at most.",
},
"pulse-day-mean": {
runtime: "long",
expireInSeconds: PULSE_DAY_MEAN_SEND_OPTIONS.expireInSeconds,
expiryVia: ["PULSE_DAY_MEAN_SEND_OPTIONS"],
stop: {
oneShot:
"A dry run or rebuild that stops part way is started again by the operator; the send sets retryLimit 0.",
},
exclusive: {
marker: "retryLimit: 0",
at: {
file: "lib/jobs/pulse-day-mean.ts",
fn: "PULSE_DAY_MEAN_SEND_OPTIONS",
},
},
why: "Walks every account's pulse history a window at a time, twice over for a dry run.",
},
"medication-intake-import": {
runtime: "long",
expireInSeconds: MEDICATION_INTAKE_IMPORT_SEND_OPTIONS.expireInSeconds,
expiryVia: ["MEDICATION_INTAKE_IMPORT_SEND_OPTIONS"],
stop: {
file: "lib/jobs/medication-intake-import.ts",
fn: "handleMedicationIntakeImport",
},
exclusive: {
marker: "FOR UPDATE",
at: {
file: "lib/jobs/medication-intake-import.ts",
fn: "processNextChunk",
},
},
why: "Imports a dose-history file chunk by chunk; its length follows the file.",
},
"intake-slot-dedup": short("One account's duplicate dose slots."),
"note-encryption-backfill": short(
"Pages of 200 rows of one account's plaintext notes, light per row.",
),
"med-notes-encryption-backfill": short(
"Pages of 200 rows of one account's plaintext notes, light per row.",
),
"free-text-encryption-backfill": short(
"Pages of 200 rows of one account's plaintext fields, light per row.",
),
"encryption-key-rotate": {
runtime: "long",
expireInSeconds: ENCRYPTION_KEY_ROTATE_EXPIRE_SECONDS,
expiryVia: ["ENCRYPTION_KEY_ROTATE_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/encryption-key-rotate.ts",
fn: "handleEncryptionKeyRotate",
},
exclusive: "lockedPass",
why: "Re-encrypts every encrypted column on the instance.",
},
"document-content-index-backfill": {
runtime: "long",
expireInSeconds: CONTENT_INDEX_BACKFILL_EXPIRE_SECONDS,
expiryVia: ["CONTENT_INDEX_BACKFILL_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/document-handlers.ts",
fn: "handleContentIndexBackfill",
},
exclusive: "lockedPass",
why: "Up to 200 documents of one account, a provider transcription each.",
},
"document-index": {
runtime: "long",
expireInSeconds: DOCUMENT_INDEX_EXPIRE_SECONDS,
expiryVia: ["DOCUMENT_INDEX_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/document-handlers.ts",
fn: "handleDocumentIndex",
},
exclusive: "lockedPass",
why: "One document: the transcription, then a lab report's staging reads, as many as fit before the job's deadline at the person's timeout.",
},
"document-ai-run": {
runtime: "long",
expireInSeconds: DOCUMENT_AI_RUN_EXPIRE_SECONDS,
expiryVia: ["DOCUMENT_AI_RUN_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/document-ai-run.ts",
fn: "handleDocumentAiRunJobs",
},
exclusive: "lockedPass",
why: "One person's document or lab scan, up to three model calls at their AI response time (up to ten minutes each).",
},
"document-ai-run-reaper": short(
"Up to 500 conditional updates and one deleteMany.",
),
"document-thumbnail": short("One document."),
"document-summary": {
runtime: "bounded",
modelSeconds: COMPLETION_CEILING_MS / 1000,
expireInSeconds: DOCUMENT_SUMMARY_EXPIRE_SECONDS,
expiryVia: ["DOCUMENT_SUMMARY_EXPIRE_SECONDS"],
why: "One document's summary: one call and its reasoning repeat at the person's timeout.",
},
"document-summary-catchup": short("Enqueues at most 200 documents."),
"document-thumbnail-backfill": short("Enqueues at most 1 000 documents."),
"environment-fetch": short(
"A fan-out of sends, or one account's bounded archive range.",
),
"dawarich-sync": short(
"A fan-out of sends, or one account's range: one timeline request per 30 days (at most 13), one visits request and at most two residency requests.",
),
"environment-aq-history": short(
"A fan-out of sends, or one account's history run: at most eight ranges of up to 90 days, two requests each, then a follow-up.",
),
};
-33
View File
@@ -1,33 +0,0 @@
import { describe, it, expect } from "vitest";
import { computeHomaIr, classifyHomaIr } from "@/lib/labs/homa-ir";
describe("computeHomaIr", () => {
it("computes the conventional-unit formula (glucose × insulin ÷ 405)", () => {
// 90 mg/dL × 5 µIU/mL ÷ 405 = 1.111…
expect(computeHomaIr(90, 5)).toBeCloseTo(1.1111, 3);
});
it("matches the SI form within rounding (mmol/L × insulin ÷ 22.5)", () => {
// 100 mg/dL = 5.556 mmol/L; SI: 5.556 × 8 ÷ 22.5 ≈ 1.975; conv: 100×8÷405 ≈ 1.975
const conv = computeHomaIr(100, 8)!;
const si = (5.5556 * 8) / 22.5;
expect(conv).toBeCloseTo(si, 2);
});
it("returns null for missing or non-positive inputs", () => {
expect(computeHomaIr(null, 5)).toBeNull();
expect(computeHomaIr(90, undefined)).toBeNull();
expect(computeHomaIr(0, 5)).toBeNull();
expect(computeHomaIr(90, -1)).toBeNull();
expect(computeHomaIr(Number.NaN, 5)).toBeNull();
});
});
describe("classifyHomaIr", () => {
it("places values in the documented bands", () => {
expect(classifyHomaIr(0.8)).toBe("optimal");
expect(classifyHomaIr(1.5)).toBe("intermediate");
expect(classifyHomaIr(2.5)).toBe("elevated");
expect(classifyHomaIr(3.5)).toBe("high");
});
});
+1 -2
View File
@@ -104,8 +104,7 @@ export const BIOMARKER_CATALOG: readonly BiomarkerSeed[] = [
upperBound: 5.7,
},
// v1.25 — longevity panel: fasting insulin (metabolically-optimal often
// cited < 8 µIU/mL; typical reference ~2.5–13). HOMA-IR is derived from
// fasting glucose × insulin (see `homa-ir.ts`), not a stored catalog marker.
// cited < 8 µIU/mL; typical reference ~2.5–13).
{
slug: "fasting-insulin",
panel: "glucose",
-47
View File
@@ -1,47 +0,0 @@
/**
* v1.25 — HOMA-IR (Homeostatic Model Assessment of Insulin Resistance).
*
* A computed longevity marker derived from fasting glucose + fasting insulin —
* NOT a stored biomarker catalog entry (BMI's derived-value precedent). Server-
* authoritative per the parity rule: compute it here, never recompute on the
* client. Pure + side-effect-free so it is trivially testable.
*
* Conventional-unit formula (fasting glucose mg/dL × fasting insulin µIU/mL ÷
* 405) and the SI form (mmol/L × µIU/mL ÷ 22.5) are equivalent
* (mg/dL ÷ 18 = mmol/L; 405 = 22.5 × 18). Population-dependent interpretive
* bands (optimal < 1.0, early IR > 1.9, significant IR > 2.9) are applied at the
* display edge, never asserted here. [HOMA-IR, PMC5033570].
*/
/** Interpretive band for a HOMA-IR index value (population-dependent guidance). */
export type HomaIrBand = "optimal" | "intermediate" | "elevated" | "high";
/**
* Compute HOMA-IR from fasting glucose (mg/dL) and fasting insulin (µIU/mL).
* Returns `null` when either input is missing or non-positive (the index is
* undefined for a zero/negative reading).
*/
export function computeHomaIr(
fastingGlucoseMgDl: number | null | undefined,
fastingInsulinUiuMl: number | null | undefined,
): number | null {
if (
fastingGlucoseMgDl == null ||
fastingInsulinUiuMl == null ||
!Number.isFinite(fastingGlucoseMgDl) ||
!Number.isFinite(fastingInsulinUiuMl) ||
fastingGlucoseMgDl <= 0 ||
fastingInsulinUiuMl <= 0
) {
return null;
}
return (fastingGlucoseMgDl * fastingInsulinUiuMl) / 405;
}
/** Place a HOMA-IR value in its descriptive band (general guidance, not a diagnosis). */
export function classifyHomaIr(value: number): HomaIrBand {
if (value < 1.0) return "optimal";
if (value <= 1.9) return "intermediate";
if (value <= 2.9) return "elevated";
return "high";
}
+1 -1
View File
@@ -150,7 +150,7 @@ export function redactSecrets(input: string): string {
// calendar-feed link (#1350).
// Same boundary-aware shape as the `sk-` rule. The
// idempotency replay-cache already rejects bodies containing
// these prefixes (CLAUDE.md headless-client-API patterns); this
// these prefixes; this
// is the matching egress guard for log/error surfaces.
.replace(/(^|[^A-Za-z0-9])hl[kpresvf]_[A-Fa-f0-9]{32,}/g, "$1[REDACTED]")
// v1.22.0 — the MCP OAuth bridge artifacts: the authorization code
+1 -1
View File
@@ -10,7 +10,7 @@
* both directions.
*
* Everything is built field by field from the parsed body. Nothing is spread
* from a request (`CLAUDE.md`, no mass assignment), and the two multi-select
* from a request (no mass assignment), and the two multi-select
* lists go through the vocabulary module's encoder rather than a local
* `JSON.stringify`.
*/
@@ -204,26 +204,6 @@ describe("dispatchLocalisedNotification — pass-through plumbing", () => {
);
});
it("annotates metadata with preferredChannel when channel is supplied", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValueOnce({
locale: "en",
} as never);
await dispatchLocalisedNotification({
userId: "u-en",
titleKey: "notifications.admin.testTitle",
messageKey: "notifications.admin.testBody",
params: { name: "Test" },
channel: "telegram",
metadata: { source: "test" },
});
expect(dispatchNotificationMock.mock.calls[0][0].metadata).toEqual({
source: "test",
preferredChannel: "telegram",
});
});
it("does not crash when the locale lookup throws (logs warning, falls back to default)", async () => {
vi.mocked(prisma.user.findUnique).mockRejectedValueOnce(
new Error("db down"),
+3 -19
View File
@@ -21,10 +21,8 @@
*
* The default `eventType` is `SYSTEM_ALERT` — the only event type that
* predates F21 outside of the medication-reminder lane. Callers that
* need a different event type pass it explicitly; the `channel` option
* is reserved for a future per-channel routing pass and is currently
* a no-op (the dispatcher fans the message across every enabled
* channel as before).
* need a different event type pass it explicitly. The dispatcher fans
* the message across every enabled channel.
*
* v1.4.28 (R1.2 H5) — the locale lookup previously fired
* `prisma.user.findUnique` on every call. A 30-second TTL LRU keyed on
@@ -50,13 +48,6 @@ interface DispatchLocalisedOptions {
titleKey: string;
messageKey: string;
params?: Record<string, string | number>;
/**
* Per-channel routing is forward-compat scaffolding. Today the
* dispatcher fans out across every enabled channel for the user; the
* option is accepted so call-sites can declare intent without
* needing a second helper later.
*/
channel?: "telegram" | "email";
/** Event type for preference gating. Defaults to SYSTEM_ALERT. */
eventType?: EventType;
/** Channel-specific extras forwarded to the dispatcher metadata. */
@@ -162,13 +153,6 @@ export async function dispatchLocalisedNotification(
);
}
// `channel` is accepted for future per-channel routing; today it
// is silently passed through. Suppress unused-var lint by referencing
// it on the metadata if present.
const metadata = opts.channel
? { ...(opts.metadata ?? {}), preferredChannel: opts.channel }
: opts.metadata;
await dispatchNotification({
eventType: opts.eventType ?? "SYSTEM_ALERT",
userId: opts.userId,
@@ -177,7 +161,7 @@ export async function dispatchLocalisedNotification(
title,
message,
renderForRecipient,
metadata,
metadata: opts.metadata,
managedFanoutEvent: opts.managedFanoutEvent,
urgent: opts.urgent,
});
+1 -1
View File
@@ -1031,7 +1031,7 @@ const IOS_METADATA_ALLOWLIST = new Set([
"phase",
"date",
// v1.16.11 — MEDICATION_LOW_STOCK deep link + context: the in-app
// path the push should open (`/medications/{id}?tab=bestand`) plus
// path the push should open (`/medications/{id}?tab=supply`) plus
// the runway / threshold figures the iOS handler can surface.
"url",
"runwayDays",
+1 -1
View File
@@ -177,7 +177,7 @@ const ALL_STOPS: readonly TourStop[] = [
id: "export",
targetId: "export-hero",
placement: "bottom",
route: "/settings/gesundheitsakte",
route: "/settings/health-record",
titleKey: "onboarding.tour.steps.export.title",
bodyKey: "onboarding.tour.steps.export.body",
},
-17
View File
@@ -23,23 +23,6 @@ export const authKeys = {
* settings/ai-section, targets/target-edit-sheet).
*/
userThresholds: () => ["user", "thresholds"] as const,
/**
* v1.7.0 — Settings → Display metric/imperial control reads its
* current value from `GET /api/auth/me/unit-preference`. The PATCH
* mutation also invalidates `authMe()` so `useAuth().unitPreference`
* (and every chart display transform that keys off it) re-renders
* without a manual reload.
*/
userUnitPreference: () => ["user", "unit-preference"] as const,
/**
* The mg/dL vs mmol/L glucose display control behind
* `GET /api/auth/me/glucose-unit`. A separate axis from the
* metric/imperial preference above — metric countries are split on
* which one they read glucose in — so it carries its own key. The
* PATCH also invalidates `authMe()`, since every glucose surface
* resolves the unit from the account payload rather than from here.
*/
userGlucoseUnit: () => ["user", "glucose-unit"] as const,
passkeys: () => ["passkeys"] as const,
+1 -1
View File
@@ -94,7 +94,7 @@ export const SETTINGS_DESTINATION_INVENTORY = {
coach: MANAGED_GUARDIAN,
api: PERSONAL,
mcp: PERSONAL,
gesundheitsakte: PERSONAL,
"health-record": PERSONAL,
export: PERSONAL,
advanced: PERSONAL,
privacy: PERSONAL,
+5 -4
View File
@@ -44,9 +44,10 @@
// canonical editors; reminder TYPES now live centrally in `notifications`,
// each row gated on its module. `/settings/reminders` 301-redirects to
// `/settings/notifications` (next.config.ts).
// v1.18.0 — per-submodule settings split. `gesundheitsakte` (the full
// v1.18.0 — per-submodule settings split. `health-record` (the full
// health-record export, always available) lifts out of Export & Import into
// its own top-level entry.
// its own top-level entry. Its address was the German `gesundheitsakte` in
// every language; that one redirects (next.config.ts).
export const SETTINGS_SECTION_SLUGS = [
"account",
// v1.23 — `security` is the dedicated account-security home: second-factor
@@ -75,7 +76,7 @@ export const SETTINGS_SECTION_SLUGS = [
// `insights`, `medications`, `mood`, `labs`, `illness`, `vorsorge`) and
// `sharing` left this list. Their URLs are owned by permanent redirects
// in `next.config.ts` (`/settings/<module>` → `/settings/layout/<module>`,
// `/settings/sharing` → `/settings/gesundheitsakte#sharing`), so the
// `/settings/sharing` → `/settings/health-record#sharing`), so the
// dynamic route could never serve them — prerendering eight unreachable
// pages and keeping eight dead component wirings. The redirects, the
// section components, and the layout-hub subpages are unchanged.
@@ -106,7 +107,7 @@ export const SETTINGS_SECTION_SLUGS = [
// assistant (Claude.ai / ChatGPT). Sits next to `api` (both are programmatic
// access surfaces). Not nav-gated — the card carries its own enable toggle.
"mcp",
"gesundheitsakte",
"health-record",
"export",
"advanced",
// v1.23 — "Data & Privacy": a single surface that assembles the already-
@@ -1,28 +0,0 @@
import { describe, expect, it } from "vitest";
import { moodStabilityLabel } from "../mood-stability-label";
/**
* v1.4.25 — threshold contract for the verbal MOOD_STABILITY label.
* The card switches from raw σ to one of three buckets; the rule lives
* here so the boundaries can be unit-tested without React.
*/
describe("moodStabilityLabel", () => {
it("returns 'stable' for σ below 1.0", () => {
expect(moodStabilityLabel(0)).toBe("stable");
expect(moodStabilityLabel(0.42)).toBe("stable");
expect(moodStabilityLabel(0.999)).toBe("stable");
});
it("returns 'variable' for σ in [1.0, 2.0)", () => {
expect(moodStabilityLabel(1.0)).toBe("variable");
expect(moodStabilityLabel(1.5)).toBe("variable");
expect(moodStabilityLabel(1.999)).toBe("variable");
});
it("returns 'highlyVariable' for σ ≥ 2.0", () => {
expect(moodStabilityLabel(2.0)).toBe("highlyVariable");
expect(moodStabilityLabel(3.5)).toBe("highlyVariable");
});
});
-24
View File
@@ -1,24 +0,0 @@
/**
* v1.4.25 — verbal label for the MOOD_STABILITY target headline.
*
* The card used to render the raw σ value ("0.42 σ"), which most users
* cannot interpret. Replace with a three-state verbal label keyed
* against translation entries `targets.mood.stability.{stable,
* variable,highlyVariable}`.
*
* Thresholds (maintainer-set, documented in the W3e implementation plan):
* σ < 1.0 → "stable" (stabil / stable)
* σ < 2.0 → "variable" (schwankend / variable)
* σ ≥ 2.0 → "highly-variable" (sehr schwankend / highly variable)
*
* Pure helper so the threshold logic can be unit-tested in isolation
* without React. Returns the stable English key — callers (the card,
* the Coach prompt builder) own the locale resolution.
*/
export type MoodStabilityLabel = "stable" | "variable" | "highlyVariable";
export function moodStabilityLabel(sigma: number): MoodStabilityLabel {
if (sigma < 1.0) return "stable";
if (sigma < 2.0) return "variable";
return "highlyVariable";
}
@@ -22,6 +22,7 @@ describe("measurementReminderTypeEnum (V3 — completeness)", () => {
"BLOOD_PRESSURE_SYS",
"PULSE",
"BLOOD_GLUCOSE",
"BLOOD_KETONES",
"OXYGEN_SATURATION",
"BODY_TEMPERATURE",
// Body composition
@@ -45,6 +45,8 @@ export const measurementReminderTypeEnum = z
"BLOOD_PRESSURE_SYS",
"PULSE",
"BLOOD_GLUCOSE",
// Ketones come off the same fingerstick meter as glucose.
"BLOOD_KETONES",
"OXYGEN_SATURATION",
"BODY_TEMPERATURE",
// Body composition (one scale reading produces the whole family)
+1 -2
View File
@@ -3,8 +3,7 @@
* (PHQ-9 / GAD-7; v1.27.9 adds WHO-5 + SCI). The item answers are small
* integers whose ceiling is instrument-specific (PHQ/GAD 0–3, SCI 0–4,
* WHO-5 0–5); the array length must match the instrument. `userId` is NEVER
* a body field — it is narrowed from the session in the handler (CLAUDE.md
* convention).
* a body field — it is narrowed from the session in the handler.
*/
import { z } from "zod/v4";
import {