Status: AMENDED — Completed with scope-clarification (Phase 2/3, 2026-05-16) Date: 2026-01-13 (original) / 2026-05-16 (amendment) Authors: Lead Developer (Claude Code) Approved By: Chief Architect (2026-01-13 original / 2026-05-16 amendment) Issue: #584 (original) / #1015 (amendment scope-clarification) Deciders: Chief Architect
Per #1015 investigation and Chief Architect ratification 2026-05-16:
RequestContext is the canonical identity-and-context object for the intent processing path (web/api/routes/intent.py → services/intent/intent_service.py → services/trust/trust_integration.py + downstream conversation persistence, telemetry, soft-invocation, multi-handler dispatch). For all other route/service surfaces (20 of 29 route files exercising authenticated flows; 9 unauthenticated route files including admin/health/debug/demo), the dependency-injection pattern (current_user: JWTClaims = Depends(get_current_user) at routes; user_id: str parameters in services) provides the canonical identity flow and is sufficient.
The two patterns are not in conflict: dependency-injection is the boundary mechanism; RequestContext is the cross-handler coordination object for the intent path specifically. Adopting RequestContext beyond the intent path is a Pattern-072 recognition-trigger decision — the trigger fires when a second non-trivial coordination surface emerges with ≥3 sub-services consuming identity-and-context together (see “Future-state criterion” below).
The original ADR-051 (Jan 13) contemplated RequestContext as a cross-cutting infrastructure primitive — every route would construct it at the boundary, every service would consume it. Phase 2/3 partial adoption landed only the intent path. The Apr 27 batch-2 codebase review (Finding H) framed the partial state as a stalled migration that needed completion. #1015 Phase 0 audit (2026-05-15) verified the actual state against current code and found three reasons the cross-cutting framing is no longer load-bearing:
current_user: JWTClaims = Depends(get_current_user)) is now the canonical identity flow at every authenticated route. The Apr 27 risk framing (“a route forgets to pass ctx, a service relies on request.state.user_id”) was real under a different middleware pattern; it doesn’t fire under the current pattern (verified: 0 routes read request.state.user_id directly).conversation_id to construct RequestContext from. Mandating construction at every endpoint would degenerate into a wrapper around current_user.sub.This isn’t ad hoc — it’s the same recognition Pattern-072 names (Registries that Grow into Architectural Shapes, promoted to Proven via #1094 2026-05-15). The pattern says a registry/typed shape becomes architectural when third+ behavior-deciding consumer materializes. RequestContext currently has one real consumer (intent_service); the dependency-injection pattern has 20. Formalizing RequestContext as cross-cutting infrastructure would be premature.
A non-trivial coordination surface qualifies for RequestContext adoption when it touches ≥3 service boundaries with state that depends on identity-and-context (not just identity). Examples that would qualify:
Examples that would NOT qualify:
When the second qualifying surface materializes, the Pattern-072 recognition trigger fires and RequestContext becomes a candidate for cross-cutting adoption. Until then, the intent-path scope is the canonical end-state.
Convention + ADR + code review, not lint. FastAPI’s dependency injection self-enforces at the route layer (route signatures must declare their dependencies). The “intent.py is the only RequestContext constructor outside services/” boundary is too narrow to lint reliably — the lint would need to know the intent path is special, which is fragile. Code review + this ADR + the explicit RequestContext docstring naming its scope is sufficient.
dev/2026/05/15/1015-issue-audit.mddev/2026/05/15/1015-phase-1-design.mdmailboxes/lead/read/memo-arch-to-lead-cc-cio-ceo-1015-phase-1-ratification-option-c-plus-12w-third-instance-2026-05-16.mddocs/internal/architecture/patterns/pattern-072-registries-that-grow-into-architectural-shapes.mdservices/domain/models.py (updated with intent-path-specific role + Pattern-072 connection in same amendment commit)The codebase has accumulated significant technical debt around identity and context management. Investigation (Issue #584) revealed:
user_id (UUID in DB, str in routes, mixed in services)session_id for three different purposesuser_id doesn’t flow through call chainsThis has caused multiple bugs (#490, #582) and will continue to cause bugs as features are added.
The issues stem from three interrelated problems:
1. Model Problem (Foundational) Three distinct domain concepts are conflated:
2. Naming Problem (Semantic)
session_id is used for:
3. Implementation Problem (Type System)
user_id has 5+ different type representations:
UUID in database modelsUUID in JWTClaims.user_id fieldstr in JWTClaims.sub field (canonical JWT claim)str when extracted in routes (current_user.sub)str/UUID in service layer parametersThis pattern emerged from:
session_id == user context| File | Issue | Severity |
|---|---|---|
web/api/routes/intent.py:221 |
Uses .sub instead of .user_id |
HIGH |
services/user_context_service.py:49 |
Falls back to session_id as user ID | CRITICAL |
services/intent/intent_service.py:140 |
Uses session_id as conversation_id | MEDIUM |
services/intent_service/canonical_handlers.py:126 |
user_id: str = None (wrong type) |
HIGH |
services/intent_service/todo_handlers.py:37 |
user_id: UUID (conflicting type) |
HIGH |
RequestContext ModelCreate a single, immutable context object that flows through the entire request lifecycle.
Chief Architect Decision: Single RequestContext approved. The three concepts have different lifecycles but same scope of need - always needed together for request processing.
# services/domain/models.py
@dataclass(frozen=True)
class RequestContext:
"""
Unified context for all request processing.
This is the single source of truth for identity and context.
Passed through all service calls - never optional, never reconstructed.
"""
# Core identity (required)
user_id: UUID # Authenticated user's database PK
conversation_id: UUID # Database PK for conversation record
request_id: UUID # Unique per-request for tracing
# Denormalized for convenience
username: str # Display name (saves lookup cost on logs)
timestamp: datetime # Request timestamp
# Future-proofing
workspace_id: Optional[UUID] = None # For future multi-tenant support
@classmethod
def from_jwt_and_request(
cls,
claims: JWTClaims,
conversation_id: str,
request_id: Optional[UUID] = None,
) -> "RequestContext":
"""Factory method to create context from JWT claims and request data."""
# Validation - fail fast on malformed input
if not claims.sub:
raise ValueError("JWT claims missing 'sub' field")
if not conversation_id:
raise ValueError("conversation_id is required")
return cls(
user_id=UUID(claims.sub), # str → UUID at boundary
conversation_id=UUID(conversation_id), # str → UUID at boundary
request_id=request_id or uuid4(),
username=claims.username,
timestamp=datetime.utcnow(),
workspace_id=UUID(claims.workspace_id) if claims.workspace_id else None,
)
def __str__(self) -> str:
"""String representation for logging/debugging."""
return f"RequestContext(user={self.user_id}, conv={self.conversation_id}, req={self.request_id})"
Decision: UUID internally, str at boundaries
| Layer | Type | Rationale |
|---|---|---|
| Routes | Accept str, convert via factory |
Boundary conversion |
| Services | Always UUID |
Type safety |
| Repositories | Always UUID |
Type safety |
| Responses | Convert to str at serialization |
API contract |
| Current Usage | Becomes |
|---|---|
| Ephemeral request context | request_id |
| Conversation identity | conversation_id |
| User-context cache key | user_id (cache was using wrong key) |
Core four IDs in RequestContext:
user_id - Who is making the requestconversation_id - Which conversation this isrequest_id - This specific request (for tracing)workspace_id - Which workspace (optional, future multi-tenant)Domain entities (NOT in RequestContext):
project_id, intent_id, workflow_id, task_id, etc. - these are processed BY requests, not context FOR requests.
# In routes - create context once at boundary
@router.post("/intent")
async def process_intent(
request: IntentRequest,
current_user: JWTClaims = Depends(get_current_user),
):
# Create context at request boundary - single source of truth
context = RequestContext.from_jwt_and_request(
claims=current_user,
conversation_id=request.conversation_id,
)
# Pass context through all calls
result = await intent_service.process(context, request.message)
return result
# In services - always receive context, never reconstruct
class IntentService:
async def process(self, ctx: RequestContext, message: str) -> IntentResult:
# Use ctx.user_id for user-scoped operations
user_context = await self.context_service.get(ctx.user_id)
# Use ctx.conversation_id for conversation operations
history = await self.conversation_repo.get_turns(ctx.conversation_id)
# Pass context to downstream services
return await self._route_intent(ctx, classified_intent)
Chief Architect Guidance: Incremental but compressed to 2-3 focused days. Do NOT let Phase 2 become permanent.
| Phase | Scope | Target |
|---|---|---|
| 1 | Add RequestContext model, factory, documentation |
Day 1 AM |
| 2 | Update routes to create context, pass alongside old params | Day 1 PM |
| 3 | Update services to use context, update tests | Day 2 |
| 4 | Remove old patterns, enforce consistency | Day 2-3 |
CRITICAL WARNING: Do NOT leave Phase 2 (dual patterns) as permanent state. This is exactly how the current mess happened.
Use FastAPI’s dependency injection to provide context automatically.
Pros: Less explicit passing, cleaner signatures Cons: Hidden dependencies, harder to test, magic behavior
Decision: Rejected - explicit is better than implicit for critical context
Use Python’s contextvars for implicit context propagation.
Pros: No parameter passing needed Cons: Hidden state, harder to reason about, async complexity
Decision: Rejected - explicit passing is more maintainable
Document the existing inconsistencies and establish conventions.
Pros: No code changes, immediate Cons: Doesn’t fix the bugs, conventions will drift
Decision: Rejected - documentation alone hasn’t prevented bugs
Create context in middleware, attach to request.state, but still pass as explicit parameter:
@app.middleware("http")
async def add_request_context(request: Request, call_next):
request.state.context = RequestContext.from_jwt_and_request(...)
return await call_next(request)
Decision: Not required for current scale, but valid for future consideration.
user_id propagationQuestions Asked:
RequestContext vs split abstractions? → Single approvedAdditional Recommendations Incorporated:
__str__ for logginguser_id propagationdev/active/memo-lead-dev-identity-model-response.mdADR created: 2026-01-13 Status: APPROVED by Chief Architect (2026-01-13) Implementation: Scheduled as focused 2-3 day sprint