-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlead_discovery.py
More file actions
2606 lines (2512 loc) · 116 KB
/
Copy pathlead_discovery.py
File metadata and controls
2606 lines (2512 loc) · 116 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 json
import os
import re
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
from urllib.parse import urlparse
import requests
from dotenv import load_dotenv
from nomad_operator_grant import operator_allows, operator_grant
load_dotenv()
ROOT = Path(__file__).resolve().parent
DEFAULT_LEAD_SOURCES_PATH = ROOT / "nomad_lead_sources.json"
DEFAULT_ADDRESSABLE_PAINS_PATH = ROOT / "nomad_addressable_painpoints.json"
DEFAULT_LEAD_FOCUS = "compute_auth"
# Hosts where issue URLs live but outbound agent contact must not target.
_ACQUIRE_EXCLUDE_HOSTS = frozenset(
{
"github.com",
"www.github.com",
"gitlab.com",
"bitbucket.org",
"discord.com",
"discord.gg",
"linkedin.com",
"www.linkedin.com",
"reddit.com",
"x.com",
"twitter.com",
"t.me",
"telegram.me",
}
)
_ACQUIRE_MACHINE_PATH_HINTS = (
"/.well-known/agent-card.json",
"/.well-known/agent.json",
"/.well-known/nomad-agent.json",
"/.well-known/nomad-gradient.json",
"/.well-known/openapi.json",
"/openapi.json",
"/a2a",
"/mcp",
"/direct",
"/message",
"/messages",
"/webhook",
"/inbox",
"/tasks",
"/service",
"/swarm/gradient",
"/swarm/attach",
)
def _machine_endpoint_urls_from_text(text: str, *, limit: int = 8) -> List[str]:
"""Collect public machine-agent/API URLs from free text, excluding issue/social hosts."""
if not text or limit <= 0:
return []
raw: List[str] = []
for match in re.finditer(r"https?://[^\s\)\]>'\"<>]+", text, flags=re.IGNORECASE):
candidate = match.group(0).rstrip(").,;:\"']>")
no_fragment = candidate.split("#", 1)[0]
parsed = urlparse(no_fragment)
if parsed.scheme not in {"http", "https"}:
continue
host = (parsed.hostname or "").lower()
if host in _ACQUIRE_EXCLUDE_HOSTS:
continue
path = parsed.path.lower().rstrip("/")
if not any(hint in path for hint in _ACQUIRE_MACHINE_PATH_HINTS):
continue
raw.append(no_fragment.rstrip("/"))
seen: set[str] = set()
uniq: List[str] = []
for url in raw:
if url in seen:
continue
seen.add(url)
uniq.append(url)
def _rank(url: str) -> tuple[int, str]:
lowered = url.lower()
if "agent-card" in lowered:
return (0, lowered)
if "/.well-known/agent" in lowered:
return (1, lowered)
if "nomad-gradient" in lowered or "/swarm/gradient" in lowered:
return (2, lowered)
if "/a2a" in lowered:
return (3, lowered)
if "/mcp" in lowered:
return (4, lowered)
if "openapi" in lowered:
return (5, lowered)
return (9, lowered)
uniq.sort(key=_rank)
return uniq[:limit]
DEFAULT_AGENT_PAIN_QUERIES = [
'"AI agent" "rate limit" is:issue is:open',
'"agent framework" "human in the loop" is:issue is:open',
'"AI agent" "human in the loop" "paid" is:issue is:open',
'"AI agent" "bounty" "agent" is:issue is:open',
'"autonomous agent" "compute" "quota" is:issue is:open',
'"MCP" "token" "agent" is:issue is:open',
'"MCP" ("tool loop" OR "is_error" OR "gateway" OR "transport" OR "401") is:issue is:open',
'"LangGraph" "deployment" "token" is:issue is:open',
]
PAIN_KEYWORDS = {
"auth": 2.2,
"authentication": 2.2,
"token": 2.0,
"permission": 1.8,
"rate limit": 2.4,
"quota": 2.4,
"timeout": 1.6,
"human": 1.8,
"approval": 1.8,
"captcha": 2.0,
"wallet": 1.8,
"compute": 2.0,
"deployment": 1.6,
"mcp": 1.8,
"inference": 1.8,
"idempotency": 1.8,
"duplicate": 1.4,
"cold start": 1.6,
"tail latency": 1.6,
"p99": 1.4,
"witness": 1.8,
"attestation": 1.8,
"handoff": 1.6,
"provenance": 1.6,
}
BUYER_INTENT_KEYWORDS = {
"bounty": 3.0,
"paid": 2.6,
"budget": 2.4,
"grant": 2.0,
"sponsor": 2.0,
"urgent": 1.8,
"blocked": 1.6,
"production": 1.8,
"enterprise": 2.0,
"consulting": 2.4,
"paid support": 2.8,
"reward": 2.2,
"help wanted": 1.6,
}
SERVICE_TYPE_SIGNAL_TERMS = {
"compute_auth": {
"auth",
"authentication",
"compute",
"deployment",
"inference",
"permission",
"quota",
"rate limit",
"timeout",
"token",
},
"human_in_loop": {
"approval",
"captcha",
"human",
},
"mcp_integration": {"mcp"},
"mcp_production": {"mcp", "timeout", "deployment"},
"attribution_clarity": {"blame", "misclassified", "shame"},
"branch_economics": {"ledger", "burn", "branch", "budget", "wasted", "marginal"},
"tool_turn_invariant": {"parallel", "cardinality", "corrupt", "unrecoverable", "session", "mute"},
"tool_transport_routing": {"mcp_call", "function_call"},
"context_propagation_contract": {"tenant", "correlation", "delegation", "principal", "envelope"},
"chain_deadline_budget": {"planner", "deadline", "exhaustion", "latency", "segment"},
"stewardship_gap": {"orphan", "operator", "monitoring", "unstaffed", "supervision", "on-call"},
"policy_lacuna": {"governance", "lacuna", "precedent", "uncovered", "unmapped"},
"wallet_payment": {"wallet"},
"inter_agent_witness": {"witness", "attestation", "provenance", "handoff"},
}
AGENT_INFRA_CORE_SERVICE_TYPES: frozenset[str] = frozenset(
{
"tool_turn_invariant",
"tool_transport_routing",
"context_propagation_contract",
"chain_deadline_budget",
"mcp_production",
"attribution_clarity",
"inter_agent_witness",
}
)
SERVICE_TYPE_SIGNAL_TERMS["agent_infra_prime"] = set().union(
*(SERVICE_TYPE_SIGNAL_TERMS[t] for t in AGENT_INFRA_CORE_SERVICE_TYPES)
)
MACHINE_HUMAN_GAP_SIGNAL_TERMS: frozenset[str] = frozenset(
{
"idempotency",
"idempotent",
"duplicate",
"dedupe",
"cold",
"cold start",
"spindown",
"hibernate",
"percentile",
"p95",
"p99",
"tail",
"tail latency",
"sampling",
"aggregate",
"compaction",
"backpressure",
"retry",
"throttle",
}
)
def focus_signal_term_set(focus_id: str) -> set[str]:
"""Pain-term set used for focus_score and qualification."""
if focus_id == "machine_human_gap":
return set(SERVICE_TYPE_SIGNAL_TERMS.get("agent_infra_prime", set())) | set(MACHINE_HUMAN_GAP_SIGNAL_TERMS)
return set(SERVICE_TYPE_SIGNAL_TERMS.get(focus_id, set()))
AGENT_INFRA_TEXT_FOCUS_MARKERS: tuple[str, ...] = (
"function response parts",
"function call parts",
"parallel tool",
"session corrupted",
"unrecoverable 400",
"mute state",
"function_call",
"mcp_call",
"hosted mcp",
"tool not found",
"identity propagation",
"tenant scope",
"correlation id",
"effective principal",
"planner budget",
"chain timeout",
"turn budget",
"false positive",
"misclassified",
"not the model",
"mcp gateway",
"is_error",
"tool calling loop",
"mcp transport",
)
MACHINE_HUMAN_GAP_TEXT_MARKERS: tuple[str, ...] = (
"works on my machine",
"only in prod",
"only in production",
"cold start",
"wake up",
"spin up",
"first request",
"health check timed out",
"readiness probe",
"retry storm",
"thundering herd",
"at-least-once",
"exactly-once",
"duplicate submission",
"lost correlation",
"no correlation id",
"p95",
"p99",
"tail latency",
"sampled logs",
"approval fatigue",
"no runbook",
"flakey",
"flaky",
"intermittent",
)
INTER_AGENT_WITNESS_TEXT_MARKERS: tuple[str, ...] = (
"witness bundle",
"inter-agent",
"inter agent",
"verifiable handoff",
"tool trace proof",
"resume without re-running",
"downstream agent",
"prove the tool",
"delegation proof",
"attestation",
"WITNESS_",
)
def _float_env(name: str, default: float) -> float:
raw = os.getenv(name)
if raw is None or not str(raw).strip():
return default
try:
return float(raw)
except ValueError:
return default
def _bool_env(name: str, default: bool = True) -> bool:
raw = (os.getenv(name) or "").strip().lower()
if not raw:
return default
if raw in {"0", "false", "no", "off"}:
return False
if raw in {"1", "true", "yes", "on"}:
return True
return default
def _agent_infra_focus_boost() -> float:
return _float_env("NOMAD_LEAD_AGENT_INFRA_FOCUS_BOOST", 2.4)
def _agent_infra_classifier_bias() -> float:
return _float_env("NOMAD_LEAD_AGENT_INFRA_CLASSIFIER_BIAS", 1.4)
DEFAULT_MIN_QUALIFIED_SCORE = {
"compute_auth": 8.0,
"human_in_loop": 7.0,
"mcp_production": 6.5,
"attribution_clarity": 6.0,
"branch_economics": 6.0,
"stewardship_gap": 6.0,
"policy_lacuna": 6.0,
"tool_turn_invariant": 6.0,
"tool_transport_routing": 6.0,
"context_propagation_contract": 6.0,
"chain_deadline_budget": 6.0,
"inter_agent_witness": 6.0,
"agent_infra_prime": 6.0,
"machine_human_gap": 6.0,
"balanced": 0.0,
}
class LeadDiscoveryScout:
"""Find public AI-agent infrastructure pain without contacting anyone."""
def __init__(
self,
session: Optional[requests.Session] = None,
github_api_base: Optional[str] = None,
) -> None:
load_dotenv()
self.session = session or requests.Session()
self.github_api_base = (
github_api_base
or os.getenv("GITHUB_API_BASE")
or "https://api.github.com"
).rstrip("/")
self.github_token = (
os.getenv("GITHUB_PERSONAL_ACCESS_TOKEN")
or os.getenv("GITHUB_TOKEN")
or ""
).strip()
self._codebuddy_brain: Optional[Any] = None
self.user_agent = (
os.getenv("NOMAD_HTTP_USER_AGENT")
or "Nomad/0.1 public-agent-lead-discovery"
).strip()
self.focus = (os.getenv("NOMAD_LEAD_FOCUS") or DEFAULT_LEAD_FOCUS).strip().lower() or DEFAULT_LEAD_FOCUS
self.sources_path = Path(
os.getenv("NOMAD_LEAD_SOURCES_PATH") or DEFAULT_LEAD_SOURCES_PATH
)
self.addressable_pains_path = Path(
os.getenv("NOMAD_ADDRESSABLE_PAINS_PATH") or DEFAULT_ADDRESSABLE_PAINS_PATH
)
self.source_catalog = self._load_source_catalog()
self.addressable_catalog = self._load_addressable_catalog()
def scout_public_leads(
self,
query: str = "",
limit: int = 5,
focus: str = "",
*,
include_calibration_bundle: bool = False,
candidate_multiplier: int = 3,
) -> Dict[str, Any]:
cleaned_query = (query or "").strip()
selected_focus = self.current_focus(focus)
queries = [cleaned_query] if cleaned_query else self.default_queries(selected_focus)
source_plan = self.source_plan(selected_focus)
raw_leads: List[Dict[str, Any]] = []
errors: List[str] = []
seen_urls: set[str] = set()
pool_cap = int(limit) * max(3, min(int(candidate_multiplier), 10))
for search_query in queries:
if len(raw_leads) >= pool_cap:
break
try:
for item in self._search_github_issues(
query=search_query,
limit=max(1, min(10, (limit * 2) - len(raw_leads))),
):
url = item.get("url", "")
if not url or url in seen_urls:
continue
seen_urls.add(url)
item["focus"] = selected_focus
item["focus_match"] = self._matches_focus(item, selected_focus)
item["seed_match"] = self._matches_seed_repo(item, source_plan)
item["focus_score"] = self._focus_score(item, selected_focus, source_plan)
item["qualified"] = self._is_qualified_lead(item, selected_focus, source_plan)
raw_leads.append(item)
if len(raw_leads) >= pool_cap:
break
except Exception as exc:
errors.append(f"{search_query}: {exc}")
prioritize_infra = _bool_env("NOMAD_LEAD_PRIORITIZE_AGENT_INFRA", True)
def _sort_key(item: Dict[str, Any]) -> tuple:
infra_prio = 0
if prioritize_infra and str(item.get("recommended_service_type") or "").strip() in AGENT_INFRA_CORE_SERVICE_TYPES:
infra_prio = 1
return (
-int(bool(item.get("qualified"))),
-infra_prio,
-int(bool(item.get("addressable_now"))),
-int(bool(item.get("monetizable_now"))),
-float(item.get("focus_score") or 0.0),
-int(bool(item.get("focus_match"))),
-int(bool(item.get("seed_match"))),
-float(item.get("addressable_score") or 0.0),
-float(item.get("buyer_readiness_score") or 0.0),
-float(item.get("pain_score") or 0.0),
item.get("title", "").lower(),
)
raw_leads.sort(key=_sort_key)
qualified_leads = [item for item in raw_leads if item.get("qualified")]
addressable_leads = [item for item in raw_leads if item.get("addressable_now")]
monetizable_leads = [item for item in raw_leads if item.get("monetizable_now")]
leads = qualified_leads or (
raw_leads[:limit]
if source_plan.get("allow_unqualified_fallback", False)
else []
)
analysis = (
f"Nomad searched public surfaces for AI-agent infrastructure pain and buyer intent with focus {selected_focus}. "
"It may inspect public pages, draft useful help, and contact public machine-readable "
"agent/API/MCP endpoints. Human-facing posts, DMs, PRs, or private access still need "
"explicit approval."
)
analysis += (
f" Candidate leads: {len(raw_leads)}. Qualified leads: {len(qualified_leads)}. "
f"Addressable now: {len(addressable_leads)}. Monetizable now: {len(monetizable_leads)}."
)
if not leads:
analysis += (
" No concrete public lead was confirmed in this pass; use the search plan "
"or provide SCOUT_SURFACE/LEAD_URL to narrow the next cycle."
)
calibration_bundle: Dict[str, Any] = {}
if include_calibration_bundle:
min_configured = float(
source_plan.get("min_focus_score")
or DEFAULT_MIN_QUALIFIED_SCORE.get(selected_focus, 0.0)
)
pool = [r for r in raw_leads if r.get("focus_match") and r.get("addressable_now")]
scores = sorted(float(x.get("focus_score") or 0.0) for x in pool)
sweep_thresholds = [4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0]
threshold_sweep: List[Dict[str, Any]] = []
for t in sweep_thresholds:
qc = sum(
1
for r in raw_leads
if self._is_qualified_lead(r, selected_focus, source_plan, min_focus_score_override=t)
)
threshold_sweep.append({"min_focus_score": t, "qualified_count": qc})
rec_lines: List[str] = []
if len(qualified_leads) >= 2:
rec_lines.append(
f"At configured min_focus_score={min_configured}, {len(qualified_leads)} leads pass the gate — "
"keep the threshold unless false positives dominate."
)
elif len(qualified_leads) == 1:
rec_lines.append(
f"Only one lead qualifies at min_focus_score={min_configured}; widen seed_queries or accept a "
"narrow funnel for this focus."
)
else:
addr_no_focus = sum(
1 for r in raw_leads if r.get("addressable_now") and not r.get("focus_match")
)
if not pool and addr_no_focus:
rec_lines.append(
f"{addr_no_focus} addressable GitHub hits did not match this focus (focus_match=false) — "
"min_focus_score alone will not help; widen titles/bodies with routing vocabulary "
"(mcp_call, function_call, tool not found, gateway) or adjust SERVICE_TYPE_SIGNAL_TERMS / queries."
)
first_hit = next((row for row in threshold_sweep if row["qualified_count"] >= 1), None)
if first_hit:
rec_lines.append(
f"No leads at {min_configured}; first sweep threshold with at least one qualified lead is "
f"{first_hit['min_focus_score']} ({first_hit['qualified_count']} leads). "
"Option: lower min_focus_score in nomad_lead_sources.json for this focus, or tighten queries "
"if scores are noise."
)
elif not rec_lines or addr_no_focus == 0:
rec_lines.append(
"No raw lead passes qualification even at the lowest sweep threshold — improve "
"focus_match signals (queries) or check that issues expose addressable pain_terms."
)
slim_candidates: List[Dict[str, Any]] = []
for r in raw_leads[:45]:
slim_candidates.append(
{
"url": r.get("url") or "",
"title": (r.get("title") or "")[:160],
"focus_score": r.get("focus_score"),
"qualified": bool(r.get("qualified")),
"focus_match": bool(r.get("focus_match")),
"addressable_now": bool(r.get("addressable_now")),
"seed_match": bool(r.get("seed_match")),
"recommended_service_type": r.get("recommended_service_type") or "",
"pain_terms": list(r.get("pain_terms") or [])[:12],
}
)
calibration_bundle = {
"schema": "nomad.lead_focus_calibration.v1",
"focus": selected_focus,
"min_focus_score_configured": min_configured,
"candidate_pool": len(raw_leads),
"focus_match_addressable_pool": len(pool),
"focus_score_stats": {
"min": scores[0] if scores else None,
"max": scores[-1] if scores else None,
"mean": round(sum(scores) / len(scores), 2) if scores else None,
},
"qualified_at_configured": len(qualified_leads),
"threshold_sweep": threshold_sweep,
"recommendation": "\n".join(rec_lines),
"raw_candidates": slim_candidates,
}
active_lead: Dict[str, Any] = {}
if leads:
top = leads[0]
active_lead = {
"name": top.get("title") or "",
"title": top.get("title") or "",
"url": top.get("url") or "",
"html_url": top.get("url") or "",
"repo_url": top.get("repo_url") or "",
"pain": top.get("pain") or "",
"pain_signal": top.get("pain") or "",
"pain_terms": top.get("pain_terms") or [],
"pain_evidence": top.get("pain_evidence") or [],
"public_issue_excerpt": (top.get("public_issue_excerpt") or "")[:1200],
"recommended_service_type": top.get("recommended_service_type") or top.get("service_type") or "",
"service_type": top.get("recommended_service_type") or top.get("service_type") or "",
"addressable_label": top.get("addressable_label") or "",
"monetizable_now": bool(top.get("monetizable_now")),
"addressable_now": bool(top.get("addressable_now")),
"first_help_action": top.get("first_help_action") or "",
"product_package": top.get("product_package") or "",
"endpoint_url": top.get("endpoint_url") or "",
"agent_contact_allowed_without_approval": bool(top.get("agent_contact_allowed_without_approval")),
}
payload: Dict[str, Any] = {
"mode": "lead_discovery",
"deal_found": False,
"generated_at": datetime.now(UTC).isoformat(),
"focus": selected_focus,
"query": cleaned_query,
"search_queries": queries,
"candidate_count": len(raw_leads),
"qualified_count": len(qualified_leads),
"addressable_count": len(addressable_leads),
"monetizable_count": len(monetizable_leads),
"leads": leads[:limit],
"active_lead": active_lead,
"source_plan": source_plan,
"addressable_portfolio": [
{
"id": item.get("id"),
"label": item.get("label"),
"service_type": item.get("service_type"),
"value_score": item.get("value_score"),
"first_offer": item.get("first_offer"),
"quote_summary": self._quote_summary(item.get("quote_native")),
"delivery_target": item.get("delivery_target"),
"product_package": item.get("product_package"),
"solution_pattern": item.get("solution_pattern"),
}
for item in (self.addressable_catalog.get("painpoints") or [])
if isinstance(item, dict)
],
"errors": errors[:3],
"outreach_policy": self.outreach_policy(),
"human_unlocks": self._human_unlocks(leads, source_plan=source_plan),
"analysis": analysis,
}
if calibration_bundle:
payload["calibration_bundle"] = calibration_bundle
return payload
def calibrate_focus_scout(
self,
focus: str = "",
*,
query: str = "",
limit: int = 12,
candidate_multiplier: int = 5,
) -> Dict[str, Any]:
"""Run GitHub scout for one focus and attach threshold sweep vs min_focus_score (for tuning nomad_lead_sources.json)."""
return self.scout_public_leads(
query=query,
limit=max(3, min(int(limit), 25)),
focus=focus,
include_calibration_bundle=True,
candidate_multiplier=max(3, min(int(candidate_multiplier), 10)),
)
def current_focus(self, focus: str = "") -> str:
cleaned = (focus or self.focus or DEFAULT_LEAD_FOCUS).strip().lower()
profiles = (self.source_catalog.get("focus_profiles") or {})
return cleaned if cleaned in profiles else ("balanced" if "balanced" in profiles else DEFAULT_LEAD_FOCUS)
def default_queries(self, focus: str = "") -> List[str]:
selected_focus = self.current_focus(focus)
plan = self.source_plan(selected_focus)
queries: List[str] = []
for key in ("seed_queries", "queries"):
queries.extend(
str(item).strip()
for item in (plan.get(key) or [])
if str(item).strip()
)
deduped: List[str] = []
seen: set[str] = set()
for item in queries:
if item in seen:
continue
seen.add(item)
deduped.append(item)
return deduped or list(DEFAULT_AGENT_PAIN_QUERIES)
def source_plan(self, focus: str = "") -> Dict[str, Any]:
selected_focus = self.current_focus(focus)
profiles = self.source_catalog.get("focus_profiles") or {}
plan = profiles.get(selected_focus) or {}
return plan if isinstance(plan, dict) else {}
def draft_first_help_action(
self,
lead: Dict[str, Any],
approval: str = "draft_only",
) -> Dict[str, Any]:
approval = (approval or "draft_only").strip().lower()
can_publish = approval in {"comment", "public_comment", "pr", "pull_request"}
grant = operator_grant()
lead_url = lead.get("url") or lead.get("html_url") or ""
pain = lead.get("pain") or lead.get("pain_signal") or "visible infrastructure pain"
title = lead.get("title") or lead.get("name") or "public agent lead"
pain_terms = [
str(item).strip().lower()
for item in (lead.get("pain_terms") or [])
if str(item).strip()
]
if not pain_terms:
pain_terms = [
item.strip().lower()
for item in str(pain).split(",")
if item.strip()
]
service_type = (
str(lead.get("recommended_service_type") or "").strip().lower()
or self._recommended_service_type(pain_terms, f"{title}\n{pain}")
)
help_pack = self._help_template_for_lead(
service_type=service_type,
pain=pain,
pain_terms=pain_terms,
)
lead_text = "\n".join(
str(part).strip()
for part in [
title,
pain,
lead.get("public_issue_excerpt") or lead.get("body_excerpt") or lead.get("body") or "",
" ".join(str(item) for item in (lead.get("addressable_deliverables") or [])),
lead.get("solution_pattern") or "",
]
if str(part).strip()
)
pain_validation = self._pain_validation(
service_type=service_type,
pain_terms=pain_terms,
lead_text=lead_text,
)
lead_specific_context = self._lead_specific_context(
service_type=service_type,
pain_terms=pain_terms,
title=title,
lead_text=lead_text,
)
if lead_specific_context:
help_pack = self._merge_lead_specific_context(help_pack, lead_specific_context)
first_useful_help_action = self._first_useful_help_action_for_lead(
lead=lead,
service_type=service_type,
pain_terms=pain_terms,
title=title,
)
price_guidance = dict(
lead.get("price_guidance")
or help_pack.get("price_guidance")
or {}
)
quote_summary = str(
lead.get("quote_summary")
or help_pack.get("quote_summary")
or ""
).strip()
delivery_target = str(
lead.get("delivery_target")
or help_pack.get("delivery_target")
or ""
).strip()
memory_upgrade = str(
lead.get("memory_upgrade")
or help_pack.get("memory_upgrade")
or ""
).strip()
product_package = str(
lead.get("product_package")
or help_pack.get("product_package")
or ""
).strip()
solution_pattern = str(
lead.get("solution_pattern")
or help_pack.get("solution_pattern")
or ""
).strip()
productized_artifacts = list(
lead.get("productized_artifacts")
or help_pack.get("productized_artifacts")
or []
)
service_offer = str(help_pack.get("service_offer") or "").strip()
if quote_summary and quote_summary not in service_offer:
service_offer = f"{service_offer} Starter quote: {quote_summary}."
if delivery_target and delivery_target not in service_offer:
service_offer = f"{service_offer} Delivery target: {delivery_target}."
private_response_draft = self._private_response_draft_for_lead(
title=title,
pain=pain,
service_type=service_type,
first_useful_help_action=first_useful_help_action,
pain_validation=pain_validation,
lead_specific_context=lead_specific_context,
quote_summary=quote_summary,
delivery_target=delivery_target,
)
return {
"mode": "lead_help_draft",
"deal_found": False,
"lead": {
"title": title,
"url": lead_url,
"pain": pain,
},
"service_type": service_type,
"approval": approval,
"can_publish": can_publish,
"operator_grant": grant,
"machine_endpoint_contact_allowed": operator_allows("agent_endpoint_contact"),
"draft_only": not can_publish,
"draft": help_pack["draft"],
"pain_validation": pain_validation,
"lead_specific_context": lead_specific_context,
"first_useful_help_action": first_useful_help_action,
"private_response_draft": private_response_draft,
"posting_gate": (
"Do not post this to a human-facing issue, PR, DM, or forum unless approval is "
"APPROVE_LEAD_HELP=comment or APPROVE_LEAD_HELP=pr_plan."
),
"diagnosis_checks": help_pack["diagnosis_checks"],
"deliverables": help_pack["deliverables"],
"comment_outline": help_pack["comment_outline"],
"pr_plan": help_pack["pr_plan"],
"service_offer": service_offer,
"price_guidance": price_guidance,
"quote_summary": quote_summary,
"delivery_target": delivery_target,
"memory_upgrade": memory_upgrade,
"product_package": product_package,
"solution_pattern": solution_pattern,
"productized_artifacts": productized_artifacts,
"next_steps": [
"Validate the issue from public data only.",
"Use first_useful_help_action as the next private artifact before broader outreach.",
"Turn the diagnosis checks into one concise comment, repro plan, or PR plan.",
"Contact only public machine-readable agent endpoints without approval; ask before human-facing outreach.",
],
"blocked_actions": self.outreach_policy()["blocked_without_approval"],
}
@staticmethod
def _merge_lead_specific_context(
help_pack: Dict[str, Any],
lead_specific_context: Dict[str, Any],
) -> Dict[str, Any]:
merged = dict(help_pack)
field_map = {
"diagnosis_checks": "diagnosis_checks",
"deliverables": "deliverables",
"comment_outline": "comment_outline",
"pr_plan": "pr_plan",
}
for target, source in field_map.items():
existing = list(merged.get(target) or [])
for item in lead_specific_context.get(source) or []:
text = str(item).strip()
if text and text not in existing:
existing.append(text)
merged[target] = existing
return merged
@staticmethod
def _lead_specific_context(
service_type: str,
pain_terms: List[str],
title: str,
lead_text: str,
) -> Dict[str, Any]:
terms = {str(item).strip().lower() for item in pain_terms if str(item).strip()}
haystack = f"{title}\n{lead_text}".lower()
guardrail_terms = {"mcp", "approval"} & terms
if service_type != "compute_auth":
return {}
if not (
guardrail_terms
or "guardrailprovider" in haystack
or "tool call interception" in haystack
or "workbench.call_tool" in haystack
or "basetool.run_json" in haystack
):
return {}
return {
"schema": "nomad.lead_specific_context.v1",
"pattern": "tool_call_guardrail_provider",
"public_facts": [
"Treat this as a pre-execution tool-call guardrail proposal, not only as provider auth failure.",
"Keep BaseTool.run_json, Workbench.call_tool or MCP tools, and AssistantAgent/provider forwarding as separate integration surfaces.",
"Preserve approval_func compatibility while allowing ALLOW, DENY, and MODIFY decisions.",
],
"diagnosis_checks": [
"Map one ALLOW, DENY, and MODIFY fixture before suggesting any public implementation path.",
"Check the workbench/MCP path for tools that do not subclass BaseTool.",
"Keep audit metadata and call_id correlation non-secret and safe to store.",
],
"deliverables": [
"A draft-only GuardrailProvider fit note covering BaseTool, Workbench/MCP, and AssistantAgent surfaces.",
"A tiny verifier matrix for ALLOW, DENY, MODIFY, approval_func compatibility, and audit metadata.",
],
"comment_outline": [
"Fit check: confirm whether maintainers want a protocol layer, an approval_func bridge, or both.",
"Test slice: propose fixtures for FunctionTool/BaseTool plus a Workbench or MCP-like tool path.",
"Safety boundary: state that public comments or PRs still need explicit approval before posting.",
],
"pr_plan": [
"Prototype the provider chain behind existing tool execution without changing default behavior.",
"Add tests for DENY short-circuit, MODIFY argument validation, approval_func wrapping, and Workbench/MCP calls.",
"Document non-goals: no secret logging, no access-control bypass, and no human approval implied by payment.",
],
}
def _help_template_for_lead(
self,
service_type: str,
pain: str,
pain_terms: List[str],
) -> Dict[str, Any]:
terms = {str(item).strip().lower() for item in pain_terms if str(item).strip()}
offer_meta = self._offer_metadata_for_service_type(service_type)
if service_type == "compute_auth":
diagnosis_checks = [
"Identify the exact failing call, tool, or endpoint and capture the smallest public repro.",
"List the credential source, scope, expiry, and the first step where auth fails.",
"Capture response code, rate-limit or quota headers, retry behavior, and whether a fallback model/lane exists.",
]
if {"token", "auth", "authentication", "permission"} & terms:
diagnosis_checks.insert(
1,
"Compare the working and failing credential path: token origin, scopes, audience, rotation, and permission boundary.",
)
if {"rate limit", "quota", "compute", "inference", "timeout"} & terms:
diagnosis_checks.append(
"Check whether the failure is hard quota exhaustion, soft concurrency pressure, timeout, or provider-side compute saturation.",
)
return {
"draft": (
f"I see a compute/auth blocker around {pain}. "
"My first move would be to reduce it to one failing call, map the credential and quota path around that call, "
"and write down the smallest unlock needed to get the agent moving again."
),
"diagnosis_checks": diagnosis_checks,
"deliverables": [
"A credential and quota diagnosis checklist tailored to the failing call.",
"A smallest-repro note with observed headers, scopes, and retry behavior.",
"A fallback-lane plan covering alternate model, provider, or reduced-scope execution.",
],
"comment_outline": [
"Problem framing: name the exact auth, token, quota, or compute symptom and where it appears.",
"Minimal repro: show the smallest failing step and the headers, scopes, or limits that matter.",
"Concrete unblock: propose one fallback lane, one credential fix, or one rate-limit mitigation.",
],
"pr_plan": [
"Add a small repro or health-check command for the failing auth/compute path.",
"Separate credential validation from quota handling so the failure mode is explicit.",
"Add bounded backoff, fallback selection, or clearer operator guidance for the blocked lane.",
],
"service_offer": (
"Bounded diagnosis: one failing call + headers/scopes; deliverables checklist + repro note. "
"Optional follow-up only after failure class is confirmed — verify with `nomad_cli.py solve-pain` "
"and guardrail compute_fallback_ladder."
),
"price_guidance": offer_meta["price_guidance"],
"quote_summary": offer_meta["quote_summary"],
"delivery_target": offer_meta["delivery_target"],
"memory_upgrade": offer_meta["memory_upgrade"],
"product_package": offer_meta["product_package"],
"solution_pattern": offer_meta["solution_pattern"],
"productized_artifacts": offer_meta["productized_artifacts"],
}
if service_type == "human_in_loop":
return {
"draft": (
f"I see a human-in-the-loop blocker around {pain}. "
"The fastest win is to isolate the exact step that needs human judgment or verification, then define a tiny handoff "
"contract with do-now, send-back, and done-when."
),
"diagnosis_checks": [
"Locate the first step that genuinely requires human judgment, approval, or verification.",
"Separate optional human review from the hard blocker that stops the run.",
"Define the minimum evidence the human needs to approve or reject the step quickly.",
],
"deliverables": [
"A minimal HITL handoff contract.",
"A queue-ready checklist for the human operator.",
"A note on which steps can be automated after the first human decision.",
],
"comment_outline": [
"Problem framing: describe the exact human gate and why automation stops there.",
"Evidence pack: list the screenshots, logs, or context a human needs.",
"Unlock path: define the decision options and what the agent should do afterward.",
],
"pr_plan": [
"Add a structured approval payload for the blocked step.",
"Persist the human decision and the follow-up action in agent memory.",
"Reduce future handoffs by auto-filling all non-judgment fields.",
],
"service_offer": (
"Bounded diagnosis: gate id + minimum evidence pack; deliverable is do-now/send-back/done-when contract. "
"Optional operator checklist after gate is classified — verify with solve-pain / hitl pattern."
),
"price_guidance": offer_meta["price_guidance"],
"quote_summary": offer_meta["quote_summary"],
"delivery_target": offer_meta["delivery_target"],
"memory_upgrade": offer_meta["memory_upgrade"],
"product_package": offer_meta["product_package"],
"solution_pattern": offer_meta["solution_pattern"],
"productized_artifacts": offer_meta["productized_artifacts"],
}
if service_type == "wallet_payment":
return {
"draft": (
f"I see a wallet/payment blocker around {pain}. "
"The first useful step is to pin down the exact payment state machine, then separate payment verification from delivery logic."