Merge feat/v125-environmental into release/v1.25.0

Environmental context module (migration 0217).
This commit is contained in:
Marc-André Bombeck committed 2026-06-28 17:02:36 +02:00
commit a1b4f0d00e
45 files changed
+2725 -64

No files matched your search

@@ -83,6 +83,7 @@ function moduleMap(
insights: true,
medications: true,
doctorReport: true,
environment: true,
mcp: true,
};
return { ...base, ...overrides };
+131
View File
@@ -0,0 +1,131 @@
/**
* v1.25 (W-ENV) — the canonical environmental-exposure field vocabulary.
*
* One declarative table that names each daily weather/daylight field HealthLog
* stores AND correlates. It is the single source the two surfaces speak:
*
* - the SIGNAL REGISTRY (`src/lib/signals/registry.ts`) registers one
* `kind:"environment"` signal per field here, so each gets a stable signal
* key + display metadata for free; and
* - the CORRELATION ENGINE reads {@link ENVIRONMENT_CHANNEL_KEYS} to fold the
* same fields in as lagged BEHAVIOUR (exposure) channels against mood /
* sleep / vitals.
*
* `key` doubles as the registry signal key AND the correlation channel key —
* the `ENV_` prefix keeps it from colliding with a `MeasurementType` and lets
* `metricFamily()` collapse all env channels into one `ENVIRONMENT` family (so
* the engine never lag-correlates two same-day weather fields against each
* other — that is a near-tautology, not an insight).
*
* `column` is the `EnvironmentContext` numeric column the field reads. Leaf
* module (no imports) so both the registry and the pure correlation engine can
* depend on it without a cycle.
*/
/** The `EnvironmentContext` numeric columns a correlation field can read. */
export type EnvironmentContextNumericColumn =
| "tempMean"
| "tempMin"
| "tempMax"
| "apparentMean"
| "sunshineSec"
| "daylightSec"
| "precipSum"
| "pressureMean"
| "pressureDelta"
| "humidityMean"
| "cloudMean";
export interface EnvironmentField {
/** Stable key — the registry signal key AND the correlation channel key. */
key: string;
/** The `EnvironmentContext` column this field's daily value comes from. */
column: EnvironmentContextNumericColumn;
/** Canonical unit (English, for prose + registry metadata). */
unit: string;
/** Stable English display name (the UI localises via `i18nLabelKey`). */
displayName: string;
/** Lower-cased phrase the correlation narration ("humanise") reads. */
narrationLabel: string;
/** i18n label key resolved by the correlation / settings surfaces. */
i18nLabelKey: string;
}
/**
* The exposure fields, ranked by evidence in the W-ENV research review:
* temperature (sleep / BP / recovery), sunshine + daylight (mood), precipitation
* (activity), pressure mean + intraday swing (headache/symptom — honestly
* caveated, optional-strength). All are BEHAVIOUR (lag-source) channels.
*/
export const ENVIRONMENT_FIELDS: readonly EnvironmentField[] = [
{
key: "ENV_TEMP_MEAN",
column: "tempMean",
unit: "°C",
displayName: "Daily temperature",
narrationLabel: "daily temperature",
i18nLabelKey: "environment.fields.tempMean",
},
{
key: "ENV_TEMP_MIN",
column: "tempMin",
unit: "°C",
displayName: "Overnight low temperature",
narrationLabel: "overnight low temperature",
i18nLabelKey: "environment.fields.tempMin",
},
{
key: "ENV_SUNSHINE",
column: "sunshineSec",
unit: "h",
displayName: "Sunshine duration",
narrationLabel: "sunshine",
i18nLabelKey: "environment.fields.sunshine",
},
{
key: "ENV_DAYLIGHT",
column: "daylightSec",
unit: "h",
displayName: "Daylight length",
narrationLabel: "daylight",
i18nLabelKey: "environment.fields.daylight",
},
{
key: "ENV_PRECIP",
column: "precipSum",
unit: "mm",
displayName: "Precipitation",
narrationLabel: "precipitation",
i18nLabelKey: "environment.fields.precip",
},
{
key: "ENV_PRESSURE_MEAN",
column: "pressureMean",
unit: "hPa",
displayName: "Barometric pressure",
narrationLabel: "barometric pressure",
i18nLabelKey: "environment.fields.pressureMean",
},
{
key: "ENV_PRESSURE_DELTA",
column: "pressureDelta",
unit: "hPa",
displayName: "Pressure swing",
narrationLabel: "intraday pressure swing",
i18nLabelKey: "environment.fields.pressureDelta",
},
] as const;
/** The correlation channel keys, in declaration order. */
export const ENVIRONMENT_CHANNEL_KEYS: readonly string[] =
ENVIRONMENT_FIELDS.map((f) => f.key);
/** True for a registered environmental channel key. */
export function isEnvironmentChannelKey(key: string): boolean {
return ENVIRONMENT_CHANNEL_KEYS.includes(key);
}
/** Resolve a field by its key, or null when unregistered. */
export function getEnvironmentField(key: string): EnvironmentField | null {
return ENVIRONMENT_FIELDS.find((f) => f.key === key) ?? null;
}
+290
View File
@@ -0,0 +1,290 @@
/**
* v1.25 (W-ENV) — Open-Meteo client (keyless historical weather + geocoding).
*
* The single outbound egress for the environmental-context module. Open-Meteo's
* Historical (Archive) API is keyless, free for non-commercial use, and offers
* a clean per-date global lat/lon endpoint — the right fit for a self-host-
* friendly, privacy-first exposure feed. Data is CC BY 4.0 ("Weather data by
* Open-Meteo.com" — credited on the settings surface).
*
* Egress goes through `safeFetch` (the documented wrapper: manual redirects +
* a request timeout). The base URL is operator config, not arbitrary user
* input, so `requirePublicHost` is deliberately NOT forced — a privacy-
* maximalist operator can point `OPENMETEO_BASE_URL` at a self-hosted Open-Meteo
* instance on a private/LAN host without it being blocked. The hosted default is
* public.
*
* Server-side only. The archive feed lags real time by a few days (reanalysis
* settling), so callers fetch with a lookback window rather than "yesterday
* only" — see the nightly job and the backfill route.
*/
import { safeFetch, SafeFetchError } from "@/lib/safe-fetch";
/** Hosted archive default; override with `OPENMETEO_BASE_URL` (self-host). */
const ARCHIVE_BASE_URL =
process.env.OPENMETEO_BASE_URL?.replace(/\/$/, "") ??
"https://archive-api.open-meteo.com";
/** Hosted geocoding default; override with `OPENMETEO_GEOCODING_URL`. */
const GEOCODING_BASE_URL =
process.env.OPENMETEO_GEOCODING_URL?.replace(/\/$/, "") ??
"https://geocoding-api.open-meteo.com";
const FETCH_TIMEOUT_MS = 15_000;
/** CC BY 4.0 attribution required by Open-Meteo; surfaced on the settings UI. */
export const OPEN_METEO_ATTRIBUTION = "Weather data by Open-Meteo.com";
/** One geocoding match — coarse city placement for the home-location picker. */
export interface GeocodeResult {
/** Rounded coarse latitude (2 dp — ~1 km, the privacy floor). */
lat: number;
/** Rounded coarse longitude (2 dp). */
lon: number;
/** Human label, e.g. "Bochum, North Rhine-Westphalia, Germany". */
label: string;
/** IANA timezone for the place (anchors the day-key of stored rows). */
timezone: string;
}
/** A single day's resolved weather observation, mapped to our column shape. */
export interface DailyEnvironmentObservation {
/** YYYY-MM-DD in the requested timezone. */
date: string;
tempMin: number | null;
tempMax: number | null;
tempMean: number | null;
apparentMean: number | null;
sunshineSec: number | null;
daylightSec: number | null;
precipSum: number | null;
pressureMean: number | null;
pressureDelta: number | null;
humidityMean: number | null;
cloudMean: number | null;
weatherCode: number | null;
}
/** Round a coordinate to 2 decimals (~1 km) — the coarse-location privacy floor. */
export function roundCoarse(value: number): number {
return Math.round(value * 100) / 100;
}
function firstNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
/** Mean of the finite numbers in `xs`, or null when none. */
function meanOf(xs: number[]): number | null {
if (xs.length === 0) return null;
const sum = xs.reduce((a, b) => a + b, 0);
return sum / xs.length;
}
interface ArchiveDaily {
time?: string[];
temperature_2m_min?: (number | null)[];
temperature_2m_max?: (number | null)[];
temperature_2m_mean?: (number | null)[];
apparent_temperature_mean?: (number | null)[];
sunshine_duration?: (number | null)[];
daylight_duration?: (number | null)[];
precipitation_sum?: (number | null)[];
weather_code?: (number | null)[];
}
interface ArchiveHourly {
time?: string[];
surface_pressure?: (number | null)[];
relative_humidity_2m?: (number | null)[];
cloud_cover?: (number | null)[];
}
interface ArchiveResponse {
daily?: ArchiveDaily;
hourly?: ArchiveHourly;
}
const DAILY_FIELDS = [
"temperature_2m_min",
"temperature_2m_max",
"temperature_2m_mean",
"apparent_temperature_mean",
"sunshine_duration",
"daylight_duration",
"precipitation_sum",
"weather_code",
].join(",");
const HOURLY_FIELDS = [
"surface_pressure",
"relative_humidity_2m",
"cloud_cover",
].join(",");
/** Per-day aggregation accumulator for the hourly-only fields. */
interface HourlyDayAgg {
pressures: number[];
humidities: number[];
clouds: number[];
}
/**
* Aggregate the hourly feed (pressure / humidity / cloud — not available as a
* daily aggregate from the archive) into per-day values: mean for each, plus the
* intraday pressure delta (max − min), the derived headache/symptom feature.
*/
function aggregateHourly(hourly: ArchiveHourly): Map<string, HourlyDayAgg> {
const byDay = new Map<string, HourlyDayAgg>();
const times = hourly.time ?? [];
for (let i = 0; i < times.length; i++) {
const day = times[i]?.slice(0, 10);
if (!day) continue;
const agg = byDay.get(day) ?? { pressures: [], humidities: [], clouds: [] };
const p = firstNumber(hourly.surface_pressure?.[i]);
const h = firstNumber(hourly.relative_humidity_2m?.[i]);
const c = firstNumber(hourly.cloud_cover?.[i]);
if (p !== null) agg.pressures.push(p);
if (h !== null) agg.humidities.push(h);
if (c !== null) agg.clouds.push(c);
byDay.set(day, agg);
}
return byDay;
}
/**
* Forward-geocode a free-text place to coarse matches. Keyless. Returns at most
* `count` results; an empty array when nothing matched or the feed errored
* (the caller surfaces "no match" rather than failing the request).
*/
export async function geocodeLocation(
query: string,
count = 5,
): Promise<GeocodeResult[]> {
const trimmed = query.trim();
if (trimmed.length === 0) return [];
const url = new URL(`${GEOCODING_BASE_URL}/v1/search`);
url.searchParams.set("name", trimmed);
url.searchParams.set("count", String(Math.min(Math.max(count, 1), 10)));
url.searchParams.set("format", "json");
let res: Response;
try {
res = await safeFetch(
url,
{ headers: { accept: "application/json" } },
{
timeoutMs: FETCH_TIMEOUT_MS,
},
);
} catch (err) {
if (err instanceof SafeFetchError) return [];
throw err;
}
if (!res.ok) return [];
const body = (await res.json()) as {
results?: Array<{
name?: string;
latitude?: number;
longitude?: number;
country?: string;
admin1?: string;
timezone?: string;
}>;
};
const out: GeocodeResult[] = [];
for (const r of body.results ?? []) {
if (typeof r.latitude !== "number" || typeof r.longitude !== "number") {
continue;
}
const parts = [r.name, r.admin1, r.country].filter(
(p): p is string => typeof p === "string" && p.length > 0,
);
out.push({
lat: roundCoarse(r.latitude),
lon: roundCoarse(r.longitude),
label: parts.join(", "),
timezone:
typeof r.timezone === "string" && r.timezone.length > 0
? r.timezone
: "auto",
});
}
return out;
}
/**
* Fetch the daily environment observations for a coarse location over a date
* range (inclusive YYYY-MM-DD). The hourly-only fields (pressure / humidity /
* cloud) are requested alongside and aggregated to per-day values here. Throws
* a {@link SafeFetchError} on egress failure so the caller can classify it.
*/
export async function fetchDailyEnvironment(args: {
lat: number;
lon: number;
timezone: string;
startDate: string;
endDate: string;
}): Promise<DailyEnvironmentObservation[]> {
const url = new URL(`${ARCHIVE_BASE_URL}/v1/archive`);
url.searchParams.set("latitude", String(args.lat));
url.searchParams.set("longitude", String(args.lon));
url.searchParams.set("start_date", args.startDate);
url.searchParams.set("end_date", args.endDate);
url.searchParams.set("daily", DAILY_FIELDS);
url.searchParams.set("hourly", HOURLY_FIELDS);
url.searchParams.set("timezone", args.timezone);
const res = await safeFetch(
url,
{ headers: { accept: "application/json" } },
{
timeoutMs: FETCH_TIMEOUT_MS,
},
);
if (!res.ok) {
throw new SafeFetchError(
`open-meteo archive returned HTTP ${res.status}`,
"network",
);
}
const body = (await res.json()) as ArchiveResponse;
const daily = body.daily ?? {};
const days = daily.time ?? [];
const hourlyByDay = aggregateHourly(body.hourly ?? {});
const observations: DailyEnvironmentObservation[] = [];
for (let i = 0; i < days.length; i++) {
const date = days[i];
if (!date) continue;
const agg = hourlyByDay.get(date);
const pressures = agg?.pressures ?? [];
const pressureMean = meanOf(pressures);
const pressureDelta =
pressures.length > 0
? Math.max(...pressures) - Math.min(...pressures)
: null;
observations.push({
date,
tempMin: firstNumber(daily.temperature_2m_min?.[i]),
tempMax: firstNumber(daily.temperature_2m_max?.[i]),
tempMean: firstNumber(daily.temperature_2m_mean?.[i]),
apparentMean: firstNumber(daily.apparent_temperature_mean?.[i]),
sunshineSec: firstNumber(daily.sunshine_duration?.[i]),
daylightSec: firstNumber(daily.daylight_duration?.[i]),
precipSum: firstNumber(daily.precipitation_sum?.[i]),
pressureMean,
pressureDelta:
pressureDelta !== null ? Math.round(pressureDelta * 10) / 10 : null,
humidityMean: meanOf(agg?.humidities ?? []),
cloudMean: meanOf(agg?.clouds ?? []),
weatherCode: firstNumber(daily.weather_code?.[i]),
});
}
return observations;
}
+239
View File
@@ -0,0 +1,239 @@
/**
* v1.25 (W-ENV) — environmental-context resolution + fetch/upsert service.
*
* Owns the location-precedence logic and the per-day upsert into
* `EnvironmentContext`. Both the nightly job and the on-demand backfill route
* call {@link fetchAndStoreEnvironment} so the precedence, the day-keying, and
* the upsert live in exactly one place.
*
* Location precedence per day (first hit wins):
* 1. a manual TRAVEL override whose [startDate, endDate] covers the day;
* 2. the user's HOME location.
* No home + no covering override ⇒ the day is skipped (the module degrades
* silently, matching the rollup "coverage miss → absent" posture).
*
* Coarse location only — the resolver never sees finer than the rounded city
* coordinates stored on the user / override.
*/
import { prisma } from "@/lib/db";
import {
fetchDailyEnvironment,
type DailyEnvironmentObservation,
} from "@/lib/environment/open-meteo";
import type { EnvironmentLocationSource } from "@/generated/prisma/client";
const MS_PER_DAY = 24 * 60 * 60 * 1000;
/** Default lookback window (days) for the nightly fetch — absorbs the archive
* settling lag and any days missed across worker reboots. */
export const ENVIRONMENT_LOOKBACK_DAYS = 7;
/** Hard cap on a single backfill span so one request can never fan out forever. */
export const ENVIRONMENT_MAX_BACKFILL_DAYS = 730;
/** A coarse resolved location for a given day. */
interface ResolvedLocation {
lat: number;
lon: number;
label: string;
source: EnvironmentLocationSource;
}
interface HomeLocation {
lat: number;
lon: number;
label: string;
timezone: string;
}
interface TravelOverride {
startDate: string;
endDate: string;
lat: number;
lon: number;
label: string;
}
/** UTC YYYY-MM-DD for `date` (used to bound the default lookback window). */
export function utcDayKey(date: Date): string {
return date.toISOString().slice(0, 10);
}
/** Inclusive list of YYYY-MM-DD keys from `start` to `end` (date arithmetic). */
export function enumerateDays(start: string, end: string): string[] {
const out: string[] = [];
const [sy, sm, sd] = start.split("-").map(Number);
const [ey, em, ed] = end.split("-").map(Number);
let cur = Date.UTC(sy, sm - 1, sd);
const last = Date.UTC(ey, em - 1, ed);
while (cur <= last) {
out.push(new Date(cur).toISOString().slice(0, 10));
cur += MS_PER_DAY;
}
return out;
}
/**
* Resolve the location for one day: a covering travel override wins, else home,
* else null. Pure — exported for unit tests.
*/
export function resolveLocationForDay(
day: string,
home: HomeLocation | null,
travels: readonly TravelOverride[],
): ResolvedLocation | null {
for (const t of travels) {
if (day >= t.startDate && day <= t.endDate) {
return { lat: t.lat, lon: t.lon, label: t.label, source: "TRAVEL" };
}
}
if (home) {
return { lat: home.lat, lon: home.lon, label: home.label, source: "HOME" };
}
return null;
}
/** A location-keyed group of days (one upstream fetch per group). */
function groupKey(loc: ResolvedLocation): string {
return `${loc.lat},${loc.lon},${loc.source},${loc.label}`;
}
export interface FetchAndStoreResult {
/** Days that resolved to a location and were upserted. */
stored: number;
/** Days skipped because no location resolved (no home, no override). */
skipped: number;
/** Distinct upstream fetches made. */
fetches: number;
}
/**
* Resolve + fetch + upsert the environment rows for a user across a date range.
* Groups days by resolved location so each location is fetched once over its
* contiguous span. A day whose observation is absent from the feed is left
* un-stored (no fabricated row). Idempotent — re-running upserts the same rows.
*/
export async function fetchAndStoreEnvironment(args: {
userId: string;
startDate: string;
endDate: string;
}): Promise<FetchAndStoreResult> {
const { userId, startDate, endDate } = args;
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
homeLat: true,
homeLon: true,
homeLabel: true,
homeTimezone: true,
timezone: true,
},
});
if (!user) return { stored: 0, skipped: 0, fetches: 0 };
const home: HomeLocation | null =
user.homeLat != null && user.homeLon != null
? {
lat: user.homeLat,
lon: user.homeLon,
label: user.homeLabel ?? "Home",
timezone: user.homeTimezone ?? user.timezone,
}
: null;
const travelRows = await prisma.environmentTravelLocation.findMany({
where: { userId },
select: {
startDate: true,
endDate: true,
lat: true,
lon: true,
label: true,
},
});
// The timezone used to enumerate AND fetch days — one tz keeps the stored
// `date` consistent with the user's day-keys elsewhere.
const timezone = home?.timezone ?? user.timezone;
const days = enumerateDays(startDate, endDate);
const resolvedByDay = new Map<string, ResolvedLocation>();
const groups = new Map<string, { loc: ResolvedLocation; days: string[] }>();
let skipped = 0;
for (const day of days) {
const loc = resolveLocationForDay(day, home, travelRows);
if (!loc) {
skipped += 1;
continue;
}
resolvedByDay.set(day, loc);
const gk = groupKey(loc);
const group = groups.get(gk) ?? { loc, days: [] };
group.days.push(day);
groups.set(gk, group);
}
let stored = 0;
let fetches = 0;
for (const { loc, days: groupDays } of groups.values()) {
const min = groupDays[0];
const max = groupDays[groupDays.length - 1];
let observations: DailyEnvironmentObservation[];
try {
observations = await fetchDailyEnvironment({
lat: loc.lat,
lon: loc.lon,
timezone,
startDate: min,
endDate: max,
});
} catch {
// A failed fetch for one location leaves its days un-stored; the nightly
// lookback re-attempts them. Other locations still get their rows.
continue;
}
fetches += 1;
const obsByDate = new Map(observations.map((o) => [o.date, o]));
const wanted = new Set(groupDays);
for (const obs of observations) {
if (!wanted.has(obs.date)) continue;
await upsertObservation(userId, loc, obs);
stored += 1;
}
// Days the feed did not return (e.g. beyond the settling lag) stay absent.
void obsByDate;
}
return { stored, skipped, fetches };
}
async function upsertObservation(
userId: string,
loc: ResolvedLocation,
obs: DailyEnvironmentObservation,
): Promise<void> {
const data = {
lat: loc.lat,
lon: loc.lon,
locationLabel: loc.label,
source: loc.source,
tempMin: obs.tempMin,
tempMax: obs.tempMax,
tempMean: obs.tempMean,
apparentMean: obs.apparentMean,
sunshineSec: obs.sunshineSec != null ? Math.round(obs.sunshineSec) : null,
daylightSec: obs.daylightSec != null ? Math.round(obs.daylightSec) : null,
precipSum: obs.precipSum,
pressureMean: obs.pressureMean,
pressureDelta: obs.pressureDelta,
humidityMean: obs.humidityMean,
cloudMean: obs.cloudMean,
weatherCode: obs.weatherCode,
fetchedAt: new Date(),
};
await prisma.environmentContext.upsert({
where: { userId_date: { userId, date: obs.date } },
create: { userId, date: obs.date, ...data },
update: data,
});
}
@@ -24,11 +24,13 @@ import {
import {
MEDICATION_COMPLIANCE_CHANNEL_KEY,
SYMPTOM_SEVERITY_CHANNEL_KEY,
type DailySeriesPoint,
type LabDrawPoint,
type NamedSeries,
} from "@/lib/insights/correlation-discovery";
import { resolveLabFields } from "@/lib/labs/serialise";
import { wallClockInTz } from "@/lib/tz/wall-clock";
import { ENVIRONMENT_FIELDS } from "@/lib/environment/fields";
import {
buildComplianceDailySeries,
buildSymptomSeverityDailySeries,
@@ -183,6 +185,59 @@ export async function fetchSymptomSeries(
});
}
/**
* v1.25 (W-ENV) — build the user's environmental-exposure BEHAVIOUR channels.
*
* One {@link NamedSeries} per registered env field (temperature, daylight,
* sunshine, precipitation, pressure mean + intraday swing), read from the daily
* `EnvironmentContext` rows the nightly job stores. Each row's `date` is already
* a YYYY-MM-DD key, so points need no re-keying. Sunshine / daylight are stored
* in seconds and surfaced as hours (correlation r is scale-invariant; hours just
* keep the series readable). A field with no non-null values yields an empty
* series that degrades to absent — never a fabricated constant. The whole set is
* empty when the user has no environment rows (module off / no home set).
*/
export async function fetchEnvironmentSeries(
userId: string,
since: Date,
): Promise<NamedSeries[]> {
const sinceKey = since.toISOString().slice(0, 10);
const rows = await prisma.environmentContext.findMany({
where: { userId, date: { gte: sinceKey } },
orderBy: { date: "asc" },
take: 1000,
select: {
date: true,
tempMean: true,
tempMin: true,
tempMax: true,
apparentMean: true,
sunshineSec: true,
daylightSec: true,
precipSum: true,
pressureMean: true,
pressureDelta: true,
humidityMean: true,
cloudMean: true,
},
});
return ENVIRONMENT_FIELDS.map((field) => {
const points: DailySeriesPoint[] = [];
for (const row of rows) {
const raw = row[field.column];
if (raw == null || !Number.isFinite(raw)) continue;
// Seconds → hours for the duration fields; pass through otherwise.
const value =
field.column === "sunshineSec" || field.column === "daylightSec"
? raw / 3600
: raw;
points.push({ day: row.date, value });
}
return { key: field.key, role: "behaviour" as const, points };
});
}
/** Day key (YYYY-MM-DD) for an instant in the user's display timezone. */
function tzDayKey(at: Date, tz: string): string {
const { year, month, day } = wallClockInTz(at, tz);
+15
View File
@@ -39,6 +39,10 @@
* link. The series builders live in `correlation-series-builders.ts`.
*/
import { pearson, MIN_PAIRED_N } from "@/lib/insights/correlations";
import {
getEnvironmentField,
isEnvironmentChannelKey,
} from "@/lib/environment/fields";
/** Default Benjamini-Hochberg target false-discovery rate. */
export const FDR_Q = 0.1;
@@ -102,6 +106,12 @@ export function metricFamily(key: string): string {
// tautology as MOOD→MOOD and is excluded too.
if (key.startsWith(FACTOR_CHANNEL_PREFIX) || key === "MOOD") return "MOOD";
if (key.startsWith("BLOOD_PRESSURE")) return "BLOOD_PRESSURE";
// v1.25 (W-ENV) — every environmental-exposure channel (ENV_TEMP_MEAN,
// ENV_DAYLIGHT, …) shares ONE family so the same-family guard never
// lag-correlates two same-day weather fields against each other (a
// near-tautology). They stay free to pair cross-domain against mood / sleep /
// vitals — the whole point of the module.
if (key.startsWith("ENV_")) return "ENVIRONMENT";
// v1.21.0 (FDREXTEND) — medication compliance and symptom severity each form
// their OWN single-channel family, so the loop's same-family guard collapses
// only the self-lag (compliance→compliance, symptom→symptom). The returned
@@ -312,6 +322,11 @@ function humanise(key: string): string {
if (key.startsWith("FACTOR:")) {
return `rated ${key.slice("FACTOR:".length).replace(/[_-]/g, " ").toLowerCase()}`;
}
// v1.25 (W-ENV) — env channels read with their descriptive label ("daily
// temperature", "daylight") rather than the raw "env temp mean" key.
if (isEnvironmentChannelKey(key)) {
return getEnvironmentField(key)?.narrationLabel ?? key.toLowerCase();
}
return key.replace(/_/g, " ").toLowerCase();
}
+185
View File
@@ -0,0 +1,185 @@
/**
* v1.25 (W-ENV) — nightly environmental-context fetch.
*
* For every account with the environmental-context module enabled AND a home
* location set, fetch the daily weather/daylight for the recent uncovered days
* and upsert into `EnvironmentContext`. A daily discovery tick (empty payload)
* fans out one per-user job; the per-user job resolves each day's location
* (travel override → home) and fetches a lookback window so the archive feed's
* settling lag (a few days) is absorbed and any day missed across worker
* reboots is re-attempted. The same handler also serves the on-demand backfill
* (an explicit `{ userId, startDate, endDate }` payload from the settings
* surface).
*
* Opt-in + privacy: the discovery filter requires both the module flag and a
* home location, so a disabled account never triggers an outbound fetch. Egress
* runs through `safeFetch` inside the Open-Meteo client. Recurring → pg-boss
* (never a CLI script; the prod image strips `tsx`).
*/
import { prisma } from "@/lib/db";
import type { PgBoss } from "pg-boss";
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
import { isModuleEnabled } from "@/lib/modules/gate";
import {
ENVIRONMENT_LOOKBACK_DAYS,
ENVIRONMENT_MAX_BACKFILL_DAYS,
fetchAndStoreEnvironment,
utcDayKey,
} from "@/lib/environment/service";
import { recordError } from "@/lib/jobs/worker-status";
import { workerLog } from "./reminder/shared";
export const ENVIRONMENT_FETCH_QUEUE = "environment-fetch";
/** Daily 02:10 Europe/Berlin — early, before the 02:30+ maintenance window so
* the night's weather rows exist before any briefing/insight pre-gen reads. */
export const ENVIRONMENT_FETCH_CRON = "10 2 * * *";
export const ENVIRONMENT_FETCH_CONCURRENCY = 1;
const MS_PER_DAY = 24 * 60 * 60 * 1000;
/**
* Per-user fetch payload. An empty payload (no `userId`) is the daily discovery
* tick. `startDate`/`endDate` (YYYY-MM-DD) drive the on-demand backfill; omitted
* ⇒ the default lookback window ending today.
*/
export interface EnvironmentFetchPayload {
userId?: string;
startDate?: string;
endDate?: string;
}
/** Resolve the date range for a per-user run (explicit range, else lookback). */
function resolveRange(payload: EnvironmentFetchPayload): {
startDate: string;
endDate: string;
} {
const today = new Date();
const endDate = payload.endDate ?? utcDayKey(today);
const startDate =
payload.startDate ??
utcDayKey(
new Date(today.getTime() - ENVIRONMENT_LOOKBACK_DAYS * MS_PER_DAY),
);
return { startDate, endDate };
}
/**
* Request-side enqueue for a single account: a default-lookback refresh (after
* the user sets/changes their home, so weather appears without waiting for the
* nightly tick) or an explicit-range backfill. No-ops cleanly when no global
* boss is bound (e.g. a web-only deployment) — the nightly cron still covers it.
* The lookback variant is singleton-coalesced per user; an explicit backfill
* range is NOT coalesced so it always runs.
*/
export async function enqueueEnvironmentFetch(
payload: EnvironmentFetchPayload & { userId: string },
): Promise<boolean> {
const boss = getGlobalBoss();
if (!boss) return false;
const options =
payload.startDate || payload.endDate
? undefined
: { singletonKey: `environment-fetch:${payload.userId}` };
await boss.send(ENVIRONMENT_FETCH_QUEUE, payload, options);
return true;
}
/**
* Discovery fan-out: enqueue one per-user fetch job for every account with the
* module on and a home location set. Idempotent (singletonKey-coalesced per
* user). Returns counts for the worker log.
*/
export async function enqueueEnvironmentFetchDiscovery(
boss: PgBoss,
): Promise<{ enqueued: number; skipped: number }> {
// Candidate set: a home location is required for any non-override day, so an
// account without one cannot produce a row. The per-candidate module check
// then enforces the opt-in flag + operator availability.
const candidates = await prisma.user.findMany({
where: { homeLat: { not: null }, homeLon: { not: null } },
select: { id: true },
});
let enqueued = 0;
let skipped = 0;
for (const { id } of candidates) {
if (!(await isModuleEnabled(id, "environment"))) {
skipped += 1;
continue;
}
await boss.send(
ENVIRONMENT_FETCH_QUEUE,
{ userId: id } satisfies EnvironmentFetchPayload,
{ singletonKey: `environment-fetch:${id}` },
);
enqueued += 1;
}
return { enqueued, skipped };
}
/**
* The queue handler. Empty payload ⇒ discovery fan-out; a `userId` payload ⇒
* fetch + upsert for that user across the resolved range. Re-checks the module
* gate on the per-user path so a backfill enqueued just before the user
* disabled the module is a no-op.
*/
export async function handleEnvironmentFetch(
boss: PgBoss,
payload: EnvironmentFetchPayload,
): Promise<void> {
if (!payload.userId) {
const { enqueued, skipped } = await enqueueEnvironmentFetchDiscovery(boss);
workerLog(
"info",
`[environment-fetch] discovery enqueued=${enqueued} skipped=${skipped}`,
);
return;
}
const userId = payload.userId;
if (!(await isModuleEnabled(userId, "environment"))) {
workerLog(
"info",
`[environment-fetch] user=${userId} module disabled — skipping`,
);
return;
}
const { startDate, endDate } = resolveRange(payload);
// Clamp the span so a crafted backfill can never fan out an unbounded range.
const span = enumerateSpanDays(startDate, endDate);
if (span > ENVIRONMENT_MAX_BACKFILL_DAYS) {
workerLog(
"error",
`[environment-fetch] user=${userId} range ${startDate}..${endDate} (${span}d) exceeds cap — skipping`,
);
return;
}
try {
const result = await fetchAndStoreEnvironment({
userId,
startDate,
endDate,
});
workerLog(
"info",
`[environment-fetch] user=${userId} ${startDate}..${endDate} stored=${result.stored} skipped=${result.skipped} fetches=${result.fetches}`,
);
} catch (err) {
recordError();
workerLog("error", `[environment-fetch] user=${userId} failed`, err);
throw err;
}
}
function enumerateSpanDays(start: string, end: string): number {
const [sy, sm, sd] = start.split("-").map(Number);
const [ey, em, ed] = end.split("-").map(Number);
const days = Math.round(
(Date.UTC(ey, em - 1, ed) - Date.UTC(sy, sm - 1, sd)) / MS_PER_DAY,
);
return days + 1;
}
@@ -75,6 +75,13 @@ import {
handleEncryptionKeyRotate,
type EncryptionKeyRotatePayload,
} from "@/lib/jobs/encryption-key-rotate";
import {
ENVIRONMENT_FETCH_QUEUE,
ENVIRONMENT_FETCH_CRON,
ENVIRONMENT_FETCH_CONCURRENCY,
handleEnvironmentFetch,
type EnvironmentFetchPayload,
} from "@/lib/jobs/environment-fetch";
import { recordError } from "@/lib/jobs/worker-status";
import { workerLog, BOOT_BACKFILL_STAGGER_SECONDS } from "./shared";
import { createAndSchedule, type ScheduleEntry } from "./registrar-shared";
@@ -216,6 +223,12 @@ const MCP_TOKEN_CLEANUP_CRON = "0 4 * * *";
const MED_NOTES_ENCRYPTION_BACKFILL_CRON = "5 4 * * *";
const allQueues = [
// v1.25 (W-ENV) — nightly environmental-context fetch. A daily discovery tick
// fans out one per-user job per opted-in account with a home location; the
// queue also serves the on-demand backfill from the Environment settings
// surface. Without this entry pg-boss never provisions it and both the cron
// and the backfill button silently no-op.
ENVIRONMENT_FETCH_QUEUE,
DATA_BACKUP_QUEUE,
RATE_LIMIT_CLEANUP_QUEUE,
IDEMPOTENCY_CLEANUP_QUEUE,
@@ -277,6 +290,9 @@ const allQueues = [
];
const schedules: ScheduleEntry[] = [
// v1.25 (W-ENV) — daily 02:10 Europe/Berlin discovery tick (empty payload)
// that fans out one per-user environment fetch per opted-in account.
[ENVIRONMENT_FETCH_QUEUE, ENVIRONMENT_FETCH_CRON],
[DATA_BACKUP_QUEUE, DATA_BACKUP_CRON],
[RATE_LIMIT_CLEANUP_QUEUE, RATE_LIMIT_CLEANUP_CRON],
[IDEMPOTENCY_CLEANUP_QUEUE, IDEMPOTENCY_CLEANUP_CRON],
@@ -601,6 +617,20 @@ export async function registerMaintenanceQueues(
},
);
// v1.25 (W-ENV) — nightly environment fetch. The daily discovery tick (empty
// payload) fans out one per-user job per opted-in account; the queue also
// serves the on-demand backfill payloads from the settings surface. Serial
// concurrency so the staggered outbound fetches never crowd the request pool.
await boss.work<EnvironmentFetchPayload>(
ENVIRONMENT_FETCH_QUEUE,
{ localConcurrency: ENVIRONMENT_FETCH_CONCURRENCY },
async (jobs) => {
for (const job of jobs) {
await handleEnvironmentFetch(boss, job.data);
}
},
);
return allQueues;
}
+7 -2
View File
@@ -352,10 +352,15 @@ describe("resolveModuleEnabled — mcp module (opt-in, default-OFF)", () => {
});
describe("registry — opt-in marker", () => {
it("marks only the mcp module opt-in (every other module is default-on)", () => {
it("marks the mcp + environment modules opt-in (every other module is default-on)", () => {
expect(isOptInModule("mcp")).toBe(true);
// v1.25 (W-ENV) — the environmental-context module is opt-in too: it
// performs an outbound weather fetch tied to a coarse location, so it ships
// dark like the remote MCP endpoint.
expect(isOptInModule("environment")).toBe(true);
const optIn = new Set(["mcp", "environment"]);
for (const key of MODULE_KEYS) {
if (key === "mcp") continue;
if (optIn.has(key)) continue;
expect(isOptInModule(key)).toBe(false);
}
});
+17
View File
@@ -115,6 +115,12 @@ export const MODULE_KEYS = [
// re-enabling finds the rows intact.
"medications",
"doctorReport",
// v1.25.0 (W-ENV) — environmental-context module. Like `mcp`, it is OPT-IN
// (off by default): it performs an outbound weather fetch tied to where the
// user physically is (a coarse home / travel location), so opt-in is the
// right privacy default. With it off no job runs, no row is written, and no
// egress happens. The `optIn` marker inverts the per-user default.
"environment",
// v1.22.0 — the remote Model Context Protocol endpoint (`/mcp`). Unlike
// every other module this is OPT-IN (off by default): it exposes a new
// external-assistant attack surface, so it ships dark and the operator /
@@ -256,6 +262,17 @@ export const MODULE_REGISTRY: Readonly<Record<ModuleKey, ModuleDefinition>> =
descriptionKey: "modules.doctorReport.description",
category: "export",
},
environment: {
key: "environment",
labelKey: "modules.environment.label",
descriptionKey: "modules.environment.description",
category: "device",
// Off by default: performs an outbound weather fetch tied to a coarse
// location, so it ships dark and the user turns it on deliberately. The
// home location + travel overrides + backfill live on the dedicated
// Environment settings surface (rendered when the module is on).
optIn: true,
},
mcp: {
key: "mcp",
labelKey: "modules.mcp.label",
+16
View File
@@ -0,0 +1,16 @@
/**
* Query keys — environmental-context module (v1.25, W-ENV). The overview
* (home + travel overrides + stored-day summary) and the geocoding search.
* Part of the centralized factory; aggregated in `./index.ts`.
*/
export const environmentKeys = {
/**
* `environment()` is the root prefix every environment write (set home, add /
* remove a travel override, trigger a backfill) invalidates through, so the
* settings surface repaints in lockstep.
*/
environment: () => ["environment"] as const,
/** Geocoding search results for a query string (cached per query). */
environmentGeocode: (query: string) =>
["environment", "geocode", query] as const,
};
+2
View File
@@ -21,6 +21,7 @@ import { coachKeys } from "./coach";
import { familyHistoryKeys } from "./family-history";
import { cycleKeys } from "./cycle";
import { dashboardKeys } from "./dashboard";
import { environmentKeys } from "./environment";
import { illnessKeys } from "./illness";
import { insightsKeys } from "./insights";
import { integrationKeys } from "./integrations";
@@ -52,6 +53,7 @@ export const queryKeys = {
...mentalHealthKeys,
...allergyKeys,
...familyHistoryKeys,
...environmentKeys,
};
/**
@@ -40,6 +40,8 @@ describe("signal registry — structural sanity", () => {
for (const signal of allSignals()) {
if (signal.kind === "biomarker") {
expect(signal.source.biomarkerKey.length).toBeGreaterThan(0);
} else if (signal.kind === "environment") {
expect(signal.source.environmentChannelKey.length).toBeGreaterThan(0);
} else {
expect(signal.source.measurementType.length).toBeGreaterThan(0);
}
@@ -57,7 +59,7 @@ describe("signal registry — structural sanity", () => {
it("signalForMeasurementType round-trips every measurement/score signal", () => {
for (const signal of allSignals()) {
if (signal.kind === "biomarker") continue;
if (signal.kind !== "measurement" && signal.kind !== "score") continue;
expect(signalForMeasurementType(signal.source.measurementType)).toBe(
signal,
);
+4 -1
View File
@@ -13,7 +13,10 @@ import { allSignals } from "@/lib/signals/registry";
export function deriveBucketedTypes(): MeasurementType[] {
const types: MeasurementType[] = [];
for (const signal of allSignals()) {
if (signal.kind === "biomarker") continue;
// biomarker (labs path) + environment (W-ENV exposure channels) are not
// `MeasurementType`-backed — env feeds the engine through its own series
// builder, not the measurement-keyed bucketed types.
if (signal.kind === "biomarker" || signal.kind === "environment") continue;
if (!signal.surfaces.correlationEligible) continue;
types.push(signal.source.measurementType);
}
+3 -1
View File
@@ -13,7 +13,9 @@ import { allSignals } from "@/lib/signals/registry";
export function deriveMeasurementLoinc(): Record<string, LoincMapping> {
const entries: Array<[string, LoincMapping]> = [];
for (const signal of allSignals()) {
if (signal.kind === "biomarker") continue;
// Only `MeasurementType`-backed signals key `MEASUREMENT_LOINC`. biomarker
// (labs) + environment (W-ENV) signals are never Measurement rows.
if (signal.kind === "biomarker" || signal.kind === "environment") continue;
if (!signal.fhir) continue;
entries.push([
signal.source.measurementType,
+1 -1
View File
@@ -15,7 +15,7 @@ import { getSignal } from "@/lib/signals/registry";
/** Build the `MetricStatusMeta` for one registered metric-status id. */
function metaFor(id: MetricStatusMetricId): MetricStatusMeta {
const signal = getSignal(id);
if (!signal || signal.kind === "biomarker") {
if (!signal || signal.kind === "biomarker" || signal.kind === "environment") {
throw new Error(`signal registry: no measurement signal for "${id}"`);
}
// Build field-by-field, omitting the optional keys when absent so the
+144 -3
View File
@@ -30,8 +30,15 @@ import type {
import type { FhirObservationCategory } from "@/lib/fhir/loinc-map";
import { FEVER_BAND_C } from "@/lib/clinical-floors";
/** Discriminator: a device/manual reading, a lab biomarker, or a computed score. */
export type SignalKind = "measurement" | "biomarker" | "score";
/**
* Discriminator: a device/manual reading, a lab biomarker, a computed score, or
* an environmental exposure. `environment` (v1.25 W-ENV) is NOT backed by a
* `MeasurementType` — its daily value lives in `EnvironmentContext` and feeds
* the correlation engine through the env channel series builder, not the
* measurement-keyed `BUCKETED_TYPES`. It registers here so the env signals get
* a stable key + display metadata in the one cross-surface table.
*/
export type SignalKind = "measurement" | "biomarker" | "score" | "environment";
/** Reuse the assessment registry's direction vocabulary verbatim. */
export type SignalDirection = MetricDirection;
@@ -114,6 +121,17 @@ export interface BiomarkerSignalSource {
biomarkerKey: string;
}
/**
* How an `environment` signal is sourced (v1.25 W-ENV). The value is a daily
* `EnvironmentContext` column, surfaced to the correlation engine under
* `environmentChannelKey` (the `ENV_*` channel key from
* `@/lib/environment/fields`). No `MeasurementType` — env data is never a
* Measurement row.
*/
export interface EnvironmentSignalSource {
environmentChannelKey: string;
}
/**
* The canonical cross-surface signal definition, discriminated on `kind`.
* `measurement` and `score` both resolve to a `MeasurementType`; `biomarker`
@@ -122,7 +140,8 @@ export interface BiomarkerSignalSource {
export type SignalDefinition =
| (SignalCommon & { kind: "measurement"; source: MeasurementSignalSource })
| (SignalCommon & { kind: "score"; source: MeasurementSignalSource })
| (SignalCommon & { kind: "biomarker"; source: BiomarkerSignalSource });
| (SignalCommon & { kind: "biomarker"; source: BiomarkerSignalSource })
| (SignalCommon & { kind: "environment"; source: EnvironmentSignalSource });
/** Convenience: build a Coach-snapshot facet from a scope token. */
function coachScope(scope: string): { scope: string } {
@@ -1504,6 +1523,128 @@ export const SIGNALS: Record<string, SignalDefinition> = {
mcp: false,
},
},
// ── v1.25 (W-ENV) environmental-context module — exposure signals ─────────
// Daily weather/daylight, fetched server-side from Open-Meteo for the user's
// coarse home (or a travel override) and stored in `EnvironmentContext`. NOT
// `MeasurementType`-backed: `correlationEligible:true` declares intent, but
// the wiring runs through the env channel series builder, not the
// measurement-keyed `BUCKETED_TYPES` (the correlation adapter skips
// `kind:"environment"`). Off the Coach snapshot + MCP surfaces in v1
// (`coachSnapshot:false ⇒ mcp:false`); no FHIR facet (env observations are
// not Measurement rows, so they never enter `MEASUREMENT_LOINC`). Direction is
// `target-band` — a neutral exposure, not a "better/worse" vital.
ENV_TEMP_MEAN: {
key: "ENV_TEMP_MEAN",
kind: "environment",
source: { environmentChannelKey: "ENV_TEMP_MEAN" },
i18nPrefix: "environment.fields.tempMean",
displayName: "Daily temperature",
unit: "°C",
direction: "target-band",
archetype: "environmental-exposure",
surfaces: {
detailPage: false,
correlationEligible: true,
coachSnapshot: false,
mcp: false,
},
},
ENV_TEMP_MIN: {
key: "ENV_TEMP_MIN",
kind: "environment",
source: { environmentChannelKey: "ENV_TEMP_MIN" },
i18nPrefix: "environment.fields.tempMin",
displayName: "Overnight low temperature",
unit: "°C",
direction: "target-band",
archetype: "environmental-exposure",
surfaces: {
detailPage: false,
correlationEligible: true,
coachSnapshot: false,
mcp: false,
},
},
ENV_SUNSHINE: {
key: "ENV_SUNSHINE",
kind: "environment",
source: { environmentChannelKey: "ENV_SUNSHINE" },
i18nPrefix: "environment.fields.sunshine",
displayName: "Sunshine duration",
unit: "h",
direction: "target-band",
archetype: "environmental-exposure",
surfaces: {
detailPage: false,
correlationEligible: true,
coachSnapshot: false,
mcp: false,
},
},
ENV_DAYLIGHT: {
key: "ENV_DAYLIGHT",
kind: "environment",
source: { environmentChannelKey: "ENV_DAYLIGHT" },
i18nPrefix: "environment.fields.daylight",
displayName: "Daylight length",
unit: "h",
direction: "target-band",
archetype: "environmental-exposure",
surfaces: {
detailPage: false,
correlationEligible: true,
coachSnapshot: false,
mcp: false,
},
},
ENV_PRECIP: {
key: "ENV_PRECIP",
kind: "environment",
source: { environmentChannelKey: "ENV_PRECIP" },
i18nPrefix: "environment.fields.precip",
displayName: "Precipitation",
unit: "mm",
direction: "target-band",
archetype: "environmental-exposure",
surfaces: {
detailPage: false,
correlationEligible: true,
coachSnapshot: false,
mcp: false,
},
},
ENV_PRESSURE_MEAN: {
key: "ENV_PRESSURE_MEAN",
kind: "environment",
source: { environmentChannelKey: "ENV_PRESSURE_MEAN" },
i18nPrefix: "environment.fields.pressureMean",
displayName: "Barometric pressure",
unit: "hPa",
direction: "target-band",
archetype: "environmental-exposure",
surfaces: {
detailPage: false,
correlationEligible: true,
coachSnapshot: false,
mcp: false,
},
},
ENV_PRESSURE_DELTA: {
key: "ENV_PRESSURE_DELTA",
kind: "environment",
source: { environmentChannelKey: "ENV_PRESSURE_DELTA" },
i18nPrefix: "environment.fields.pressureDelta",
displayName: "Pressure swing",
unit: "hPa",
direction: "target-band",
archetype: "environmental-exposure",
surfaces: {
detailPage: false,
correlationEligible: true,
coachSnapshot: false,
mcp: false,
},
},
};
/** Type guard: narrow an arbitrary string to a registered signal key. */
+70
View File
@@ -0,0 +1,70 @@
/**
* v1.25 (W-ENV) — environmental-context request validation.
*
* The home location, the travel overrides, and the backfill span. Coordinates
* are bounded to valid lat/lon; the labels are length-capped plaintext (a city
* name, never a quasi-identifier). Dates are strict YYYY-MM-DD. The shared
* shapes are reused by the OpenAPI registry so the wire contract stays
* single-source.
*/
import { z } from "zod/v4";
/** Strict YYYY-MM-DD calendar day. */
export const dayStringSchema = z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "Expected a YYYY-MM-DD date");
const latSchema = z.number().gte(-90).lte(90);
const lonSchema = z.number().gte(-180).lte(180);
const labelSchema = z.string().trim().min(1).max(200);
/** A coarse home location set in settings (city-level granularity). */
export const homeLocationSchema = z
.object({
lat: latSchema,
lon: lonSchema,
label: labelSchema,
/** IANA timezone (anchors the stored day-key). */
timezone: z.string().trim().min(1).max(64),
})
.strict();
export type HomeLocationInput = z.infer<typeof homeLocationSchema>;
/** A manual travel override covering an inclusive date range. */
export const travelLocationSchema = z
.object({
startDate: dayStringSchema,
endDate: dayStringSchema,
lat: latSchema,
lon: lonSchema,
label: labelSchema,
})
.strict()
.refine((v) => v.startDate <= v.endDate, {
message: "startDate must be on or before endDate",
path: ["endDate"],
});
export type TravelLocationInput = z.infer<typeof travelLocationSchema>;
/** A backfill request: fetch + store the environment rows over a date range. */
export const environmentBackfillSchema = z
.object({
startDate: dayStringSchema,
endDate: dayStringSchema,
})
.strict()
.refine((v) => v.startDate <= v.endDate, {
message: "startDate must be on or before endDate",
path: ["endDate"],
});
export type EnvironmentBackfillInput = z.infer<
typeof environmentBackfillSchema
>;
/** Geocoding search query (`?q=`). */
export const geocodeQuerySchema = z
.object({ q: z.string().trim().min(1).max(120) })
.strict();