Phase 2 part 4: discovery per signal (Claude web search, explee.com)

Each signal's page can search for organizations that show it, by hand or
every 7, 14 or 30 days. Claude with the web_search_20260209 server tool
(pause_turn resumed) works from the signal's "How to spot it" lines and
the profile's targets; a company is kept only if its evidence URL was
among the pages searched. explee.com's company search runs the signal's
description in the target sizes, scored against the hypothesis, keeping
strong matches. Our sites, the inventory, existing prospects, CRM
Accounts and suppressed domains are left out. New companies go to Review
tagged with the signal. Schema 8 adds discovery_runs (counts, searches,
why companies were left out) and the signal's schedule and explee.com
description.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 18:27:35 -07:00
co-authored by Claude Opus 5.5
parent b025a97e4a
commit 157902f7e2
15 changed files with 1234 additions and 15 deletions
+3
View File
@@ -143,6 +143,8 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /signals/{id}", s.signalPage)
mux.HandleFunc("POST /signals/{id}", s.signalSave)
mux.HandleFunc("POST /signals/{id}/delete", s.signalDelete)
mux.HandleFunc("POST /signals/{id}/discover/{source}", s.signalDiscover)
mux.HandleFunc("GET /signals/{id}/runs", s.signalRuns)
mux.HandleFunc("POST /funnel/{id}/delete", s.funnelDelete)
mux.HandleFunc("GET /settings/sources", s.sourcesPage)
mux.HandleFunc("POST /settings/sources", s.sourcesSave)
@@ -374,6 +376,7 @@ var flashes = map[string]string{
"unsuppressed": "Taken off the suppression list.",
"prospect-added": "Added. Review it below.",
"outcome": "Outcome recorded.",
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.",
"rules-refreshed": "Rules refreshed.",
"imported": "Imported.",
"oauth-expired": "That sign-in took too long or was already used. Try again.",
+38
View File
@@ -687,3 +687,41 @@ func TestSignalsFunnel(t *testing.T) {
t.Error("delete")
}
}
// The discovery card: what it needs before it can search, its schedule,
// and the run list.
func TestSignalDiscoveryCard(t *testing.T) {
s, h := newTestServer(t, nil)
postForm(h, "/signals/new", url.Values{"name": {"Leaving Microsoft 365"}, "spot": {"m365 alternative"},
"discover_every_days": {"7"}, "explee_definition": {"managed IT services"}})
sig, err := signals.Get(s.DB, 1)
if err != nil || sig.DiscoverEveryDays != 7 || sig.ExpleeDefinition != "managed IT services" {
t.Fatalf("saved: %+v %v", sig, err)
}
body := do(h, http.MethodGet, "/signals/1", nil, nil).Body.String()
for _, want := range []string{"Find companies", "No searches yet", `<option value="7" selected>Every 7 days</option>`,
"Save an explee.com API key"} {
if !strings.Contains(body, want) {
t.Errorf("signal page lacks %q", want)
}
}
if strings.Contains(body, `action="/signals/1/discover/claude"`) {
t.Error("the web search button shows without an AI key")
}
if rec := postForm(h, "/signals/1/discover/claude", nil); rec.Code == http.StatusSeeOther {
t.Error("a search started without an AI key")
}
s.Secrets.Set(map[string]string{secrets.ExpleeAPIKey: "k"})
if body := do(h, http.MethodGet, "/signals/1", nil, nil).Body.String(); !strings.Contains(body, `action="/signals/1/discover/explee"`) {
t.Error("the explee.com button doesn't show with a key and a description")
}
s.DB.Exec(`INSERT INTO discovery_runs (signal_id, source, status, started_at, found, added, skipped, searches, notes)
VALUES (1, 'claude', 'done', '2026-11-21T10:00:00Z', 5, 3, 2, 6, '["Rival: in your inventory (competitor)"]'),
(1, 'claude', 'running', '2026-11-21T11:00:00Z', 0, 0, 0, 0, '[]')`)
body = do(h, http.MethodGet, "/signals/1/runs", nil, nil).Body.String()
for _, want := range []string{"searching…", "3 new", "6 web searches", "Rival: in your inventory", `hx-trigger="every 4s"`} {
if !strings.Contains(body, want) {
t.Errorf("runs lack %q in %s", want, body)
}
}
}
+183 -1
View File
@@ -10,9 +10,12 @@ import (
"strings"
"time"
"supermarket/internal/ai"
"supermarket/internal/api/explee"
"supermarket/internal/api/origami"
"supermarket/internal/discovery"
"supermarket/internal/leadsource"
"supermarket/internal/profile"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/signals"
@@ -83,6 +86,14 @@ type signalData struct {
Campaigns []signals.Campaign
Events []signals.Event
Prospects int // new prospects tagged with it
Runs []discovery.Run
Running bool
Research string // why Claude can't search, or ""
ExpleeKey bool
EveryDays []int
MaxSearch int
MaxResults int
}
type channelRow struct {
@@ -110,7 +121,12 @@ func (s *Server) signalPage(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) renderSignal(w http.ResponseWriter, r *http.Request, sig *signals.Signal, errMsg string) {
d := signalData{S: sig, Statuses: signals.Statuses, Stages: signals.Stages}
d := signalData{S: sig, Statuses: signals.Statuses, Stages: signals.Stages,
EveryDays: []int{0, 7, 14, 30}, MaxSearch: discovery.MaxSearches, MaxResults: discovery.MaxCompanies,
ExpleeKey: s.Secrets.Has(secrets.ExpleeAPIKey)}
if _, err := s.researcher(); err != nil {
d.Research = err.Error()
}
title := "New signal"
if sig.ID != 0 {
title = sig.Name
@@ -156,6 +172,13 @@ func (s *Server) renderSignal(w http.ResponseWriter, r *http.Request, sig *signa
return
}
d.Prospects = len(cs) + len(ps)
if d.Runs, err = discovery.Runs(s.DB, sig.ID, 8); err != nil {
s.serverError(w, err)
return
}
for _, r := range d.Runs {
d.Running = d.Running || r.Status == "running"
}
}
s.render(w, r, "signal", page{Title: title, Nav: "prospects/signals", Error: errMsg, Data: d})
}
@@ -180,6 +203,8 @@ func (s *Server) signalSave(w http.ResponseWriter, r *http.Request) {
f := r.PostFormValue
sig.Name, sig.Slug, sig.Hypothesis, sig.Spot, sig.Angle, sig.Status =
f("name"), f("slug"), f("hypothesis"), f("spot"), f("angle"), f("status")
sig.ExpleeDefinition = f("explee_definition")
sig.DiscoverEveryDays, _ = strconv.Atoi(f("discover_every_days"))
if err := signals.Save(s.DB, sig); err != nil {
s.renderSignal(w, r, sig, err.Error())
return
@@ -446,3 +471,160 @@ func (s *Server) RunImports(ctx context.Context) {
}
}
}
// --- Discovery ---
// researcher is the AI client, if it can search the web.
func (s *Server) researcher() (ai.Researcher, error) {
cfg, err := ai.LoadConfig(s.DB)
if err != nil {
return nil, err
}
c, err := ai.New(cfg, s.Secrets)
if err != nil {
return nil, err
}
r, ok := c.(ai.Researcher)
if !ok {
return nil, ai.ErrNoResearch
}
return r, nil
}
// discoverTimeout bounds one run: several web searches and a long reply.
const discoverTimeout = 15 * time.Minute
// discover runs one search for a signal. It runs in the background, since
// it takes minutes; the signal's page shows its progress.
func (s *Server) discover(sig *signals.Signal, source string) error {
prof, err := profile.Load(s.DB)
if err != nil {
return err
}
var run func(ctx context.Context) (*discovery.Run, error)
switch source {
case discovery.SourceClaude:
r, err := s.researcher()
if err != nil {
return err
}
run = func(ctx context.Context) (*discovery.Run, error) {
return discovery.FindWithClaude(ctx, s.DB, r, sig, prof, time.Now())
}
case discovery.SourceExplee:
key := s.Secrets.Get(secrets.ExpleeAPIKey)
if key == "" {
return errors.New("save your explee.com API key first, under Settings → Lead sources")
}
if strings.TrimSpace(sig.ExpleeDefinition) == "" {
return errors.New("describe what the companies do, for explee.com, in the signal's form below")
}
run = func(ctx context.Context) (*discovery.Run, error) {
return discovery.FindWithExplee(ctx, s.DB, explee.New(key), sig, prof, time.Now())
}
default:
return errors.New("unknown source")
}
started := make(chan error, 1)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), discoverTimeout)
defer cancel()
res, err := run(ctx)
if res == nil {
started <- err // didn't start: already running
return
}
started <- nil
if err != nil {
s.Log.Warn("discovery failed", "signal", sig.ID, "source", source, "err", err)
return
}
s.Log.Info("discovery finished", "signal", sig.ID, "source", source, "found", res.Found, "added", res.Added,
"searches", res.Searches)
}()
// Wait briefly, to report a run that couldn't start.
select {
case err := <-started:
return err
case <-time.After(1500 * time.Millisecond):
return nil
}
}
func (s *Server) signalDiscover(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
sig, err := signals.Get(s.DB, id)
if err != nil {
http.NotFound(w, r)
return
}
if err := s.discover(sig, r.PathValue("source")); err != nil {
s.renderSignal(w, r, sig, err.Error())
return
}
redirect(w, r, "/signals/"+strconv.FormatInt(id, 10)+"#discovery", "discovering")
}
// signalRuns is the discovery card's run list, polled while a run is going.
func (s *Server) signalRuns(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
runs, err := discovery.Runs(s.DB, id, 8)
if err != nil {
s.serverError(w, err)
return
}
running := false
for _, run := range runs {
running = running || run.Status == "running"
}
s.fragment(w, "signal", "runs", map[string]any{"ID": id, "Runs": runs, "Running": running})
}
// RunDiscovery searches for signals that ask to be searched on a schedule.
func (s *Server) RunDiscovery(ctx context.Context) {
if err := discovery.RecoverInterrupted(s.DB); err != nil {
s.Log.Error("discovery: recovering interrupted runs", "err", err)
}
tick := time.NewTicker(30 * time.Minute)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
}
list, err := signals.List(s.DB)
if err != nil {
s.Log.Error("discovery: listing signals", "err", err)
continue
}
for i := range list {
sig := &list[i]
if sig.DiscoverEveryDays <= 0 || sig.Status == signals.StatusRetired {
continue
}
due := time.Duration(sig.DiscoverEveryDays) * 24 * time.Hour
sources := []string{discovery.SourceClaude}
if sig.ExpleeDefinition != "" && s.Secrets.Has(secrets.ExpleeAPIKey) {
sources = append(sources, discovery.SourceExplee)
}
for _, src := range sources {
last, err := discovery.LastStarted(s.DB, sig.ID, src)
if err != nil || time.Since(last) < due {
continue
}
if err := s.discover(sig, src); err != nil {
s.Log.Warn("discovery: scheduled run didn't start", "signal", sig.ID, "source", src, "err", err)
}
}
}
}
}
+3
View File
@@ -418,3 +418,6 @@ table.scorecard td:first-child .badge { margin-left: 0.25rem; }
button.link { background: none; border: 0; box-shadow: none; padding: 0; color: hsl(var(--primary)); text-decoration: underline; cursor: pointer; font-weight: normal; }
.danger-zone { margin-top: 2rem; }
pre.sample { max-height: 24rem; overflow: auto; font-size: 0.78rem; }
#discovery .grid { margin-top: 0.5rem; }
#discovery h3 { margin: 0 0 0.3rem; }
table.runs { margin-top: 0.75rem; }
+58
View File
@@ -26,6 +26,30 @@
{{end}}
{{end}}
{{if $s.ID}}
<section class="card" id="discovery">
<h2>Find companies</h2>
<p>Supermarket searches for organizations that show this signal now and adds them to <a href="/prospects?status=new&amp;signal={{$s.ID}}">Review</a>, tagged with it. Nothing is contacted or sent to your CRM until you accept it.</p>
<div class="grid">
<div>
<h3>Claude, with web search</h3>
<p class="small">Up to {{.MaxSearch}} web searches from “How to spot it”, for up to {{.MaxResults}} companies. Each company comes with the page that shows the signal; any whose page wasn't among the search results is left out. Web searches are billed by Anthropic on top of the tokens.</p>
{{if .Research}}<p class="warn-text small">{{.Research}}</p>
{{else if not $s.SpotLines}}<p class="warn-text small">Fill in “How to spot it” below first.</p>
{{else}}<form method="post" action="/signals/{{$s.ID}}/discover/claude" data-busy="Starting…"><button type="submit" {{if .Running}}disabled{{end}}>Search the web now</button></form>{{end}}
</div>
<div>
<h3>explee.com company search</h3>
<p class="small">Companies that do what you describe below, in your target sizes, scored against the hypothesis; only strong matches are added. The first 10 results of a search are free on explee.com.</p>
{{if not .ExpleeKey}}<p class="small">Save an explee.com API key under <a href="/settings/sources">Settings → Lead sources</a> to use it.</p>
{{else if not $s.ExpleeDefinition}}<p class="small">Describe what the companies do, under “explee.com description” below.</p>
{{else}}<form method="post" action="/signals/{{$s.ID}}/discover/explee" data-busy="Starting…"><button type="submit" class="secondary" {{if .Running}}disabled{{end}}>Search explee.com now</button></form>{{end}}
</div>
</div>
{{template "runs" (dict "ID" $s.ID "Runs" .Runs "Running" .Running)}}
</section>
{{end}}
<form method="post" action="{{if $s.ID}}/signals/{{$s.ID}}{{else}}/signals/new{{end}}" class="card">
<div class="cols">
<label>Name <input name="name" value="{{$s.Name}}" required placeholder="Leaving Microsoft 365"></label>
@@ -39,6 +63,15 @@
<span class="help">Discovery (next) runs these as searches, so write them the way you'd search for the companies.</span></label>
<label>Angle <textarea name="angle" rows="3" placeholder="The pain, and what we promise about it">{{$s.Angle}}</textarea>
<span class="help">What emails, LinkedIn messages and content for this signal should say.</span></label>
<div class="cols">
<label>Search automatically
<select name="discover_every_days">{{range .EveryDays}}<option value="{{.}}" {{if eq . $s.DiscoverEveryDays}}selected{{end}}>{{if eq . 0}}Only when I ask{{else}}Every {{.}} days{{end}}</option>{{end}}</select>
<span class="help">Runs the searches above on a schedule, while the signal isn't retired. Each run costs web searches.</span>
</label>
<label>explee.com description <input name="explee_definition" value="{{$s.ExpleeDefinition}}" placeholder="e.g. law firm, managed IT services, nonprofit">
<span class="help">What the companies do, in a few words, for explee.com's company search.</span>
</label>
</div>
<label>Campaign tag <input name="slug" value="{{$s.Slug}}" placeholder="made from the name">
<span class="help">Used as <code>utm_campaign</code> on links for this signal, so visits and sign-ups are counted against it. Change it before using it, not after.</span></label>
<div class="actions">
@@ -67,3 +100,28 @@
</form>
{{end}}
{{end}}{{end}}
{{define "runs"}}
<div id="runs" {{if .Running}}hx-get="/signals/{{.ID}}/runs" hx-trigger="every 4s" hx-swap="outerHTML"{{end}}>
{{if .Runs}}
<table class="list runs">
<thead><tr><th>Started</th><th>Source</th><th>Result</th></tr></thead>
<tbody>
{{range .Runs}}
<tr>
<td>{{ago .StartedAt}}</td>
<td>{{if eq .Source "claude"}}Claude web search{{else}}explee.com{{end}}</td>
<td>
{{if eq .Status "running"}}<span class="badge scheduled">searching…</span>
{{else if eq .Status "failed"}}<span class="badge failed">failed</span> <span class="small">{{.Error}}</span>
{{else}}<strong>{{.Added}} new</strong>{{if .Existing}}, {{.Existing}} already in Review{{end}}{{if .Skipped}}, {{.Skipped}} left out{{end}} <span class="muted small">of {{.Found}} found</span>{{end}}
{{if .Searches}}<span class="muted small"> · {{.Searches}} {{if eq .Source "claude"}}web searches{{else}}search{{end}}</span>{{end}}
{{if .Notes}}<details class="small"><summary>Why some were left out</summary><ul>{{range .Notes}}<li>{{.}}</li>{{end}}</ul></details>{{end}}
</td>
</tr>
{{end}}
</tbody>
</table>
{{else}}<p class="help">No searches yet.</p>{{end}}
</div>
{{end}}