Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

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__.py
index 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 importlib
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
+ from ._datetime import UTCDateTime
from .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.py
new file mode 100644
index 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.py
index 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 datetime
from typing import Literal
from pydantic import BaseModel, Field
from repowise.core.analysis.next_call import ActionCommand
+from repowise.server.schemas._datetime import UTCDateTime
class ActionWhy(BaseModel):
@@ -113,7 +113,7 @@ class ActionStateRequest(BaseModel):
class ActionStateResponse(BaseModel):
action_id: str
state: Literal["dismissed", "snoozed", "done"] | None
- until: datetime | None = None
+ until: UTCDateTime | None = None
class WorkspaceRepoActions(BaseModel):
diff --git a/packages/server/src/repowise/server/schemas/chat.py b/packages/server/src/repowise/server/schemas/chat.py
index 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 annotations
import json
-from datetime import datetime
from typing import Any, Literal
from pydantic import BaseModel, Field
from repowise.server.chat_artifacts import normalize_message_artifacts
+from repowise.server.schemas._datetime import UTCDateTime
from repowise.server.schemas.evidence import CardRef
@@ -69,8 +69,8 @@ class ConversationResponse(BaseModel):
title: str
message_count: int = 0
pinned: bool = False
- created_at: datetime
- updated_at: datetime
+ created_at: UTCDateTime
+ updated_at: UTCDateTime
@classmethod
def from_orm(cls, obj: object, message_count: int = 0) -> ConversationResponse:
@@ -104,7 +104,7 @@ class ChatMessageResponse(BaseModel):
conversation_id: str
role: str
content: dict
- created_at: datetime
+ created_at: UTCDateTime
@classmethod
def 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.py
index 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 annotations
import json
-from datetime import datetime
from typing import Literal
from 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 UTCDateTime
from .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: int
by_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: str
severity: str
snippet: 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 | None
found_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.py
index 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 annotations
import json
-from datetime import datetime
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
@@ -11,6 +10,7 @@ from pydantic import BaseModel, ConfigDict, Field
from repowise.core.analysis.decisions.lifecycle import DECISION_KINDS
from repowise.core.analysis.decisions.policy import DISCOVERY_BOUNDS
from repowise.core.analysis.decisions.scope import derive_decision_scope
+from repowise.server.schemas._datetime import UTCDateTime
class EvidencePreview(BaseModel):
@@ -51,9 +51,9 @@ class DecisionRecordResponse(BaseModel):
# the linkage fields, so old records get it too.
scope: str | None = None
superseded_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 full
diff --git a/packages/server/src/repowise/server/schemas/doc_drift.py b/packages/server/src/repowise/server/schemas/doc_drift.py
index 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 datetime
from typing import Any, Literal
from 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 = False
diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.py
index 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 annotations
import json
-from datetime import datetime
from typing import Any
from pydantic import BaseModel
from repowise.core.attribution import file_share
from repowise.core.co_change import parse_partners
+from repowise.server.schemas._datetime import UTCDateTime
from repowise.server.schemas.history import HealthDeltaSummaryResponse
from repowise.server.schemas.pagination import Paginated
from repowise.server.schemas.risk_semantics import RiskAuthority
@@ -20,8 +20,8 @@ class GitMetadataResponse(BaseModel):
commit_count_total: int
commit_count_90d: int
commit_count_30d: int
- first_commit_at: datetime | None
- last_commit_at: datetime | None
+ first_commit_at: UTCDateTime | None
+ last_commit_at: UTCDateTime | None
primary_owner_name: str | None
primary_owner_email: str | None
primary_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 = None
temporal_hotspot_score: float | None = None
commit_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 = 0
commit_count_capped: bool = False
age_days: int = 0
- last_commit_at: datetime | None = None
+ last_commit_at: UTCDateTime | None = None
# Change-complexity + defect-history signals.
change_entropy: float = 0.0
change_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 = None
original_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: str
author_name: str
author_email: str
- committed_at: datetime | None
+ committed_at: UTCDateTime | None
subject: str
lines_added: int
lines_deleted: int
diff --git a/packages/server/src/repowise/server/schemas/history.py b/packages/server/src/repowise/server/schemas/history.py
index 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 datetime
from typing import Literal
from 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 = None
total: int
improved: int
mixed: int
@@ -94,7 +95,7 @@ class WinsResolvingCommit(BaseModel):
sha: str
subject: str
author_name: str
- committed_at: datetime | None = None
+ committed_at: UTCDateTime | None = None
resolved: 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 = None
top: list[WinsFileGain] = []
@@ -130,7 +131,7 @@ class WinsRefactoring(BaseModel):
file_path: str
target_symbol: str
refactoring_type: str
- resolved_at: datetime | None = None
+ resolved_at: UTCDateTime | None = None
before_ccn: int | None = None
after_ccn: int | None = None
before_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 = None
author: str | None = None
findings_resolved: WinsFindingsResolved
files_improved: WinsFilesImproved
diff --git a/packages/server/src/repowise/server/schemas/ownership.py b/packages/server/src/repowise/server/schemas/ownership.py
index 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 datetime
from typing import Literal
from 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 | None
bus_factor_risk_files: int # files they own whose bus_factor is exactly 1
@@ -70,7 +71,7 @@ class OwnerFileEntry(BaseModel):
churn_percentile: float # 0-100
bus_factor: int
is_hotspot: bool
- last_commit_at: datetime | None
+ last_commit_at: UTCDateTime | None
primary_owner_commit_pct: float | None
@@ -103,8 +104,8 @@ class OwnerProfileResponse(BaseModel):
dead_code_lines_owned: int
commit_count_90d: int | None
commit_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 | None
bus_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 | None
files_owned: int
changing_files_owned: int # owned files with a commit in the last 90 days
diff --git a/packages/server/src/repowise/server/schemas/pages.py b/packages/server/src/repowise/server/schemas/pages.py
index 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 annotations
import json
-from datetime import datetime
from 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 = 0
section_number: str | None = None
structural_key: str | None = None
- created_at: datetime
- updated_at: datetime
+ created_at: UTCDateTime
+ updated_at: UTCDateTime
@classmethod
def from_orm(cls, obj: object) -> PageSummaryResponse:
@@ -189,7 +190,7 @@ class PageVersionResponse(BaseModel):
input_tokens: int
output_tokens: int
confidence: float
- archived_at: datetime
+ archived_at: UTCDateTime
@classmethod
def from_orm(cls, obj: object) -> PageVersionResponse:
@@ -222,10 +223,10 @@ class JobResponse(BaseModel):
current_level: int
error_message: str | None
config: 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 client
diff --git a/packages/server/src/repowise/server/schemas/repository.py b/packages/server/src/repowise/server/schemas/repository.py
index 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 annotations
import json
-from datetime import datetime
from pathlib import Path
from pydantic import BaseModel, field_validator
@@ -11,6 +10,7 @@ from pydantic import BaseModel, field_validator
from repowise.core.docs_mode import DocsMode
from repowise.core.forges import strip_credentials
from repowise.core.index_scope import load_index_scope
+from repowise.server.schemas._datetime import UTCDateTime
class RepoCreate(BaseModel):
@@ -52,8 +52,8 @@ class RepoResponse(BaseModel):
default_branch: str
head_commit: str | None
settings: 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: str
name: str
local_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 = None
hotspot_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.json
index 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.json
index 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.py
new file mode 100644
index 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}"