Spaces:
Sleeping
Closed-loop feedback: recipients reply, system digests, recap surfaces
Browse filesAdds a feedback round-trip so each weekly digest learns from the
recipient's reply to the previous one.
Capture
- Every lead in the email gets a stable feedback token
(lead-<company-slug>-<isoYYYYwWW>) printed as a small grey tag
next to the company name.
- A "Help us tune this β just reply" footer is appended to every
email body, telling recipients they can either quote a lead token
("lead-bentley-motors-2026w19 β already knew") or write naturally
("more food manufacturing", "loved the FDE theme").
- Reply-To remains the existing ADMIN_EMAIL convention; no recipient
workflow change required.
Ingest (feedback_ingest.py)
- Polls the mailbox via the SAME Microsoft Graph app registration
used for sendMail. Requires Mail.Read permission to be granted
on the app β fails cleanly with a 403 in logs otherwise (digest
still ships, recap section just renders empty).
- Mailbox priority: FEEDBACK_INBOX > MS_GRAPH_REPLY_TO > ADMIN_EMAIL
> MS_GRAPH_FROM_EMAIL.
- For each new reply: filters obvious auto-replies / OOO, then sends
the body to Claude to parse into structured feedback_signals
(sentiment, target_type, target_token, target_label, suggestion).
- Idempotent on message_id β re-runs safe.
Digest header (feedback_digest.py)
- Pulls the last 8 days of feedback_signals and asks Claude to write
a "What you told us last week" recap that sits at the very top of
this week's digest.
- Each bullet attributes the feedback to a recipient and states what
the system is doing about it in honest language ("added to this
week's focus" / "noted β needs more signal" / "no change yet").
- The block is NEVER speculative or auto-tuning: it shows visibility,
not action. Auto-tuning over small N is unsafe; this lets the human
decide what to push into config based on patterns they can now see.
Cron sequencing (scripts/weekly_hunt_and_email.py)
- New Step 1.5: ingest replies AFTER state pull (so dedup against
historic feedback_messages works) but BEFORE the hunt (so the
recap header in this week's digests is current). Non-fatal β a
Graph permission gap doesn't block the send.
Schema
- New feedback_messages (raw inbox poll, UNIQUE on message_id) and
feedback_signals (LLM-parsed structured records). Both idempotent
ALTER TABLE / CREATE IF NOT EXISTS migrations.
Smoke test
- Faked a reply ("Loved the FDE theme. Bentley felt thin. Want more
food manufacturing.") β Claude parsed 3 distinct signals β recap
rendered with per-bullet attribution + honest "what we're doing"
clauses β digest body now opens with the recap, lead tokens
visible per lead, feedback prompt closes the email.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- collator.py +53 -0
- feedback_digest.py +183 -0
- feedback_ingest.py +420 -0
- scripts/weekly_hunt_and_email.py +19 -0
- weekly_digest.py +93 -9
|
@@ -391,6 +391,9 @@ def init_company_db():
|
|
| 391 |
# Schema migration: weekly_themes (Phase 3 β cross-sector theme cache)
|
| 392 |
_migrate_weekly_themes()
|
| 393 |
|
|
|
|
|
|
|
|
|
|
| 394 |
|
| 395 |
PIPELINE_STAGES = [
|
| 396 |
"new", "researching", "ready_to_approach", "approached",
|
|
@@ -549,6 +552,56 @@ def _migrate_weekly_themes():
|
|
| 549 |
conn.close()
|
| 550 |
|
| 551 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
def _store_signal_facts(company_id: int, signal_table: str, signal_id: int,
|
| 553 |
quantified_facts: list | None,
|
| 554 |
executive_quotes: list | None) -> None:
|
|
|
|
| 391 |
# Schema migration: weekly_themes (Phase 3 β cross-sector theme cache)
|
| 392 |
_migrate_weekly_themes()
|
| 393 |
|
| 394 |
+
# Schema migration: feedback closed loop (recipient replies β digest)
|
| 395 |
+
_migrate_feedback()
|
| 396 |
+
|
| 397 |
|
| 398 |
PIPELINE_STAGES = [
|
| 399 |
"new", "researching", "ready_to_approach", "approached",
|
|
|
|
| 552 |
conn.close()
|
| 553 |
|
| 554 |
|
| 555 |
+
def _migrate_feedback():
|
| 556 |
+
"""Closed-loop feedback: recipient replies β ingested β digested.
|
| 557 |
+
|
| 558 |
+
Two tables:
|
| 559 |
+
- feedback_messages: raw inbox messages we've pulled via Graph.
|
| 560 |
+
Keyed on message_id so re-polls are idempotent.
|
| 561 |
+
- feedback_signals: LLM-parsed structured records (one or more per
|
| 562 |
+
message). These are what feedback_digest.py summarises into the
|
| 563 |
+
next week's digest header.
|
| 564 |
+
"""
|
| 565 |
+
conn = sqlite3.connect(DATABASE)
|
| 566 |
+
cursor = conn.cursor()
|
| 567 |
+
cursor.execute("""
|
| 568 |
+
CREATE TABLE IF NOT EXISTS feedback_messages (
|
| 569 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 570 |
+
message_id TEXT UNIQUE NOT NULL, -- Graph message id (or generated for non-Graph sources)
|
| 571 |
+
sender TEXT, -- email address that replied
|
| 572 |
+
sender_name TEXT,
|
| 573 |
+
subject TEXT,
|
| 574 |
+
body_text TEXT,
|
| 575 |
+
received_at TEXT, -- ISO timestamp from the mailbox
|
| 576 |
+
ingested_at TEXT NOT NULL,
|
| 577 |
+
parsed INTEGER DEFAULT 0 -- 1 once feedback_signals rows exist
|
| 578 |
+
)
|
| 579 |
+
""")
|
| 580 |
+
cursor.execute("""
|
| 581 |
+
CREATE TABLE IF NOT EXISTS feedback_signals (
|
| 582 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 583 |
+
message_id INTEGER, -- FK to feedback_messages.id
|
| 584 |
+
recipient TEXT, -- which team_email name this came from (matched on sender)
|
| 585 |
+
sentiment TEXT, -- 'positive' | 'negative' | 'neutral'
|
| 586 |
+
target_type TEXT, -- 'lead' | 'theme' | 'macro' | 'general'
|
| 587 |
+
target_token TEXT, -- lead-bentley-2026w20 | theme-fde-rollouts | NULL
|
| 588 |
+
target_label TEXT, -- human-readable thing it referred to
|
| 589 |
+
suggestion TEXT, -- the actual ask / preference / complaint
|
| 590 |
+
applied_at TEXT, -- NULL until the system reflects this back
|
| 591 |
+
received_at TEXT NOT NULL,
|
| 592 |
+
FOREIGN KEY (message_id) REFERENCES feedback_messages(id)
|
| 593 |
+
)
|
| 594 |
+
""")
|
| 595 |
+
cursor.execute("CREATE INDEX IF NOT EXISTS idx_feedback_msgs_received "
|
| 596 |
+
"ON feedback_messages(received_at DESC)")
|
| 597 |
+
cursor.execute("CREATE INDEX IF NOT EXISTS idx_feedback_signals_target "
|
| 598 |
+
"ON feedback_signals(target_type, target_token)")
|
| 599 |
+
cursor.execute("CREATE INDEX IF NOT EXISTS idx_feedback_signals_received "
|
| 600 |
+
"ON feedback_signals(received_at DESC)")
|
| 601 |
+
conn.commit()
|
| 602 |
+
conn.close()
|
| 603 |
+
|
| 604 |
+
|
| 605 |
def _store_signal_facts(company_id: int, signal_table: str, signal_id: int,
|
| 606 |
quantified_facts: list | None,
|
| 607 |
executive_quotes: list | None) -> None:
|
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Feedback Digest (feedback_digest.py) β closes the loop visibly.
|
| 3 |
+
|
| 4 |
+
Reads feedback_signals from the last N days and produces:
|
| 5 |
+
1. A short LLM-written "What you told us / what we're doing" HTML
|
| 6 |
+
block that sits at the very top of the weekly digest.
|
| 7 |
+
2. (Optional) A structured per-recipient view so each colleague's
|
| 8 |
+
own feedback is acknowledged in their own digest.
|
| 9 |
+
|
| 10 |
+
Design notes
|
| 11 |
+
- This module ONLY summarises β it does NOT auto-tune scoring,
|
| 12 |
+
thresholds, or prompts. Auto-tuning over small N is unsafe; the
|
| 13 |
+
feedback recap creates the visibility a human needs to make those
|
| 14 |
+
decisions. Marking signals applied=true is done by hand or by a
|
| 15 |
+
future iteration.
|
| 16 |
+
- Cached per-week in `feedback_recap` (created on the fly here β small
|
| 17 |
+
enough that a separate migration would be overkill). Reads from
|
| 18 |
+
feedback_signals.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import os
|
| 24 |
+
import json
|
| 25 |
+
import sqlite3
|
| 26 |
+
from datetime import datetime, timedelta, date
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
from typing import Optional, Callable
|
| 29 |
+
|
| 30 |
+
from dotenv import load_dotenv
|
| 31 |
+
|
| 32 |
+
env_path = Path(__file__).parent / '.env'
|
| 33 |
+
load_dotenv(dotenv_path=env_path, override=True)
|
| 34 |
+
|
| 35 |
+
DATABASE = "leads.db"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _week_start_iso(d: Optional[date] = None) -> str:
|
| 39 |
+
d = d or date.today()
|
| 40 |
+
return (d - timedelta(days=d.weekday())).isoformat()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def fetch_recent_feedback(days: int = 7,
|
| 44 |
+
recipient: Optional[str] = None) -> list[dict]:
|
| 45 |
+
"""Pull structured feedback signals from the last `days` days.
|
| 46 |
+
|
| 47 |
+
If `recipient` is given, narrow to that colleague's own feedback.
|
| 48 |
+
"""
|
| 49 |
+
cutoff = (datetime.utcnow() - timedelta(days=days)).isoformat()
|
| 50 |
+
conn = sqlite3.connect(DATABASE)
|
| 51 |
+
conn.row_factory = sqlite3.Row
|
| 52 |
+
if recipient:
|
| 53 |
+
rows = conn.execute("""
|
| 54 |
+
SELECT id, recipient, sentiment, target_type, target_token,
|
| 55 |
+
target_label, suggestion, received_at, applied_at
|
| 56 |
+
FROM feedback_signals
|
| 57 |
+
WHERE received_at >= ? AND recipient = ?
|
| 58 |
+
ORDER BY received_at DESC
|
| 59 |
+
""", (cutoff, recipient)).fetchall()
|
| 60 |
+
else:
|
| 61 |
+
rows = conn.execute("""
|
| 62 |
+
SELECT id, recipient, sentiment, target_type, target_token,
|
| 63 |
+
target_label, suggestion, received_at, applied_at
|
| 64 |
+
FROM feedback_signals
|
| 65 |
+
WHERE received_at >= ?
|
| 66 |
+
ORDER BY received_at DESC
|
| 67 |
+
""", (cutoff,)).fetchall()
|
| 68 |
+
conn.close()
|
| 69 |
+
return [dict(r) for r in rows]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# LLM summary
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
_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.
|
| 76 |
+
|
| 77 |
+
You receive a JSON array of structured feedback signals from the last week (sentiment, target_type, target_label, suggestion, recipient name).
|
| 78 |
+
|
| 79 |
+
Output a short HTML block following this exact pattern:
|
| 80 |
+
|
| 81 |
+
<h2 style="color:#1a237e;font-size:1.05em;margin:8px 0 8px 0;border-bottom:1px solid #cfd8dc;padding-bottom:4px;">What you told us last week</h2>
|
| 82 |
+
<ul style="margin:0 0 12px 18px;padding:0;">
|
| 83 |
+
<li style="margin:6px 0;"><strong>{Recipient or "Team"}:</strong> "{one-sentence paraphrase of suggestion}" β {what the system is doing about it in one short clause, e.g. "added food manufacturing to this week's theme search" / "noted β we'll watch for repeat freshness misses" / "no change yet β too small a sample"}.</li>
|
| 84 |
+
β¦
|
| 85 |
+
</ul>
|
| 86 |
+
|
| 87 |
+
Strict rules:
|
| 88 |
+
- Maximum 5 bullets. Cluster duplicates (3 people saying "more food manufacturing" β ONE bullet).
|
| 89 |
+
- Each bullet attributes the feedback to a recipient name when one is set, else "Team".
|
| 90 |
+
- 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.
|
| 91 |
+
- UK English. No emoji. No hedging ("we'll try to", "hopefully") β just say what's happening.
|
| 92 |
+
- If feedback signals contradict each other (e.g. "more X" vs "less X"), say so explicitly: "Mixed signal on X β flagging for review."
|
| 93 |
+
|
| 94 |
+
If the input array is empty, return ONLY the literal string `__NO_FEEDBACK__`.
|
| 95 |
+
|
| 96 |
+
Do NOT include `<html>`/`<body>` tags. Do NOT include any preamble or explanation. Start directly with `<h2>`."""
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def build_recap_html(days: int = 7,
|
| 100 |
+
recipient: Optional[str] = None,
|
| 101 |
+
progress_cb: Optional[Callable[[str], None]] = None
|
| 102 |
+
) -> str:
|
| 103 |
+
"""LLM-build the recap HTML block. Returns "" if there's nothing to
|
| 104 |
+
report (so the digest skips the section cleanly).
|
| 105 |
+
"""
|
| 106 |
+
signals = fetch_recent_feedback(days=days, recipient=recipient)
|
| 107 |
+
if not signals:
|
| 108 |
+
return ""
|
| 109 |
+
|
| 110 |
+
api_key = os.environ.get("ANTHROPIC_API_KEY")
|
| 111 |
+
if not api_key:
|
| 112 |
+
if progress_cb:
|
| 113 |
+
progress_cb("feedback recap: no ANTHROPIC_API_KEY β fallback rendering")
|
| 114 |
+
return _fallback_recap_html(signals)
|
| 115 |
+
|
| 116 |
+
from anthropic import Anthropic
|
| 117 |
+
client = Anthropic(api_key=api_key)
|
| 118 |
+
|
| 119 |
+
user_msg = (
|
| 120 |
+
f"Here are the {len(signals)} feedback signals from the last "
|
| 121 |
+
f"{days} days. Build the recap.\n\n"
|
| 122 |
+
f"{json.dumps(signals, indent=2, default=str)}"
|
| 123 |
+
)
|
| 124 |
+
try:
|
| 125 |
+
msg = client.messages.create(
|
| 126 |
+
model="claude-sonnet-4-20250514",
|
| 127 |
+
max_tokens=1500,
|
| 128 |
+
system=_SUMMARY_PROMPT,
|
| 129 |
+
messages=[{"role": "user", "content": user_msg}],
|
| 130 |
+
)
|
| 131 |
+
except Exception as e:
|
| 132 |
+
if progress_cb:
|
| 133 |
+
progress_cb(f"feedback recap: LLM call failed: {e} β using fallback")
|
| 134 |
+
return _fallback_recap_html(signals)
|
| 135 |
+
|
| 136 |
+
body = msg.content[0].text.strip()
|
| 137 |
+
if body == "__NO_FEEDBACK__":
|
| 138 |
+
return ""
|
| 139 |
+
if body.startswith("```"):
|
| 140 |
+
parts = body.split("```")
|
| 141 |
+
if len(parts) >= 2:
|
| 142 |
+
body = parts[1]
|
| 143 |
+
if body.startswith("html"):
|
| 144 |
+
body = body[4:]
|
| 145 |
+
body = body.strip()
|
| 146 |
+
return body
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _fallback_recap_html(signals: list[dict]) -> str:
|
| 150 |
+
"""No-LLM fallback: render every feedback signal as a literal bullet.
|
| 151 |
+
Used only when the LLM is unavailable so the loop still closes."""
|
| 152 |
+
parts = [
|
| 153 |
+
'<h2 style="color:#1a237e;font-size:1.05em;margin:8px 0 8px 0;'
|
| 154 |
+
'border-bottom:1px solid #cfd8dc;padding-bottom:4px;">'
|
| 155 |
+
'What you told us last week</h2>',
|
| 156 |
+
'<ul style="margin:0 0 12px 18px;padding:0;">',
|
| 157 |
+
]
|
| 158 |
+
for s in signals[:5]:
|
| 159 |
+
who = s.get("recipient") or "Team"
|
| 160 |
+
suggestion = (s.get("suggestion") or "").strip()
|
| 161 |
+
parts.append(
|
| 162 |
+
f'<li style="margin:6px 0;"><strong>{who}:</strong> '
|
| 163 |
+
f'"{suggestion}" β noted, no automatic change applied (LLM summariser unavailable).</li>'
|
| 164 |
+
)
|
| 165 |
+
parts.append('</ul>')
|
| 166 |
+
return "\n".join(parts)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
import argparse
|
| 171 |
+
p = argparse.ArgumentParser()
|
| 172 |
+
p.add_argument("--days", type=int, default=7)
|
| 173 |
+
p.add_argument("--recipient", default=None)
|
| 174 |
+
args = p.parse_args()
|
| 175 |
+
|
| 176 |
+
def log(msg: str) -> None:
|
| 177 |
+
print(f"[feedback-digest] {msg}", flush=True)
|
| 178 |
+
|
| 179 |
+
html = build_recap_html(days=args.days, recipient=args.recipient, progress_cb=log)
|
| 180 |
+
if not html:
|
| 181 |
+
print("(no feedback in the window β recap would be omitted)")
|
| 182 |
+
else:
|
| 183 |
+
print(html)
|
|
@@ -0,0 +1,420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Feedback Ingest (feedback_ingest.py) β closes the loop on the weekly digest.
|
| 3 |
+
|
| 4 |
+
What it does
|
| 5 |
+
- Polls the digest sender's mailbox via Microsoft Graph for replies since
|
| 6 |
+
the last ingest, treating each reply as free-form feedback.
|
| 7 |
+
- Uses Claude to parse each reply into one or more structured signals
|
| 8 |
+
(sentiment, target lead/theme, suggestion) so feedback_digest can
|
| 9 |
+
summarise "what you said last week" at the top of the next digest.
|
| 10 |
+
- Stores raw messages + structured signals in `feedback_messages` /
|
| 11 |
+
`feedback_signals`. Idempotent on message_id, so re-runs are safe.
|
| 12 |
+
|
| 13 |
+
Auth & permissions
|
| 14 |
+
- Reuses the same Azure AD App Registration as mailer._graph_send.
|
| 15 |
+
- Needs `Mail.Read` (or `Mail.ReadBasic.All`) Application permission on
|
| 16 |
+
the same app β admin-consent same as Mail.Send. If the permission
|
| 17 |
+
isn't granted, ingest fails cleanly with a 403 and the digest still
|
| 18 |
+
ships without the feedback recap.
|
| 19 |
+
|
| 20 |
+
CLI usage
|
| 21 |
+
python feedback_ingest.py # poll last 7 days
|
| 22 |
+
python feedback_ingest.py --days 14 # broader window for first run
|
| 23 |
+
python feedback_ingest.py --dry-run # show what would be ingested
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import os
|
| 29 |
+
import json
|
| 30 |
+
import sqlite3
|
| 31 |
+
import argparse
|
| 32 |
+
from datetime import datetime, timedelta
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
from typing import Optional, Callable
|
| 35 |
+
|
| 36 |
+
from dotenv import load_dotenv
|
| 37 |
+
|
| 38 |
+
env_path = Path(__file__).parent / '.env'
|
| 39 |
+
load_dotenv(dotenv_path=env_path, override=True)
|
| 40 |
+
|
| 41 |
+
DATABASE = "leads.db"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# ---------------------------------------------------------------------------
|
| 45 |
+
# Microsoft Graph mailbox poll
|
| 46 |
+
# ---------------------------------------------------------------------------
|
| 47 |
+
def _graph_token() -> Optional[str]:
|
| 48 |
+
"""Acquire an app-only token via client credentials. Same flow as
|
| 49 |
+
mailer._graph_send. Returns None on failure (caller handles)."""
|
| 50 |
+
try:
|
| 51 |
+
import msal
|
| 52 |
+
except ImportError:
|
| 53 |
+
return None
|
| 54 |
+
tenant = os.environ.get("MS_GRAPH_TENANT_ID")
|
| 55 |
+
client_id = os.environ.get("MS_GRAPH_CLIENT_ID")
|
| 56 |
+
client_secret = os.environ.get("MS_GRAPH_CLIENT_SECRET")
|
| 57 |
+
if not (tenant and client_id and client_secret):
|
| 58 |
+
return None
|
| 59 |
+
app = msal.ConfidentialClientApplication(
|
| 60 |
+
client_id,
|
| 61 |
+
authority=f"https://login.microsoftonline.com/{tenant}",
|
| 62 |
+
client_credential=client_secret,
|
| 63 |
+
)
|
| 64 |
+
result = app.acquire_token_for_client(
|
| 65 |
+
scopes=["https://graph.microsoft.com/.default"]
|
| 66 |
+
)
|
| 67 |
+
return result.get("access_token")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _mailbox_address() -> Optional[str]:
|
| 71 |
+
"""Which mailbox to read replies from.
|
| 72 |
+
|
| 73 |
+
Preference order (matches what the cron uses as Reply-To):
|
| 74 |
+
1. FEEDBACK_INBOX env var (explicit override)
|
| 75 |
+
2. MS_GRAPH_REPLY_TO (Graph send override, if set)
|
| 76 |
+
3. ADMIN_EMAIL (the cron's de-facto reply-to β see
|
| 77 |
+
scripts/weekly_hunt_and_email.py)
|
| 78 |
+
4. MS_GRAPH_FROM_EMAIL (the sender mailbox itself β replies still
|
| 79 |
+
land here even if Reply-To points elsewhere, as long as users
|
| 80 |
+
hit "Reply" rather than reply-to-list)
|
| 81 |
+
|
| 82 |
+
Note: Graph can only read mailboxes inside the same Azure AD tenant
|
| 83 |
+
as the app registration. If ADMIN_EMAIL is a personal address
|
| 84 |
+
outside that tenant, ingest will get a 404; set FEEDBACK_INBOX to
|
| 85 |
+
an in-tenant mailbox instead.
|
| 86 |
+
"""
|
| 87 |
+
return (
|
| 88 |
+
os.environ.get("FEEDBACK_INBOX")
|
| 89 |
+
or os.environ.get("MS_GRAPH_REPLY_TO")
|
| 90 |
+
or os.environ.get("ADMIN_EMAIL")
|
| 91 |
+
or os.environ.get("MS_GRAPH_FROM_EMAIL")
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def fetch_recent_messages(days: int = 7,
|
| 96 |
+
progress_cb: Optional[Callable[[str], None]] = None
|
| 97 |
+
) -> list[dict]:
|
| 98 |
+
"""Pull the inbox's messages from the last `days` days via Graph.
|
| 99 |
+
|
| 100 |
+
Returns a list of {message_id, sender, sender_name, subject,
|
| 101 |
+
body_text, received_at} dicts. Empty list on auth/permission failure
|
| 102 |
+
(logged via progress_cb so the cron still proceeds).
|
| 103 |
+
"""
|
| 104 |
+
import requests
|
| 105 |
+
|
| 106 |
+
mailbox = _mailbox_address()
|
| 107 |
+
if not mailbox:
|
| 108 |
+
if progress_cb:
|
| 109 |
+
progress_cb("feedback: no mailbox configured (FEEDBACK_INBOX / "
|
| 110 |
+
"MS_GRAPH_REPLY_TO / MS_GRAPH_FROM_EMAIL all unset)")
|
| 111 |
+
return []
|
| 112 |
+
token = _graph_token()
|
| 113 |
+
if not token:
|
| 114 |
+
if progress_cb:
|
| 115 |
+
progress_cb("feedback: could not acquire Graph token β check MS_GRAPH_* secrets")
|
| 116 |
+
return []
|
| 117 |
+
|
| 118 |
+
since = (datetime.utcnow() - timedelta(days=days)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 119 |
+
# Pull inbox messages; we filter app-side to keep the URL simple.
|
| 120 |
+
url = (
|
| 121 |
+
f"https://graph.microsoft.com/v1.0/users/{mailbox}/mailFolders/inbox/messages"
|
| 122 |
+
f"?$top=50&$orderby=receivedDateTime desc"
|
| 123 |
+
f"&$select=id,subject,from,bodyPreview,body,receivedDateTime,isRead"
|
| 124 |
+
f"&$filter=receivedDateTime ge {since}"
|
| 125 |
+
)
|
| 126 |
+
try:
|
| 127 |
+
r = requests.get(
|
| 128 |
+
url,
|
| 129 |
+
headers={"Authorization": f"Bearer {token}",
|
| 130 |
+
"Prefer": 'outlook.body-content-type="text"'},
|
| 131 |
+
timeout=30,
|
| 132 |
+
)
|
| 133 |
+
except Exception as e:
|
| 134 |
+
if progress_cb:
|
| 135 |
+
progress_cb(f"feedback: Graph HTTP error: {type(e).__name__}: {e}")
|
| 136 |
+
return []
|
| 137 |
+
|
| 138 |
+
if r.status_code != 200:
|
| 139 |
+
if progress_cb:
|
| 140 |
+
progress_cb(f"feedback: Graph {r.status_code} β "
|
| 141 |
+
f"{r.text[:300]} "
|
| 142 |
+
f"(if 403, grant the app 'Mail.Read' permission + admin consent)")
|
| 143 |
+
return []
|
| 144 |
+
|
| 145 |
+
out = []
|
| 146 |
+
for item in r.json().get("value", []) or []:
|
| 147 |
+
sender_info = (item.get("from") or {}).get("emailAddress") or {}
|
| 148 |
+
body = item.get("body") or {}
|
| 149 |
+
body_text = body.get("content") or item.get("bodyPreview") or ""
|
| 150 |
+
out.append({
|
| 151 |
+
"message_id": item.get("id"),
|
| 152 |
+
"sender": (sender_info.get("address") or "").lower(),
|
| 153 |
+
"sender_name": sender_info.get("name") or "",
|
| 154 |
+
"subject": item.get("subject") or "",
|
| 155 |
+
"body_text": body_text,
|
| 156 |
+
"received_at": item.get("receivedDateTime") or "",
|
| 157 |
+
})
|
| 158 |
+
if progress_cb:
|
| 159 |
+
progress_cb(f"feedback: pulled {len(out)} recent messages from {mailbox}")
|
| 160 |
+
return out
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------
|
| 164 |
+
# Recipient mapping β match reply sender to a colleague name in config
|
| 165 |
+
# ---------------------------------------------------------------------------
|
| 166 |
+
def _recipient_for_sender(sender: str) -> Optional[str]:
|
| 167 |
+
"""Match a reply sender's address to a team_emails colleague name.
|
| 168 |
+
|
| 169 |
+
Uses the same yaml team_emails block weekly_digest reads. Tolerant
|
| 170 |
+
of case + missing env vars.
|
| 171 |
+
"""
|
| 172 |
+
try:
|
| 173 |
+
import yaml
|
| 174 |
+
cfg = yaml.safe_load((Path(__file__).parent / "config.yaml").read_text())
|
| 175 |
+
except Exception:
|
| 176 |
+
return None
|
| 177 |
+
sender = (sender or "").lower().strip()
|
| 178 |
+
if not sender:
|
| 179 |
+
return None
|
| 180 |
+
for entry in (cfg.get("team_emails") or []):
|
| 181 |
+
addr = (entry.get("email") or "").strip()
|
| 182 |
+
if addr.startswith("ENV:"):
|
| 183 |
+
addr = os.environ.get(addr[4:].strip(), "")
|
| 184 |
+
if addr and addr.lower() == sender:
|
| 185 |
+
return entry.get("name")
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# ---------------------------------------------------------------------------
|
| 190 |
+
# LLM parser β turn free-form reply into structured feedback signals
|
| 191 |
+
# ---------------------------------------------------------------------------
|
| 192 |
+
_PARSE_SYSTEM_PROMPT = """You are parsing replies to the Curium Sales Intelligence weekly digest into structured feedback.
|
| 193 |
+
|
| 194 |
+
The digest contains:
|
| 195 |
+
- UK macro pulse (4-8 quantified indicators)
|
| 196 |
+
- Cross-sector themes (3-5 named patterns spanning β₯2 companies)
|
| 197 |
+
- Warm-route leads (per-company, sometimes prefixed [CLIENT])
|
| 198 |
+
|
| 199 |
+
Each lead in the email carries a stable token shaped like `lead-<slug>-<weekcode>` (e.g. `lead-bentley-motors-2026w19`). Each theme has a slug token (e.g. `theme-fde-rollouts`).
|
| 200 |
+
|
| 201 |
+
Your job: turn ONE reply into a list of structured feedback signals. Be generous β a single reply can contain multiple signals (e.g. "Loved the FDE theme but Bentley wasn't useful β please add more food manufacturing"). Be conservative β if the reply is just "Thanks" or out-of-office boilerplate, return an empty array.
|
| 202 |
+
|
| 203 |
+
Each signal has:
|
| 204 |
+
- `sentiment`: "positive" | "negative" | "neutral"
|
| 205 |
+
- `target_type`: "lead" | "theme" | "macro" | "general" (general = wider preference, not tied to a specific item)
|
| 206 |
+
- `target_token`: the token from the email if quoted/referenced, else null
|
| 207 |
+
- `target_label`: a human-readable handle ("Bentley restructure lead", "Forward-Deployed Engineers theme", "more food manufacturing")
|
| 208 |
+
- `suggestion`: the actual ask in 1 short sentence (UK English, factual)
|
| 209 |
+
|
| 210 |
+
Output: ONLY a JSON array, no other text.
|
| 211 |
+
|
| 212 |
+
If the reply is purely an out-of-office bounce ("I am on holiday untilβ¦"), an automated mailer-daemon, or contains no actionable feedback, return `[]`.
|
| 213 |
+
|
| 214 |
+
Examples (illustrative β the actual reply text will be plain prose):
|
| 215 |
+
|
| 216 |
+
Reply: "Great digest. Loved the FDE theme. Bentley lead was a bit thin β we already knew. Want more on food manufacturing next week."
|
| 217 |
+
Output:
|
| 218 |
+
[
|
| 219 |
+
{"sentiment":"positive","target_type":"theme","target_token":null,"target_label":"Forward-Deployed Engineers theme","suggestion":"Keep clustering AI-services patterns like FDE."},
|
| 220 |
+
{"sentiment":"negative","target_type":"lead","target_token":null,"target_label":"Bentley restructure lead","suggestion":"Skip leads where the recipient already knows the story β add a freshness check."},
|
| 221 |
+
{"sentiment":"neutral","target_type":"general","target_token":null,"target_label":"Food manufacturing coverage","suggestion":"Surface more food manufacturing signals β Valeo, Compleat, Premier Foods, etc."}
|
| 222 |
+
]
|
| 223 |
+
|
| 224 |
+
Reply: "Out of office until 18th."
|
| 225 |
+
Output: []
|
| 226 |
+
"""
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def parse_reply_to_signals(reply_body: str,
|
| 230 |
+
progress_cb: Optional[Callable[[str], None]] = None
|
| 231 |
+
) -> list[dict]:
|
| 232 |
+
"""Use Claude to extract structured signals from one reply body."""
|
| 233 |
+
if not reply_body or not reply_body.strip():
|
| 234 |
+
return []
|
| 235 |
+
api_key = os.environ.get("ANTHROPIC_API_KEY")
|
| 236 |
+
if not api_key:
|
| 237 |
+
if progress_cb:
|
| 238 |
+
progress_cb("feedback: ANTHROPIC_API_KEY not set β skipping LLM parse")
|
| 239 |
+
return []
|
| 240 |
+
|
| 241 |
+
from anthropic import Anthropic
|
| 242 |
+
client = Anthropic(api_key=api_key)
|
| 243 |
+
|
| 244 |
+
# Trim very long replies (full quoted-history threads) β Claude
|
| 245 |
+
# doesn't need 50KB of quoted prior emails to understand the
|
| 246 |
+
# current reply. Keep the first 4KB which is almost always the
|
| 247 |
+
# actual new content.
|
| 248 |
+
snippet = reply_body[:4000]
|
| 249 |
+
|
| 250 |
+
try:
|
| 251 |
+
msg = client.messages.create(
|
| 252 |
+
model="claude-sonnet-4-20250514",
|
| 253 |
+
max_tokens=1500,
|
| 254 |
+
system=_PARSE_SYSTEM_PROMPT,
|
| 255 |
+
messages=[{"role": "user",
|
| 256 |
+
"content": f"Reply text:\n\n{snippet}\n\nExtract feedback signals as a JSON array."}],
|
| 257 |
+
)
|
| 258 |
+
except Exception as e:
|
| 259 |
+
if progress_cb:
|
| 260 |
+
progress_cb(f"feedback: LLM call failed: {e}")
|
| 261 |
+
return []
|
| 262 |
+
|
| 263 |
+
text = msg.content[0].text.strip()
|
| 264 |
+
if text.startswith("```"):
|
| 265 |
+
lines = text.split("\n")
|
| 266 |
+
if lines[0].startswith("```"):
|
| 267 |
+
lines = lines[1:]
|
| 268 |
+
if lines and lines[-1].strip() == "```":
|
| 269 |
+
lines = lines[:-1]
|
| 270 |
+
text = "\n".join(lines).strip()
|
| 271 |
+
|
| 272 |
+
try:
|
| 273 |
+
raw = json.loads(text)
|
| 274 |
+
except json.JSONDecodeError:
|
| 275 |
+
if progress_cb:
|
| 276 |
+
progress_cb(f"feedback: LLM returned non-JSON: {text[:120]}")
|
| 277 |
+
return []
|
| 278 |
+
if not isinstance(raw, list):
|
| 279 |
+
return []
|
| 280 |
+
|
| 281 |
+
valid_sentiments = {"positive", "negative", "neutral"}
|
| 282 |
+
valid_targets = {"lead", "theme", "macro", "general"}
|
| 283 |
+
out = []
|
| 284 |
+
for r in raw:
|
| 285 |
+
if not isinstance(r, dict):
|
| 286 |
+
continue
|
| 287 |
+
suggestion = (r.get("suggestion") or "").strip()
|
| 288 |
+
if not suggestion:
|
| 289 |
+
continue
|
| 290 |
+
out.append({
|
| 291 |
+
"sentiment": (r.get("sentiment") or "neutral").lower()[:20]
|
| 292 |
+
if (r.get("sentiment") or "").lower() in valid_sentiments else "neutral",
|
| 293 |
+
"target_type": (r.get("target_type") or "general").lower()[:20]
|
| 294 |
+
if (r.get("target_type") or "").lower() in valid_targets else "general",
|
| 295 |
+
"target_token": (r.get("target_token") or None),
|
| 296 |
+
"target_label": (r.get("target_label") or "")[:200],
|
| 297 |
+
"suggestion": suggestion[:500],
|
| 298 |
+
})
|
| 299 |
+
return out[:8]
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
# ---------------------------------------------------------------------------
|
| 303 |
+
# Persistence
|
| 304 |
+
# ---------------------------------------------------------------------------
|
| 305 |
+
def _store_message(msg: dict, signals: list[dict]) -> int:
|
| 306 |
+
"""Persist a raw message + its parsed signals. Idempotent on message_id."""
|
| 307 |
+
conn = sqlite3.connect(DATABASE)
|
| 308 |
+
cur = conn.cursor()
|
| 309 |
+
now = datetime.utcnow().isoformat()
|
| 310 |
+
try:
|
| 311 |
+
cur.execute("""
|
| 312 |
+
INSERT INTO feedback_messages
|
| 313 |
+
(message_id, sender, sender_name, subject, body_text,
|
| 314 |
+
received_at, ingested_at, parsed)
|
| 315 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
| 316 |
+
""", (
|
| 317 |
+
msg["message_id"], msg["sender"], msg["sender_name"],
|
| 318 |
+
msg["subject"][:300], msg["body_text"][:8000],
|
| 319 |
+
msg["received_at"], now, 1 if signals else 0,
|
| 320 |
+
))
|
| 321 |
+
msg_row_id = cur.lastrowid
|
| 322 |
+
except sqlite3.IntegrityError:
|
| 323 |
+
# Already ingested β return the existing row id and skip signal writes
|
| 324 |
+
row = cur.execute(
|
| 325 |
+
"SELECT id FROM feedback_messages WHERE message_id = ?",
|
| 326 |
+
(msg["message_id"],),
|
| 327 |
+
).fetchone()
|
| 328 |
+
conn.close()
|
| 329 |
+
return row[0] if row else 0
|
| 330 |
+
|
| 331 |
+
recipient = _recipient_for_sender(msg["sender"])
|
| 332 |
+
for s in signals:
|
| 333 |
+
cur.execute("""
|
| 334 |
+
INSERT INTO feedback_signals
|
| 335 |
+
(message_id, recipient, sentiment, target_type, target_token,
|
| 336 |
+
target_label, suggestion, received_at)
|
| 337 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
| 338 |
+
""", (
|
| 339 |
+
msg_row_id, recipient, s["sentiment"], s["target_type"],
|
| 340 |
+
s["target_token"], s["target_label"], s["suggestion"],
|
| 341 |
+
msg["received_at"] or now,
|
| 342 |
+
))
|
| 343 |
+
conn.commit()
|
| 344 |
+
conn.close()
|
| 345 |
+
return msg_row_id
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def ingest(days: int = 7, dry_run: bool = False,
|
| 349 |
+
progress_cb: Optional[Callable[[str], None]] = None) -> dict:
|
| 350 |
+
"""End-to-end: poll mailbox β parse new replies β persist.
|
| 351 |
+
|
| 352 |
+
Returns {pulled, new, signals} counts. Never raises β failures are
|
| 353 |
+
logged so the digest cron continues.
|
| 354 |
+
"""
|
| 355 |
+
try:
|
| 356 |
+
from collator import init_company_db
|
| 357 |
+
init_company_db()
|
| 358 |
+
except Exception:
|
| 359 |
+
pass
|
| 360 |
+
|
| 361 |
+
msgs = fetch_recent_messages(days=days, progress_cb=progress_cb)
|
| 362 |
+
if not msgs:
|
| 363 |
+
return {"pulled": 0, "new": 0, "signals": 0}
|
| 364 |
+
|
| 365 |
+
# Skip messages we've already ingested
|
| 366 |
+
conn = sqlite3.connect(DATABASE)
|
| 367 |
+
seen_ids = {r[0] for r in conn.execute(
|
| 368 |
+
"SELECT message_id FROM feedback_messages").fetchall()}
|
| 369 |
+
conn.close()
|
| 370 |
+
new_msgs = [m for m in msgs if m["message_id"] not in seen_ids]
|
| 371 |
+
if progress_cb:
|
| 372 |
+
progress_cb(f"feedback: {len(new_msgs)} new messages to parse "
|
| 373 |
+
f"({len(msgs) - len(new_msgs)} already ingested)")
|
| 374 |
+
|
| 375 |
+
total_signals = 0
|
| 376 |
+
for m in new_msgs:
|
| 377 |
+
# Filter out obvious noise BEFORE paying for the LLM call
|
| 378 |
+
body_lower = (m["body_text"] or "").lower()
|
| 379 |
+
subject_lower = (m["subject"] or "").lower()
|
| 380 |
+
if any(k in subject_lower for k in [
|
| 381 |
+
"out of office", "automatic reply", "auto-reply", "undeliverable",
|
| 382 |
+
"delivery has failed", "mailer-daemon",
|
| 383 |
+
]):
|
| 384 |
+
if progress_cb:
|
| 385 |
+
progress_cb(f"feedback: skipping auto-reply from {m['sender']}")
|
| 386 |
+
continue
|
| 387 |
+
if len(body_lower.strip()) < 20:
|
| 388 |
+
if progress_cb:
|
| 389 |
+
progress_cb(f"feedback: skipping near-empty reply from {m['sender']}")
|
| 390 |
+
continue
|
| 391 |
+
|
| 392 |
+
signals = parse_reply_to_signals(m["body_text"], progress_cb=progress_cb)
|
| 393 |
+
if progress_cb:
|
| 394 |
+
progress_cb(f"feedback: {m['sender']} β {len(signals)} signals")
|
| 395 |
+
if dry_run:
|
| 396 |
+
for s in signals:
|
| 397 |
+
progress_cb and progress_cb(f" [dry] {s['sentiment']} | {s['target_type']} | {s['suggestion']}")
|
| 398 |
+
continue
|
| 399 |
+
_store_message(m, signals)
|
| 400 |
+
total_signals += len(signals)
|
| 401 |
+
|
| 402 |
+
return {"pulled": len(msgs), "new": len(new_msgs), "signals": total_signals}
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
# ---------------------------------------------------------------------------
|
| 406 |
+
# CLI
|
| 407 |
+
# ---------------------------------------------------------------------------
|
| 408 |
+
if __name__ == "__main__":
|
| 409 |
+
p = argparse.ArgumentParser()
|
| 410 |
+
p.add_argument("--days", type=int, default=7,
|
| 411 |
+
help="How many days of mailbox history to poll (default 7)")
|
| 412 |
+
p.add_argument("--dry-run", action="store_true",
|
| 413 |
+
help="Poll + parse but don't persist")
|
| 414 |
+
args = p.parse_args()
|
| 415 |
+
|
| 416 |
+
def log(msg: str) -> None:
|
| 417 |
+
print(f"[feedback] {msg}", flush=True)
|
| 418 |
+
|
| 419 |
+
summary = ingest(days=args.days, dry_run=args.dry_run, progress_cb=log)
|
| 420 |
+
log(f"done: pulled={summary['pulled']} new={summary['new']} signals={summary['signals']}")
|
|
@@ -76,6 +76,25 @@ def main() -> int:
|
|
| 76 |
else:
|
| 77 |
_log("skipping state pull (--no-sync)")
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
# ---- Step 2: run the hunt ---------------------------------------------
|
| 80 |
if not args.no_hunt:
|
| 81 |
try:
|
|
|
|
| 76 |
else:
|
| 77 |
_log("skipping state pull (--no-sync)")
|
| 78 |
|
| 79 |
+
# ---- Step 1.5: ingest replies to last week's digest -------------------
|
| 80 |
+
# Reads the inbox via Microsoft Graph, parses each reply into
|
| 81 |
+
# structured feedback_signals, persists. Runs AFTER state pull
|
| 82 |
+
# (so dedup against historic feedback_messages works) but BEFORE
|
| 83 |
+
# the hunt (so the recap header in this week's digests is current).
|
| 84 |
+
# Non-fatal β digests still ship if Mail.Read permission isn't
|
| 85 |
+
# granted yet; the recap section just renders empty.
|
| 86 |
+
try:
|
| 87 |
+
from feedback_ingest import ingest as _ingest_feedback
|
| 88 |
+
summary = _ingest_feedback(days=8,
|
| 89 |
+
progress_cb=lambda m: _log(f"feedback: {m}"))
|
| 90 |
+
_log(
|
| 91 |
+
f"feedback ingest: pulled={summary['pulled']} "
|
| 92 |
+
f"new={summary['new']} signals={summary['signals']}"
|
| 93 |
+
)
|
| 94 |
+
except Exception as e:
|
| 95 |
+
_log(f"β οΈ feedback ingest failed (recap will be empty): {e}")
|
| 96 |
+
traceback.print_exc()
|
| 97 |
+
|
| 98 |
# ---- Step 2: run the hunt ---------------------------------------------
|
| 99 |
if not args.no_hunt:
|
| 100 |
try:
|
|
@@ -318,6 +318,10 @@ def fetch_warm_leads_for_colleague(colleague_name: str, days: int = 7,
|
|
| 318 |
}
|
| 319 |
info["signal_count"] = (len(info["jobs"]) + len(info["news"])
|
| 320 |
+ len(info["tenders"]))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
out.append(info)
|
| 322 |
if skipped_oos:
|
| 323 |
# Print to stdout (visible in GH Actions logs) so we can audit
|
|
@@ -448,7 +452,7 @@ If only 1-2 leads survive, skip sector subheadings.
|
|
| 448 |
- Optional `<h2>Your warm-route leads</h2>` section header before the first lead, in the same colour style as the upstream macro/themes headers (`<h2 style="color:#1a237e;font-size:1.05em;margin:24px 0 8px 0;border-bottom:1px solid #cfd8dc;padding-bottom:4px;">Your warm-route leads</h2>`).
|
| 449 |
- If grouping by sector, use `<h4 style="color:#37474f;margin:18px 0 6px 0;">Sector name</h4>` between groups.
|
| 450 |
- For each kept lead:
|
| 451 |
-
- `<h3>` β `[CLIENT] ` (only if a Curium client) + Company name
|
| 452 |
- `<p>` *Why now*: 1-2 sentences. **Lead with a quantified fact or quote** if any are in the data. NOT "they hired someone senior" β say what programme that hire suggests, anchored to the numbers.
|
| 453 |
- `<p>` *Your route in*: name the contact (with role); flag if mover/promoted/senior.
|
| 454 |
- `<ul>` *Sources* β each `<li>` has the signal type + a short clickable `<a href="β¦">title</a>` (use the URLs in the raw data, don't invent).
|
|
@@ -491,6 +495,64 @@ def _sector_block() -> str:
|
|
| 491 |
return "\n".join(lines)
|
| 492 |
|
| 493 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
def _macro_pulse_html() -> str:
|
| 495 |
"""Render the cached UK macro pulse as a top-of-digest section.
|
| 496 |
|
|
@@ -702,30 +764,38 @@ def build_digest_html(colleague_name: str, leads: list[dict]) -> str:
|
|
| 702 |
"""Compose the email body HTML for one colleague. Returns the inner
|
| 703 |
HTML (no <html>/<body> wrappers β caller wraps for SMTP).
|
| 704 |
|
| 705 |
-
Layout (
|
|
|
|
| 706 |
1. UK macro pulse (cached weekly indicators β Phase 2)
|
| 707 |
2. Cross-sector themes (cached weekly clusters β Phase 3)
|
| 708 |
-
3. Per-colleague warm-route leads (LLM-composed, sector-grouped
|
|
|
|
|
|
|
|
|
|
| 709 |
Each section is omitted gracefully when its data is empty.
|
| 710 |
"""
|
|
|
|
| 711 |
macro = _macro_pulse_html()
|
| 712 |
themes = _themes_html()
|
| 713 |
leads_body = _compose_leads_body(colleague_name, leads)
|
|
|
|
|
|
|
|
|
|
| 714 |
|
| 715 |
-
if not leads_body and not macro and not themes:
|
| 716 |
return _NO_LEADS_BODY_HTML.format(name=colleague_name)
|
| 717 |
|
| 718 |
-
# If there are no leads but we DO have macro/themes, use a
|
| 719 |
-
# opener so the email still feels addressed to the colleague.
|
| 720 |
if not leads_body:
|
| 721 |
opener = (
|
| 722 |
f'<p>Morning {colleague_name},</p>'
|
| 723 |
f'<p>No new warm-route activity in your network this week, but '
|
| 724 |
f'the wider UK pulse + cross-sector themes are below.</p>'
|
| 725 |
)
|
| 726 |
-
return opener + macro + themes
|
| 727 |
|
| 728 |
-
return macro + themes + leads_body
|
| 729 |
|
| 730 |
|
| 731 |
def _fallback_html(colleague_name: str, leads: list[dict]) -> str:
|
|
@@ -851,9 +921,23 @@ def build_aggregate_digest(recipient_name: str, days: int = 7) -> dict:
|
|
| 851 |
f"{'s' if own_n != 1 else ''} appear first; the rest of the team "
|
| 852 |
f"follows below.</p>"
|
| 853 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 854 |
macro = _macro_pulse_html()
|
| 855 |
themes = _themes_html()
|
| 856 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 857 |
full_html = _wrap_html(recipient_name, body_html)
|
| 858 |
text_fallback = _html_to_text(full_html)
|
| 859 |
today = datetime.now().strftime("%-d %b %Y") if os.name != "nt" else datetime.now().strftime("%d %b %Y")
|
|
|
|
| 318 |
}
|
| 319 |
info["signal_count"] = (len(info["jobs"]) + len(info["news"])
|
| 320 |
+ len(info["tenders"]))
|
| 321 |
+
# Stable feedback token for this lead. Recipients can reference
|
| 322 |
+
# it in replies β feedback_ingest matches it back via
|
| 323 |
+
# feedback_signals.target_token. Format: lead-<company-slug>-<weekcode>.
|
| 324 |
+
info["feedback_token"] = _make_lead_token(cn)
|
| 325 |
out.append(info)
|
| 326 |
if skipped_oos:
|
| 327 |
# Print to stdout (visible in GH Actions logs) so we can audit
|
|
|
|
| 452 |
- Optional `<h2>Your warm-route leads</h2>` section header before the first lead, in the same colour style as the upstream macro/themes headers (`<h2 style="color:#1a237e;font-size:1.05em;margin:24px 0 8px 0;border-bottom:1px solid #cfd8dc;padding-bottom:4px;">Your warm-route leads</h2>`).
|
| 453 |
- If grouping by sector, use `<h4 style="color:#37474f;margin:18px 0 6px 0;">Sector name</h4>` between groups.
|
| 454 |
- For each kept lead:
|
| 455 |
+
- `<h3>` β `[CLIENT] ` (only if a Curium client) + Company name. After the company name, append the lead's `feedback_token` (which is in the raw data) as a small grey tag: `<span style="font-size:0.7em;color:#90a4ae;font-weight:400;">lead-β¦</span>`. This is how recipients reference the lead in feedback replies β do NOT omit it.
|
| 456 |
- `<p>` *Why now*: 1-2 sentences. **Lead with a quantified fact or quote** if any are in the data. NOT "they hired someone senior" β say what programme that hire suggests, anchored to the numbers.
|
| 457 |
- `<p>` *Your route in*: name the contact (with role); flag if mover/promoted/senior.
|
| 458 |
- `<ul>` *Sources* β each `<li>` has the signal type + a short clickable `<a href="β¦">title</a>` (use the URLs in the raw data, don't invent).
|
|
|
|
| 495 |
return "\n".join(lines)
|
| 496 |
|
| 497 |
|
| 498 |
+
def _make_lead_token(company_name: str, when: Optional[datetime] = None) -> str:
|
| 499 |
+
"""Stable, human-readable token referencing a lead in a given week.
|
| 500 |
+
|
| 501 |
+
Format: lead-<slug>-YYYYwWW (ISO week number). Example:
|
| 502 |
+
lead-bentley-motors-2026w19. Recipients quote this verbatim in
|
| 503 |
+
feedback replies so feedback_ingest can match it back.
|
| 504 |
+
"""
|
| 505 |
+
import re as _re
|
| 506 |
+
slug = _re.sub(r"[^a-z0-9]+", "-", (company_name or "").lower()).strip("-")[:48]
|
| 507 |
+
dt = when or datetime.now()
|
| 508 |
+
iso_year, iso_week, _ = dt.isocalendar()
|
| 509 |
+
return f"lead-{slug}-{iso_year}w{iso_week:02d}"
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _feedback_recap_html(recipient: Optional[str] = None) -> str:
|
| 513 |
+
"""Render the 'what you told us last week' recap. Pulled from the
|
| 514 |
+
feedback_signals table populated by feedback_ingest.
|
| 515 |
+
|
| 516 |
+
`recipient` narrows to one colleague's own feedback so each digest
|
| 517 |
+
acknowledges what THEY said. The aggregate digest passes None and
|
| 518 |
+
gets the cross-team recap."""
|
| 519 |
+
try:
|
| 520 |
+
from feedback_digest import build_recap_html
|
| 521 |
+
except ImportError:
|
| 522 |
+
return ""
|
| 523 |
+
try:
|
| 524 |
+
return build_recap_html(days=8, recipient=recipient) or ""
|
| 525 |
+
except Exception:
|
| 526 |
+
# Never let a feedback recap failure block the digest itself
|
| 527 |
+
return ""
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def _feedback_prompt_html(token_examples: list[str]) -> str:
|
| 531 |
+
"""Closing block telling recipients HOW to give feedback. Mentions
|
| 532 |
+
the lead tokens they can reference. Empty token_examples = generic
|
| 533 |
+
prompt, no per-lead reference."""
|
| 534 |
+
ref_line = ""
|
| 535 |
+
if token_examples:
|
| 536 |
+
ref_line = (
|
| 537 |
+
f'<li>Reference a specific lead by its token, e.g. '
|
| 538 |
+
f'<code>{token_examples[0]}</code> β '
|
| 539 |
+
f'"<em>{token_examples[0]} β already knew, skip next time</em>".</li>'
|
| 540 |
+
)
|
| 541 |
+
return (
|
| 542 |
+
'<hr style="border:none;border-top:1px solid #eceff1;margin:24px 0 12px 0;">'
|
| 543 |
+
'<h3 style="color:#1a237e;font-size:0.95em;margin:8px 0 6px 0;">'
|
| 544 |
+
'Help us tune this β just reply</h3>'
|
| 545 |
+
'<p style="margin:4px 0;color:#37474f;">'
|
| 546 |
+
'Reply to this email with any feedback. The system reads every '
|
| 547 |
+
'reply and threads it into next Monday\'s digest.</p>'
|
| 548 |
+
'<ul style="margin:4px 0 8px 18px;color:#37474f;">'
|
| 549 |
+
+ ref_line +
|
| 550 |
+
'<li>Or just write naturally: "more food manufacturing", '
|
| 551 |
+
'"Bentley felt thin", "loved the FDE theme".</li>'
|
| 552 |
+
'</ul>'
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
def _macro_pulse_html() -> str:
|
| 557 |
"""Render the cached UK macro pulse as a top-of-digest section.
|
| 558 |
|
|
|
|
| 764 |
"""Compose the email body HTML for one colleague. Returns the inner
|
| 765 |
HTML (no <html>/<body> wrappers β caller wraps for SMTP).
|
| 766 |
|
| 767 |
+
Layout (mirrors the manual benchmark + closed-loop feedback):
|
| 768 |
+
0. "What you told us last week" recap (from feedback_signals)
|
| 769 |
1. UK macro pulse (cached weekly indicators β Phase 2)
|
| 770 |
2. Cross-sector themes (cached weekly clusters β Phase 3)
|
| 771 |
+
3. Per-colleague warm-route leads (LLM-composed, sector-grouped,
|
| 772 |
+
each lead carries a feedback_token recipients can quote in
|
| 773 |
+
replies)
|
| 774 |
+
4. Feedback prompt (how to reply β closes the loop)
|
| 775 |
Each section is omitted gracefully when its data is empty.
|
| 776 |
"""
|
| 777 |
+
recap = _feedback_recap_html(recipient=colleague_name)
|
| 778 |
macro = _macro_pulse_html()
|
| 779 |
themes = _themes_html()
|
| 780 |
leads_body = _compose_leads_body(colleague_name, leads)
|
| 781 |
+
token_examples = [l.get("feedback_token") for l in (leads or [])
|
| 782 |
+
if l.get("feedback_token")][:1]
|
| 783 |
+
fb_prompt = _feedback_prompt_html(token_examples)
|
| 784 |
|
| 785 |
+
if not leads_body and not macro and not themes and not recap:
|
| 786 |
return _NO_LEADS_BODY_HTML.format(name=colleague_name)
|
| 787 |
|
| 788 |
+
# If there are no leads but we DO have macro/themes/recap, use a
|
| 789 |
+
# thinner opener so the email still feels addressed to the colleague.
|
| 790 |
if not leads_body:
|
| 791 |
opener = (
|
| 792 |
f'<p>Morning {colleague_name},</p>'
|
| 793 |
f'<p>No new warm-route activity in your network this week, but '
|
| 794 |
f'the wider UK pulse + cross-sector themes are below.</p>'
|
| 795 |
)
|
| 796 |
+
return opener + recap + macro + themes + fb_prompt
|
| 797 |
|
| 798 |
+
return recap + macro + themes + leads_body + fb_prompt
|
| 799 |
|
| 800 |
|
| 801 |
def _fallback_html(colleague_name: str, leads: list[dict]) -> str:
|
|
|
|
| 921 |
f"{'s' if own_n != 1 else ''} appear first; the rest of the team "
|
| 922 |
f"follows below.</p>"
|
| 923 |
)
|
| 924 |
+
# Recap shows ALL feedback across the team for the aggregate
|
| 925 |
+
# digest β the admin recipient (digest_role="all") sees the whole
|
| 926 |
+
# team's signal at once.
|
| 927 |
+
recap = _feedback_recap_html(recipient=None)
|
| 928 |
macro = _macro_pulse_html()
|
| 929 |
themes = _themes_html()
|
| 930 |
+
# Pull a sample token from the recipient's own leads (idx 0) for the
|
| 931 |
+
# feedback prompt example β falls back to no example if they had none.
|
| 932 |
+
own_token_example: list[str] = []
|
| 933 |
+
own_leads = fetch_warm_leads_for_colleague(recipient_name, days=days)
|
| 934 |
+
for l in own_leads:
|
| 935 |
+
t = l.get("feedback_token")
|
| 936 |
+
if t:
|
| 937 |
+
own_token_example = [t]
|
| 938 |
+
break
|
| 939 |
+
fb_prompt = _feedback_prompt_html(own_token_example)
|
| 940 |
+
body_html = intro + recap + macro + themes + "\n".join(sections) + fb_prompt
|
| 941 |
full_html = _wrap_html(recipient_name, body_html)
|
| 942 |
text_fallback = _html_to_text(full_html)
|
| 943 |
today = datetime.now().strftime("%-d %b %Y") if os.name != "nt" else datetime.now().strftime("%d %b %Y")
|