Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(api): serialize response datetimes as UTC (#2220)
Just One More Night82de6732476c
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex 78b1ca04a..6c4a1a976 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -11,6 +11,7 @@ import importlibfrom typing import TYPE_CHECKING, Anyif TYPE_CHECKING:+ from ._datetime import UTCDateTimefrom .architecture import (ArchEdgeResponse,ArchitectureViewResponse,@@ -352,6 +353,7 @@ if TYPE_CHECKING:# Loaded on first access (PEP 562), so importing one model does not pay for# every submodule, one of which pulls in the whole dead-code analyzer._EXPORTS: dict[str, tuple[str, ...]] = {+ "_datetime": ("UTCDateTime",),"architecture": ("ArchEdgeResponse","ArchitectureViewResponse",@@ -910,6 +912,7 @@ __all__ = ["SymbolResponse","TableView","TransitiveEntry",+ "UTCDateTime","UnclusteredFiles","UpdateMcpToolsRequest","VersionResponse",diff --git a/packages/server/src/repowise/server/schemas/_datetime.py b/packages/server/src/repowise/server/schemas/_datetime.pynew file mode 100644index 000000000..96a511c87--- /dev/null+++ b/packages/server/src/repowise/server/schemas/_datetime.py@@ -0,0 +1,26 @@+"""Shared datetime types for the REST API."""++from __future__ import annotations++from datetime import UTC, datetime+from typing import Annotated++from pydantic import PlainSerializer+++def _serialize_utc(value: datetime) -> str:+ """Serialize an instant as an explicit UTC ISO-8601 value.++ SQLite drops ``tzinfo`` when round-tripping SQLAlchemy datetime columns,+ while PostgreSQL preserves it. The persistence layer stores these values as+ UTC, so a naive value read from SQLite is UTC as well. Stamping it here+ keeps every REST client from interpreting it as local browser time.+ """+ value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return value.isoformat().replace("+00:00", "Z")+++UTCDateTime = Annotated[+ datetime,+ PlainSerializer(_serialize_utc, return_type=str, when_used="json"),+]diff --git a/packages/server/src/repowise/server/schemas/actions.py b/packages/server/src/repowise/server/schemas/actions.pyindex 1cce61e3e..863bdfff4 100644--- a/packages/server/src/repowise/server/schemas/actions.py+++ b/packages/server/src/repowise/server/schemas/actions.py@@ -2,12 +2,12 @@from __future__ import annotations-from datetime import datetimefrom typing import Literalfrom pydantic import BaseModel, Fieldfrom repowise.core.analysis.next_call import ActionCommand+from repowise.server.schemas._datetime import UTCDateTimeclass ActionWhy(BaseModel):@@ -113,7 +113,7 @@ class ActionStateRequest(BaseModel):class ActionStateResponse(BaseModel):action_id: strstate: Literal["dismissed", "snoozed", "done"] | None- until: datetime | None = None+ until: UTCDateTime | None = Noneclass WorkspaceRepoActions(BaseModel):diff --git a/packages/server/src/repowise/server/schemas/chat.py b/packages/server/src/repowise/server/schemas/chat.pyindex c3878b9cb..b5b336f04 100644--- a/packages/server/src/repowise/server/schemas/chat.py+++ b/packages/server/src/repowise/server/schemas/chat.py@@ -3,12 +3,12 @@from __future__ import annotationsimport json-from datetime import datetimefrom typing import Any, Literalfrom pydantic import BaseModel, Fieldfrom repowise.server.chat_artifacts import normalize_message_artifacts+from repowise.server.schemas._datetime import UTCDateTimefrom repowise.server.schemas.evidence import CardRef@@ -69,8 +69,8 @@ class ConversationResponse(BaseModel):title: strmessage_count: int = 0pinned: bool = False- created_at: datetime- updated_at: datetime+ created_at: UTCDateTime+ updated_at: UTCDateTime@classmethoddef from_orm(cls, obj: object, message_count: int = 0) -> ConversationResponse:@@ -104,7 +104,7 @@ class ChatMessageResponse(BaseModel):conversation_id: strrole: strcontent: dict- created_at: datetime+ created_at: UTCDateTime@classmethoddef from_orm(cls, obj: object) -> ChatMessageResponse:diff --git a/packages/server/src/repowise/server/schemas/code_quality.py b/packages/server/src/repowise/server/schemas/code_quality.pyindex e7f135a6f..8b77f52e5 100644--- a/packages/server/src/repowise/server/schemas/code_quality.py+++ b/packages/server/src/repowise/server/schemas/code_quality.py@@ -3,7 +3,6 @@from __future__ import annotationsimport json-from datetime import datetimefrom typing import Literalfrom pydantic import BaseModel, Field@@ -13,6 +12,7 @@ from repowise.core.analysis.dead_code.risk_factors import (path_risk_factors,)from repowise.core.analysis.finding_registry import preview_label, verification_label+from repowise.server.schemas._datetime import UTCDateTimefrom .preview import PreviewLabelled@@ -44,7 +44,7 @@ class DeadCodeFindingResponse(PreviewLabelled, BaseModel):# confidence ladder. Deliberately not ``age_days``: that is measured from# the *first* commit, so it answers "how old is this file", not "how long# has this been dead", and the two disagree on 75% of findings.- last_commit_at: datetime | None+ last_commit_at: UTCDateTime | None# Commits to the file in the last 90 days. Top rung of the confidence# ladder (0 commits is what earns the high tiers), so surfacing it is what# makes a low confidence score legible: the file is still being worked on.@@ -108,7 +108,7 @@ class DeadCodeSummaryResponse(BaseModel):total_lines: intby_kind: dict# When dead-code analysis last ran; None = never ran or unknown (not all-clear).- analyzed_at: datetime | None = None+ analyzed_at: UTCDateTime | None = None#: Open findings a language gate held back, ``{language: {count, reason}}``.gated: dict = {}@@ -119,7 +119,7 @@ class SecurityFindingResponse(BaseModel):kind: strseverity: strsnippet: str | None- detected_at: datetime+ detected_at: UTCDateTime# Where in the file. Checked against the live tree before serving, so a# line that drifted is either corrected or withdrawn — see# ``services/security_lines.py``. ``None`` means the snippet is gone from@@ -131,7 +131,7 @@ class SecurityFindingResponse(BaseModel):# Present when the finding was sourced from git history (full-history# scan). ``None`` for working-tree findings produced during indexing.commit_sha: str | None- commit_at: datetime | None+ commit_at: UTCDateTime | Nonefound_in_history: bool# Shipped source, tests, or docs (``services/security_classes.py``).path_class: Literal["source", "test", "docs"] = "source"@@ -139,7 +139,7 @@ class SecurityFindingResponse(BaseModel):class SecuritySummaryResponse(BaseModel):# When the pattern scan last ran; None = never ran or unknown (not all-clear).- scanned_at: datetime | None = None+ scanned_at: UTCDateTime | None = None# Every stored finding, and how many sit in shipped source, tests and docs# (``services/security_classes.py``). The page lede reads these rather# than counting a capped list.diff --git a/packages/server/src/repowise/server/schemas/decisions.py b/packages/server/src/repowise/server/schemas/decisions.pyindex 79586ec44..50c328e08 100644--- a/packages/server/src/repowise/server/schemas/decisions.py+++ b/packages/server/src/repowise/server/schemas/decisions.py@@ -3,7 +3,6 @@from __future__ import annotationsimport json-from datetime import datetimefrom typing import Literalfrom pydantic import BaseModel, ConfigDict, Field@@ -11,6 +10,7 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom repowise.core.analysis.decisions.lifecycle import DECISION_KINDSfrom repowise.core.analysis.decisions.policy import DISCOVERY_BOUNDSfrom repowise.core.analysis.decisions.scope import derive_decision_scope+from repowise.server.schemas._datetime import UTCDateTimeclass EvidencePreview(BaseModel):@@ -51,9 +51,9 @@ class DecisionRecordResponse(BaseModel):# the linkage fields, so old records get it too.scope: str | None = Nonesuperseded_by: str | None- last_code_change: datetime | None- created_at: datetime- updated_at: datetime+ last_code_change: UTCDateTime | None+ created_at: UTCDateTime+ updated_at: UTCDateTime# List-row evidence preview: the top-ranked evidence row's verbatim quote# plus how many evidence rows back the record. Populated by the list# endpoint only (None on detail/graph responses, which have the fulldiff --git a/packages/server/src/repowise/server/schemas/doc_drift.py b/packages/server/src/repowise/server/schemas/doc_drift.pyindex 2f5207c0f..c1aeb8c57 100644--- a/packages/server/src/repowise/server/schemas/doc_drift.py+++ b/packages/server/src/repowise/server/schemas/doc_drift.py@@ -14,7 +14,6 @@ claim that the tree is clean, and only a populated store can support it.from __future__ import annotations-from datetime import datetimefrom typing import Any, Literalfrom pydantic import BaseModel, model_validator@@ -25,6 +24,7 @@ from repowise.core.analysis.doc_drift.constants import (UNAVAILABLE_READ_FAILED,)from repowise.core.analysis.doc_drift.serialize import derive_doc_drift_id, fingerprint_of+from repowise.server.schemas._datetime import UTCDateTime#: Why a drift answer could not be given, from the engine's own vocabulary so#: the literal cannot be renamed on one side alone.@@ -63,7 +63,7 @@ class DocDriftFindingResponse(BaseModel):suggestion_basis: str | None = None#: When first found, carried across updates; ``None`` when present at the#: first check or when the store keeps no history (an artifact).- first_seen_at: datetime | None = None+ first_seen_at: UTCDateTime | None = None#: First found by the latest update that stored a finding.is_new: bool = Falsediff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex 9511a9698..a90528393 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -3,13 +3,13 @@from __future__ import annotationsimport json-from datetime import datetimefrom typing import Anyfrom pydantic import BaseModelfrom repowise.core.attribution import file_sharefrom repowise.core.co_change import parse_partners+from repowise.server.schemas._datetime import UTCDateTimefrom repowise.server.schemas.history import HealthDeltaSummaryResponsefrom repowise.server.schemas.pagination import Paginatedfrom repowise.server.schemas.risk_semantics import RiskAuthority@@ -20,8 +20,8 @@ class GitMetadataResponse(BaseModel):commit_count_total: intcommit_count_90d: intcommit_count_30d: int- first_commit_at: datetime | None- last_commit_at: datetime | None+ first_commit_at: UTCDateTime | None+ last_commit_at: UTCDateTime | Noneprimary_owner_name: str | Noneprimary_owner_email: str | Noneprimary_owner_commit_pct: float | None@@ -55,7 +55,7 @@ class GitMetadataResponse(BaseModel):# the same at two weeks and two years. Empty/None on a pre-rollup index.fix_symbol_counts: dict = {}bug_magnet: bool = False- last_fix_at: datetime | None = None+ last_fix_at: UTCDateTime | None = Nonetemporal_hotspot_score: float | None = Nonecommit_count_capped: bool = False# Rename lineage: the file's path before its most recent move, if any.@@ -165,7 +165,7 @@ class HotspotResponse(BaseModel):merge_commit_count_90d: int = 0commit_count_capped: bool = Falseage_days: int = 0- last_commit_at: datetime | None = None+ last_commit_at: UTCDateTime | None = None# Change-complexity + defect-history signals.change_entropy: float = 0.0change_entropy_pct: float = 0.0@@ -174,7 +174,7 @@ class HotspotResponse(BaseModel):# age describes "fixed 4x last month" and "fixed 4x two years ago"# identically. Consumers drop the flag when the timestamp is missing.bug_magnet: bool = False- last_fix_at: datetime | None = None+ last_fix_at: UTCDateTime | None = Noneoriginal_path: str | None = None#: Changing faster over the last 30 days than over the last 90, on a file#: older than that window (see ``services.hotspots.is_accelerating``).@@ -228,7 +228,7 @@ class CommitResponse(BaseModel):short_sha: strauthor_name: strauthor_email: str- committed_at: datetime | None+ committed_at: UTCDateTime | Nonesubject: strlines_added: intlines_deleted: intdiff --git a/packages/server/src/repowise/server/schemas/history.py b/packages/server/src/repowise/server/schemas/history.pyindex 5e6b720ed..69452cf8b 100644--- a/packages/server/src/repowise/server/schemas/history.py+++ b/packages/server/src/repowise/server/schemas/history.py@@ -3,11 +3,12 @@ headlines and wins. Twins of :mod:`repowise.core.analysis.history`."""from __future__ import annotations-from datetime import datetimefrom typing import Literalfrom pydantic import BaseModel+from repowise.server.schemas._datetime import UTCDateTime+DeltaKindLiteral = Literal["improved", "worsened", "mixed", "neutral"]@@ -75,8 +76,8 @@ class PeriodHealthSummaryResponse(BaseModel):recent commits refill as updates rescan them."""- since: datetime | None = None- until: datetime | None = None+ since: UTCDateTime | None = None+ until: UTCDateTime | None = Nonetotal: intimproved: intmixed: int@@ -94,7 +95,7 @@ class WinsResolvingCommit(BaseModel):sha: strsubject: strauthor_name: str- committed_at: datetime | None = None+ committed_at: UTCDateTime | None = Noneresolved: int@@ -119,8 +120,8 @@ class WinsFilesImproved(BaseModel):at ``baseline_at`` and the one at ``current_at``."""count: int- baseline_at: datetime | None = None- current_at: datetime | None = None+ baseline_at: UTCDateTime | None = None+ current_at: UTCDateTime | None = Nonetop: list[WinsFileGain] = []@@ -130,7 +131,7 @@ class WinsRefactoring(BaseModel):file_path: strtarget_symbol: strrefactoring_type: str- resolved_at: datetime | None = None+ resolved_at: UTCDateTime | None = Nonebefore_ccn: int | None = Noneafter_ccn: int | None = Nonebefore_nloc: int | None = None@@ -150,8 +151,8 @@ class WinsResponse(BaseModel):from stored data (no history is kept for them)."""- since: datetime- until: datetime | None = None+ since: UTCDateTime+ until: UTCDateTime | None = Noneauthor: str | None = Nonefindings_resolved: WinsFindingsResolvedfiles_improved: WinsFilesImproveddiff --git a/packages/server/src/repowise/server/schemas/ownership.py b/packages/server/src/repowise/server/schemas/ownership.pyindex d70e0e47a..ad4e8f69d 100644--- a/packages/server/src/repowise/server/schemas/ownership.py+++ b/packages/server/src/repowise/server/schemas/ownership.py@@ -2,11 +2,12 @@from __future__ import annotations-from datetime import datetimefrom typing import Literalfrom pydantic import BaseModel+from repowise.server.schemas._datetime import UTCDateTime+#: Who an identity is: a person, other automation, or a coding agent.IdentityKindField = Literal["human", "bot", "agent"]@@ -53,7 +54,7 @@ class OwnerListEntry(BaseModel):commit_count_90d: int | None# A floor of that count when the indexed commits stop inside the window.commit_count_90d_at_least: int | None = None- last_commit_at: datetime | None+ last_commit_at: UTCDateTime | Nonebus_factor_risk_files: int # files they own whose bus_factor is exactly 1@@ -70,7 +71,7 @@ class OwnerFileEntry(BaseModel):churn_percentile: float # 0-100bus_factor: intis_hotspot: bool- last_commit_at: datetime | None+ last_commit_at: UTCDateTime | Noneprimary_owner_commit_pct: float | None@@ -103,8 +104,8 @@ class OwnerProfileResponse(BaseModel):dead_code_lines_owned: intcommit_count_90d: int | Nonecommit_count_90d_at_least: int | None = None- last_commit_at: datetime | None- first_commit_at: datetime | None+ last_commit_at: UTCDateTime | None+ first_commit_at: UTCDateTime | Nonebus_factor_risk_files: int# 90d activity proxies (approximated from file-level totals weighted by@@ -152,7 +153,7 @@ class SiloModule(BaseModel):class QuietOwner(OwnerRef):- last_commit_at: datetime | None+ last_commit_at: UTCDateTime | Nonefiles_owned: intchanging_files_owned: int # owned files with a commit in the last 90 daysdiff --git a/packages/server/src/repowise/server/schemas/pages.py b/packages/server/src/repowise/server/schemas/pages.pyindex 5c3bb2549..6d64e1aba 100644--- a/packages/server/src/repowise/server/schemas/pages.py+++ b/packages/server/src/repowise/server/schemas/pages.py@@ -3,10 +3,11 @@from __future__ import annotationsimport json-from datetime import datetimefrom pydantic import BaseModel+from repowise.server.schemas._datetime import UTCDateTime+def _layer_stamp(obj: object, metadata: dict | None) -> tuple[str | None, str | None]:"""Which layer this page belongs to, read off its metadata blob.@@ -148,8 +149,8 @@ class PageSummaryResponse(BaseModel):display_order: int = 0section_number: str | None = Nonestructural_key: str | None = None- created_at: datetime- updated_at: datetime+ created_at: UTCDateTime+ updated_at: UTCDateTime@classmethoddef from_orm(cls, obj: object) -> PageSummaryResponse:@@ -189,7 +190,7 @@ class PageVersionResponse(BaseModel):input_tokens: intoutput_tokens: intconfidence: float- archived_at: datetime+ archived_at: UTCDateTime@classmethoddef from_orm(cls, obj: object) -> PageVersionResponse:@@ -222,10 +223,10 @@ class JobResponse(BaseModel):current_level: interror_message: str | Noneconfig: dict- created_at: datetime- updated_at: datetime- started_at: datetime | None- finished_at: datetime | None+ created_at: UTCDateTime+ updated_at: UTCDateTime+ started_at: UTCDateTime | None+ finished_at: UTCDateTime | None# Short-lived token for the SSE progress stream (an EventSource can't send# the bearer header). Only minted while the job is live; ``None`` once it# reaches a terminal state, since there's nothing left to stream. Any clientdiff --git a/packages/server/src/repowise/server/schemas/repository.py b/packages/server/src/repowise/server/schemas/repository.pyindex 517b80422..f783b1447 100644--- a/packages/server/src/repowise/server/schemas/repository.py+++ b/packages/server/src/repowise/server/schemas/repository.py@@ -3,7 +3,6 @@from __future__ import annotationsimport json-from datetime import datetimefrom pathlib import Pathfrom pydantic import BaseModel, field_validator@@ -11,6 +10,7 @@ from pydantic import BaseModel, field_validatorfrom repowise.core.docs_mode import DocsModefrom repowise.core.forges import strip_credentialsfrom repowise.core.index_scope import load_index_scope+from repowise.server.schemas._datetime import UTCDateTimeclass RepoCreate(BaseModel):@@ -52,8 +52,8 @@ class RepoResponse(BaseModel):default_branch: strhead_commit: str | Nonesettings: dict- created_at: datetime- updated_at: datetime+ created_at: UTCDateTime+ updated_at: UTCDateTime# Workspace context — populated when the server is running in# workspace mode. ``status`` indicates whether the repo has been# indexed yet; the web UI uses it to render "needs index" CTA cards@@ -129,7 +129,7 @@ class RepoSummaryRow(BaseModel):id: strname: strlocal_path: str- updated_at: datetime | None = None+ updated_at: UTCDateTime | None = None#: "indexed" | "needs_index" | "missing_dir" — same vocabulary as#: ``RepoResponse.workspace_status``, which the sidebar already renders.status: str = "indexed"@@ -155,7 +155,7 @@ class RepoSummaryRow(BaseModel):#: distinct from a score of 0, which would mean "analysed, and terrible".average_health: float | None = Nonehotspot_health: float | None = None- health_taken_at: datetime | None = None+ health_taken_at: UTCDateTime | None = None#: Index-vs-checkout freshness. ``index_behind`` is ``None`` when the#: comparison could not run (no git checkout on disk, unreadable HEAD)diff --git a/tests/unit/server/golden/overview_summary.json b/tests/unit/server/golden/overview_summary.jsonindex 06cb6edf5..27c31675d 100644--- a/tests/unit/server/golden/overview_summary.json+++ b/tests/unit/server/golden/overview_summary.json@@ -398,7 +398,7 @@"merge_commit_count_90d": 0,"commit_count_capped": false,"age_days": 0,- "last_commit_at": "2026-08-20T00:00:00",+ "last_commit_at": "2026-08-20T00:00:00Z","change_entropy": 0.0,"change_entropy_pct": 0.0,"prior_defect_count": 0,@@ -430,7 +430,7 @@"merge_commit_count_90d": 0,"commit_count_capped": false,"age_days": 0,- "last_commit_at": "2026-08-22T00:00:00",+ "last_commit_at": "2026-08-22T00:00:00Z","change_entropy": 0.0,"change_entropy_pct": 0.0,"prior_defect_count": 0,diff --git a/tests/unit/server/golden/ownership_rollups.json b/tests/unit/server/golden/ownership_rollups.jsonindex 9d3bb5d96..8095af6be 100644--- a/tests/unit/server/golden/ownership_rollups.json+++ b/tests/unit/server/golden/ownership_rollups.json@@ -150,7 +150,7 @@"churn_percentile": 95.0,"bus_factor": 1,"is_hotspot": true,- "last_commit_at": "2026-08-01T12:00:00",+ "last_commit_at": "2026-08-01T12:00:00Z","primary_owner_commit_pct": 0.7},{@@ -168,7 +168,7 @@"churn_percentile": 60.0,"bus_factor": 1,"is_hotspot": true,- "last_commit_at": "2026-07-01T00:00:00",+ "last_commit_at": "2026-07-01T00:00:00Z","primary_owner_commit_pct": 0.9}],@@ -240,7 +240,7 @@"churn_percentile": 60.0,"bus_factor": 1,"is_hotspot": true,- "last_commit_at": "2026-07-01T00:00:00",+ "last_commit_at": "2026-07-01T00:00:00Z","primary_owner_commit_pct": 0.9},{@@ -249,7 +249,7 @@"churn_percentile": 95.0,"bus_factor": 1,"is_hotspot": true,- "last_commit_at": "2026-08-01T12:00:00",+ "last_commit_at": "2026-08-01T12:00:00Z","primary_owner_commit_pct": 0.7},{@@ -321,7 +321,7 @@"churn_percentile": 10.0,"bus_factor": 1,"is_hotspot": false,- "last_commit_at": "2020-03-03T00:00:00",+ "last_commit_at": "2020-03-03T00:00:00Z","primary_owner_commit_pct": 1.0},{@@ -330,7 +330,7 @@"churn_percentile": 95.0,"bus_factor": 1,"is_hotspot": true,- "last_commit_at": "2026-08-01T12:00:00",+ "last_commit_at": "2026-08-01T12:00:00Z","primary_owner_commit_pct": 0.7}],diff --git a/tests/unit/server/test_datetime_serialization.py b/tests/unit/server/test_datetime_serialization.pynew file mode 100644index 000000000..3203aca8a--- /dev/null+++ b/tests/unit/server/test_datetime_serialization.py@@ -0,0 +1,98 @@+"""REST datetime fields must identify UTC explicitly."""++import importlib+import inspect+import pkgutil+from datetime import UTC, datetime, timedelta, timezone+from typing import Annotated, get_args, get_origin++from pydantic import BaseModel, PlainSerializer++from repowise.server.schemas import (+ ChatMessageResponse,+ JobResponse,+ RepoResponse,+)+++def test_naive_sqlite_datetime_is_serialized_as_utc() -> None:+ response = RepoResponse(+ id="repo",+ name="repo",+ url="",+ local_path="/tmp/repo",+ default_branch="main",+ head_commit=None,+ settings={},+ created_at=datetime(2026, 9, 8, 20, 2, 58, 949469),+ updated_at=datetime(2026, 9, 8, 20, 2, 58, 949469),+ )++ payload = response.model_dump(mode="json")++ assert payload["created_at"] == "2026-09-08T20:02:58.949469Z"+ assert payload["updated_at"] == "2026-09-08T20:02:58.949469Z"+++def test_aware_datetime_is_normalized_to_utc() -> None:+ response = ChatMessageResponse(+ id="message",+ conversation_id="conversation",+ role="user",+ content={"text": "hello"},+ created_at=datetime(2026, 9, 8, 22, 2, 58, tzinfo=timezone(timedelta(hours=2))),+ )++ assert response.model_dump(mode="json")["created_at"] == "2026-09-08T20:02:58Z"+++def test_optional_job_datetimes_keep_null_and_emit_utc() -> None:+ response = JobResponse(+ id="job",+ repository_id="repo",+ status="running",+ provider_name="mock",+ model_name="mock",+ total_pages=1,+ completed_pages=0,+ failed_pages=0,+ current_level=0,+ error_message=None,+ config={},+ created_at=datetime(2026, 9, 8, tzinfo=UTC),+ updated_at=datetime(2026, 9, 8, tzinfo=UTC),+ started_at=datetime(2026, 9, 8),+ finished_at=None,+ )++ payload = response.model_dump(mode="json")++ assert payload["started_at"] == "2026-09-08T00:00:00Z"+ assert payload["finished_at"] is None+++def _naive_datetime(annotation: object, metadata: tuple = ()) -> bool:+ """True when ``annotation`` holds a ``datetime`` without the UTC serializer."""+ if annotation is datetime:+ return not any(isinstance(m, PlainSerializer) for m in metadata)+ if get_origin(annotation) is Annotated:+ inner, *extra = get_args(annotation)+ return _naive_datetime(inner, (*metadata, *extra))+ return any(_naive_datetime(arg) for arg in get_args(annotation))+++def test_every_schema_datetime_field_serializes_as_utc() -> None:+ """New response fields must use ``UTCDateTime``, not a bare ``datetime``."""+ import repowise.server.schemas as schemas++ offenders = []+ for info in pkgutil.iter_modules(schemas.__path__):+ module = importlib.import_module(f"{schemas.__name__}.{info.name}")+ for name, cls in inspect.getmembers(module, inspect.isclass):+ if not issubclass(cls, BaseModel) or cls.__module__ != module.__name__:+ continue+ for field_name, field in cls.model_fields.items():+ if _naive_datetime(field.annotation, tuple(field.metadata)):+ offenders.append(f"{module.__name__}.{name}.{field_name}")++ assert offenders == [], f"use UTCDateTime for these fields: {offenders}"