smriti/backend/app/schemas/__init__.py
Himanshu Dongre 713ed9a007 Refuse to silently extract mock content into a real Space
A fresh Smriti install with no provider configured could still run
`smriti checkpoint create --extract`, which silently returned
MockAdapter content like "Mock decision from provider". If committed,
that placeholder text became part of the user's real reasoning state.

Root cause: backend/app/api/routes/checkpoint.py:417 called
`get_adapter(cfg.background.provider, allow_mock=True)`. The
`allow_mock=True` flag means the registry quietly returns MockAdapter
when no API key is configured, rather than raising. The CLI received
the canned mock JSON and committed it without inspecting whether it
came from a real LLM.

The extract endpoint was the only route in the codebase with this
pattern — draft, review, chat title, and chat send already correctly
pass `allow_mock=False`.

The new contract:

- Core Smriti (setup, doctor, quickstart, state/current/metrics,
  claims, attach, manual JSON checkpoints) requires no API key.
- Real LLM-backed paths (`--extract`, draft, review, chat send)
  require a configured provider — OpenAI / Anthropic / OpenRouter /
  generic OpenAI-compatible (local models like Ollama).
- Mock extraction still works for tests and demos, but only when the
  caller explicitly opts in (use_mock=true on the HTTP payload).
  It is never silently the default.

Backend:
- POST /api/v5/checkpoint/extract now passes allow_mock=False and
  catches ProviderNotConfiguredError, returning HTTP 412 with a
  structured detail: error code, human message, the provider it
  tried, and a list of fix paths the CLI surfaces.
- CheckpointExtractResponse gains `provider` and `model` echo fields
  (additive, default empty) so callers can confirm what answered.

CLI:
- checkpoint create --extract catches 412 and prints the actionable
  fix list; exits 78 (EX_CONFIG). Defense in depth: even on a 200,
  refuses to commit if response.provider == "mock" on the default
  path (so any future regression in the backend is still caught).
- smriti doctor surfaces background provider state prominently:
  `ready (real LLM extraction enabled)` or `⚠ MOCK or DISABLED — …
  will fail until a provider is configured`.
- smriti doctor --strict exits 78 when the background provider is
  mock/disabled or the backend is unreachable. Safe to wire into
  CI before any --extract step.
- On a successful --extract commit, the CLI shows `extracted via
  <provider>/<model>` under the commit confirmation.

Docs:
- README: new "Provider configuration (LLM-backed features)" section
  drawing the boundary explicitly; mentions the generic provider for
  local OpenAI-compatible models; flags mock as test-only.
- .env.example: rewrote the provider section so an empty key or a
  model-without-a-key is not interpreted as "ready".
- Skill pack template: new §4.1 "Before your first --extract: verify
  the provider" telling agents to run `smriti doctor`, refuse
  --extract when background_provider is mock/disabled, and fall back
  to manual JSON checkpoints or ask the human to configure a
  provider. Re-rendered to AGENTS.md (Codex target). The Claude Code
  target (.claude/skills/smriti/SKILL.md) is gitignored per-user
  install; rerun `smriti skills install claude-code` to refresh.
- website/index.html: Try-it lede now spells out which features need
  a provider rather than gesturing at "optional LLM features".

Tests:
- test_extract_without_provider_fails_loud: regression for the bug —
  monkeypatches get_adapter to raise ProviderNotConfiguredError,
  asserts HTTP 412 with the structured detail shape, and asserts
  the response body contains neither "Mock decision from provider"
  nor "Mock Checkpoint". This test would fail on pre-fix code.
- test_extract_with_provider_echoes_provider_and_model: pins the
  green path — provider and model must be echoed and must not be
  "mock" when the real adapter answers.
- test_extract_happy_path_with_mock: unchanged, still pins the
  explicit use_mock=true contract.
- Full backend integration suite: 165 passed locally (with the
  pre-existing real-provider draft test passing under
  backend/config/providers.yaml).
2026-05-23 17:48:14 +05:30

166 lines
5.5 KiB
Python

"""API request and response schemas using Pydantic."""
import uuid
from datetime import datetime
from typing import Any, Optional, Union
from pydantic import BaseModel, Field, field_validator
from app.domain.enums import SessionStatus, TargetTool
# ── Request Schemas ──────────────────────────────────────────────────────────
class SessionCreateRequest(BaseModel):
"""Request body for creating a new session."""
raw_transcript: str = Field(..., min_length=1, description="The raw transcript text")
title: str | None = Field(None, max_length=255, description="Optional session title")
source_tool: str | None = Field(None, description="Source AI tool")
class ContextPackCreateRequest(BaseModel):
"""Request body for generating a context pack."""
target_tool: TargetTool = Field(..., description="Target tool for continuation pack")
# ── Response Schemas ─────────────────────────────────────────────────────────
class SessionResponse(BaseModel):
"""Response for a session."""
id: uuid.UUID
title: str | None
source_tool: str | None
status: SessionStatus
raw_transcript: str
created_at: datetime
model_config = {"from_attributes": True}
class DecisionResponse(BaseModel):
description: str
context: str = ""
class TaskResponse(BaseModel):
description: str
status: str = "pending"
class OpenQuestionResponse(BaseModel):
question: str
context: str = ""
class EntityResponse(BaseModel):
name: str
type: str
context: str = ""
class CodeSnippetResponse(BaseModel):
language: str
code: str
description: str = ""
class ArtifactsResponse(BaseModel):
"""Response for extracted artifacts."""
summary: str
decisions: list[DecisionResponse]
tasks: list[TaskResponse]
open_questions: list[OpenQuestionResponse]
entities: list[EntityResponse]
code_snippets: list[CodeSnippetResponse]
class ContextPackResponse(BaseModel):
"""Response for a generated context pack."""
id: uuid.UUID
session_id: uuid.UUID
target_tool: str
content: str
format: str
created_at: datetime
model_config = {"from_attributes": True}
class ErrorResponse(BaseModel):
"""Standard error response."""
error: str
detail: str | None = None
class CheckpointDraftRequest(BaseModel):
session_id: uuid.UUID
num_turns: int = Field(15, ge=1, le=100)
mounted_checkpoint_id: Optional[str] = Field(
None,
description="If set, draft only uses turns after history_base_seq (mirrors send_message isolation)."
)
history_base_seq: Optional[int] = Field(
None,
description="Sequence boundary from mount event. Only turns with sequence_number > this value are included."
)
class CheckpointDraftResponse(BaseModel):
title: str = ""
objective: str = ""
summary: str = ""
decisions: list[str] = Field(default_factory=list)
assumptions: list[str] = Field(default_factory=list)
tasks: list[Union[str, dict[str, Any]]] = Field(default_factory=list)
open_questions: list[str] = Field(default_factory=list)
entities: list[str] = Field(default_factory=list)
class ReviewIssue(BaseModel):
type: str # contradiction, hidden_assumption, resolved_question, unused_entity
description: str
class CheckpointReviewResponse(BaseModel):
checkpoint_id: uuid.UUID
issues: list[ReviewIssue] = Field(default_factory=list)
suggestions: list[str] = Field(default_factory=list)
class CheckpointExtractRequest(BaseModel):
"""Request body for the freeform-markdown checkpoint extractor.
Takes a freeform markdown document and asks the background LLM to
extract Smriti checkpoint schema fields from it. Stateless — no
session or checkpoint ID required.
"""
content: str = Field(..., description="Freeform markdown document to extract checkpoint fields from")
use_mock: bool = Field(False, description="Force MockAdapter even when a real provider is configured (for tests and dry-run flows)")
@field_validator("content")
@classmethod
def validate_content(cls, v: str) -> str:
stripped = v.strip()
if not stripped:
raise ValueError("content must not be empty")
if len(stripped) > 200_000:
raise ValueError("content exceeds 200000 character limit")
return v
class CheckpointExtractResponse(BaseModel):
title: str = ""
objective: str = ""
summary: str = ""
decisions: list[str] = Field(default_factory=list)
assumptions: list[str] = Field(default_factory=list)
tasks: list[Union[str, dict[str, Any]]] = Field(default_factory=list)
open_questions: list[str] = Field(default_factory=list)
entities: list[str] = Field(default_factory=list)
artifacts: list[dict] = Field(default_factory=list)
# Echo the provider/model that actually answered, so callers can confirm
# whether the extraction came from a real LLM or the mock adapter. The
# CLI surfaces this on every --extract commit and uses it to refuse to
# persist mock content into a real project.
provider: str = Field("", description="Provider that produced this extraction (e.g. 'openai', 'anthropic', 'mock').")
model: str = Field("", description="Model identifier that produced this extraction (or 'mock').")