""" Feedback Digest (feedback_digest.py) — closes the loop visibly. Reads feedback_signals from the last N days and produces: 1. A short LLM-written "What you told us / what we're doing" HTML block that sits at the very top of the weekly digest. 2. (Optional) A structured per-recipient view so each colleague's own feedback is acknowledged in their own digest. Design notes - This module ONLY summarises — it does NOT auto-tune scoring, thresholds, or prompts. Auto-tuning over small N is unsafe; the feedback recap creates the visibility a human needs to make those decisions. Marking signals applied=true is done by hand or by a future iteration. - Cached per-week in `feedback_recap` (created on the fly here — small enough that a separate migration would be overkill). Reads from feedback_signals. """ from __future__ import annotations import os import json import sqlite3 from datetime import datetime, timedelta, date from pathlib import Path from typing import Optional, Callable from dotenv import load_dotenv env_path = Path(__file__).parent / '.env' load_dotenv(dotenv_path=env_path, override=True) DATABASE = "leads.db" def _week_start_iso(d: Optional[date] = None) -> str: d = d or date.today() return (d - timedelta(days=d.weekday())).isoformat() def fetch_recent_feedback(days: int = 7, recipient: Optional[str] = None) -> list[dict]: """Pull structured feedback signals from the last `days` days. If `recipient` is given, narrow to that colleague's own feedback. """ cutoff = (datetime.utcnow() - timedelta(days=days)).isoformat() conn = sqlite3.connect(DATABASE) conn.row_factory = sqlite3.Row if recipient: rows = conn.execute(""" SELECT id, recipient, sentiment, target_type, target_token, target_label, suggestion, received_at, applied_at FROM feedback_signals WHERE received_at >= ? AND recipient = ? ORDER BY received_at DESC """, (cutoff, recipient)).fetchall() else: rows = conn.execute(""" SELECT id, recipient, sentiment, target_type, target_token, target_label, suggestion, received_at, applied_at FROM feedback_signals WHERE received_at >= ? ORDER BY received_at DESC """, (cutoff,)).fetchall() conn.close() return [dict(r) for r in rows] # --------------------------------------------------------------------------- # LLM summary # --------------------------------------------------------------------------- _SUMMARY_PROMPT = """You are writing the "What you told us last week" recap that sits at the top of the Curium Sales Intelligence weekly digest. Tone: terse, factual, addresses the team directly. Goal: show each contributor their feedback was heard, without flattering or hedging. You receive a JSON array of structured feedback signals from the last week (sentiment, target_type, target_label, suggestion, recipient name). Output a short HTML block following this exact pattern:

What you told us last week

Strict rules: - Maximum 5 bullets. Cluster duplicates (3 people saying "more food manufacturing" → ONE bullet). - Each bullet attributes the feedback to a recipient name when one is set, else "Team". - The "what we're doing" clause must be honest. Allowed options: "added to this week's focus", "noted — recurring pattern, will adjust", "noted — single instance, watching", "no change yet — needs more signal", "already applied". Don't invent capabilities the system doesn't have. - UK English. No emoji. No hedging ("we'll try to", "hopefully") — just say what's happening. - If feedback signals contradict each other (e.g. "more X" vs "less X"), say so explicitly: "Mixed signal on X — flagging for review." If the input array is empty, return ONLY the literal string `__NO_FEEDBACK__`. Do NOT include ``/`` tags. Do NOT include any preamble or explanation. Start directly with `

`.""" def build_recap_html(days: int = 7, recipient: Optional[str] = None, progress_cb: Optional[Callable[[str], None]] = None ) -> str: """LLM-build the recap HTML block. Returns "" if there's nothing to report (so the digest skips the section cleanly). """ signals = fetch_recent_feedback(days=days, recipient=recipient) if not signals: return "" api_key = os.environ.get("ANTHROPIC_API_KEY") if not api_key: if progress_cb: progress_cb("feedback recap: no ANTHROPIC_API_KEY — fallback rendering") return _fallback_recap_html(signals) from anthropic import Anthropic client = Anthropic(api_key=api_key) user_msg = ( f"Here are the {len(signals)} feedback signals from the last " f"{days} days. Build the recap.\n\n" f"{json.dumps(signals, indent=2, default=str)}" ) try: msg = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1500, system=_SUMMARY_PROMPT, messages=[{"role": "user", "content": user_msg}], ) except Exception as e: if progress_cb: progress_cb(f"feedback recap: LLM call failed: {e} — using fallback") return _fallback_recap_html(signals) body = msg.content[0].text.strip() if body == "__NO_FEEDBACK__": return "" if body.startswith("```"): parts = body.split("```") if len(parts) >= 2: body = parts[1] if body.startswith("html"): body = body[4:] body = body.strip() return body def _fallback_recap_html(signals: list[dict]) -> str: """No-LLM fallback: render every feedback signal as a literal bullet. Used only when the LLM is unavailable so the loop still closes.""" parts = [ '

' 'What you told us last week

', '') return "\n".join(parts) if __name__ == "__main__": import argparse p = argparse.ArgumentParser() p.add_argument("--days", type=int, default=7) p.add_argument("--recipient", default=None) args = p.parse_args() def log(msg: str) -> None: print(f"[feedback-digest] {msg}", flush=True) html = build_recap_html(days=args.days, recipient=args.recipient, progress_cb=log) if not html: print("(no feedback in the window — recap would be omitted)") else: print(html)