Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions .github/workflows/backend-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ on:
branches: [main]
paths:
- "backend/**"
# The chat contract the backend tests read from the frontend
# (tests/test_contract.py): a change there is checked against the server.
- "frontend/src/services/chatService.ts"
- "frontend/src/types/chat.ts"
- "frontend/src/chat/useHomeChat.ts"
- "frontend/src/chat/sheetFor.ts"
- "frontend/src/components/writing/AskDock.tsx"

env:
BACKEND_DIR: backend
Expand Down Expand Up @@ -55,9 +62,9 @@ jobs:
working-directory: ${{ env.BACKEND_DIR }}
# Context-layer regressions only, and none of them reach the network:
# what the model is given, what must never reach it, and what it must
# never be asked to answer without. The prompt itself is evaluated by
# evals/run_eval.py, which is run by hand because it costs Gemini quota
# and its most useful checks are the ones a person reads.
# never be asked to answer without. The prompt itself is checked by hand
# against the question set in backend/README.md, because that costs
# Gemini quota and its most useful checks are the ones a person reads.
run: pytest -q

- name: Audit dependencies
Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,15 @@ Stated plainly, so you know what you are forking:
- **The edge Worker is deployed by hand, not by CI.** Neither workflow in `.github/workflows/`
touches `edge/`; see [edge/README.md](edge/README.md).
- **The edge secret is enforced only when it is set.** With `ORIGIN_SHARED_SECRET` unset the
backend accepts direct requests (`backend/main.py`).
backend accepts direct requests (`backend/settings.py`, `backend/main.py`).
- **The chat answers only from the committed markdown, so it declines what is not there.** The
corpus is the files under `backend/docs/` and nothing else (`backend/context.py`). Whether the
model always follows that instruction cannot be proven offline (unverified).
- **The profile documents are public.** Everything under `backend/docs/` is tracked in this
repository and sent to the Gemini API; the profile folder is also served by `/api/content/`.
- **Which documents an answer used is the model's own word.** `used` is checked against what was
sent, so it can only name a real document, but whether the answer leaned on it is the model's
claim, not a measurement (`backend/main.py`).
claim, not a measurement (`used_sources` in `backend/replies.py`).
- **Document selection is word overlap with English and Hebrew stopword lists.** A starter
question with a drawing also sends its topic, and the projects that drawing shows are always
included (`TOPIC_PROJECTS`). A Hebrew
Expand All @@ -170,7 +170,7 @@ Stated plainly, so you know what you are forking:
which a new document needs an entry in. At most three documents go beside the profile; every
other document is named to the model in one line. When no word matches, only the profile and
that list are sent (`backend/selection.py`).
- **The SMTP host is fixed in code** to one mail provider (`backend/main.py`).
- **The SMTP host is fixed in code** to one mail provider (`backend/mailer.py`).
- **The frontend has no automated tests.** `frontend/package.json` defines typecheck, lint,
format and build scripts, and no test script.

Expand All @@ -189,7 +189,7 @@ Each item names the file or test that shows it. Tests are in `backend/tests/` an
| The owner's name never decides which document a question gets | `test_selection.py::test_the_owners_name_does_not_pick_a_document` |
| A reply written without the model still names its sources | `test_writing_phase2.py::test_the_latest_posts_reply_names_its_sources` |
| A bare address to an unknown host never becomes a link | `test_guard.py::test_a_bare_address_to_an_unknown_host_never_becomes_a_link` |
| Oversized or empty chat requests are rejected | `backend/main.py`; `test_context_layer.py::test_oversized_message_is_rejected`, `::test_empty_message_is_rejected`, `::test_unbounded_history_is_rejected` |
| Oversized or empty chat requests are rejected | `backend/schemas.py`; `test_context_layer.py::test_oversized_message_is_rejected`, `::test_empty_message_is_rejected`, `::test_unbounded_history_is_rejected` |
| Interface banners are not replayed to the model as conversation | `test_context_layer.py::test_ui_chrome_is_not_replayed_as_conversation` |
| Per-client and global rate limits, answering 429 with `Retry-After` | `backend/rate_limit.py` (code; no limiter test was read for this list) |
| The client identity used for rate limiting cannot be claimed by a forged header | `test_client_identity.py` |
Expand All @@ -198,7 +198,7 @@ Each item names the file or test that shows it. Tests are in `backend/tests/` an
| An invalid address or oversized message never reaches mail delivery or spends a rate-limit slot | `test_contact_endpoint.py` |
| An address left in the chat is emailed, and a failed send tells the visitor so | `test_email_delivery.py` (mail transport stubbed) |
| When the upstream API refuses, the chat falls back through its model list and then answers "busy" without queueing | `test_quota_resilience.py`; `test_context_layer.py::test_quota_exhaustion_advances_through_every_model` |
| `/api/content/` is confined to the profile folder | `backend/main.py` (`get_content`; code, no test was read) |
| `/api/content/` is confined to the profile folder | `backend/routes/content.py` (`get_content`; code, no test was read) |
| Usage figures are shown only for answers a model produced | `test_context_layer.py::test_a_reply_the_model_never_produced_carries_no_trace` |
| Pull requests run verify jobs; deploys run only on a push to `main` | `.github/workflows/backend-deploy.yml`, `.github/workflows/frontend-deploy.yml` |
| Frontend typecheck, lint, format check and build | scripts in `frontend/package.json`, run by `frontend-deploy.yml` |
Expand Down
11 changes: 10 additions & 1 deletion backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,16 @@ backend/
│ ├── he/ # Hebrew twins of the above, used for Hebrew questions
│ ├── templates/ # placeholders for forks; never sent to the model
│ └── search-phrases.json # how visitors phrase each document (selection only)
├── main.py # FastAPI app: schemas, routes, CORS, the chat flow
├── main.py # the app: edge-secret check, cache headers, CORS, routers
├── settings.py # configuration read from the environment, in one place
├── schemas.py # every request and reply shape (Pydantic)
├── routes/
│ ├── chat.py # the chat route: contact steps, posts list, model answer
│ ├── contact.py # the contact form
│ ├── booking.py # the discovery-call booking
│ └── content.py # read-only profile, projects and writing
├── replies.py # the parts a chat reply is built from: cards, sources, checks
├── mailer.py # sending the contact mail over SMTP
├── selection.py # picks the documents each question gets (deterministic)
├── context.py # assembles + caches the corpus, per-section
├── prompt.py # the behavioural contract: grounding, voice, boundaries
Expand Down
4 changes: 2 additions & 2 deletions backend/gemini_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ class Handoff(BaseModel):

Asked in the same call as the answer, so it costs a few output tokens and
no extra request. The model only judges and restates; whether a card is
shown is the server's decision (see main.py), so a model that says "ready"
shown is the server's decision (see replies.handoff_card), so a model that says "ready"
on every turn cannot make the site pushy.

The summary follows the shape of a sales recap: where the visitor stands,
Expand Down Expand Up @@ -341,7 +341,7 @@ class ParsedReply(NamedTuple):
declined: Optional[bool] = None
handoff: Optional[Handoff] = None
# Titles the model says the answer drew on; checked against what it was
# actually sent before anything is shown (see main._cited_sections).
# actually sent before anything is shown (see replies.cited_sections).
used: Tuple[str, ...] = ()


Expand Down
127 changes: 127 additions & 0 deletions backend/mailer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"""Mail to Yanir: the contact notification, and the visitor's short reply.

Used by the contact form (routes/contact.py) and by an address left in the
chat (routes/chat.py), so both paths send the same message and fail the same
way. The message bodies themselves are built in site_mail.py.
"""

import logging
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from typing import Optional

from email_validator import validate_email
from fastapi import HTTPException
from fastapi.concurrency import run_in_threadpool

import settings
import site_mail

logger = logging.getLogger(__name__)

# Seconds one SMTP connection may take. Without a ceiling a stalled mail server
# would hold a worker thread for as long as the socket stayed open.
SMTP_TIMEOUT_SECONDS = 10


def validated_address(candidate: str) -> str:
"""Returns the normalised address, or raises EmailNotValidError.

Syntax only. The deliverability check is a DNS lookup, which is a blocking
network call on the request path for a result the SMTP send reports anyway.
"""
return validate_email(candidate, check_deliverability=False).email


def smtp_send(
msg: MIMEMultipart,
sender_email: str,
sender_password: str,
follow_up: Optional[MIMEMultipart] = None,
) -> None:
"""Sends a prepared message, then an optional second one, over one SMTP login.

Blocking; call from a worker thread. Only the first message decides the
outcome: the follow-up is the visitor's courtesy reply, and failing to send
it must not report their message to Yanir as lost.
"""
logger.info("Attempting to connect to SMTP server...")
with smtplib.SMTP_SSL(
'smtp.gmail.com', 465, timeout=SMTP_TIMEOUT_SECONDS
) as server:
logger.info("Connected to SMTP server, attempting login...")
server.login(sender_email, sender_password)
logger.info("Logged in successfully, sending email...")
server.send_message(msg)
logger.info("Contact notification email sent")
if follow_up is not None:
try:
server.send_message(follow_up)
logger.info("Visitor auto-reply sent")
except Exception:
logger.exception("Visitor auto-reply failed")


async def send_contact_email(
email: str,
message: str,
*,
topic: Optional[str] = None,
route: str = "chat",
lang: Optional[str] = None,
reply_to_visitor: bool = False,
) -> None:
"""Delivers a collected address to Yanir's inbox.

Raises HTTPException on a configuration or SMTP failure; callers decide how
that reads to the visitor. The chat flow answers with a message offering the
address directly, while the HTTP route surfaces the status.
"""
try:
# Email configuration
sender_email = os.getenv("EMAIL_ADDRESS")
sender_password = os.getenv("EMAIL_PASSWORD")
receiver_email = os.getenv("YOUR_EMAIL")

logger.info("Preparing contact notification email")

if not all([sender_email, sender_password, receiver_email]):
logger.error("Missing email configuration")
raise HTTPException(status_code=500, detail=settings.INTERNAL_ERROR_DETAIL)

# Yanir's notification in the site's look; replying to it answers the
# visitor. The mail form also sends the visitor a fixed short reply.
msg = site_mail.notification(
sender_email,
receiver_email,
visitor=email,
message=message,
topic=topic,
route=route,
lang=lang,
replied=reply_to_visitor,
)
follow_up = (
site_mail.auto_reply(sender_email, receiver_email, email, lang or "he")
if reply_to_visitor
else None
)

try:
# smtplib is synchronous; see the note on the Gemini call.
await run_in_threadpool(
smtp_send, msg, sender_email, sender_password, follow_up
)
except Exception:
# The raw SMTP error names the sender account and the server, so it
# stays server-side: returning it would reflect both back to anyone
# who can make a send fail.
logger.exception("SMTP send failed")
raise HTTPException(status_code=500, detail=settings.INTERNAL_ERROR_DETAIL)

except HTTPException:
raise
except Exception:
logger.exception("Contact delivery error")
raise HTTPException(status_code=500, detail=settings.INTERNAL_ERROR_DETAIL)
Loading
Loading