-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1256 lines (1095 loc) · 42.2 KB
/
server.py
File metadata and controls
1256 lines (1095 loc) · 42.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
from dotenv import load_dotenv
from pathlib import Path
from services.seo import is_indexable
# CRITICAL: load .env BEFORE importing provider modules — they read env vars at import time.
ROOT_DIR = Path(__file__).parent
load_dotenv(ROOT_DIR / ".env", override=True)
from fastapi import (
FastAPI,
APIRouter,
HTTPException,
Request,
Response,
Cookie,
Header,
BackgroundTasks,
)
from starlette.middleware.cors import CORSMiddleware
from motor.motor_asyncio import AsyncIOMotorClient
import os
import json
import logging
import uuid
import asyncio
import secrets
import httpx
from pydantic import BaseModel, Field
from typing import List, Optional, Literal
from datetime import datetime, timezone, timedelta
from llm_provider import run_llm, run_llm_cheap
from auth_provider import (
attach_auth_routes,
get_current_user_from_token,
extract_token,
AUTH_PROVIDER,
)
# Mongo
mongo_url = os.environ["MONGO_URL"]
client = AsyncIOMotorClient(mongo_url)
db = client[os.environ["DB_NAME"]]
EMERGENT_LLM_KEY = os.environ.get("EMERGENT_LLM_KEY", "")
app = FastAPI()
api = APIRouter(prefix="/api")
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
JSON_REPAIR_SYSTEM_PROMPT = """You repair malformed JSON.
Return ONLY valid JSON.
- Preserve the original meaning and fields.
- Do not add commentary or markdown fences.
- Escape quotes and newlines correctly inside string values.
- Keep arrays, numbers, booleans, and nulls as proper JSON types."""
# ---------- Rate limiting ----------
RL_IDEA_COOLDOWN_SEC = int(os.environ.get("RL_IDEA_COOLDOWN_SEC", "60"))
RL_DIAGNOSE_COOLDOWN_SEC = int(os.environ.get("RL_DIAGNOSE_COOLDOWN_SEC", "1800"))
RL_DIAGNOSE_PER_WEEK = int(os.environ.get("RL_DIAGNOSE_PER_WEEK", "5"))
IST = timezone(timedelta(hours=5, minutes=30))
async def _has_unlimited_access(user_id: str) -> bool:
"""Return True for users who should bypass product rate limits."""
users = getattr(db, "users", None)
if users is None:
return False
user = await users.find_one({"user_id": user_id}, {"_id": 0, "access_tier": 1})
return (user or {}).get("access_tier") == "unlimited"
async def _check_rate_limit(user_id: str, action: str, cooldown_sec: int = 0):
"""Mongo-backed per-user cooldown. Records the accepted call."""
if cooldown_sec <= 0:
return
if await _has_unlimited_access(user_id):
return
now = datetime.now(timezone.utc)
last = await db.rate_limits.find_one(
{"user_id": user_id, "action": action},
{"_id": 0, "ts": 1},
sort=[("ts", -1)],
)
if action == "create_idea":
await _check_new_idea_gate(user_id)
if last:
last_ts = last["ts"]
if isinstance(last_ts, str):
last_ts = datetime.fromisoformat(last_ts)
if last_ts.tzinfo is None:
last_ts = last_ts.replace(tzinfo=timezone.utc)
wait = cooldown_sec - int((now - last_ts).total_seconds())
if wait > 0:
raise HTTPException(
status_code=429, detail=f"Slow down. Try again in {wait}s."
)
await db.rate_limits.insert_one(
{"user_id": user_id, "action": action, "ts": now.isoformat()}
)
async def _check_new_idea_gate(user_id: str):
"""Enforce weekly diagnosis limit before allowing new ideas."""
if await _has_unlimited_access(user_id):
return
usage = await _diagnosis_usage(user_id)
weekly_count = usage["weekly_used"]
if weekly_count >= RL_DIAGNOSE_PER_WEEK:
raise HTTPException(
status_code=429,
detail={
"message": "Come back after making progress.",
"code": "diagnosis_weekly_limit",
**usage,
},
)
async def _check_diagnosis_gate(user_id: str, idea_id: str):
"""Enforce cheap product gates before spending tokens on another diagnosis."""
if await _has_unlimited_access(user_id):
return
usage = await _diagnosis_usage(user_id)
weekly_count = usage["weekly_used"]
if weekly_count >= RL_DIAGNOSE_PER_WEEK:
raise HTTPException(
status_code=429,
detail={
"message": "Come back after making progress.",
"code": "diagnosis_weekly_limit",
**usage,
},
)
latest_diag = await db.diagnoses.find_one(
{"idea_id": idea_id, "user_id": user_id}, {"_id": 0}, sort=[("created_at", -1)]
)
if latest_diag:
actions = latest_diag.get("this_week_actions", [])
if not any(a.get("done") for a in actions):
raise HTTPException(
status_code=400,
detail={
"message": "Complete 1 task to unlock.",
"code": "diagnosis_action_required",
**usage,
},
)
if usage["cooldown_remaining_seconds"] > 0:
detail = (
"This only improves if your situation changes. Go execute."
if weekly_count >= 2
else f"Wait {max(1, usage['cooldown_remaining_seconds'] // 60)}m before re-checking."
)
raise HTTPException(
status_code=429,
detail={
"message": detail,
"code": "diagnosis_cooldown",
**usage,
},
)
await db.rate_limits.insert_one(
{
"user_id": user_id,
"action": "diagnose",
"ts": datetime.now(timezone.utc).isoformat(),
}
)
def _coerce_dt(value):
if not value:
return None
if isinstance(value, str):
value = datetime.fromisoformat(value)
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value
def _to_ist_iso(value):
dt = _coerce_dt(value)
return dt.astimezone(IST).isoformat() if dt else None
def _add_ist_fields(doc: dict, fields: List[str]) -> dict:
for field in fields:
if field in doc:
doc[f"{field}_ist"] = _to_ist_iso(doc.get(field))
return doc
async def _diagnosis_usage(user_id: str) -> dict:
now = datetime.now(timezone.utc)
week_ago = (now - timedelta(days=7)).isoformat()
weekly_count = await db.rate_limits.count_documents(
{"user_id": user_id, "action": "diagnose", "ts": {"$gte": week_ago}}
)
last = await db.rate_limits.find_one(
{"user_id": user_id, "action": "diagnose"},
{"_id": 0, "ts": 1},
sort=[("ts", -1)],
)
last_ts = _coerce_dt(last.get("ts")) if last else None
unlimited = await _has_unlimited_access(user_id)
cooldown_remaining = 0
next_recheck_at = None
if last_ts and not unlimited:
cooldown_remaining = max(
0, RL_DIAGNOSE_COOLDOWN_SEC - int((now - last_ts).total_seconds())
)
next_recheck_at = (
last_ts + timedelta(seconds=RL_DIAGNOSE_COOLDOWN_SEC)
).astimezone(IST)
return {
"unlimited": unlimited,
"weekly_used": weekly_count,
"weekly_limit": None if unlimited else RL_DIAGNOSE_PER_WEEK,
"weekly_remaining": (
None if unlimited else max(0, RL_DIAGNOSE_PER_WEEK - weekly_count)
),
"cooldown_seconds": 0 if unlimited else RL_DIAGNOSE_COOLDOWN_SEC,
"cooldown_remaining_seconds": cooldown_remaining,
"last_diagnosis_at_ist": (
last_ts.astimezone(IST).isoformat() if last_ts else None
),
"next_recheck_at_ist": next_recheck_at.isoformat() if next_recheck_at else None,
"timezone": "Asia/Kolkata",
}
# ---------- Cheap prefilter ----------
PREFILTER_SYSTEM = """You are a sharp triage filter for a startup-idea evaluation tool.
Your ONLY job: decide whether the submission is worth running through the expensive deep-diagnosis pipeline.
When you reject, the reason must be a savage, sarcastic one-liner. Be funny and sharp, but no slurs,
threats, profanity, or personal attacks. Roast the submission, not the founder.
REJECT (passes=false) when:
- gibberish: the text is empty, single random words, keyboard mashing ("asdf", "test test"), or filler ipsum
- non_startup: the submission is clearly not a startup idea
- duplicate: the submission is essentially the same idea as one this founder already submitted
ACCEPT (passes=true) when:
- It's a real attempt at describing a startup/product idea, even if rough or vague.
OUTPUT CONTRACT - return ONLY this JSON, no prose, no fences:
{
"passes": true | false,
"category": "ok" | "gibberish" | "non_startup" | "duplicate",
"reason": "one short sentence. If passes=false, make it savage and sarcastic. If duplicate, name the existing idea."
}"""
async def _prefilter_idea(payload: "IdeaCreate", existing_ideas: List[dict]) -> dict:
existing_block = (
"\n".join(
f"- {i.get('title', '')}: {i.get('one_liner', '')}" for i in existing_ideas
)
or "(none - first idea)"
)
user_msg = (
"NEW SUBMISSION:\n"
f"Title: {payload.title}\n"
f"One-liner: {payload.one_liner}\n"
f"Problem: {payload.problem}\n"
f"Target user: {payload.target_user}\n"
f"Access to users: {payload.access_to_users}\n"
f"Domain experience: {payload.domain_experience}\n"
f"Motivation: {payload.motivation}\n"
f"Extra: {payload.extra_context or '(none)'}\n\n"
f"FOUNDER'S EXISTING IDEAS:\n{existing_block}\n\n"
"Return ONLY the JSON object."
)
try:
raw = await run_llm_cheap(PREFILTER_SYSTEM, user_msg)
except Exception as e:
logger.warning("prefilter call failed, allowing through: %s", e)
return {"passes": True, "category": "ok", "reason": "prefilter unavailable"}
text = raw.strip()
if text.startswith("```"):
text = text.strip("`")
if text.lower().startswith("json"):
text = text[4:].strip()
start = text.find("{")
end = text.rfind("}")
if start == -1 or end == -1:
logger.warning("prefilter returned non-JSON, allowing through: %s", raw[:160])
return {"passes": True, "category": "ok", "reason": "prefilter unparseable"}
try:
parsed = json.loads(text[start : end + 1])
except json.JSONDecodeError:
return {"passes": True, "category": "ok", "reason": "prefilter unparseable"}
return {
"passes": bool(parsed.get("passes", True)),
"category": parsed.get("category", "ok"),
"reason": parsed.get("reason", ""),
}
# ---------- Models ----------
class User(BaseModel):
user_id: str
email: str
name: str
picture: Optional[str] = None
access_tier: Optional[str] = "free"
founder_type: Optional[str] = (
None # first_time | technical | non_technical | repeat
)
created_at: datetime
class IdeaCreate(BaseModel):
title: str
one_liner: str
problem: str
target_user: str
access_to_users: str # how you'll reach them
domain_experience: str
motivation: str
extra_context: Optional[str] = ""
class Idea(BaseModel):
idea_id: str
user_id: str
title: str
one_liner: str
problem: str
target_user: str
access_to_users: str
domain_experience: str
motivation: str
extra_context: str
status: str = "active" # active | killed | pivoted | archived
latest_verdict: Optional[str] = None # pursue | pivot | kill
latest_fmf_score: Optional[int] = None
latest_wtp_score: Optional[int] = None
latest_momentum_score: Optional[int] = None
streak: int = 0
last_checkin_at: Optional[datetime] = None
created_at: datetime
updated_at: datetime
class CheckinCreate(BaseModel):
actions_completed: List[str] = [] # list of action ids
what_changed: str = ""
new_learnings: str = ""
blockers: str = ""
class Action(BaseModel):
action_id: str
title: str
why: str
how: str # hyper-specific steps/script
assumption: str # assumption it validates
effort: str # S/M/L
done: bool = False
class Diagnosis(BaseModel):
diagnosis_id: str
idea_id: str
user_id: str
verdict: Literal["pursue", "pivot", "kill"]
verdict_headline: str # one sharp sentence
diagnosis: str # 2-3 sentences, what's really going on
key_insight: str # what they're missing
kill_conditions: List[str] # hard truths, triggers to kill
momentum_signals: List[str] # what would prove traction
fmf_score: int # 0-100 founder-market fit
fmf_reason: str
wtp_score: int # 0-100 willingness to pay
wtp_reason: str
execution_risk: int # 0-100
execution_risk_reason: str
momentum_score: int # 0-100
momentum_reason: str
competitor_signal: str # one crisp paragraph
this_week_actions: List[Action]
created_at: datetime
class Checkin(BaseModel):
checkin_id: str
idea_id: str
user_id: str
actions_completed: List[str]
what_changed: str
new_learnings: str
blockers: str
delta_summary: str = "" # AI-generated "what changed since last week"
created_at: datetime
# ---------- Auth ----------
async def get_current_user(
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
) -> User:
token = extract_token(session_token_cookie, authorization)
if not token:
raise HTTPException(status_code=401, detail="Not authenticated")
user_doc = await get_current_user_from_token(token, db)
if not user_doc:
raise HTTPException(status_code=401, detail="Invalid or expired session")
if isinstance(user_doc.get("created_at"), str):
user_doc["created_at"] = datetime.fromisoformat(user_doc["created_at"])
# strip fields not in User model (e.g. password_hash)
user_doc.pop("password_hash", None)
return User(**user_doc)
# Mount provider-specific auth routes (login/register OR /auth/session)
attach_auth_routes(api, db)
@api.get("/auth/me")
async def auth_me(
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
user = await get_current_user(request, session_token_cookie, authorization)
return _add_ist_fields(user.model_dump(), ["created_at"])
@api.post("/auth/founder-type")
async def set_founder_type(
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
user = await get_current_user(request, session_token_cookie, authorization)
body = await request.json()
ftype = body.get("founder_type")
if ftype not in ["first_time", "technical", "non_technical", "repeat"]:
raise HTTPException(status_code=400, detail="Invalid founder_type")
await db.users.update_one(
{"user_id": user.user_id}, {"$set": {"founder_type": ftype}}
)
return {"ok": True, "founder_type": ftype}
# ---------- Ideas ----------
def _serialize_idea(doc: dict) -> dict:
for k in ["created_at", "updated_at", "last_checkin_at", "archived_at"]:
v = doc.get(k)
if isinstance(v, str):
try:
doc[k] = datetime.fromisoformat(v)
except Exception:
pass
return _add_ist_fields(
doc, ["created_at", "updated_at", "last_checkin_at", "archived_at"]
)
def _serialize_timeline_doc(doc: Optional[dict]) -> Optional[dict]:
if not doc:
return doc
return _add_ist_fields(
doc, ["created_at", "updated_at", "last_checkin_at", "archived_at"]
)
@api.post("/ideas")
async def create_idea(
payload: IdeaCreate,
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
user = await get_current_user(request, session_token_cookie, authorization)
await _check_rate_limit(
user.user_id, "create_idea", cooldown_sec=RL_IDEA_COOLDOWN_SEC
)
existing_ideas = (
await db.ideas.find(
{"user_id": user.user_id, "status": {"$ne": "archived"}},
{"_id": 0, "title": 1, "one_liner": 1},
)
.sort("created_at", -1)
.to_list(50)
)
prefilter = await _prefilter_idea(payload, existing_ideas)
if not prefilter.get("passes", True):
raise HTTPException(
status_code=400,
detail={
"code": "idea_prefilter_failed",
"category": prefilter.get("category", "rejected"),
"reason": prefilter.get("reason", "Submission was rejected."),
},
)
now = datetime.now(timezone.utc)
idea_id = f"idea_{uuid.uuid4().hex[:12]}"
doc = {
"idea_id": idea_id,
"user_id": user.user_id,
**payload.model_dump(),
"status": "active",
"latest_verdict": None,
"latest_fmf_score": None,
"latest_wtp_score": None,
"latest_momentum_score": None,
"streak": 0,
"last_checkin_at": None,
"created_at": now.isoformat(),
"updated_at": now.isoformat(),
}
await db.ideas.insert_one(doc)
doc.pop("_id", None)
return _serialize_idea({**doc})
@api.get("/ideas")
async def list_ideas(
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
user = await get_current_user(request, session_token_cookie, authorization)
ideas = (
await db.ideas.find(
{"user_id": user.user_id, "status": {"$ne": "archived"}}, {"_id": 0}
)
.sort("created_at", -1)
.to_list(200)
)
return [_serialize_idea(i) for i in ideas]
@api.get("/ideas/{idea_id}")
async def get_idea(
idea_id: str,
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
user = await get_current_user(request, session_token_cookie, authorization)
idea = await db.ideas.find_one(
{"idea_id": idea_id, "user_id": user.user_id, "status": {"$ne": "archived"}},
{"_id": 0},
)
if not idea:
raise HTTPException(404, "Idea not found")
diag = await db.diagnoses.find_one(
{"idea_id": idea_id}, {"_id": 0}, sort=[("created_at", -1)]
)
checkins = (
await db.checkins.find({"idea_id": idea_id}, {"_id": 0})
.sort("created_at", -1)
.to_list(50)
)
diagnoses = (
await db.diagnoses.find({"idea_id": idea_id}, {"_id": 0})
.sort("created_at", -1)
.to_list(50)
)
return {
"idea": _serialize_idea(idea),
"latest_diagnosis": _serialize_timeline_doc(diag),
"checkins": [_serialize_timeline_doc(c) for c in checkins],
"diagnoses": [_serialize_timeline_doc(d) for d in diagnoses],
"diagnosis_limits": await _diagnosis_usage(user.user_id),
}
@api.get("/usage/limits")
async def usage_limits(
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
user = await get_current_user(request, session_token_cookie, authorization)
return {"diagnosis": await _diagnosis_usage(user.user_id)}
@api.delete("/ideas/{idea_id}")
async def delete_idea(
idea_id: str,
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
user = await get_current_user(request, session_token_cookie, authorization)
now = datetime.now(timezone.utc).isoformat()
await db.ideas.update_one(
{"idea_id": idea_id, "user_id": user.user_id},
{"$set": {"status": "archived", "archived_at": now, "updated_at": now}},
)
return {"ok": True, "archived": True}
# ---------- AI: Diagnose ----------
SYSTEM_PROMPT = """You are a brutally honest, highly intelligent startup advisor. Think like Paul Graham meets a no-BS angel investor who has seen 1000 founders.
YOUR JOB:
- Diagnose BEFORE prescribing.
- Be ruthlessly honest, but constructive. Never a motivational coach.
- Never give generic advice. Every sentence must be specific to THIS founder and THIS idea.
- Cut through vague thinking. Call out delusion. Surface the one thing they're missing.
- Every action must include exact people to talk to, exact messages to send, exact assumptions to validate.
OUTPUT CONTRACT:
You MUST respond with ONLY valid JSON matching this schema. No prose before or after. No markdown fences.
All string values must be valid JSON strings: escape any inner double quotes and use \\n instead of literal line breaks inside strings.
{
"verdict": "pursue" | "pivot" | "kill",
"verdict_headline": "one sharp sentence, max 14 words, that lands like a punch",
"diagnosis": "2-3 sentences: what is REALLY going on with this idea and this founder. Be specific.",
"key_insight": "the one non-obvious thing they're missing. Start with 'You're missing...' or 'The real question is...'",
"kill_conditions": ["hard, specific conditions where they should kill this", "max 3"],
"momentum_signals": ["specific leading indicators that would prove real traction", "max 3"],
"fmf_score": 0-100,
"fmf_reason": "one sentence why (founder-market fit, based on domain experience + access to users + motivation)",
"wtp_score": 0-100,
"wtp_reason": "one sentence why (willingness to pay — is this a painkiller or vitamin?)",
"execution_risk": 0-100,
"execution_risk_reason": "one sentence why",
"momentum_score": 0-100,
"momentum_reason": "one sentence why (current traction/evidence velocity based on actions, check-ins, or lack of proof)",
"competitor_signal": "one crisp paragraph: who exists, what's the honest positioning gap, is the space hot or crowded",
"this_week_actions": [
{
"action_id": "a1",
"title": "short punchy title",
"why": "one sentence why this matters THIS week",
"how": "hyper-specific: exact steps, exact DM/email scripts in quotes, exact names/channels to target. No generic 'talk to users' — say 'post in r/X with this hook: ...' or 'message these 5 archetypes on LinkedIn: ...'",
"assumption": "the exact assumption this validates or invalidates",
"effort": "S" | "M" | "L"
}
]
}
Rules for this_week_actions: produce exactly 3-5 actions. Each must be doable in under 7 days. At least one must be a user-facing validation action with an exact script.
Adapt tone to founder_type:
- first_time: extra bluntness about assumptions, less jargon
- technical: push hard on distribution/users, not features
- non_technical: push hard on validation without building, scrappy paths
- repeat: skip basics, go deeper on strategic risks"""
def _extract_json_candidate(raw: str) -> str:
text = raw.strip()
if text.startswith("```"):
text = text.strip("`")
if text.lower().startswith("json"):
text = text[4:].strip()
start = text.find("{")
end = text.rfind("}")
if start == -1 or end == -1 or end <= start:
raise ValueError(f"Model did not return JSON: {raw[:200]}")
return text[start : end + 1]
async def _parse_or_repair_json(raw: str, session_id: str) -> dict:
candidate = _extract_json_candidate(raw)
try:
return json.loads(candidate)
except json.JSONDecodeError as e:
logger.warning("diagnosis JSON parse failed, attempting repair: %s", e)
repair_user_msg = (
"Repair this malformed JSON so it becomes valid JSON with the same structure "
"and content. Return ONLY the repaired JSON.\n\n"
f"Parse error: {e}\n\n"
f"{candidate}"
)
repaired_raw = await run_llm_cheap(
JSON_REPAIR_SYSTEM_PROMPT,
repair_user_msg,
session_id=f"{session_id}_repair",
)
repaired_candidate = _extract_json_candidate(repaired_raw)
try:
return json.loads(repaired_candidate)
except json.JSONDecodeError as repair_error:
raise ValueError(
"LLM produced invalid JSON and repair failed: "
f"{repair_error}. Original error: {e}. "
f"Excerpt: {candidate[:200]}"
) from repair_error
def _build_idea_brief(
user: User, idea: dict, prior_diag: Optional[dict], last_checkin: Optional[dict]
) -> str:
lines = [
f"FOUNDER: {user.name}",
f"FOUNDER_TYPE: {user.founder_type or 'unknown'}",
"",
f"IDEA TITLE: {idea['title']}",
f"ONE-LINER: {idea['one_liner']}",
f"PROBLEM: {idea['problem']}",
f"TARGET USER: {idea['target_user']}",
f"ACCESS TO USERS: {idea['access_to_users']}",
f"DOMAIN EXPERIENCE: {idea['domain_experience']}",
f"MOTIVATION: {idea['motivation']}",
f"EXTRA CONTEXT: {idea.get('extra_context', '') or '(none)'}",
]
if prior_diag:
lines += [
"",
"PRIOR DIAGNOSIS:",
f"- Previous verdict: {prior_diag.get('verdict')}",
f"- Previous key insight: {prior_diag.get('key_insight')}",
]
if last_checkin:
lines += [
"",
"LAST CHECK-IN:",
f"- Actions completed: {last_checkin.get('actions_completed')}",
f"- What changed: {last_checkin.get('what_changed')}",
f"- New learnings: {last_checkin.get('new_learnings')}",
f"- Blockers: {last_checkin.get('blockers')}",
"",
"IMPORTANT: Re-diagnose based on new evidence. Verdict MAY change. Reference what they learned. If they didn't complete actions, call it out.",
]
return "\n".join(lines)
async def _run_diagnosis_llm(brief: str, session_id: str) -> dict:
user_msg = (
f"Diagnose this idea. Return ONLY the JSON object per the contract.\n\n{brief}"
)
raw = await run_llm(SYSTEM_PROMPT, user_msg, session_id=session_id)
parsed = await _parse_or_repair_json(raw, session_id)
# ensure action_ids are unique
for i, a in enumerate(parsed.get("this_week_actions", []), 1):
a["action_id"] = a.get("action_id") or f"a{i}"
a["done"] = False
return parsed
@api.post("/ideas/{idea_id}/diagnose")
async def diagnose(
idea_id: str,
request: Request,
background_tasks: BackgroundTasks,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
"""Kick off an async diagnosis job. Returns immediately with a job_id.
Poll GET /api/ideas/{idea_id}/diagnose/jobs/{job_id} for status."""
user = await get_current_user(request, session_token_cookie, authorization)
idea = await db.ideas.find_one(
{"idea_id": idea_id, "user_id": user.user_id, "status": {"$ne": "archived"}},
{"_id": 0},
)
if not idea:
raise HTTPException(404, "Idea not found")
await _check_diagnosis_gate(user.user_id, idea_id)
job_id = f"job_{uuid.uuid4().hex[:12]}"
now = datetime.now(timezone.utc)
await db.diagnosis_jobs.insert_one(
{
"job_id": job_id,
"idea_id": idea_id,
"user_id": user.user_id,
"status": "pending", # pending | done | error
"error": None,
"diagnosis_id": None,
"created_at": now.isoformat(),
}
)
background_tasks.add_task(_run_diagnosis_job, job_id, idea_id, user.user_id)
return {"job_id": job_id, "status": "pending"}
async def _run_diagnosis_job(job_id: str, idea_id: str, user_id: str):
try:
user_doc = await db.users.find_one({"user_id": user_id}, {"_id": 0})
idea = await db.ideas.find_one(
{"idea_id": idea_id, "user_id": user_id, "status": {"$ne": "archived"}},
{"_id": 0},
)
if not user_doc or not idea:
raise RuntimeError("idea or user vanished")
if isinstance(user_doc.get("created_at"), str):
user_doc["created_at"] = datetime.fromisoformat(user_doc["created_at"])
user = User(**user_doc)
prior = await db.diagnoses.find_one(
{"idea_id": idea_id}, {"_id": 0}, sort=[("created_at", -1)]
)
last_checkin = await db.checkins.find_one(
{"idea_id": idea_id}, {"_id": 0}, sort=[("created_at", -1)]
)
brief = _build_idea_brief(user, idea, prior, last_checkin)
parsed = await asyncio.wait_for(
_run_diagnosis_llm(brief, f"diag_{idea_id}_{uuid.uuid4().hex[:8]}"),
timeout=240.0,
)
now = datetime.now(timezone.utc)
diag = {
"diagnosis_id": f"diag_{uuid.uuid4().hex[:12]}",
"idea_id": idea_id,
"user_id": user_id,
"verdict": parsed["verdict"],
"verdict_headline": parsed["verdict_headline"],
"diagnosis": parsed["diagnosis"],
"key_insight": parsed["key_insight"],
"kill_conditions": parsed.get("kill_conditions", []),
"momentum_signals": parsed.get("momentum_signals", []),
"fmf_score": int(parsed.get("fmf_score", 0)),
"fmf_reason": parsed.get("fmf_reason", ""),
"wtp_score": int(parsed.get("wtp_score", 0)),
"wtp_reason": parsed.get("wtp_reason", ""),
"execution_risk": int(parsed.get("execution_risk", 0)),
"execution_risk_reason": parsed.get("execution_risk_reason", ""),
"momentum_score": int(parsed.get("momentum_score", 0)),
"momentum_reason": parsed.get("momentum_reason", ""),
"competitor_signal": parsed.get("competitor_signal", ""),
"this_week_actions": parsed.get("this_week_actions", []),
"share_slug": None,
"created_at": now.isoformat(),
}
await db.diagnoses.insert_one({**diag})
await db.ideas.update_one(
{"idea_id": idea_id},
{
"$set": {
"latest_verdict": diag["verdict"],
"latest_fmf_score": diag["fmf_score"],
"latest_wtp_score": diag["wtp_score"],
"latest_momentum_score": diag["momentum_score"],
"updated_at": now.isoformat(),
}
},
)
await db.diagnosis_jobs.update_one(
{"job_id": job_id},
{"$set": {"status": "done", "diagnosis_id": diag["diagnosis_id"]}},
)
except Exception as e:
logger.exception("diagnosis job failed")
await db.diagnosis_jobs.update_one(
{"job_id": job_id},
{"$set": {"status": "error", "error": str(e)[:400]}},
)
@api.get("/ideas/{idea_id}/diagnose/jobs/{job_id}")
async def get_diagnosis_job(
idea_id: str,
job_id: str,
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
user = await get_current_user(request, session_token_cookie, authorization)
job = await db.diagnosis_jobs.find_one(
{"job_id": job_id, "idea_id": idea_id, "user_id": user.user_id}, {"_id": 0}
)
if not job:
raise HTTPException(404, "Job not found")
out = {"job_id": job_id, "status": job["status"], "error": job.get("error")}
if job["status"] == "done" and job.get("diagnosis_id"):
diag = await db.diagnoses.find_one(
{"diagnosis_id": job["diagnosis_id"]}, {"_id": 0}
)
out["diagnosis"] = _serialize_timeline_doc(diag)
return out
@api.post("/ideas/{idea_id}/actions/{action_id}/toggle")
async def toggle_action(
idea_id: str,
action_id: str,
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
user = await get_current_user(request, session_token_cookie, authorization)
diag = await db.diagnoses.find_one(
{"idea_id": idea_id, "user_id": user.user_id},
{"_id": 0},
sort=[("created_at", -1)],
)
if not diag:
raise HTTPException(404, "No diagnosis")
actions = diag.get("this_week_actions", [])
for a in actions:
if a.get("action_id") == action_id:
a["done"] = not a.get("done", False)
break
await db.diagnoses.update_one(
{"diagnosis_id": diag["diagnosis_id"]},
{"$set": {"this_week_actions": actions}},
)
return {"ok": True, "actions": actions}
# ---------- Weekly Check-in ----------
@api.post("/ideas/{idea_id}/checkins")
async def create_checkin(
idea_id: str,
payload: CheckinCreate,
request: Request,
session_token_cookie: Optional[str] = Cookie(None, alias="session_token"),
authorization: Optional[str] = Header(None),
):
user = await get_current_user(request, session_token_cookie, authorization)
idea = await db.ideas.find_one(
{"idea_id": idea_id, "user_id": user.user_id, "status": {"$ne": "archived"}},
{"_id": 0},
)
if not idea:
raise HTTPException(404, "Idea not found")
now = datetime.now(timezone.utc)
last_cki = await db.checkins.find_one(
{"idea_id": idea_id}, {"_id": 0}, sort=[("created_at", -1)]
)
# streak: if last check-in within 14 days of now, increment; else reset to 1
streak = idea.get("streak", 0) or 0
if last_cki:
last_at = last_cki.get("created_at")
if isinstance(last_at, str):
last_at = datetime.fromisoformat(last_at)
if last_at and last_at.tzinfo is None:
last_at = last_at.replace(tzinfo=timezone.utc)
delta_days = (now - last_at).days if last_at else 999
streak = streak + 1 if delta_days <= 14 else 1
else:
streak = 1
checkin_id = f"cki_{uuid.uuid4().hex[:12]}"
doc = {
"checkin_id": checkin_id,
"idea_id": idea_id,
"user_id": user.user_id,
"actions_completed": payload.actions_completed,
"what_changed": payload.what_changed,
"new_learnings": payload.new_learnings,
"blockers": payload.blockers,
"delta_summary": "",
"created_at": now.isoformat(),
}
await db.checkins.insert_one({**doc})
await db.ideas.update_one(
{"idea_id": idea_id},
{
"$set": {
"last_checkin_at": now.isoformat(),
"streak": streak,
"updated_at": now.isoformat(),
}
},
)
# Also mark completed actions as done in latest diagnosis
latest_diag = await db.diagnoses.find_one(
{"idea_id": idea_id}, {"_id": 0}, sort=[("created_at", -1)]
)
if latest_diag:
actions = latest_diag.get("this_week_actions", [])
completed = set(payload.actions_completed or [])
for a in actions:
if a.get("action_id") in completed:
a["done"] = True
await db.diagnoses.update_one(
{"diagnosis_id": latest_diag["diagnosis_id"]},
{"$set": {"this_week_actions": actions}},
)
return _serialize_timeline_doc({**doc, "streak": streak})
@api.get("/dashboard/summary")
async def dashboard_summary(