Output:
Chunk ID: 3dbda0
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 3675
Output:
"""Read-only, allowlisted data provider for Dashboard v5."""
from __future__ import annotations

import json
import re
import sqlite3
from collections import defaultdict
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from statistics import median
from typing import Any

from apple_health_analytics import daily_series as apple_daily
from dashboard_v5.contracts import SCHEMA_VERSION
from dashboard_v5.lab_registry import EXACT_LAB_NUMBER, LAB_ALLOWLIST
from dashboard_v5.metric_registry import BY_ID, public_explorer, public_registry

TZ = "Europe/Zurich"
SYMPTOM_LABELS = {
    "Aphthen/Mundulzera", "GI/Darm", "Müdigkeit/Fatigue", "Haut", "Augen",
    "Gelenke", "Vaskulär/Thrombose-Warnzeichen",
}
APPLE_SPECS = {
    "apple.sleep": ("sleep_analysis", "sum"),
    "apple.resting_heart_rate": ("resting_heart_rate", "avg"),
    "apple.hrv": ("heart_rate_variability", "avg"),
    "apple.steps": ("step_count", "sum"),
}
ADMINISTERED = {
    "administered", "verabreicht",
    "erste injektion / therapiebeginn", "planmäßige injektion", "planmässige injektion", "planmaessige injektion",
}
EXPLICIT_PLANS = {"planned", "scheduled", "geplant"}
EXCLUDED_PLANS = {"cancelled", "canceled", "abgesagt", "missed", "verpasst"}
PUBLIC_TEXT = re.compile(r"^[^\x00-\x1f\x7f]{1,160}$")
IDENTIFIER = re.compile(r"^[a-z0-9_:.-]+$")

def public_text(value: Any, maximum: int = 120, *, allow_empty: bool = False) -> str | None:
    text = " ".join(str(value or "").split())
    if (not text and not allow_empty) or len(text) > maximum or not PUBLIC_TEXT.fullmatch(text or " "):
        return None
    if re.search(r"^(?:/|~/|[A-Za-z]:[\\/]|file:|https?://)|(?:^|/)\.hermes(?:/|$)", text, re.I):
        return None
    return text

def connect(path: Path) -> sqlite3.Connection:
    connection = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
    connection.row_factory = sqlite3.Row
    return connection

def table_exists(connection: sqlite3.Connection, name: str) -> bool:
    return connection.execute(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,)
    ).fetchone() is not None

def slug(value: Any) -> str:
    normalized = str(value or "").casefold().translate(
        str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss"})
    )
    return re.sub(r"[^a-z0-9]+", "_", normalized).strip("_")

def unit_slug(value: Any) -> str:
    return slug(str(value or "").replace("µ", "u").replace("μ", "u").replace("%", " percent "))

def parse_day(value: Any) -> str | None:
    text = str(value or "").strip()
    if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", text):
        return None
    try:
        return date.fromisoformat(text).isoformat()
    except ValueError:
        return None

def parse_score(value: Any) -> int | None:
    match = re.search(r"(?:^|\()([0-3])\)?\s*$", str(value or "").strip())
    return int(match.group(1)) if match else None

def rolling_baseline(points: list[dict[str, Any]], days: int, minimum: int = 7) -> list[dict[str, Any]]:
    observed = {date.fromisoformat(p["date"]): float(p["value"]) for p in points if p["value"] is not None}
    result: list[dict[str, Any]] = []
    for point in points:
        current = date.fromisoformat(point["date"])
        start = current - timedelta(days=days)
        values = [value for day, value in observed.items() if start <= day < current]
        result.append({"date": point["date"], "value": round(median(values), 3) if len(values) >= minimum else None})
    return result

def symptom_series(connection: sqlite3.Connection) -> tuple[list[dict[str, Any]], set[str]]:
    if not table_exists(connection, "symptom_log"):
        return [], set()
    grouped: dict[str, dict[str, list[int | None]]] = defaultdict(lambda: defaultdict(list))
    for row in connection.execute(
        "SELECT datum,symptom,schwergrad FROM symptom_log WHERE kontext='daily_quick_score' ORDER BY datum,id"
    ):
        day = parse_day(row["datum"])
        score = parse_score(row["schwergrad"])
        label = str(row["symptom"] or "")
        if day and label in SYMPTOM_LABELS:
            grouped[day][label].append(score)
    complete = {
        day
        for day, values in grouped.items()
        if set(values) == SYMPTOM_LABELS
        and all(len(scores) == 1 and scores[0] is not None for scores in values.values())
    }
    return [
        {"date": day, "value": sum(score for scores in grouped[day].values() for score in scores if score is not None), "quality": "complete"}
        for day in sorted(complete)
    ], complete

def apple_series(connection: sqlite3.Connection, metric: str, mode: str) -> list[dict[str, Any]]:
    if not table_exists(connection, "apple_health_records"):
        return []
    rows = list(connection.execute(
        """SELECT id,metric,value,unit,start_date,end_date,source_name,file_name,file_hash
           FROM apple_health_records WHERE metric=? AND value IS NOT NULL AND start_date IS NOT NULL
           ORDER BY start_date,end_date,source_name,id""", (metric,)
    ))
    values = apple_daily(metric, mode, _rows=rows)
    return [{"date": day, "value": value, "quality": "observed"} for day, value in sorted(values.items())]

def medication_data(connection: sqlite3.Connection, today: str) -> tuple[dict[str, Any], list[dict[str, Any]]]:
    if not table_exists(connection, "medication_administrations"):
        return {"last_administered": None, "next_planned": None}, []
    rows = list(connection.execute(
        "SELECT datum,medication_name,dose,event_type,scheduled_next_date FROM medication_administrations ORDER BY datum"
    ))
    actual = [
        row for row in rows
        if str(row["event_type"] or "").strip().casefold() in ADMINISTERED
        and (administered_day := parse_day(row["datum"])) is not None
        and administered_day <= today
    ]
    last = actual[-1] if actual else None
    cancelled_plans = {
        (str(row["medication_name"] or "").strip().casefold(), day)
        for row in rows
        if str(row["event_type"] or "").strip().casefold() in EXCLUDED_PLANS
        for day in (parse_day(row["datum"]), parse_day(row["scheduled_next_date"]))
        if day
    }
    candidates = []
    for row in rows:
        event_type = str(row["event_type"] or "").strip().casefold()
        medication_key = str(row["medication_name"] or "").strip().casefold()
        scheduled = parse_day(row["scheduled_next_date"])
        explicit_day = parse_day(row["datum"])
        planned = None
        if (
            scheduled
            and event_type in ADMINISTERED
            and explicit_day is not None
            and explicit_day <= today
        ):
            planned = scheduled
        elif event_type in EXPLICIT_PLANS:
            planned = explicit_day
        if planned and planned > today and (medication_key, planned) not in cancelled_plans:
            candidates.append((planned, row))
    next_item = min(candidates, key=lambda item: item[0]) if candidates else None
    def public_medication(row: sqlite3.Row | None, day: str | None, *, planned: bool) -> dict[str, Any] | None:
        if row is None or day is None:
            return None
        name = public_text(row["medication_name"], 120)
        dose = public_text(row["dose"], 40, allow_empty=True)
        if name is None or dose is None:
            return None
        item: dict[str, Any] = {"date": day, "name": name, "dose": dose}
        if planned:
            item["status"] = "planned"
        return item

    medication = {
        "last_administered": public_medication(last, parse_day(last["datum"]) if last else None, planned=False),
        "next_planned": public_medication(next_item[1], next_item[0], planned=True) if next_item else None,
    }
    events = []
    for row in actual:
        label = public_text(row["medication_name"], 120)
        day = parse_day(row["datum"])
        if label and day:
            events.append({"date": day, "type": "medication_administered", "label": label})
    return medication, events

def verified_labs(
    connection: sqlite3.Connection,
    limit: int = 12,
    *,
    through_day: str | None = None,
) -> list[dict[str, Any]]:
    if not table_exists(connection, "laborwerte"):
        return []
    rows = list(connection.execute(
        """SELECT parameter_name,wert,einheit,reference_min,reference_max,abnahme_datum,befund_datum,
                  reference_range_source,source_type
           FROM laborwerte
           WHERE lower(trim(COALESCE(validierungsstatus,'')))='validiert'
             AND verified_against_original=1
             AND reference_range_source='scanned_original'
             AND trim(COALESCE(einheit,''))<>''
           ORDER BY id"""
    ))
    candidates: dict[tuple[str, str, str], list[sqlite3.Row]] = defaultdict(list)
    for row in rows:
        raw_key = (slug(row["parameter_name"]), unit_slug(row["einheit"]))
        canonical = LAB_ALLOWLIST.get(raw_key)
        day = parse_day(row["abnahme_datum"]) or parse_day(row["befund_datum"])
        if canonical and day and (through_day is None or day <= through_day):
            canonical_parameter, canonical_unit = canonical
            candidates[(canonical_parameter, canonical_unit, day)].append(row)
    result = []
    for (canonical_parameter, canonical_unit, day), same_day in candidates.items():
        if len(same_day) != 1:
            continue
        row = same_day[0]
        if not EXACT_LAB_NUMBER.fullmatch(str(row["wert"] or "").strip()):
            continue
        result.append({
            "parameter": canonical_parameter, "value": str(row["wert"]).strip(),
            "unit": canonical_unit, "date": day,
            "reference_min": row["reference_min"], "reference_max": row["reference_max"],
            "quality": "verified_original", "source_type": "scanned_original",
        })
    result.sort(key=lambda item: item["date"], reverse=True)
    return result[:limit]

def nutrition_data(connection: sqlite3.Connection) -> dict[str, Any]:
    daily: list[dict[str, Any]] = []
    if table_exists(connection, "nutrition_daily_summary_v2"):
        for row in connection.execute("SELECT * FROM nutrition_daily_summary_v2 ORDER BY datum DESC LIMIT 180"):
            day = parse_day(row["datum"])
            complete = (
                day is not None and row["item_count"] is not None and int(row["item_count"]) > 0
                and row["histamine_unknown_count"] is not None and int(row["histamine_unknown_count"]) == 0
                and row["histamine_score"] is not None
                and row["histamine_label"] in {"green", "yellow", "orange", "red"}
            )
            if day:
                daily.append({
                    "date": day, "kcal": row["kcal"], "item_count": row["item_count"],
                    "histamine_score": row["histamine_score"] if complete else None,
                    "histamine_status": str(row["histamine_label"]) if complete else "unknown",
                    "unknown_items": row["histamine_unknown_count"], "quality": "complete" if complete else "incomplete",
                })
    review = []
    if table_exists(connection, "nutrition_review_queue"):
        for row in connection.execute("SELECT normalized_name,example_name,occurrence_count,suggested_canonical_food,suggested_score FROM nutrition_review_queue WHERE status='open' ORDER BY occurrence_count DESC,last_seen DESC LIMIT 25"):
            name = public_text(row["example_name"], 160)
            if name:
                queue_key = slug(row["normalized_name"])
                suggested = public_text(row["suggested_canonical_food"], 120, allow_empty=True)
                score = row["suggested_score"] if row["suggested_score"] in (0, 1, 2, 3) else None
                review.append({
                    "queue_key": queue_key,
                    "name": name,
                    "occurrences": int(row["occurrence_count"] or 0),
                    "reason": "Zuordnung fehlt",
                    "suggested_canonical_food": suggested or "",
                    "suggested_score": score if score is not None else "unknown",
                    "suggested_traffic_light": "unknown",
                })
    return {"daily": list(reversed(daily)), "mapping_review": review, "mapping_open_count": len(review)}

def correlations(connection: sqlite3.Connection) -> dict[str, Any]:
    dimensions = {
        "lag_days": [0, 1, 2, 3],
        "medication_phases": ["baseline_pre_treatment", "early_treatment", "stable_treatment", "unknown"],
        "lag_direction": "predictor_d_to_target_d_plus_lag",
    }
    if not table_exists(connection, "multimodal_correlation_results"):
        return {"dimensions": dimensions, "results": []}

    import multimodal_correlations as engine

    results = []
    rows = connection.execute(
        """SELECT predictor,target,lag_days,medication_phase,n,eligible_target_days,
                  expected_target_days,target_coverage,missing_pairs,rho,p_value,q_value,
                  status,method,quality_flags,interpretation
           FROM multimodal_correlation_results
           ORDER BY predictor,target,lag_days,medication_phase LIMIT 1000"""
    )
    for row in rows:
        try:
            flags_raw = json.loads(str(row["quality_flags"]))
            if not isinstance(flags_raw, list) or not all(isinstance(flag, str) for flag in flags_raw):
                continue
            result = engine.CorrelationResult(
                predictor=str(row["predictor"]), target=str(row["target"]),
                lag_days=int(row["lag_days"]), medication_phase=str(row["medication_phase"]),
                n=int(row["n"]), eligible_target_days=int(row["eligible_target_days"]),
                expected_target_days=int(row["expected_target_days"]),
                target_coverage=float(row["target_coverage"]), missing_pairs=int(row["missing_pairs"]),
                rho=row["rho"], p_value=row["p_value"], q_value=row["q_value"],
                status=str(row["status"]), method=str(row["method"]),
                quality_flags=tuple(flags_raw), interpretation=str(row["interpretation"]),
            )
            engine._validate_result_for_storage(result)
        except (TypeError, ValueError, json.JSONDecodeError):
            continue
        results.append({
            "id": {"predictor": result.predictor, "target": result.target},
            "dimensions": {"lag_days": result.lag_days, "medication_phase": result.medication_phase},
            "sample": {
                "eligible_target_days": result.eligible_target_days,
                "expected_target_days": result.expected_target_days,


Output:
Chunk ID: 1f4da0
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2442
Output:
"""Bounded read-only data API provider for Dashboard v5 Sprint 6B."""

from __future__ import annotations

import base64
import hashlib
import hmac
import json
import math
import re
import secrets
import sqlite3
import time
from statistics import median
from collections import defaultdict
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs
from zoneinfo import ZoneInfo

from apple_health_analytics import daily_points
from dashboard_v5.data_provider import (
    ADMINISTERED,
    SYMPTOM_LABELS,
    parse_day,
    parse_score,
    public_text,
)
from dashboard_v5.document_chunks import (
    decode_chunk_cursor,
    document_chunks,
    encode_chunk_cursor,
)
from dashboard_v5.document_originals import probe_original
from dashboard_v5.lab_registry import EXACT_LAB_NUMBER, LAB_ALLOWLIST
from dashboard_v5.metric_catalog_v2 import (
    APPLE_ANALYTICS_UNITS,
    APPLE_SOURCE_SPECS,
    BY_ID_V2,
    LAB_CATALOG_SPECS,
    MetricV2,
    SourceInventoryLimitError,
    catalog_search,
    inventory_sources,
    public_catalog,
)

TZ_NAME = "Europe/Zurich"
LOCAL_TZ = ZoneInfo(TZ_NAME)
MAX_RANGE_DAYS = 3660
MAX_SERIES_ROWS = 3660
MAX_RAW_APPLE_ROWS = 100000
MAX_RAW_LAB_ROWS = 10000
MAX_EVENT_SOURCE_ROWS = 10000
MAX_DAILY_SOURCE_ROWS = 30000
MAX_EVENT_ROWS = 1000
MAX_LAB_ROWS = 100
MAX_SEARCH_ROWS_PER_GROUP = 20
MAX_CALENDAR_DAYS = 62
MAX_NUTRITION_DAYS = 180
MAX_NUTRITION_ITEMS = 200
MAX_NUTRITION_QUEUE = 50
MAX_FUTURE_DAYS = 366
MAX_QUERY_BYTES = 512
QUERY_TIMEOUT_SECONDS = 1.0
ALLOWED_RESOLUTIONS = frozenset({"day", "week"})
ALLOWED_EVENT_TYPES = frozenset(
    {"medication_administered", "symptom_day", "health_event", "health_period"}
)
NUTRIENT_ALLOWLIST = {
    "energy.energy": ("Energie", "kcal"),
    "nutrient.protein": ("Protein", "g"),
    "nutrient.carb": ("Kohlenhydrate", "g"),
    "nutrient.fat": ("Fett", "g"),
    "nutrient.fiber": ("Ballaststoffe", "g"),
    "nutrient.sugar": ("Zucker", "g"),
    "nutrient.salt": ("Salz", "g"),
    "nutrient.sodium": ("Natrium", "mg"),
    "nutrient.vitamin_c": ("Vitamin C", "mg"),
    "nutrient.calcium": ("Calcium", "mg"),
    "nutrient.iron": ("Eisen", "mg"),
    "nutrient.magnesium": ("Magnesium", "mg"),
}
MEAL_LABELS = {
    "breakfast": "Frühstück",
    "lunch": "Mittagessen",
    "dinner": "Abendessen",
    "snack": "Snack",
    "unknown": "Unbekannt",
}
FORBIDDEN_METADATA_TEXT = re.compile(
    r"(?:/home/|/tmp/|/Users/|/(?:var|etc|usr|opt|srv|root|run|mnt|media|private)/|"
    r"~/|file:|https?://|[A-Za-z]:[\\/]|"
    r"(?:^|[\s:|])/(?:[^/\s]+/)+[^/\s]+|\.\.[\\/]|\\\\[^\\/\s]+[\\/]|"
    r"\.hermes(?:/|$))",
    re.IGNORECASE,
)
DRIVE_ID_TOKEN = re.compile(r"(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{25,}(?![A-Za-z0-9_-])")
API_PATHS = frozenset(
    {
        "/api/v1/metric-catalog",
        "/api/v1/series",
        "/api/v1/events",
        "/api/v1/labs",
        "/api/v1/calendar",
        "/api/v1/search",
        "/api/v1/nutrition/days",
        "/api/v1/nutrition/mapping-queue",
    }
)
EXPECTED_ANALYTICS_UNITS = APPLE_ANALYTICS_UNITS

@dataclass
class APIError(Exception):
    status: int
    code: str

    def __str__(self) -> str:
        return self.code

def safe_metadata_text(
    value: Any, maximum: int, *, allow_empty: bool = False
) -> str | None:
    text = public_text(value, maximum, allow_empty=allow_empty)
    drive_id_like = bool(
        text
        and any(
            any(char.isalpha() for char in token)
            and any(char.isdigit() for char in token)
            for token in DRIVE_ID_TOKEN.findall(text)
        )
    )
    if text is None or FORBIDDEN_METADATA_TEXT.search(text) or drive_id_like:
        return None
    return text

def api_document_id(
    raw_id: Any, document_day: str | None, category: str, institution: str
) -> str:
    material = json.dumps(
        [int(raw_id), document_day, category, institution],
        ensure_ascii=False,
        separators=(",", ":"),
    ).encode("utf-8")
    return f"api-document-{hashlib.sha256(b'health-api-document-v1:' + material).hexdigest()[:24]}"

def connect_read_only(database: Path) -> sqlite3.Connection:
    connection = sqlite3.connect(f"{database.resolve().as_uri()}?mode=ro", uri=True)
    connection.row_factory = sqlite3.Row
    connection.execute("PRAGMA query_only=ON")
    connection.execute("PRAGMA trusted_schema=OFF")
    deadline = time.monotonic() + QUERY_TIMEOUT_SECONDS
    connection.set_progress_handler(lambda: int(time.monotonic() > deadline), 1000)
    return connection

def table_exists(connection: sqlite3.Connection, table: str) -> bool:
    return (
        connection.execute(
            "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,)
        ).fetchone()
        is not None
    )

def parse_query(query: str, allowed: set[str]) -> dict[str, str]:
    if len(query.encode("utf-8")) > MAX_QUERY_BYTES:
        raise APIError(414, "query_too_large")
    try:
        parsed = (
            parse_qs(
                query,
                keep_blank_values=True,
                strict_parsing=True,
                max_num_fields=max(1, len(allowed) + 1),
            )
            if query
            else {}
        )
    except ValueError as error:
        raise APIError(400, "invalid_query") from error
    if not set(parsed) <= allowed:
        raise APIError(400, "unknown_parameter")
    if any(len(values) != 1 for values in parsed.values()):
        raise APIError(400, "duplicate_parameter")
    return {key: values[0] for key, values in parsed.items()}

def parse_iso_day(raw: str, *, code: str = "invalid_date") -> date:
    if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", raw):
        raise APIError(400, code)
    try:
        return date.fromisoformat(raw)
    except ValueError as error:
        raise APIError(400, code) from error

def local_today() -> date:
    return datetime.now(LOCAL_TZ).date()

def parse_range(
    params: dict[str, str], *, required: bool = False
) -> tuple[date | None, date | None]:
    raw_start = params.get("from")
    raw_end = params.get("to")
    if bool(raw_start) != bool(raw_end):
        raise APIError(400, "incomplete_range")
    if required and not raw_start:
        raise APIError(400, "range_required")
    if not raw_start:
        return None, None
    start = parse_iso_day(raw_start)
    end = parse_iso_day(raw_end or "")
    if end < start:
        raise APIError(400, "range_reversed")
    if start > local_today() or end > local_today():
        raise APIError(422, "future_range_not_allowed")
    if (end - start).days + 1 > MAX_RANGE_DAYS:
        raise APIError(422, "range_too_large")
    return start, end

def _apple_rows(
    connection: sqlite3.Connection,
    identifier: str,
    start: date | None,
    end: date | None,
    *,
    include_raw_json: bool = False,
) -> list[sqlite3.Row]:
    if include_raw_json:
        sql = """SELECT id,metric,value,unit,start_date,end_date,source_name,
                        file_name,file_hash,raw_json
                 FROM apple_health_records WHERE metric=? AND start_date IS NOT NULL"""
    else:
        sql = """SELECT id,metric,value,unit,start_date,end_date,source_name,file_name,file_hash
                 FROM apple_health_records WHERE metric=? AND start_date IS NOT NULL"""
    parameters: list[Any] = [identifier]
    # Keep the (metric,start_date) index usable with a deliberately coarse raw
    # candidate interval.  It includes one whole calendar day on either side;
    # the upper edge is exclusive so all lexical ISO values on end + 1 are kept.
    # daily_points remains the sole authority for Europe/Zurich assignment and
    # exact start/end filtering—this SQL clause never assigns a health day.
    if start is not None and start > date.min:
        sql += " AND start_date>=?"
        parameters.append((start - timedelta(days=1)).isoformat())
    # date.max cannot represent the exclusive edge after end + 1.  Omitting
    # that impossible upper bound preserves the exact canonical filter while
    # avoiding an arithmetic overflow at the ISO boundary.
    if end is not None and end < date.max - timedelta(days=1):
        sql += " AND start_date<?"
        parameters.append((end + timedelta(days=2)).isoformat())
    sql += " ORDER BY start_date,end_date,source_name,id LIMIT ?"
    parameters.append(MAX_RAW_APPLE_ROWS + 1)
    rows = list(connection.execute(sql, parameters))
    if len(rows) > MAX_RAW_APPLE_ROWS:
        raise APIError(422, "source_row_limit_exceeded")
    return rows

def _numeric(value: float, precision: int, value_type: str) -> int | float:
    rounded = round(float(value), precision)
    if value_type == "integer" or (precision == 0 and rounded.is_integer()):
        return int(rounded)
    return rounded

def _apple_points(
    connection: sqlite3.Connection,
    metric: MetricV2,
    start: date | None,
    end: date | None,
) -> list[dict[str, Any]]:
    rows = _apple_rows(connection, metric.source_identifier, start, end)
    points = daily_points(
        metric.source_identifier,
        mode=metric.aggregation,
        stable_only=False,
        start_date=start.isoformat() if start else None,
        end_date=end.isoformat() if end else None,
        _rows=rows,
    )
    result = []
    for day, point in sorted(points.items()):
        if point.unit != EXPECTED_ANALYTICS_UNITS.get(metric.source_identifier):
            continue
        result.append(
            {
                "date": day,
                "value": _numeric(point.value, metric.precision, metric.value_type),
                "quality": point.quality,
                "source_class": point.source_class,
            }


sed -n '320,700p' scripts/health/health_dashboard_action_worker.py


sed -n '300,760p' scripts/health/dashboard_v5/read_api.py


sed -n '1,300p' scripts/health/health_dashboard_server.py


sed -n '1,260p' scripts/health/dashboard_v5/contracts.py


Output:
Chunk ID: 54e684
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1720
Output:
           (datum,kcal,protein_g,carb_g,fat_g,item_count,nutrient_json,histamine_score,histamine_max,histamine_unknown_count,histamine_label,updated_at)
           VALUES(?,?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)""",
        (day, round(totals["kcal"], 1), round(totals["protein"], 1), round(totals["carb"], 1), round(totals["fat"], 1), int(totals["items"]), "{}", round(totals["load"], 1), max_score, int(totals["unknown"]), label),
    )

def apply_mapping_action(payload: dict[str, Any], action_id: str) -> None:
    if DASHBOARD_DB is None:
        raise RuntimeError("HEALTH_DASHBOARD_DB is required")
    action_hash = hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
    connection = sqlite3.connect(DASHBOARD_DB)
    connection.row_factory = sqlite3.Row
    try:
        with connection:
            ensure_nutrition_mapping_schema(connection)
            existing = connection.execute("SELECT action_hash FROM nutrition_mapping_action_log WHERE action_id=?", (action_id,)).fetchone()
            if existing is not None:
                if existing["action_hash"] != action_hash:
                    raise RuntimeError("conflicting idempotency key")
                return
            queue = connection.execute("SELECT normalized_name,example_name FROM nutrition_review_queue WHERE status='open'").fetchall()
            matched = [row for row in queue if _slug(str(row["normalized_name"])) == payload["queue_key"]]
            if len(matched) != 1:
                raise RuntimeError("mapping queue item not found")
            normalized = str(matched[0]["normalized_name"])
            canonical = payload["canonical_food"]
            score = payload["sighi_score"]
            light = payload["traffic_light"]
            affected = sorted({row["datum"] for row in connection.execute("SELECT datum FROM nutrition_items WHERE lower(name)=lower(?)", (matched[0]["example_name"],)) if row["datum"]})
            if len(affected) > 366:
                raise RuntimeError("affected day limit exceeded")
            if re.search(r"\+|,|;|\bmit\b|\bund\b", str(matched[0]["example_name"]), re.I):
                connection.execute(
                    """INSERT OR REPLACE INTO nutrition_composite_product_review
                       (normalized_name,canonical_food,status,updated_at)
                       VALUES(?,?, 'needs_ingredient_review', CURRENT_TIMESTAMP)""",
                    (normalized, canonical),
                )
                score = None
                light = "unknown"
            for row in connection.execute("SELECT id FROM nutrition_items WHERE lower(name)=lower(?)", (matched[0]["example_name"],)):
                connection.execute(
                    """INSERT OR REPLACE INTO nutrition_histamine_scores
                       (item_id,canonical_food,sighi_score,traffic_light,tags,confidence,reason,scored_at)
                       VALUES(?,?,?,?,?,?,?,CURRENT_TIMESTAMP)""",
                    (row["id"], canonical or None, score, light, "worker_mapping_v1", "medium", "local validated mapping action"),
                )
            connection.execute("UPDATE nutrition_review_queue SET status='mapped',updated_at=CURRENT_TIMESTAMP WHERE normalized_name=?", (normalized,))
            if payload["personal_tolerance"] != "unknown" and canonical:
                connection.execute(
                    """INSERT INTO personal_food_tolerance(canonical_food,personal_status,evidence_level,notes,updated_at)
                       VALUES(?,?, 'low', 'separate personal tolerance label from mapping action', CURRENT_TIMESTAMP)
                       ON CONFLICT(canonical_food) DO UPDATE SET personal_status=excluded.personal_status,updated_at=CURRENT_TIMESTAMP""",
                    (canonical, payload["personal_tolerance"]),
                )
            for day in affected:
                recompute_nutrition_day(connection, str(day))
                connection.execute(
                    """INSERT OR IGNORE INTO nutrition_mapping_provenance
                       (action_id,normalized_name,canonical_food,sighi_score,traffic_light,mapping_scope,affected_day)
                       VALUES(?,?,?,?,?,?,?)""",
                    (action_id, normalized, canonical or None, score, light, payload["mapping_scope"], str(day)),
                )
            connection.execute(
                "INSERT INTO nutrition_mapping_action_log(action_id,action_hash,queue_key) VALUES(?,?,?)",
                (action_id, action_hash, payload["queue_key"]),
            )
    finally:
        connection.close()

def apply_action(payload: dict[str, Any] | str, action_id: str | dict[str, int], notes: str | None = None) -> None:
    if isinstance(payload, str):
        if not isinstance(action_id, dict) or notes is None:
            raise ValueError("invalid legacy symptom action")
        normalized_payload: dict[str, Any] = {
            "action": "symptom_checkin",
            "date": payload,
            "scores": action_id,
            "notes": notes,
        }
        normalized_action_id = "legacy-symptom-action"
    else:
        normalized_payload = payload
        if not isinstance(action_id, str):
            raise ValueError("invalid action id")
        normalized_action_id = action_id
    if normalized_payload["action"] == "symptom_checkin":
        apply_symptom_action(normalized_payload["date"], normalized_payload["scores"], normalized_payload["notes"])
    elif normalized_payload["action"] == "nutrition_mapping":
        apply_mapping_action(normalized_payload, normalized_action_id)
    else:
        raise ValueError("unsupported action")
    if DASHBOARD_V5_FILE is not None:
        v5_command = [
            sys.executable,
            str(DASHBOARD_V5),
            "--db",
            str(DASHBOARD_DB),
            "--output",
            str(DASHBOARD_V5_FILE),
            "--today",
            local_today().isoformat(),
        ]
        if DASHBOARD_V5_PROFILE == V5_PROFILE_HEALTH_RECORD_6E:
            v5_command.append("--health-record-6e")
        subprocess.run(
            v5_command,
            check=True,
            timeout=120,
            capture_output=True,
            text=True,
        )

def main() -> int:
    if DASHBOARD_DB is None:
        print("HEALTH_DASHBOARD_DB is required", file=sys.stderr)
        return 2
    ensure_private_inbox()
    failures = 0
    for path in sorted(ACTION_INBOX.glob("*.json")):
        try:
            payload = load_action(path)
            apply_action(payload, path.stem)
            path.unlink()
        except Exception:
            failures += 1
            try:
                path.replace(path.with_suffix(".failed"))
            except OSError:
                pass
    return 1 if failures else 0

if __name__ == "__main__":
    raise SystemExit(main())


Output:
Chunk ID: 893c69
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 4416
Output:
            }
        )
    return result

def _blood_pressure_points(
    connection: sqlite3.Connection,
    metric: MetricV2,
    start: date | None,
    end: date | None,
) -> list[dict[str, Any]]:
    component = "systolic" if metric.id.endswith(".systolic") else "diastolic"
    by_day: dict[str, tuple[datetime, float]] = {}
    for row in _apple_rows(
        connection, "blood_pressure", start, end, include_raw_json=True
    ):
        try:
            timestamp = datetime.fromisoformat(
                str(row["start_date"]).replace("Z", "+00:00")
            )
            if timestamp.tzinfo is None:
                timestamp = timestamp.replace(tzinfo=LOCAL_TZ)
            day = timestamp.astimezone(LOCAL_TZ).date()
            payload = json.loads(str(row["raw_json"] or ""))
            unit = re.sub(r"[^a-z]", "", str(row["unit"] or "").casefold())
            systolic = float(payload["systolic"])
            diastolic = float(payload["diastolic"])
            if unit != "mmhg" or not all(
                math.isfinite(item) for item in (systolic, diastolic)
            ):
                continue
            value = systolic if component == "systolic" else diastolic
        except (ValueError, TypeError, KeyError, json.JSONDecodeError):
            continue
        if not math.isfinite(value):
            continue
        if start is not None and day < start:
            continue
        if end is not None and day > end:
            continue
        existing = by_day.get(day.isoformat())
        if existing is None or timestamp > existing[0]:
            by_day[day.isoformat()] = (timestamp, value)
    return [
        {
            "date": day,
            "value": _numeric(item[1], metric.precision, metric.value_type),
            "quality": "paired_observation",
            "source_class": "apple_health",
        }
        for day, item in sorted(by_day.items())
    ]

def _symptom_dimension_points(
    connection: sqlite3.Connection,
    metric: MetricV2,
    start: date | None,
    end: date | None,
) -> list[dict[str, Any]]:
    sql = "SELECT datum,schwergrad FROM symptom_log WHERE kontext='daily_quick_score' AND symptom=?"
    parameters: list[Any] = [metric.source_identifier]
    if start:
        sql += " AND datum>=?"
        parameters.append(start.isoformat())
    if end:
        sql += " AND datum<=?"
        parameters.append(end.isoformat())
    sql += " ORDER BY datum,id LIMIT ?"
    parameters.append(MAX_DAILY_SOURCE_ROWS + 1)
    rows = list(connection.execute(sql, parameters))
    if len(rows) > MAX_DAILY_SOURCE_ROWS:
        raise APIError(422, "source_row_limit_exceeded")
    grouped: dict[str, list[int | None]] = defaultdict(list)
    for row in rows:
        day = parse_day(row["datum"])
        if day:
            grouped[day].append(parse_score(row["schwergrad"]))
    return [
        {"date": day, "value": scores[0], "quality": "observed"}
        for day, scores in sorted(grouped.items())
        if len(scores) == 1 and scores[0] is not None
    ]

def _symptom_total_points(
    connection: sqlite3.Connection,
    start: date | None,
    end: date | None,
) -> list[dict[str, Any]]:
    sql = "SELECT datum,symptom,schwergrad FROM symptom_log WHERE kontext='daily_quick_score'"
    parameters: list[Any] = []
    if start:
        sql += " AND datum>=?"
        parameters.append(start.isoformat())
    if end:
        sql += " AND datum<=?"
        parameters.append(end.isoformat())
    sql += " ORDER BY datum,id LIMIT ?"
    parameters.append(MAX_DAILY_SOURCE_ROWS + 1)
    rows = list(connection.execute(sql, parameters))
    if len(rows) > MAX_DAILY_SOURCE_ROWS:
        raise APIError(422, "source_row_limit_exceeded")
    grouped: dict[str, dict[str, list[int | None]]] = defaultdict(
        lambda: defaultdict(list)
    )
    for row in rows:
        day = parse_day(row["datum"])
        label = str(row["symptom"] or "")
        if day and label in SYMPTOM_LABELS:
            grouped[day][label].append(parse_score(row["schwergrad"]))
    result = []
    for day, dimensions in sorted(grouped.items()):
        if set(dimensions) != SYMPTOM_LABELS:
            continue
        if not all(
            len(scores) == 1 and scores[0] is not None for scores in dimensions.values()
        ):
            continue
        result.append(
            {
                "date": day,
                "value": sum(int(scores[0]) for scores in dimensions.values()),
                "quality": "complete",
            }
        )
    return result

def _nutrition_points(
    connection: sqlite3.Connection,
    start: date | None,
    end: date | None,
) -> list[dict[str, Any]]:
    sql = """SELECT datum,histamine_score,item_count,histamine_unknown_count,histamine_label
             FROM nutrition_daily_summary_v2 WHERE item_count>0
               AND histamine_unknown_count=0 AND histamine_score IS NOT NULL
               AND histamine_label IN ('green','yellow','orange','red')"""
    parameters: list[Any] = []
    if start:
        sql += " AND datum>=?"
        parameters.append(start.isoformat())
    if end:
        sql += " AND datum<=?"
        parameters.append(end.isoformat())
    sql += " ORDER BY datum LIMIT ?"
    parameters.append(MAX_DAILY_SOURCE_ROWS + 1)
    rows = list(connection.execute(sql, parameters))
    if len(rows) > MAX_DAILY_SOURCE_ROWS:
        raise APIError(422, "source_row_limit_exceeded")
    result = []
    for row in rows:
        day = parse_day(row["datum"])
        try:
            value = float(row["histamine_score"])
        except (TypeError, ValueError):
            continue
        if day and math.isfinite(value):
            result.append({"date": day, "value": value, "quality": "complete"})
    return result

def _lab_key(parameter: Any, unit: Any) -> tuple[str, str]:
    def slug(value: Any) -> str:
        normalized = (
            str(value or "")
            .casefold()
            .replace("µ", "u")
            .replace("μ", "u")
            .replace("%", " percent ")
        )
        return re.sub(r"[^a-z0-9]+", "_", normalized).strip("_")

    return slug(parameter), slug(unit)

def _verified_lab_rows(
    connection: sqlite3.Connection,
    *,
    include_missing_reference: bool = False,
    start: date | None = None,
    end: date | None = None,
) -> list[dict[str, Any]]:
    if not table_exists(connection, "laborwerte"):
        return []
    date_expression = "COALESCE(NULLIF(l.abnahme_datum,''),l.befund_datum)"
    filters = [
        "lower(trim(COALESCE(l.validierungsstatus,'')))='validiert'",
        "l.verified_against_original=1",
        "l.reference_range_source='scanned_original'",
        "trim(COALESCE(l.einheit,''))<>''",
    ]
    values: list[Any] = []
    if start:
        filters.append(f"{date_expression}>=?")
        values.append(start.isoformat())
    if end:
        filters.append(f"{date_expression}<=?")
        values.append(end.isoformat())
    rows = list(
        connection.execute(
            """SELECT l.id,l.parameter_name,l.wert,l.einheit,l.reference_min,l.reference_max,
                  l.abnahme_datum,l.befund_datum,l.reference_range_source,l.source_type,
                  l.canonical_document_id,d.document_date,d.kategorie,d.institution,d.review_status
               FROM laborwerte l LEFT JOIN dokumente d ON d.id=l.canonical_document_id
               WHERE """
            + " AND ".join(filters)
            + f" ORDER BY {date_expression},l.id LIMIT ?",
            (*values, MAX_RAW_LAB_ROWS + 1),
        )
    )
    if len(rows) > MAX_RAW_LAB_ROWS:
        raise APIError(422, "source_row_limit_exceeded")
    grouped: dict[tuple[str, str, str], list[sqlite3.Row]] = defaultdict(list)
    for row in rows:
        canonical = LAB_ALLOWLIST.get(_lab_key(row["parameter_name"], row["einheit"]))
        day = parse_day(row["abnahme_datum"]) or parse_day(row["befund_datum"])
        if canonical and day and date.fromisoformat(day) <= local_today():
            grouped[(canonical[0], canonical[1], day)].append(row)
    result: list[dict[str, Any]] = []
    for (parameter, unit, day), same_day in sorted(grouped.items()):
        if len(same_day) != 1:
            continue
        row = same_day[0]
        raw_value = ("" if row["wert"] is None else str(row["wert"])).strip()
        if not EXACT_LAB_NUMBER.fullmatch(raw_value):
            continue
        numeric = float(raw_value.replace(",", "."))
        if not math.isfinite(numeric):
            continue
        value: int | float = int(numeric) if numeric.is_integer() else numeric
        reference_min = str(row["reference_min"] or "").strip()
        reference_max = str(row["reference_max"] or "").strip()
        reference_min = (
            reference_min
            if EXACT_LAB_NUMBER.fullmatch(reference_min)
            and math.isfinite(float(reference_min.replace(",", ".")))
            else None
        )
        reference_max = (
            reference_max
            if EXACT_LAB_NUMBER.fullmatch(reference_max)
            and math.isfinite(float(reference_max.replace(",", ".")))
            else None
        )
        item: dict[str, Any] = {
            "id": f"lab-observation-{int(row['id'])}",
            "metric_id": LAB_CATALOG_SPECS[parameter].metric_id,
            "parameter": parameter,
            "value": value,
            "unit": unit,
            "date": day,
            "quality": "verified_original",
        }
        if reference_min is None and reference_max is None:
            if not include_missing_reference:
                continue
            item["reference_status"] = "missing_reference"
        else:
            item["reference"] = {
                "min": reference_min,
                "max": reference_max,
                "source": "scanned_original",
            }
            item["reference_status"] = "verified_observation_specific"
        if (
            row["canonical_document_id"] is not None
            and row["review_status"] == "geprueft"
        ):
            category = safe_metadata_text(row["kategorie"], 80, allow_empty=True)
            institution = safe_metadata_text(row["institution"], 120, allow_empty=True)
            document_day = parse_day(row["document_date"])
            if category is not None and institution is not None:
                item["document"] = {
                    "id": api_document_id(
                        row["canonical_document_id"],
                        document_day,
                        category,
                        institution,
                    ),
                    "date": document_day,
                    "category": category,
                    "institution": institution,
                }
        result.append(item)
    return result

def _metric_points(
    connection: sqlite3.Connection,
    metric: MetricV2,
    start: date | None,
    end: date | None,
) -> list[dict[str, Any]]:
    if metric.value_type == "panel":
        raise APIError(400, "metric_not_series")
    if metric.source == "apple_health":
        if metric.source_identifier == "blood_pressure":
            return _blood_pressure_points(connection, metric, start, end)
        return _apple_points(connection, metric, start, end)
    if metric.id == "symptom.total":
        return _symptom_total_points(connection, start, end)
    if metric.id == "symptom.aphthae":
        return _symptom_dimension_points(connection, metric, start, end)
    if metric.id == "nutrition.histamine":
        return _nutrition_points(connection, start, end)
    if metric.source == "laborwerte":
        return [
            {
                key: row[key]
                for key in ("date", "value", "quality", "reference", "reference_status")
                if key in row
            }
            for row in _verified_lab_rows(connection, include_missing_reference=True)
            if row["metric_id"] == metric.id
            and (start is None or row["date"] >= start.isoformat())
            and (end is None or row["date"] <= end.isoformat())
        ]
    return []

def _weekly_rule(metric: MetricV2) -> dict[str, Any]:
    if metric.aggregation == "observation" or metric.value_type == "panel":
        return {
            "id": "unsupported_for_metric",
            "minimum_observations": None,
            "requires_complete_calendar_week": False,
        }
    if metric.expected_frequency == "daily":
        return {
            "id": "complete_calendar_week_daily_metric",
            "minimum_observations": 7,
            "requires_complete_calendar_week": True,
        }
    if metric.expected_frequency == "intermittent":
        return {
            "id": "observed_measurements_within_iso_week",
            "minimum_observations": 1,
            "requires_complete_calendar_week": False,
        }
    return {
        "id": "unsupported_for_metric",
        "minimum_observations": None,
        "requires_complete_calendar_week": False,
    }

def _add_past_only_baselines(points: list[dict[str, Any]], metric: MetricV2) -> None:
    rule = metric.baseline_rule
    if not rule:
        return
    window = int(rule["window_days"])
    minimum = int(rule["minimum_observations"])
    for point in points:
        day = date.fromisoformat(point["date"])
        prior = [
            float(candidate["value"])
            for candidate in points
            if date.fromisoformat(candidate["date"]) < day
            and (day - date.fromisoformat(candidate["date"])).days <= window
        ]
        point["baseline"] = (
            _numeric(float(median(prior)), metric.precision, metric.value_type)
            if len(prior) >= minimum
            else None
        )

def _weekly(
    points: list[dict[str, Any]], metric: MetricV2, rule: dict[str, Any]
) -> list[dict[str, Any]]:
    if rule["id"] == "unsupported_for_metric":
        return []
    grouped: dict[tuple[int, int], list[dict[str, Any]]] = defaultdict(list)
    for point in points:
        day = date.fromisoformat(point["date"])
        iso = day.isocalendar()
        grouped[(iso.year, iso.week)].append(point)
    result = []
    for (year, week), rows in sorted(grouped.items()):
        distinct = {row["date"] for row in rows}
        if rule["requires_complete_calendar_week"] and len(distinct) != 7:
            continue
        values = [float(row["value"]) for row in rows]
        if metric.aggregation == "sum":
            value = sum(values)
        elif metric.aggregation == "last":
            value = float(max(rows, key=lambda row: row["date"])["value"])
        else:
            value = sum(values) / len(values)
        week_start = date.fromisocalendar(year, week, 1)
        week_end = week_start + timedelta(days=6)
        item = {
            "week": f"{year}-W{week:02d}",
            "date": min(distinct),
            "week_start": week_start.isoformat(),
            "week_end": week_end.isoformat(),
            "drilldown_date": week_start.isoformat(),
            "value": _numeric(value, metric.precision, metric.value_type),
            "observation_count": len(rows),
            "observed_days": len(distinct),
            "quality": (
                "complete_calendar_week"
                if rule["requires_complete_calendar_week"]
                else "observed_measurements"
            ),
        }
        result.append(item)
    return result

def _coverage(
    points: list[dict[str, Any]], start: date | None, end: date | None
) -> dict[str, Any]:
    observed = sorted({date.fromisoformat(point["date"]) for point in points})
    effective_start = start or (observed[0] if observed else None)
    effective_end = end or (observed[-1] if observed else None)
    if effective_start is not None and effective_end is not None:
        span = (effective_end - effective_start).days + 1
        if span > MAX_RANGE_DAYS:
            raise APIError(422, "range_too_large")
    else:
        span = 0
    return {
        "from": effective_start.isoformat() if effective_start else None,
        "to": effective_end.isoformat() if effective_end else None,
        "expected_days": span,
        "observed_days": len(observed),
        "observation_count": len(points),
        "missing_days": max(0, span - len(observed)),
        "gaps": "omitted_not_interpolated",
    }

def _series(connection: sqlite3.Connection, params: dict[str, str]) -> dict[str, Any]:
    metric_id = params.get("metric", "")
    metric = BY_ID_V2.get(metric_id)
    if metric is None:
        raise APIError(404, "metric_not_allowed")
    resolution = params.get("resolution", "day")
    if resolution not in ALLOWED_RESOLUTIONS:
        raise APIError(400, "resolution_not_allowed")
    start, end = parse_range(params)
    points = _metric_points(connection, metric, start, end)
    today = local_today().isoformat()
    points = [point for point in points if point["date"] <= today]
    _add_past_only_baselines(points, metric)
    if start is None and points:
        observed_start = date.fromisoformat(points[0]["date"])
        observed_end = date.fromisoformat(points[-1]["date"])
        if (observed_end - observed_start).days + 1 > MAX_RANGE_DAYS:
            raise APIError(422, "range_too_large")
    coverage = _coverage(points, start, end)
    if end is None:
        coverage["to"] = today
        if coverage["from"] is not None:
            coverage["expected_days"] = (
                date.fromisoformat(today) - date.fromisoformat(coverage["from"])
            ).days + 1
            coverage["missing_days"] = max(
                0, coverage["expected_days"] - coverage["observed_days"]


Output:
Chunk ID: 734855
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2542
Output:
#!/usr/bin/env python3
"""Serve the local Health Dashboard with strict routes and privacy headers."""

from __future__ import annotations

import mimetypes
import json
import os
import re
import secrets
import sqlite3
import stat
import threading
import time
from datetime import date, datetime
from http.cookies import CookieError, SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, quote, unquote, urlparse
from zoneinfo import ZoneInfo

from dashboard_v5.read_api import (
    APIError,
    connect_read_only,
    dispatch_api,
    _resolve_record_document,
)
from dashboard_v5.document_originals import configured_original_roots, probe_original

BASE = Path.home() / ".hermes" / "assets" / "Gesundheit"
API_DB = (
    Path(os.environ["HEALTH_DASHBOARD_DB"]).resolve()
    if os.environ.get("HEALTH_DASHBOARD_DB")
    else None
)
DB = BASE / "health_data.db"
REPORTS = BASE / "reports"
DASHBOARD_FILE = Path(os.environ["HEALTH_DASHBOARD_FILE"]).resolve()
DASHBOARD_V5_FILE = (
    Path(os.environ["HEALTH_DASHBOARD_V5_FILE"]).resolve()
    if os.environ.get("HEALTH_DASHBOARD_V5_FILE")
    else None
)
ASSET_DIR = Path(
    os.environ.get(
        "HEALTH_DASHBOARD_ASSET_DIR",
        str(BASE / "scripts" / "assets" / "health-assets"),
    )
).resolve()
BIND_HOST = os.environ.get("HEALTH_DASHBOARD_HOST", "127.0.0.1")
BIND_PORT = int(os.environ.get("HEALTH_DASHBOARD_PORT", "8014"))
ALLOWED_HOSTS = {
    value.strip().lower().rstrip(".")
    for value in os.environ.get(
        "HEALTH_DASHBOARD_ALLOWED_HOSTS", "127.0.0.1,localhost"
    ).split(",")
    if value.strip()
}
ROUTE = "/health-dashboard"
V5_ROUTE = "/health-dashboard-v5"
ASSET_ROUTES = {
    "/health-assets/chart.umd.min.js": (
        "chart.umd.min.js",
        "text/javascript; charset=utf-8",
    ),
    "/health-assets/dashboard-v5.js": (
        "dashboard-v5.js",
        "text/javascript; charset=utf-8",
    ),
    "/health-assets/dashboard-v5-range.js": (
        "dashboard-v5-range.js",
        "text/javascript; charset=utf-8",
    ),
    "/health-assets/dashboard-v5-global-search.js": (
        "dashboard-v5-global-search.js",
        "text/javascript; charset=utf-8",
    ),
    "/health-assets/dashboard-v5-api-explorer.js": (
        "dashboard-v5-api-explorer.js",
        "text/javascript; charset=utf-8",
    ),
    "/health-assets/dashboard-v5-echarts.js": (
        "dashboard-v5-echarts.js",
        "text/javascript; charset=utf-8",
    ),
    "/health-assets/dashboard-v5-day-controller.js": (
        "dashboard-v5-day-controller.js",
        "text/javascript; charset=utf-8",
    ),
    "/health-assets/dashboard-v5-record.js": (
        "dashboard-v5-record.js",
        "text/javascript; charset=utf-8",
    ),
    "/health-assets/dashboard-v5.css": ("dashboard-v5.css", "text/css; charset=utf-8"),
    "/health-assets/echarts-6.1.0.min.js": (
        "echarts-6.1.0.min.js",
        "text/javascript; charset=utf-8",
    ),
    "/health-assets/fullcalendar-6.1.21.min.js": (
        "fullcalendar-6.1.21.min.js",
        "text/javascript; charset=utf-8",
    ),
    "/health-assets/dashboard-v5-echarts-prototype.js": (
        "dashboard-v5-echarts-prototype.js",
        "text/javascript; charset=utf-8",
    ),
}
CHECKIN_ROUTE = "/health-actions/symptom-checkin"
NUTRITION_MAPPING_ROUTE = "/health-actions/nutrition-mapping"
ACTION_INBOX = Path(
    os.environ.get(
        "HEALTH_DASHBOARD_ACTION_INBOX",
        str(BASE / "runtime" / "dashboard-actions"),
    )
).resolve()
TEST_INSTANCE_ID = os.environ.get("HEALTH_DASHBOARD_TEST_INSTANCE_ID", "").strip()
API_TOKEN_FILE = (
    Path(os.environ["HEALTH_DASHBOARD_API_TOKEN_FILE"]).expanduser()
    if os.environ.get("HEALTH_DASHBOARD_API_TOKEN_FILE")
    else None
)
BROWSER_SESSION_TTL_SECONDS = max(
    60, min(int(os.environ.get("HEALTH_DASHBOARD_BROWSER_SESSION_TTL", "900")), 3600)
)
BROWSER_SESSION_COOKIE_SECURE = (
    os.environ.get("HEALTH_DASHBOARD_BROWSER_SESSION_COOKIE_SECURE") == "1"
)
if TEST_INSTANCE_ID:
    if not re.fullmatch(r"[A-Za-z0-9_-]{8,64}", TEST_INSTANCE_ID):
        raise RuntimeError("invalid HEALTH_DASHBOARD_TEST_INSTANCE_ID")
    if not ACTION_INBOX.is_relative_to(Path("/tmp").resolve()):
        raise RuntimeError(
            "synthetic test instance requires an action inbox below /tmp"
        )
SYMPTOM_FIELDS = ("aphthen", "gi", "fatigue", "skin", "eyes", "joints", "vascular")
MAPPING_SCORES = {"0", "1", "2", "3", "unknown"}
MAPPING_LIGHTS = {"green", "yellow", "orange", "red", "unknown"}
MAPPING_SCOPES = {"canonical"}
PERSONAL_TOLERANCE = {"unknown", "safe", "problematic", "unclear"}
CSRF_TTL_SECONDS = max(
    60, min(int(os.environ.get("HEALTH_DASHBOARD_CSRF_TTL", "900")), 3600)
)
QUEUE_RECEIPT_TTL_SECONDS = 120
MAX_API_RESPONSE_BYTES = 512_000
CAPTURE_TIMEZONE = ZoneInfo("Europe/Zurich")
MAX_PENDING_ACTIONS = max(
    1, min(int(os.environ.get("HEALTH_DASHBOARD_MAX_PENDING_ACTIONS", "64")), 256)
)
MAX_ORIGINAL_BYTES = 20 * 1024 * 1024
ORIGINAL_MIME_MAGIC = (
    (b"%PDF-", "application/pdf", ".pdf"),
    (b"\x89PNG\r\n\x1a\n", "image/png", ".png"),
    (b"\xff\xd8\xff", "image/jpeg", ".jpg"),
)
ORIGINAL_ROOTS = configured_original_roots()
_csrf_tokens: dict[str, float] = {}
_csrf_lock = threading.Lock()
_queue_receipts: dict[str, float] = {}
_queue_receipt_lock = threading.Lock()
_browser_sessions: dict[str, float] = {}
_browser_session_lock = threading.Lock()
_action_lock = threading.Lock()

class QueueFullError(OSError):
    """Raised when the bounded private action queue cannot accept more work."""

def load_api_token() -> str:
    if API_TOKEN_FILE is None:
        raise OSError("read-only API authentication is not configured")
    descriptor = os.open(
        API_TOKEN_FILE,
        os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
    )
    try:
        metadata = os.fstat(descriptor)
        if (
            not stat.S_ISREG(metadata.st_mode)
            or metadata.st_uid != os.getuid()
            or stat.S_IMODE(metadata.st_mode) != 0o600
            or metadata.st_size > 256
        ):
            raise OSError("read-only API token file is not private")
        raw = os.read(descriptor, 257)
    finally:
        os.close(descriptor)
    token = raw.decode("ascii").strip()
    if not re.fullmatch(r"[A-Za-z0-9_-]{32,128}", token):
        raise OSError("read-only API token is invalid")
    return token

def api_request_is_authenticated(header: str, token: str) -> bool:
    if not header.startswith("Bearer ") or header.count(" ") != 1:
        return False
    supplied = header.removeprefix("Bearer ")
    return len(supplied) == len(token) and secrets.compare_digest(supplied, token)

def issue_browser_session() -> str:
    now = time.monotonic()
    with _browser_session_lock:
        expired = [key for key, expiry in _browser_sessions.items() if expiry <= now]
        for key in expired:
            del _browser_sessions[key]
        session_id = secrets.token_urlsafe(32)
        _browser_sessions[session_id] = now + BROWSER_SESSION_TTL_SECONDS
    return session_id

def browser_session_is_authenticated(cookie_header: str) -> bool:
    try:
        cookie = SimpleCookie(cookie_header)
    except (CookieError, ValueError):
        return False
    morsel = cookie.get("health_api_session")
    if morsel is None:
        return False
    session_id = morsel.value
    if not re.fullmatch(r"[A-Za-z0-9_-]{32,128}", session_id):
        return False
    now = time.monotonic()
    with _browser_session_lock:
        expiry = _browser_sessions.get(session_id)
        if expiry is None or expiry <= now:
            _browser_sessions.pop(session_id, None)
            return False
        return True

def resolve_doc_path(*values: object) -> Path | None:
    for value in values:
        if not value:
            continue
        raw = str(value)
        candidates = [
            Path(os.path.expanduser(raw)),
            BASE / raw,
            Path.home() / raw,
            Path(raw.replace(str(Path.home() / "Gesundheit"), str(BASE))),
        ]
        for candidate in candidates:
            try:
                resolved = candidate.resolve()
                if resolved.is_file() and (
                    resolved.is_relative_to(BASE.resolve())
                    or resolved.is_relative_to(REPORTS.resolve())
                ):
                    return resolved
            except OSError:
                continue
    return None

def document_path(doc_id: int) -> tuple[Path, str] | None:
    connection = sqlite3.connect(f"{DB.resolve().as_uri()}?mode=ro", uri=True)
    connection.execute("PRAGMA query_only=ON")
    connection.row_factory = sqlite3.Row
    try:
        row = connection.execute(
            "SELECT datei_name,dateipfad,local_original_path FROM dokumente WHERE id=?",
            (doc_id,),
        ).fetchone()
        if not row:
            return None
        path = resolve_doc_path(row["local_original_path"], row["dateipfad"])
        if not path:
            return None
        return path, str(row["datei_name"] or path.name)
    finally:
        connection.close()

def _open_regular_beneath(root: Path, candidate: Path) -> int:
    """Open each path component without following symlinks."""
    root = root.absolute()
    candidate = candidate.absolute()
    try:
        relative = candidate.relative_to(root)
    except ValueError as error:
        raise OSError("outside_root") from error
    if not relative.parts or any(part in {"", ".", ".."} for part in relative.parts):
        raise OSError("invalid_path")
    directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
    try:
        for part in relative.parts[:-1]:
            child = os.open(
                part,
                os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
                dir_fd=directory,
            )
            os.close(directory)
            directory = child
        return os.open(
            relative.parts[-1],
            os.O_RDONLY | os.O_NOFOLLOW | getattr(os, "O_NONBLOCK", 0),
            dir_fd=directory,
        )
    finally:


Output:
Chunk ID: 014123
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 3567
Output:
"""Versioned, privacy-minimised Dashboard v5 bundle contract."""
from __future__ import annotations

import json
import math
import re
from datetime import date, datetime, timedelta
from statistics import median
from typing import Any

from dashboard_v5.lab_registry import EXACT_LAB_NUMBER, PUBLIC_LAB_PAIRS
from dashboard_v5.metric_registry import public_explorer, public_registry

SCHEMA_VERSION = "health_dashboard.bundle.v2"
ALLOWED_TOP_LEVEL = {
    "schema_version", "generated_at", "timezone", "today", "metrics", "explorer", "series",
    "events", "medication", "labs", "nutrition", "tasks", "notices", "freshness",
    "correlations",
}
MAX_BUNDLE_BYTES = 512_000
MAX_METRICS = 32
MAX_SERIES_POINTS = 3_660
MAX_EVENTS = 1_000
MAX_LABS = 100
MAX_NUTRITION_DAYS = 1_000
MAX_REVIEW_ITEMS = 100
MAX_TASKS = 20
MAX_PRESETS = 16
MAX_CORRELATIONS = 4_096
PATH_LIKE = re.compile(r"^(?:/|~/|[A-Za-z]:[\\/]|file:|https?://)|(?:^|/)\.hermes(?:/|$)", re.I)

def _bounded_list(value: Any, path: str, maximum: int) -> list[Any]:
    if not isinstance(value, list):
        raise TypeError(f"{path} must be a list")
    if len(value) > maximum:
        raise ValueError(f"too many items at {path}")
    return value

def _exact(mapping: Any, keys: set[str], path: str) -> dict[str, Any]:
    if not isinstance(mapping, dict) or set(mapping) != keys:
        raise ValueError(f"invalid fields at {path}")
    return mapping

def _bounded_text(value: Any, path: str, maximum: int = 200, *, allow_empty: bool = False) -> str:
    if not isinstance(value, str):
        raise TypeError(f"non-string at {path}")
    if value != value.strip() or any(ord(char) < 32 for char in value):
        raise ValueError(f"unsafe whitespace at {path}")
    if (not value and not allow_empty) or len(value) > maximum or PATH_LIKE.search(value):
        raise ValueError(f"unsafe text at {path}")
    return value

def _iso_day(value: Any, path: str) -> str:
    text = _bounded_text(value, path, 10)
    if date.fromisoformat(text).isoformat() != text:
        raise ValueError(f"invalid day at {path}")
    return text

def _finite_optional(value: Any, path: str) -> None:
    if value is None:
        return
    if type(value) not in {int, float} or not math.isfinite(value):
        raise ValueError(f"non-finite/non-numeric value at {path}")

def _validate_metric(entry: Any, index: int) -> str:
    path = f"metrics[{index}]"
    metric = _exact(entry, {
        "id", "label", "unit", "unit_family", "raw_overlay_group", "group", "aggregation",
        "baseline_days", "baseline_min_observations", "index_mode", "correlation_id", "decimals",
    }, path)
    metric_id = _bounded_text(metric["id"], f"{path}.id", 80)
    if not re.fullmatch(r"[a-z][a-z0-9_.]*", metric_id):
        raise ValueError(f"invalid metric id at {path}")
    for field, maximum in (("label", 80), ("unit", 24), ("unit_family", 40), ("raw_overlay_group", 40), ("correlation_id", 80), ("group", 40), ("aggregation", 16)):
        _bounded_text(metric[field], f"{path}.{field}", maximum)
    if not re.fullmatch(r"[a-z][a-z0-9_:]*", metric["correlation_id"]):
        raise ValueError(f"invalid correlation id at {path}")
    if metric["index_mode"] not in {"ratio_100", "unsupported"}:
        raise ValueError(f"invalid index mode at {path}")
    if type(metric["baseline_days"]) is not int or not 1 <= metric["baseline_days"] <= 365:
        raise ValueError(f"invalid baseline at {path}")
    if type(metric["baseline_min_observations"]) is not int or not 1 <= metric["baseline_min_observations"] <= metric["baseline_days"]:
        raise ValueError(f"invalid baseline minimum at {path}")
    if type(metric["decimals"]) is not int or not 0 <= metric["decimals"] <= 4:
        raise ValueError(f"invalid decimals at {path}")
    return metric_id

def validate_bundle(bundle: dict[str, Any]) -> None:
    _exact(bundle, ALLOWED_TOP_LEVEL, "bundle")
    if bundle["schema_version"] != SCHEMA_VERSION:
        raise ValueError("unsupported schema version")
    datetime.fromisoformat(_bounded_text(bundle["generated_at"], "generated_at", 40).replace("Z", "+00:00"))
    if bundle["timezone"] != "Europe/Zurich":
        raise ValueError("unexpected timezone")
    today = _iso_day(bundle["today"], "today")

    metrics = _bounded_list(bundle["metrics"], "metrics", MAX_METRICS)
    metric_ids = {_validate_metric(entry, index) for index, entry in enumerate(metrics)}
    if len(metric_ids) != len(metrics):
        raise ValueError("duplicate metric id")
    if metrics != public_registry():
        raise ValueError("metric registry differs from the canonical server configuration")

    explorer = _exact(bundle["explorer"], {"modes", "presets"}, "explorer")
    modes = _exact(explorer["modes"], {"raw", "baseline_index"}, "explorer.modes")
    if modes["raw"] != {"max_series": 2, "compatibility": "same_raw_overlay_group"}:
        raise ValueError("invalid raw Explorer contract")
    if modes["baseline_index"] != {"max_series": 4, "reference": 100}:
        raise ValueError("invalid baseline Explorer contract")
    metric_by_id = {entry["id"]: entry for entry in metrics}
    preset_ids: set[str] = set()
    presets = _bounded_list(explorer["presets"], "explorer.presets", MAX_PRESETS)
    for index, entry in enumerate(presets):
        path = f"explorer.presets[{index}]"
        preset = _exact(entry, {"id", "label", "mode", "metric_ids"}, path)
        preset_id = _bounded_text(preset["id"], f"{path}.id", 60)
        _bounded_text(preset["label"], f"{path}.label", 80)
        if preset_id in preset_ids or preset["mode"] not in modes:
            raise ValueError(f"invalid preset at {path}")
        preset_ids.add(preset_id)
        selected = preset["metric_ids"]
        if not isinstance(selected, list) or not selected or len(selected) != len(set(selected)):
            raise ValueError(f"invalid preset metrics at {path}")
        maximum = modes[preset["mode"]]["max_series"]
        if len(selected) > maximum or any(metric_id not in metric_ids for metric_id in selected):
            raise ValueError(f"preset exceeds allowlist or limit at {path}")
        if preset["mode"] == "raw":
            groups = {metric_by_id[metric_id]["raw_overlay_group"] for metric_id in selected}
            if len(groups) != 1:
                raise ValueError(f"incompatible raw preset at {path}")
        elif any(metric_by_id[metric_id]["index_mode"] != "ratio_100" for metric_id in selected):
            raise ValueError(f"unsupported index preset at {path}")
    if explorer != public_explorer():
        raise ValueError("Explorer registry differs from the canonical server configuration")

    if not isinstance(bundle["series"], dict) or set(bundle["series"]) != metric_ids:
        raise ValueError("series must exactly match the metric registry")
    for metric_id, points_value in bundle["series"].items():
        points = _bounded_list(points_value, f"series.{metric_id}", MAX_SERIES_POINTS)
        metric = metric_by_id[metric_id]
        previous_day: str | None = None
        observed: list[tuple[date, float]] = []
        for index, entry in enumerate(points):
            path = f"series.{metric_id}[{index}]"
            point = _exact(entry, {"date", "value", "quality", "baseline"}, path)
            day = _iso_day(point["date"], f"{path}.date")
            if day > today:
                raise ValueError(f"future measurement day at {path}")
            if previous_day is not None and day <= previous_day:
                raise ValueError(f"series dates must be strictly ascending at {path}")
            previous_day = day
            _finite_optional(point["value"], f"{path}.value")
            _finite_optional(point["baseline"], f"{path}.baseline")
            quality = point["quality"]
            if quality not in {"complete", "observed", "incomplete"}:
                raise ValueError(f"invalid quality at {path}")
            if (quality == "incomplete") != (point["value"] is None):
                raise ValueError(f"inconsistent value/quality at {path}")
            current_day = date.fromisoformat(day)
            start = current_day - timedelta(days=metric["baseline_days"])
            prior = [value for prior_day, value in observed if start <= prior_day < current_day]
            expected_baseline = round(median(prior), 3) if len(prior) >= metric["baseline_min_observations"] else None
            if expected_baseline is None:
                if point["baseline"] is not None:
                    raise ValueError(f"premature baseline at {path}")
            elif point["baseline"] is None or not math.isclose(float(point["baseline"]), expected_baseline, rel_tol=0, abs_tol=1e-9):
                raise ValueError(f"incorrect baseline at {path}")
            if point["value"] is not None:
                observed.append((current_day, float(point["value"])))

    events = _bounded_list(bundle["events"], "events", MAX_EVENTS)
    for index, entry in enumerate(events):
        event = _exact(entry, {"date", "type", "label"}, f"events[{index}]")
        event_day = _iso_day(event["date"], f"events[{index}].date")
        if event_day > today or event["type"] != "medication_administered":
            raise ValueError(f"invalid event day or type at events[{index}]")
        _bounded_text(event["type"], f"events[{index}].type", 40)
        _bounded_text(event["label"], f"events[{index}].label", 120)

    medication = _exact(bundle["medication"], {"last_administered", "next_planned"}, "medication")
    for field, keys in (
        ("last_administered", {"date", "name", "dose"}),
        ("next_planned", {"date", "name", "dose", "status"}),
    ):
        item = medication[field]
        if item is None:
            continue
        item = _exact(item, keys, f"medication.{field}")
        medication_day = _iso_day(item["date"], f"medication.{field}.date")
        if (field == "last_administered" and medication_day > today) or (field == "next_planned" and medication_day <= today):
            raise ValueError(f"invalid medication date at medication.{field}")
        _bounded_text(item["name"], f"medication.{field}.name", 120)
        _bounded_text(item["dose"], f"medication.{field}.dose", 40, allow_empty=True)
        if field == "next_planned" and item["status"] != "planned":
            raise ValueError("invalid planned medication status")

    labs = _bounded_list(bundle["labs"], "labs", MAX_LABS)
    for index, entry in enumerate(labs):
        path = f"labs[{index}]"
        lab = _exact(entry, {"parameter", "value", "unit", "date", "reference_min", "reference_max", "quality", "source_type"}, path)
        for field, maximum in (("parameter", 100), ("value", 32), ("unit", 24), ("source_type", 32)):
            _bounded_text(lab[field], f"{path}.{field}", maximum)
        for field in ("reference_min", "reference_max"):
            if lab[field] is not None:
                reference_value = str(lab[field]).strip()
                _bounded_text(reference_value, f"{path}.{field}", 32)
                if not EXACT_LAB_NUMBER.fullmatch(reference_value):
                    raise ValueError(f"non-numeric lab reference at {path}.{field}")
        if _iso_day(lab["date"], f"{path}.date") > today:
            raise ValueError(f"future lab day at {path}")
        if not EXACT_LAB_NUMBER.fullmatch(lab["value"]):
            raise ValueError(f"non-numeric verified lab value at {path}")
        if lab["quality"] != "verified_original" or lab["source_type"] != "scanned_original":
            raise ValueError(f"invalid lab provenance at {path}")
        if (lab["parameter"], lab["unit"]) not in PUBLIC_LAB_PAIRS:
            raise ValueError(f"non-allowlisted lab parameter/unit at {path}")

    nutrition = _exact(bundle["nutrition"], {"daily", "mapping_review", "mapping_open_count"}, "nutrition")
    if type(nutrition["mapping_open_count"]) is not int or nutrition["mapping_open_count"] < 0:
        raise ValueError("invalid mapping count")
    daily_rows = _bounded_list(nutrition["daily"], "nutrition.daily", MAX_NUTRITION_DAYS)
    previous_nutrition_day: str | None = None
    for index, entry in enumerate(daily_rows):
        path = f"nutrition.daily[{index}]"
        row = _exact(entry, {"date", "kcal", "item_count", "histamine_score", "histamine_status", "unknown_items", "quality"}, path)
        nutrition_day = _iso_day(row["date"], f"{path}.date")
        if nutrition_day > today or (previous_nutrition_day is not None and nutrition_day <= previous_nutrition_day):
            raise ValueError(f"invalid nutrition date order at {path}")
        previous_nutrition_day = nutrition_day
        for field in ("kcal", "histamine_score"):
            _finite_optional(row[field], f"{path}.{field}")
        for field in ("item_count", "unknown_items"):
            if row[field] is not None and (type(row[field]) is not int or row[field] < 0):
                raise ValueError(f"invalid count at {path}.{field}")
        if row["histamine_status"] not in {"green", "yellow", "orange", "red", "unknown"}:
            raise ValueError(f"invalid histamine status at {path}")
        if row["quality"] not in {"complete", "incomplete"}:
            raise ValueError(f"invalid nutrition quality at {path}")
        if row["quality"] == "complete":
            if row["histamine_score"] is None or row["histamine_status"] == "unknown" or row["unknown_items"] != 0:
                raise ValueError(f"inconsistent complete nutrition row at {path}")
        elif row["histamine_score"] is not None or row["histamine_status"] != "unknown":
            raise ValueError(f"inconsistent incomplete nutrition row at {path}")
    review_rows = _bounded_list(nutrition["mapping_review"], "nutrition.mapping_review", MAX_REVIEW_ITEMS)
    for index, entry in enumerate(review_rows):
        path = f"nutrition.mapping_review[{index}]"
        allowed = {
            "name", "occurrences", "reason", "queue_key", "suggested_canonical_food",
            "suggested_score", "suggested_traffic_light",
        }
        if not isinstance(entry, dict) or not {"name", "occurrences", "reason"} <= set(entry) <= allowed:
            raise ValueError(f"invalid fields at {path}")
        row = entry


sed -n '260,620p' scripts/health/dashboard_v5/contracts.py


sed -n '300,700p' scripts/health/health_dashboard_server.py


sed -n '760,1180p' scripts/health/dashboard_v5/read_api.py


sed -n '1,360p' scripts/health/assets/health-assets/dashboard-v5.js


Output:
Chunk ID: 76d091
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1610
Output:
        row = entry
        _bounded_text(row["name"], f"{path}.name", 160)
        _bounded_text(row["reason"], f"{path}.reason", 120)
        if type(row["occurrences"]) is not int or row["occurrences"] < 0:
            raise ValueError(f"invalid occurrences at {path}")
        if "queue_key" in row:
            if not isinstance(row["queue_key"], str) or not re.fullmatch(r"[a-z0-9_]{0,80}", row["queue_key"]):
                raise ValueError(f"invalid queue key at {path}")
        if "suggested_canonical_food" in row:
            _bounded_text(row["suggested_canonical_food"], f"{path}.suggested_canonical_food", 120, allow_empty=True)
        if "suggested_score" in row and row["suggested_score"] not in {0, 1, 2, 3, "unknown"}:
            raise ValueError(f"invalid suggested score at {path}")
        if "suggested_traffic_light" in row and row["suggested_traffic_light"] not in {"green", "yellow", "orange", "red", "unknown"}:
            raise ValueError(f"invalid suggested traffic light at {path}")

    tasks = _bounded_list(bundle["tasks"], "tasks", min(MAX_TASKS, 3))
    for index, entry in enumerate(tasks):
        allowed = {"id", "label", "action", "count"}
        if not isinstance(entry, dict) or not {"id", "label", "action"} <= set(entry) <= allowed:
            raise ValueError(f"invalid task at {index}")
        for field in ("id", "label", "action"):
            _bounded_text(entry[field], f"tasks[{index}].{field}", 120)
        if "count" in entry and (type(entry["count"]) is not int or entry["count"] < 0):
            raise ValueError(f"invalid task count at {index}")

    if bundle["notices"] != [] or bundle["freshness"] != []:
        raise ValueError("notices/freshness are reserved in bundle v2")

    import multimodal_correlations as engine

    correlations = _exact(bundle["correlations"], {"dimensions", "results"}, "correlations")
    dimensions = _exact(correlations["dimensions"], {"lag_days", "medication_phases", "lag_direction"}, "correlations.dimensions")
    if dimensions != {
        "lag_days": list(engine.LAGS),
        "medication_phases": sorted(engine.ALLOWED_PHASES),
        "lag_direction": "predictor_d_to_target_d_plus_lag",
    }:
        raise ValueError("invalid correlation dimensions")
    result_rows = _bounded_list(correlations["results"], "correlations.results", MAX_CORRELATIONS)
    previous_order: tuple[str, str, int, str] | None = None
    base_flags = ["complete_case", "phase_stratified", "7d_block_permutation", "no_causality"]
    for index, entry in enumerate(result_rows):
        path = f"correlations.results[{index}]"
        row = _exact(entry, {"id", "dimensions", "sample", "statistics", "status", "method", "quality_flags"}, path)
        identity = _exact(row["id"], {"predictor", "target"}, f"{path}.id")
        dims = _exact(row["dimensions"], {"lag_days", "medication_phase"}, f"{path}.dimensions")
        sample = _exact(row["sample"], {"eligible_target_days", "expected_target_days", "observed_pairs", "missing_pairs", "target_coverage"}, f"{path}.sample")
        statistics = _exact(row["statistics"], {"rho", "p_value", "q_value"}, f"{path}.statistics")
        if identity["predictor"] not in engine.ALLOWED_PREDICTORS or identity["target"] not in engine.ALLOWED_TARGETS:
            raise ValueError(f"unallowlisted correlation identity at {path}")
        if dims["lag_days"] not in engine.LAGS or dims["medication_phase"] not in engine.ALLOWED_PHASES:
            raise ValueError(f"invalid correlation dimensions at {path}")
        if row["status"] not in engine.ALLOWED_STATUSES or row["method"] != engine.METHOD:
            raise ValueError(f"invalid correlation status or method at {path}")
        order = (identity["predictor"], identity["target"], dims["lag_days"], dims["medication_phase"])
        if previous_order is not None and order <= previous_order:
            raise ValueError("correlation results are not uniquely and deterministically ordered")
        previous_order = order
        counts = [sample[key] for key in ("observed_pairs", "eligible_target_days", "expected_target_days", "missing_pairs")]
        if any(type(value) is not int or value < 0 for value in counts):
            raise ValueError(f"invalid correlation counts at {path}")
        n, eligible, expected, missing = counts
        if expected < 1 or not n <= eligible <= expected or missing != eligible - n:
            raise ValueError(f"inconsistent correlation counts at {path}")
        coverage = sample["target_coverage"]
        _finite_optional(coverage, f"{path}.sample.target_coverage")
        if not 0 <= coverage <= 1 or not math.isclose(coverage, eligible / expected, rel_tol=0, abs_tol=5e-7):
            raise ValueError(f"inconsistent target coverage at {path}")
        for field, lower, upper in (("rho", -1, 1), ("p_value", 0, 1), ("q_value", 0, 1)):
            value = statistics[field]
            _finite_optional(value, f"{path}.statistics.{field}")
            if value is not None and not lower <= value <= upper:
                raise ValueError(f"out-of-range statistic at {path}.{field}")
        if row["status"] == "computed":
            if any(statistics[field] is None for field in statistics) or coverage < engine.MIN_TARGET_COVERAGE or n < engine.MIN_PAIRS:
                raise ValueError(f"inconsistent computed result at {path}")
            expected_flags = base_flags
        elif row["status"] == "insufficient_coverage":
            if any(statistics[field] is not None for field in statistics) or coverage >= engine.MIN_TARGET_COVERAGE:
                raise ValueError(f"inconsistent low-coverage result at {path}")
            expected_flags = base_flags + ["low_target_coverage"]
        else:
            if any(statistics[field] is not None for field in statistics) or coverage < engine.MIN_TARGET_COVERAGE:
                raise ValueError(f"inconsistent low-n result at {path}")
            expected_flags = base_flags + ["low_n_or_variance"]
        if row["quality_flags"] != expected_flags:
            raise ValueError(f"invalid quality flags at {path}")

def safe_json(bundle: dict[str, Any]) -> str:
    validate_bundle(bundle)
    payload = json.dumps(bundle, ensure_ascii=False, separators=(",", ":")).replace("<", "\\u003c")
    if len(payload.encode("utf-8")) > MAX_BUNDLE_BYTES:
        raise ValueError("bundle exceeds serialized size budget")
    return payload


Output:
Chunk ID: e1f3b5
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 3708
Output:
    finally:
        os.close(directory)

def open_verified_original(
    database: Path, opaque: str
) -> tuple[int, int, str, str] | None:
    """Resolve a reviewed document and pin the same descriptor used by HEAD/GET."""
    connection = connect_read_only(database)
    try:
        row = _resolve_record_document(connection, opaque, reviewed=True)
    except APIError:
        return None
    finally:
        connection.close()
    roots = (
        ORIGINAL_ROOTS
        if os.environ.get("HEALTH_DASHBOARD_ORIGINAL_ROOTS")
        else (BASE.absolute(), REPORTS.absolute())
    )
    probe = probe_original(
        row["local_original_path"] or row["dateipfad"],
        reviewed=True,
        roots=roots,
        max_bytes=MAX_ORIGINAL_BYTES,
        opener=_open_regular_beneath,
    )
    if probe.status != "available" or probe.descriptor is None:
        probe.close()
        return None
    return probe.descriptor, probe.size, probe.mime, probe.download_name

def safe_report_path(name: str) -> Path | None:
    clean = Path(unquote(name)).name
    path = (REPORTS / clean).resolve()
    try:
        if path.is_file() and path.is_relative_to(REPORTS.resolve()):
            return path
    except OSError:
        return None
    return None

def canonical_request_host(raw_host: str) -> str | None:
    if not raw_host or any(char in raw_host for char in ("/", "@", "\\")):
        return None
    try:
        parsed = urlparse("//" + raw_host)
        host = parsed.hostname
        _ = parsed.port
    except ValueError:
        return None
    return host.lower().rstrip(".") if host else None

def host_is_allowed(raw_host: str) -> bool:
    host = canonical_request_host(raw_host)
    return host is not None and host in ALLOWED_HOSTS

def origin_matches_request(origin: str, raw_host: str) -> bool:
    try:
        request_authority = urlparse("//" + raw_host)
        supplied = urlparse(origin)
        request_port = request_authority.port
        supplied_port = supplied.port
    except ValueError:
        return False
    if (
        supplied.scheme != "http"
        or not supplied.hostname
        or supplied.username is not None
        or supplied.password is not None
        or supplied.path
        or supplied.params
        or supplied.query
        or supplied.fragment
    ):
        return False
    request_host = request_authority.hostname
    return (
        request_host is not None
        and supplied.hostname.lower().rstrip(".") == request_host.lower().rstrip(".")
        and supplied_port == request_port
    )

def issue_csrf_token(now: float | None = None) -> str:
    issued_at = time.monotonic() if now is None else now
    token = secrets.token_urlsafe(24)
    with _csrf_lock:
        expired = [
            existing
            for existing, timestamp in _csrf_tokens.items()
            if issued_at - timestamp > CSRF_TTL_SECONDS
        ]
        for existing in expired:
            _csrf_tokens.pop(existing, None)
        _csrf_tokens[token] = issued_at
        while len(_csrf_tokens) > 256:
            oldest = min(_csrf_tokens, key=_csrf_tokens.get)  # type: ignore[arg-type]
            _csrf_tokens.pop(oldest, None)
    return token

def consume_csrf_token(token: str, now: float | None = None) -> bool:
    checked_at = time.monotonic() if now is None else now
    with _csrf_lock:
        issued_at = _csrf_tokens.pop(token, None)
    return issued_at is not None and 0 <= checked_at - issued_at <= CSRF_TTL_SECONDS

def issue_queue_receipt(now: float | None = None) -> str:
    issued_at = time.monotonic() if now is None else now
    token = secrets.token_urlsafe(18)
    with _queue_receipt_lock:
        _queue_receipts[token] = issued_at
        expired = [
            key
            for key, timestamp in _queue_receipts.items()
            if issued_at - timestamp > QUEUE_RECEIPT_TTL_SECONDS
        ]
        for key in expired:
            _queue_receipts.pop(key, None)
        while len(_queue_receipts) > 256:
            oldest = min(_queue_receipts, key=_queue_receipts.get)  # type: ignore[arg-type]
            _queue_receipts.pop(oldest, None)
    return token

def consume_queue_receipt(token: str, now: float | None = None) -> bool:
    checked_at = time.monotonic() if now is None else now
    with _queue_receipt_lock:
        issued_at = _queue_receipts.pop(token, None)
    return (
        issued_at is not None
        and 0 <= checked_at - issued_at <= QUEUE_RECEIPT_TTL_SECONDS
    )

def dashboard_html_with_nonce(
    path: Path,
    *,
    capture_queued: bool = False,
) -> tuple[bytes, str, str, str]:
    nonce = secrets.token_urlsafe(18)
    csrf_token = issue_csrf_token()
    browser_session_csrf_token = issue_csrf_token()
    text = path.read_text(encoding="utf-8")
    capture_day = local_today()
    text = text.replace("__CSRF_TOKEN__", csrf_token)
    text = text.replace("__BROWSER_SESSION_CSRF__", browser_session_csrf_token)
    text = text.replace("__CAPTURE_QUEUED__", "true" if capture_queued else "false")
    text = text.replace("__CAPTURE_DATE__", capture_day.isoformat())
    text = text.replace("__CAPTURE_DATE_LABEL__", capture_day.strftime("%d.%m.%Y"))
    text = text.replace("<script", f"<script nonce='{nonce}'")
    text = text.replace("<style", f"<style nonce='{nonce}'")
    return text.encode("utf-8"), nonce, csrf_token, browser_session_csrf_token

def local_today() -> date:
    return datetime.now(CAPTURE_TIMEZONE).date()

def validate_symptom_form(
    form: dict[str, list[str]],
) -> tuple[str, dict[str, int], str]:
    day = (form.get("date") or [""])[0]
    try:
        parsed_day = date.fromisoformat(day)
    except ValueError as exc:
        raise ValueError("invalid date") from exc
    if parsed_day.year < 2000 or parsed_day > local_today():
        raise ValueError("date outside allowed range")
    scores: dict[str, int] = {}
    for field in SYMPTOM_FIELDS:
        raw = (form.get(field) or [""])[0]
        if raw not in {"0", "1", "2", "3"}:
            raise ValueError(f"invalid or missing score: {field}")
        scores[field] = int(raw)
    notes = (form.get("notes") or [""])[0].strip()
    if len(notes) > 300:
        raise ValueError("notes too long")
    return parsed_day.isoformat(), scores, notes

def validate_symptom_submission(
    form: dict[str, list[str]],
) -> tuple[str, dict[str, int], str, str]:
    required = {"csrf_token", "date", "notes", *SYMPTOM_FIELDS}
    allowed = required | {"return_to"}
    keys = frozenset(form)
    if keys not in {frozenset(required), frozenset(allowed)}:
        raise ValueError("invalid submission shape")
    if any(len(values) != 1 for values in form.values()):
        raise ValueError("every field must have a single value")
    return_to = form.get("return_to", ["v4"])[0]
    if return_to not in {"v4", "v5"}:
        raise ValueError("invalid return target")
    day, scores, notes = validate_symptom_form(form)
    return day, scores, notes, return_to

def validate_mapping_submission(form: dict[str, list[str]]) -> tuple[dict[str, object], str]:
    required = {
        "csrf_token",
        "queue_key",
        "canonical_food",
        "sighi_score",
        "traffic_light",
        "mapping_scope",
        "personal_tolerance",
        "return_to",
    }
    if frozenset(form) != frozenset(required) or any(len(values) != 1 for values in form.values()):
        raise ValueError("invalid mapping shape")
    return_to = form["return_to"][0]
    if return_to != "v5":
        raise ValueError("invalid return target")
    queue_key = form["queue_key"][0].strip()
    canonical_food = " ".join(form["canonical_food"][0].split())
    score = form["sighi_score"][0]
    traffic_light = form["traffic_light"][0]
    scope = form["mapping_scope"][0]
    tolerance = form["personal_tolerance"][0]
    if not re.fullmatch(r"[a-z0-9_]{1,80}", queue_key):
        raise ValueError("invalid queue key")
    if len(canonical_food) > 120 or re.search(r"[\x00-\x1f\x7f]|https?://|/|\\\\|\.hermes", canonical_food, re.I):
        raise ValueError("invalid canonical food")
    if score not in MAPPING_SCORES or traffic_light not in MAPPING_LIGHTS or scope not in MAPPING_SCOPES or tolerance not in PERSONAL_TOLERANCE:
        raise ValueError("invalid mapping value")
    if score == "unknown" and traffic_light != "unknown":
        raise ValueError("unknown score must keep unknown light")
    if score != "unknown" and not canonical_food:
        raise ValueError("canonical food required")
    return {
        "version": 1,
        "action": "nutrition_mapping",
        "queue_key": queue_key,
        "canonical_food": canonical_food,
        "sighi_score": None if score == "unknown" else int(score),
        "traffic_light": traffic_light,
        "mapping_scope": scope,
        "personal_tolerance": tolerance,
    }, return_to

def ensure_private_inbox() -> None:
    ACTION_INBOX.mkdir(mode=0o700, parents=True, exist_ok=True)
    metadata = ACTION_INBOX.lstat()
    if not stat.S_ISDIR(metadata.st_mode) or metadata.st_uid != os.getuid():
        raise OSError("action inbox is not a private owned directory")
    os.chmod(ACTION_INBOX, 0o700)

def write_action_payload(payload: dict[str, object]) -> None:
    """Atomically enqueue a validated action; the network server never writes the DB."""
    with _action_lock:
        ensure_private_inbox()
        if sum(1 for _ in ACTION_INBOX.glob("*.json")) >= MAX_PENDING_ACTIONS:
            raise QueueFullError("private action queue is full")
        token = secrets.token_hex(16)
        temporary = ACTION_INBOX / f".{token}.tmp"
        destination = ACTION_INBOX / f"{token}.json"
        packed = json.dumps(
            payload,
            ensure_ascii=False,
            separators=(",", ":"),
        ).encode("utf-8")
        descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        try:
            with os.fdopen(descriptor, "wb") as handle:
                handle.write(packed)
                handle.flush()
                os.fsync(handle.fileno())
            temporary.replace(destination)
            directory = os.open(ACTION_INBOX, os.O_RDONLY | os.O_DIRECTORY)
            try:
                os.fsync(directory)
            finally:
                os.close(directory)
        except Exception:
            temporary.unlink(missing_ok=True)
            raise

def write_symptom_checkin(day: str, scores: dict[str, int], notes: str) -> None:
    write_action_payload(
        {
            "version": 1,
            "action": "symptom_checkin",
            "date": day,
            "scores": scores,
            "notes": notes,
        }
    )

class Handler(BaseHTTPRequestHandler):
    def send_error(
        self,
        code: int,
        message: str | None = None,
        explain: str | None = None,
    ) -> None:
        request_path = urlparse(getattr(self, "path", "")).path
        if request_path.startswith("/api/v1/"):
            send_body = getattr(self, "command", "") != "HEAD"
            if not host_is_allowed(self.headers.get("Host", "")):
                self._send_api_error(421, "invalid_host", send_body)
                return
            status = 405 if code == 501 else code
            error_code = "read_only_endpoint" if code == 501 else "request_rejected"
            self._send_api_error(status, error_code, send_body)
            return
        super().send_error(code, message, explain)

    def _reject_unsupported(self) -> None:
        if not host_is_allowed(self.headers.get("Host", "")):
            if urlparse(self.path).path.startswith("/api/v1/"):
                self._send_api_error(421, "host_not_allowed", self.command != "HEAD")
            else:
                self.send_error(421)
            return
        if urlparse(self.path).path.startswith("/api/v1/"):
            self._send_api_error(405, "read_only_endpoint", self.command != "HEAD")
            return
        self.send_error(405)

    do_OPTIONS = _reject_unsupported  # noqa: N815
    do_PUT = _reject_unsupported  # noqa: N815
    do_DELETE = _reject_unsupported  # noqa: N815
    do_PATCH = _reject_unsupported  # noqa: N815
    do_TRACE = _reject_unsupported  # noqa: N815
    do_CONNECT = _reject_unsupported  # noqa: N815

    def do_HEAD(self) -> None:  # noqa: N802
        if not host_is_allowed(self.headers.get("Host", "")):
            if urlparse(self.path).path.startswith("/api/v1/"):
                self._send_api_error(421, "host_not_allowed", False)
            else:
                self.send_error(421)
            return
        self._handle(send_body=False)

    def do_GET(self) -> None:  # noqa: N802
        if not host_is_allowed(self.headers.get("Host", "")):
            if urlparse(self.path).path.startswith("/api/v1/"):
                self._send_api_error(421, "host_not_allowed", True)
            else:
                self.send_error(421)
            return
        self._handle(send_body=True)

    def do_POST(self) -> None:  # noqa: N802
        if not host_is_allowed(self.headers.get("Host", "")):
            if urlparse(self.path).path.startswith("/api/v1/"):
                self._send_api_error(421, "host_not_allowed", True)
            else:
                self.send_error(421)
            return
        api_path = urlparse(self.path).path
        if api_path.startswith("/api/v1/"):
            if api_path == "/api/v1/browser-session":
                self._handle_browser_session(True)
            else:
                self._send_api_error(405, "read_only_endpoint", True)
            return
        action_path = urlparse(self.path).path
        if action_path not in {CHECKIN_ROUTE, NUTRITION_MAPPING_ROUTE}:
            self.send_error(404)
            return
        origin = self.headers.get("Origin", "")
        host = self.headers.get("Host", "")
        if not origin_matches_request(origin, host):
            self.send_error(403)
            return
        if self.headers.get_content_type() != "application/x-www-form-urlencoded":
            self.send_error(415)
            return
        try:
            length = int(self.headers.get("Content-Length", "0"))
        except ValueError:
            self.send_error(400)
            return
        if length < 1 or length > 4096:
            self.send_error(413)
            return
        try:
            form = parse_qs(
                self.rfile.read(length).decode("utf-8"),
                keep_blank_values=True,
                strict_parsing=True,
            )
        except (UnicodeError, ValueError):
            self.send_error(400)
            return
        token = (form.get("csrf_token") or [""])[0]
        cookie = SimpleCookie(self.headers.get("Cookie", ""))
        cookie_token = cookie.get("health_csrf")