Add rescoring and a posting-date order to the leads inbox
Test and deploy / test (push) Successful in 1m56s
Test and deploy / deploy (push) Successful in 1m8s

rescoreJobLeads (RescoreAll, "Rescore all" on /cv/leads) scores every
matched inbox lead again, for after the profile or the model has
changed. Scores are not wiped first: a lead keeps its old score until
the new one is saved, and the new scored_at column marks which leads the
job has reached, so a job that dies partway leaves no gaps. Leads that
had used up their attempts get them back.

The inbox can also be ordered by when a posting went up, falling back to
when it was found where the source gave no date.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-12 15:52:33 +01:00
co-authored by Claude Opus 5.5
parent 3764ea9c0b
commit 8b902350ad
9 changed files with 261 additions and 32 deletions
+8 -2
View File
@@ -290,12 +290,18 @@ throughout (`graph/schema/job_lead.graphql`, all `@admin`) with the work in
for the backlog a first poll of several boards leaves behind, or leads for the backlog a first poll of several boards leaves behind, or leads
that arrived before the profile was written. A lead that fails is tried that arrived before the profile was written. A lead that fails is tried
once per press. It stops after an hour; pressing again continues. once per press. It stops after an hour; pressing again continues.
- **Rescoring.** The `rescoreJobLeads` mutation (`RescoreAll`, "Rescore all"
on the page) scores every matched inbox lead again, for after the profile
or `CLAUDE_MODEL` has changed. It does not wipe scores first: a lead keeps
its old score until the new one is saved, and `scored_at` is what marks a
lead as done by this job. A job that fails partway leaves a mix of old and
new scores, and pressing again starts over.
- **When it runs.** `JOB_LEADS_ENABLED=true` starts a timer - **When it runs.** `JOB_LEADS_ENABLED=true` starts a timer
(`JOB_LEADS_INTERVAL`, default `6h`); it does not run at start-up, so a (`JOB_LEADS_INTERVAL`, default `6h`); it does not run at start-up, so a
deploy spends nothing. The `runJobLeadSync` mutation starts a run in a deploy spends nothing. The `runJobLeadSync` mutation starts a run in a
goroutine and returns at once, whether or not the timer is on, and goroutine and returns at once, whether or not the timer is on, and
`jobLeadSyncStatus` reports on it (and on `scoreJobLeads`; only one of `jobLeadSyncStatus` reports on it (and on `scoreJobLeads` and
the two jobs runs at a time) — a run can take minutes, so unlike `rescoreJobLeads`; only one of the three jobs runs at a time) — a run can take minutes, so unlike
`POST /email/sync` it does not hold the request open. The status is in `POST /email/sync` it does not hold the request open. The status is in
memory and resets on restart. memory and resets on restart.
- **Promotion** (`promoteJobLead`) is the only way a lead reaches the tracker. - **Promotion** (`promoteJobLead`) is the only way a lead reaches the tracker.
+88
View File
@@ -121,6 +121,7 @@ type ComplexityRoot struct {
PostedAt func(childComplexity int) int PostedAt func(childComplexity int) int
Score func(childComplexity int) int Score func(childComplexity int) int
ScoreReasons func(childComplexity int) int ScoreReasons func(childComplexity int) int
ScoredAt func(childComplexity int) int
SourceKind func(childComplexity int) int SourceKind func(childComplexity int) int
State func(childComplexity int) int State func(childComplexity int) int
URL func(childComplexity int) int URL func(childComplexity int) int
@@ -187,6 +188,7 @@ type ComplexityRoot struct {
Logout func(childComplexity int) int Logout func(childComplexity int) int
PromoteJobLead func(childComplexity int, id int) int PromoteJobLead func(childComplexity int, id int) int
RefreshToken func(childComplexity int) int RefreshToken func(childComplexity int) int
RescoreJobLeads func(childComplexity int) int
RestoreJobLead func(childComplexity int, id int) int RestoreJobLead func(childComplexity int, id int) int
RunJobLeadSync func(childComplexity int) int RunJobLeadSync func(childComplexity int) int
ScoreJobLeads func(childComplexity int) int ScoreJobLeads func(childComplexity int) int
@@ -340,6 +342,7 @@ type MutationResolver interface {
UpdateJobSearchProfile(ctx context.Context, input model.UpdateJobSearchProfileInput) (*models.JobSearchProfile, error) UpdateJobSearchProfile(ctx context.Context, input model.UpdateJobSearchProfileInput) (*models.JobSearchProfile, error)
RunJobLeadSync(ctx context.Context) (bool, error) RunJobLeadSync(ctx context.Context) (bool, error)
ScoreJobLeads(ctx context.Context) (bool, error) ScoreJobLeads(ctx context.Context) (bool, error)
RescoreJobLeads(ctx context.Context) (bool, error)
CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error)
UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error)
DeletePlace(ctx context.Context, id int) (*models.Place, error) DeletePlace(ctx context.Context, id int) (*models.Place, error)
@@ -736,6 +739,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
} }
return e.ComplexityRoot.JobLead.ScoreReasons(childComplexity), true return e.ComplexityRoot.JobLead.ScoreReasons(childComplexity), true
case "JobLead.scoredAt":
if e.ComplexityRoot.JobLead.ScoredAt == nil {
break
}
return e.ComplexityRoot.JobLead.ScoredAt(childComplexity), true
case "JobLead.sourceKind": case "JobLead.sourceKind":
if e.ComplexityRoot.JobLead.SourceKind == nil { if e.ComplexityRoot.JobLead.SourceKind == nil {
break break
@@ -1142,6 +1151,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
} }
return e.ComplexityRoot.Mutation.RefreshToken(childComplexity), true return e.ComplexityRoot.Mutation.RefreshToken(childComplexity), true
case "Mutation.rescoreJobLeads":
if e.ComplexityRoot.Mutation.RescoreJobLeads == nil {
break
}
return e.ComplexityRoot.Mutation.RescoreJobLeads(childComplexity), true
case "Mutation.restoreJobLead": case "Mutation.restoreJobLead":
if e.ComplexityRoot.Mutation.RestoreJobLead == nil { if e.ComplexityRoot.Mutation.RestoreJobLead == nil {
break break
@@ -1999,6 +2014,8 @@ func (ec *executionContext) childFields_JobLead(ctx context.Context, field graph
return ec.fieldContext_JobLead_score(ctx, field) return ec.fieldContext_JobLead_score(ctx, field)
case "scoreReasons": case "scoreReasons":
return ec.fieldContext_JobLead_scoreReasons(ctx, field) return ec.fieldContext_JobLead_scoreReasons(ctx, field)
case "scoredAt":
return ec.fieldContext_JobLead_scoredAt(ctx, field)
case "jobAppId": case "jobAppId":
return ec.fieldContext_JobLead_jobAppId(ctx, field) return ec.fieldContext_JobLead_jobAppId(ctx, field)
} }
@@ -4263,6 +4280,29 @@ func (ec *executionContext) fieldContext_JobLead_scoreReasons(_ context.Context,
return graphql.NewScalarFieldContext("JobLead", field, false, false, errors.New("field of type String does not have child fields")) return graphql.NewScalarFieldContext("JobLead", field, false, false, errors.New("field of type String does not have child fields"))
} }
func (ec *executionContext) _JobLead_scoredAt(ctx context.Context, field graphql.CollectedField, obj *models.JobLead) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
ec.OperationContext,
field,
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.fieldContext_JobLead_scoredAt(ctx, field)
},
func(ctx context.Context) (any, error) {
return obj.ScoredAt, nil
},
nil,
func(ctx context.Context, selections ast.SelectionSet, v *time.Time) graphql.Marshaler {
return ec.marshalOTime2ᚖtimeᚐTime(ctx, selections, v)
},
true,
false,
)
}
func (ec *executionContext) fieldContext_JobLead_scoredAt(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
return graphql.NewScalarFieldContext("JobLead", field, false, false, errors.New("field of type Time does not have child fields"))
}
func (ec *executionContext) _JobLead_jobAppId(ctx context.Context, field graphql.CollectedField, obj *models.JobLead) (ret graphql.Marshaler) { func (ec *executionContext) _JobLead_jobAppId(ctx context.Context, field graphql.CollectedField, obj *models.JobLead) (ret graphql.Marshaler) {
return graphql.ResolveField( return graphql.ResolveField(
ctx, ctx,
@@ -6047,6 +6087,42 @@ func (ec *executionContext) fieldContext_Mutation_scoreJobLeads(_ context.Contex
return graphql.NewScalarFieldContext("Mutation", field, true, true, errors.New("field of type Boolean does not have child fields")) return graphql.NewScalarFieldContext("Mutation", field, true, true, errors.New("field of type Boolean does not have child fields"))
} }
func (ec *executionContext) _Mutation_rescoreJobLeads(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
ec.OperationContext,
field,
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.fieldContext_Mutation_rescoreJobLeads(ctx, field)
},
func(ctx context.Context) (any, error) {
return ec.Resolvers.Mutation().RescoreJobLeads(ctx)
},
func(ctx context.Context, next graphql.Resolver) graphql.Resolver {
directive0 := next
directive1 := func(ctx context.Context) (any, error) {
if ec.Directives.Admin == nil {
var zeroVal bool
return zeroVal, errors.New("directive admin is not implemented")
}
return ec.Directives.Admin(ctx, nil, directive0)
}
next = directive1
return next
},
func(ctx context.Context, selections ast.SelectionSet, v bool) graphql.Marshaler {
return ec.marshalNBoolean2bool(ctx, selections, v)
},
true,
true,
)
}
func (ec *executionContext) fieldContext_Mutation_rescoreJobLeads(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
return graphql.NewScalarFieldContext("Mutation", field, true, true, errors.New("field of type Boolean does not have child fields"))
}
func (ec *executionContext) _Mutation_createPlace(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { func (ec *executionContext) _Mutation_createPlace(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
return graphql.ResolveField( return graphql.ResolveField(
ctx, ctx,
@@ -11223,6 +11299,11 @@ func (ec *executionContext) _JobLead(ctx context.Context, sel ast.SelectionSet,
if out.Values[i] == graphql.RequiredNull { if out.Values[i] == graphql.RequiredNull {
out.Invalids++ out.Invalids++
} }
case "scoredAt":
out.Values[i] = ec._JobLead_scoredAt(ctx, field, obj)
if out.Values[i] == graphql.RequiredNull {
out.Invalids++
}
case "jobAppId": case "jobAppId":
out.Values[i] = ec._JobLead_jobAppId(ctx, field, obj) out.Values[i] = ec._JobLead_jobAppId(ctx, field, obj)
if out.Values[i] == graphql.RequiredNull { if out.Values[i] == graphql.RequiredNull {
@@ -11723,6 +11804,13 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet)
if out.Values[i] == graphql.Null { if out.Values[i] == graphql.Null {
out.Invalids++ out.Invalids++
} }
case "rescoreJobLeads":
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
return ec._Mutation_rescoreJobLeads(ctx, field)
})
if out.Values[i] == graphql.Null {
out.Invalids++
}
case "createPlace": case "createPlace":
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
return ec._Mutation_createPlace(ctx, field) return ec._Mutation_createPlace(ctx, field)
+11 -3
View File
@@ -144,7 +144,7 @@ func (r *mutationResolver) RunJobLeadSync(ctx context.Context) (bool, error) {
if r.Store.JobLeads == nil { if r.Store.JobLeads == nil {
return false, fmt.Errorf("job leads are not configured") return false, fmt.Errorf("job leads are not configured")
} }
return r.Store.JobLeads.RunInBackground(false), nil return r.Store.JobLeads.RunInBackground(services.LeadJobSync), nil
} }
// ScoreJobLeads is the resolver for the scoreJobLeads field. // ScoreJobLeads is the resolver for the scoreJobLeads field.
@@ -152,7 +152,15 @@ func (r *mutationResolver) ScoreJobLeads(ctx context.Context) (bool, error) {
if r.Store.JobLeads == nil { if r.Store.JobLeads == nil {
return false, fmt.Errorf("job leads are not configured") return false, fmt.Errorf("job leads are not configured")
} }
return r.Store.JobLeads.RunInBackground(true), nil return r.Store.JobLeads.RunInBackground(services.LeadJobScore), nil
}
// RescoreJobLeads is the resolver for the rescoreJobLeads field.
func (r *mutationResolver) RescoreJobLeads(ctx context.Context) (bool, error) {
if r.Store.JobLeads == nil {
return false, fmt.Errorf("job leads are not configured")
}
return r.Store.JobLeads.RunInBackground(services.LeadJobRescore), nil
} }
// JobSources is the resolver for the jobSources field. // JobSources is the resolver for the jobSources field.
@@ -176,7 +184,7 @@ func (r *queryResolver) JobLeads(ctx context.Context, state *string, includeUnma
if includeUnmatched == nil || !*includeUnmatched { if includeUnmatched == nil || !*includeUnmatched {
// A promoted or dismissed lead is shown whatever the filter now says // A promoted or dismissed lead is shown whatever the filter now says
// about it; `matched` only decides what the inbox offers. // about it; `matched` only decides what the inbox offers.
query = query.Where("matched = ? OR state <> ?", true, services.LeadNew) query = query.Where("(matched = ? OR state <> ?)", true, services.LeadNew)
} }
var leads []*models.JobLead var leads []*models.JobLead
// Best first, unscored after scored, newest first within a score. The // Best first, unscored after scored, newest first within a score. The
+7
View File
@@ -67,6 +67,7 @@ type JobLead {
state: String! state: String!
score: Int score: Int
scoreReasons: String scoreReasons: String
scoredAt: Time
jobAppId: ID jobAppId: ID
} }
@@ -135,4 +136,10 @@ extend type Mutation {
# source. Background and polled like runJobLeadSync, and refused (false) # source. Background and polled like runJobLeadSync, and refused (false)
# while either is running. # while either is running.
scoreJobLeads: Boolean! @admin scoreJobLeads: Boolean! @admin
# Scores every matched inbox lead again, scored or not, for after the
# profile or the model has changed. A lead keeps its old score until its
# new one arrives. Background and polled like the two above, and refused
# (false) while any of the three is running.
rescoreJobLeads: Boolean! @admin
} }
+5 -2
View File
@@ -291,8 +291,10 @@ type JobSource struct {
// Matched says whether the lead passed the keyword pre-filter the last time // Matched says whether the lead passed the keyword pre-filter the last time
// the fetcher ran; only matched leads are shown by default and only they are // the fetcher ran; only matched leads are shown by default and only they are
// scored. Score (0-100) and ScoreReasons are Claude's, and nil until scored. // scored. Score (0-100) and ScoreReasons are Claude's, and nil until scored.
// ScoreAttempts counts failed tries, so a posting Claude can never score // ScoredAt is when that score was given, which is how a rescore tells the
// stops costing a call per run. // leads it has redone from the ones it has yet to reach; it is nil on a lead
// scored before the column existed. ScoreAttempts counts failed tries, so a
// posting Claude can never score stops costing a call per run.
type JobLead struct { type JobLead struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
@@ -311,6 +313,7 @@ type JobLead struct {
State string `gorm:"not null;default:new;index" json:"state"` State string `gorm:"not null;default:new;index" json:"state"`
Score *int `json:"score"` Score *int `json:"score"`
ScoreReasons *string `json:"scoreReasons"` ScoreReasons *string `json:"scoreReasons"`
ScoredAt *time.Time `json:"scoredAt"`
ScoreAttempts int `gorm:"not null;default:0" json:"scoreAttempts"` ScoreAttempts int `gorm:"not null;default:0" json:"scoreAttempts"`
JobAppID *uint `json:"jobAppId"` JobAppID *uint `json:"jobAppId"`
} }
+70 -13
View File
@@ -162,18 +162,32 @@ func (s *JobLeadService) StartScheduler(ctx context.Context) {
} }
} }
// RunInBackground starts a run and returns at once, reporting false when one // LeadJob names one of the pipeline's three jobs, for RunInBackground.
// was already going. It backs the page's two buttons — "Check now" (Run) and type LeadJob int
// "Score unscored" (ScoreAll, when scoreOnly is set). Either can take minutes,
// far longer than a request should be held open, so the page polls Status const (
// instead of waiting. // LeadJobSync is Run: poll the sources, then score up to a cap.
func (s *JobLeadService) RunInBackground(scoreOnly bool) bool { LeadJobSync LeadJob = iota
// LeadJobScore is ScoreAll: score every unscored lead, polling nothing.
LeadJobScore
// LeadJobRescore is RescoreAll: score every inbox lead again.
LeadJobRescore
)
// RunInBackground starts a job and returns at once, reporting false when one
// was already going. It backs the page's buttons — "Check now", "Score
// unscored" and "Rescore all". Any of them can take minutes, far longer than
// a request should be held open, so the page polls Status instead of waiting.
func (s *JobLeadService) RunInBackground(job LeadJob) bool {
if s.Status().Running { if s.Status().Running {
return false return false
} }
run := s.Run run := s.Run
if scoreOnly { switch job {
case LeadJobScore:
run = s.ScoreAll run = s.ScoreAll
case LeadJobRescore:
run = s.RescoreAll
} }
go func() { go func() {
// Not the request's context: the request is over long before this is. // Not the request's context: the request is over long before this is.
@@ -199,6 +213,28 @@ func (s *JobLeadService) Run(ctx context.Context) error {
// decide what gets scored. There is no cap on the count — the person pressed a // decide what gets scored. There is no cap on the count — the person pressed a
// button that says "all" — only maxScoreAllDuration on the time. // button that says "all" — only maxScoreAllDuration on the time.
func (s *JobLeadService) ScoreAll(ctx context.Context) error { func (s *JobLeadService) ScoreAll(ctx context.Context) error {
return s.scoreAll(ctx, false)
}
// RescoreAll scores every matched lead in the inbox again, including the
// ones that already have a score. It is for when what a score means has
// changed: the profile was rewritten, or CLAUDE_MODEL was switched.
//
// Old scores are not wiped first. Each lead keeps the score it has until its
// new one arrives, so the inbox stays sorted and readable while the job runs,
// and a job that dies halfway (no API key, a restart) leaves every lead with
// a score, some new and some old, rather than half of them blank. What is
// left to do is told apart by ScoredAt: anything scored before this job
// started is still due. Pressing the button again after a failure therefore
// starts over rather than resuming, which costs calls but is never wrong.
//
// Leads that had used up their attempts get them back: a posting the old
// model could not score may be fine on the new one.
func (s *JobLeadService) RescoreAll(ctx context.Context) error {
return s.scoreAll(ctx, true)
}
func (s *JobLeadService) scoreAll(ctx context.Context, rescore bool) error {
return s.exclusive(ctx, maxScoreAllDuration, func(ctx context.Context) error { return s.exclusive(ctx, maxScoreAllDuration, func(ctx context.Context) error {
profile, err := LoadJobSearchProfile(s.DB) profile, err := LoadJobSearchProfile(s.DB)
if err != nil { if err != nil {
@@ -211,7 +247,19 @@ func (s *JobLeadService) ScoreAll(ctx context.Context) error {
return fmt.Errorf("re-applying the filter: %w", err) return fmt.Errorf("re-applying the filter: %w", err)
} }
log.Println("[JobLeads] Scoring all unscored leads") var due *time.Time
if rescore {
started := time.Now()
due = &started
if err := s.DB.Model(&models.JobLead{}).
Where("state = ? AND matched = ? AND score_attempts > 0", LeadNew, true).
UpdateColumn("score_attempts", 0).Error; err != nil {
return fmt.Errorf("resetting score attempts: %w", err)
}
log.Println("[JobLeads] Rescoring every inbox lead")
} else {
log.Println("[JobLeads] Scoring all unscored leads")
}
total := 0 total := 0
var failed []uint var failed []uint
for { for {
@@ -220,7 +268,7 @@ func (s *JobLeadService) ScoreAll(ctx context.Context) error {
// it, not all three — a passing Claude hiccup should not write a // it, not all three — a passing Claude hiccup should not write a
// lead off for good. That is also why the loop terminates: every // lead off for good. That is also why the loop terminates: every
// lead a pass looks at is either scored or added to `failed`. // lead a pass looks at is either scored or added to `failed`.
scored, tried, nowFailed, err := s.scoreLeads(ctx, profile, failed) scored, tried, nowFailed, err := s.scoreLeads(ctx, profile, failed, due)
total += scored total += scored
failed = append(failed, nowFailed...) failed = append(failed, nowFailed...)
if err != nil || tried == 0 { if err != nil || tried == 0 {
@@ -302,7 +350,7 @@ func (s *JobLeadService) fetchAndScore(ctx context.Context) error {
if err := s.refilter(filter); err != nil { if err := s.refilter(filter); err != nil {
return fmt.Errorf("re-applying the filter: %w", err) return fmt.Errorf("re-applying the filter: %w", err)
} }
scored, _, _, err := s.scoreLeads(ctx, profile, nil) scored, _, _, err := s.scoreLeads(ctx, profile, nil, nil)
log.Printf("[JobLeads] Run finished: %d new leads, %d scored", added, scored) log.Printf("[JobLeads] Run finished: %d new leads, %d scored", added, scored)
return err return err
} }
@@ -678,13 +726,22 @@ type scoreRequest struct {
// tried is zero once nothing is left to score, which is what ScoreAll loops // tried is zero once nothing is left to score, which is what ScoreAll loops
// on. // on.
// //
// rescoreBefore, when set, widens "has no score yet" to "has no score from
// this job": a lead whose score is older than that time is due again. Its old
// score stays in place until the new one is saved, and through a failure.
//
// With no profile text there is nothing to score against, so it does nothing // With no profile text there is nothing to score against, so it does nothing
// — leads still arrive and can be read, they just carry no score. // — leads still arrive and can be read, they just carry no score.
func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSearchProfile, skip []uint) (scored, tried int, failed []uint, err error) { func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSearchProfile, skip []uint, rescoreBefore *time.Time) (scored, tried int, failed []uint, err error) {
if strings.TrimSpace(profile.Profile) == "" { if strings.TrimSpace(profile.Profile) == "" {
return 0, 0, nil, nil return 0, 0, nil, nil
} }
query := s.DB.Where("state = ? AND matched = ? AND score IS NULL AND score_attempts < ?", LeadNew, true, maxScoreAttempts) query := s.DB.Where("state = ? AND matched = ? AND score_attempts < ?", LeadNew, true, maxScoreAttempts)
if rescoreBefore == nil {
query = query.Where("score IS NULL")
} else {
query = query.Where("(score IS NULL OR scored_at IS NULL OR scored_at < ?)", *rescoreBefore)
}
if len(skip) > 0 { if len(skip) > 0 {
query = query.Where("id NOT IN ?", skip) query = query.Where("id NOT IN ?", skip)
} }
@@ -703,7 +760,7 @@ func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSear
case err == nil: case err == nil:
reasons := strings.TrimSpace(result.Reasons) reasons := strings.TrimSpace(result.Reasons)
score := min(max(result.Score, 0), 100) score := min(max(result.Score, 0), 100)
if dbErr := s.DB.Model(lead).Updates(map[string]any{"score": score, "score_reasons": reasons}).Error; dbErr != nil { if dbErr := s.DB.Model(lead).Updates(map[string]any{"score": score, "score_reasons": reasons, "scored_at": time.Now()}).Error; dbErr != nil {
return scored, tried, failed, fmt.Errorf("saving a score: %w", dbErr) return scored, tried, failed, fmt.Errorf("saving a score: %w", dbErr)
} }
scored++ scored++
+3 -2
View File
@@ -239,8 +239,9 @@ until **Track** is pressed on a lead, which adds it to `/cv/jobs` as Saved.
Same conventions as the tracker: the children emit `fail` / `ok` for the Same conventions as the tracker: the children emit `fail` / `ok` for the
parent's banner, and a lead's `description` is fetched per row. Two things parent's banner, and a lead's `description` is fetched per row. Two things
differ. "Check now" (poll the sources, score up to forty) and "Score differ. "Check now" (poll the sources, score up to forty), "Score unscored"
unscored" (poll nothing, score the whole backlog) do not wait for the job — (poll nothing, score the whole backlog) and "Rescore all" (score every inbox
lead again) do not wait for the job —
the mutation returns at once and the page polls `jobLeadSyncStatus` every the mutation returns at once and the page polls `jobLeadSyncStatus` every
three seconds, reloading the leads as it goes and the sources at the end. And the box styles the children share (`.jl-box`, three seconds, reloading the leads as it goes and the sources at the end. And the box styles the children share (`.jl-box`,
`.jl-hint`, `.jl-warn`) are in an unscoped `<style>` block in `JobLeads.vue`, `.jl-hint`, `.jl-warn`) are in an unscoped `<style>` block in `JobLeads.vue`,
+12 -2
View File
@@ -18,7 +18,7 @@ import { gql } from "@/graphql";
// `description` is deliberately not here: it is the full text of the posting // `description` is deliberately not here: it is the full text of the posting
// and is fetched per lead when asked for, as on the tracker. // and is fetched per lead when asked for, as on the tracker.
const LEAD_FIELDS = `id createdAt sourceKind jobTitle company location url postedAt lastSeenAt matched state score scoreReasons jobAppId`; const LEAD_FIELDS = `id createdAt sourceKind jobTitle company location url postedAt lastSeenAt matched state score scoreReasons scoredAt jobAppId`;
export const useJobLeadsStore = defineStore("jobLeads", () => { export const useJobLeadsStore = defineStore("jobLeads", () => {
const leads = ref([]); const leads = ref([]);
@@ -107,5 +107,15 @@ export const useJobLeadsStore = defineStore("jobLeads", () => {
return data.scoreJobLeads; return data.scoreJobLeads;
} }
return { leads, loading, error, status, fetch, dismiss, restore, promote, fetchDescription, fetchStatus, runSync, scoreAll }; /**
* Score every inbox lead again, scored or not — for after the profile or
* the model has changed. Same contract as runSync(). Each lead keeps its old
* score until its new one lands, so the list never goes blank.
*/
async function rescoreAll() {
const data = await gql(`mutation RescoreJobLeads { rescoreJobLeads }`);
return data.rescoreJobLeads;
}
return { leads, loading, error, status, fetch, dismiss, restore, promote, fetchDescription, fetchStatus, runSync, scoreAll, rescoreAll };
}); });
+57 -8
View File
@@ -12,11 +12,12 @@
* This view owns the page frame, the single error banner, the run button and * This view owns the page frame, the single error banner, the run button and
* the list. Data access is in stores/jobLeads.js; nothing here calls gql(). * the list. Data access is in stores/jobLeads.js; nothing here calls gql().
* *
* There are two server jobs. "Check now" polls the sources and scores up to * There are three server jobs. "Check now" polls the sources and scores up to
* forty new leads; "Score unscored" polls nothing and scores the whole * forty new leads; "Score unscored" polls nothing and scores the whole
* backlog. Either takes from seconds to many minutes, so the button does not * backlog; "Rescore all" scores every inbox lead again, for after the profile
* wait: the server starts the job and this page polls its status, then * or the model has changed. Each takes from seconds to many minutes, so the
* reloads the list when it finishes. * button does not wait: the server starts the job and this page polls its
* status, then reloads the list when it finishes.
*/ */
import { ref, computed, onMounted, onBeforeUnmount } from "vue"; import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { RouterLink } from "vue-router"; import { RouterLink } from "vue-router";
@@ -48,6 +49,9 @@ const search = ref("");
// rejected (not loaded at all until asked for — that is most of every board). // rejected (not loaded at all until asked for — that is most of every board).
const showLowScores = ref(false); const showLowScores = ref(false);
const showUnmatched = ref(false); const showUnmatched = ref(false);
// "score" is the order the server sends; "posted" re-sorts here by the
// posting's own date.
const sortBy = ref("score");
const busyId = ref(null); const busyId = ref(null);
const sourcesBox = ref(null); const sourcesBox = ref(null);
@@ -88,16 +92,22 @@ const hiddenLow = computed(() =>
tab.value === "new" && !showLowScores.value ? inTab.value.filter(isLow).length : 0, tab.value === "new" && !showLowScores.value ? inTab.value.filter(isLow).length : 0,
); );
/** When the posting went up; when we first saw it if the source gave no date. */
const postedTime = (lead) => new Date(lead.postedAt ?? lead.createdAt).getTime();
// The server already sorts best-first, unscored after scored, newest first // The server already sorts best-first, unscored after scored, newest first
// within a score, so this only filters. // within a score, so by score this only filters. By date it re-sorts a copy;
// Array.sort is stable, so postings of the same day stay best-first.
const visibleLeads = computed(() => { const visibleLeads = computed(() => {
const needle = search.value.trim().toLowerCase(); const needle = search.value.trim().toLowerCase();
return inTab.value.filter((lead) => { const shown = inTab.value.filter((lead) => {
if (tab.value === "new" && !showLowScores.value && isLow(lead)) return false; if (tab.value === "new" && !showLowScores.value && isLow(lead)) return false;
if (!needle) return true; if (!needle) return true;
return [lead.jobTitle, lead.company, lead.location, lead.scoreReasons] return [lead.jobTitle, lead.company, lead.location, lead.scoreReasons]
.some((field) => field?.toLowerCase().includes(needle)); .some((field) => field?.toLowerCase().includes(needle));
}); });
if (sortBy.value === "posted") shown.sort((a, b) => postedTime(b) - postedTime(a));
return shown;
}); });
function scoreClass(lead) { function scoreClass(lead) {
@@ -107,6 +117,15 @@ function scoreClass(lead) {
return "jl-score-low"; return "jl-score-low";
} }
/** The tooltip says when, which during a rescore is how to tell new from old. */
function scoreTitle(lead) {
if (lead.score == null) return "Not scored";
const when = lead.scoredAt
? `, scored ${new Date(lead.scoredAt).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })}`
: "";
return `Fit score ${lead.score} out of 100${when}`;
}
function ageLabel(lead) { function ageLabel(lead) {
const at = lead.postedAt ?? lead.createdAt; const at = lead.postedAt ?? lead.createdAt;
if (!at) return ""; if (!at) return "";
@@ -172,7 +191,7 @@ async function pollStatus() {
await Promise.all([fetchLeads(), sourcesBox.value?.refresh()]); await Promise.all([fetchLeads(), sourcesBox.value?.refresh()]);
} }
/** Start one of the two server jobs ("runSync" or "scoreAll") and wait on it. */ /** Start one of the server jobs ("runSync", "scoreAll", "rescoreAll") and wait on it. */
async function start(job) { async function start(job) {
try { try {
// false means a job was already going (the scheduler's, say); either way // false means a job was already going (the scheduler's, say); either way
@@ -187,6 +206,19 @@ async function start(job) {
} }
} }
// Matched inbox leads that have a score: what "Rescore all" would redo, on
// top of the unscored ones.
const scoredCount = computed(
() => leads.value.filter((lead) => lead.state === "new" && lead.matched && lead.score != null).length,
);
function rescore() {
const total = scoredCount.value + unscoredCount.value;
// One Claude call per lead, and it replaces scores that were paid for.
if (!confirm(`Score all ${total} inbox leads again? This makes one Claude call per lead.`)) return;
start("rescoreAll");
}
// Matched inbox leads with no score: what "Score unscored" would work // Matched inbox leads with no score: what "Score unscored" would work
// through. A lead Claude failed on three times stays in this count, though // through. A lead Claude failed on three times stays in this count, though
// the server will not try it again. // the server will not try it again.
@@ -223,6 +255,15 @@ onBeforeUnmount(stopPolling);
</div> </div>
<div class="jl-header-right"> <div class="jl-header-right">
<span class="jl-hint">{{ lastRun }}</span> <span class="jl-hint">{{ lastRun }}</span>
<button
v-if="scoredCount"
class="cv-btn"
:disabled="running"
title="Score every inbox lead again, including ones already scored. Use after changing the profile or the model. Old scores stay until replaced."
@click="rescore"
>
Rescore all
</button>
<button <button
v-if="unscoredCount" v-if="unscoredCount"
class="cv-btn" class="cv-btn"
@@ -266,6 +307,10 @@ onBeforeUnmount(stopPolling);
<div class="jl-filterbar"> <div class="jl-filterbar">
<input v-model="search" class="ja-input" type="search" placeholder="Search title, company, location, reasons…" /> <input v-model="search" class="ja-input" type="search" placeholder="Search title, company, location, reasons…" />
<select v-model="sortBy" class="ja-input ja-select jl-sort" title="Order of the list">
<option value="score">Best score first</option>
<option value="posted">Newest posting first</option>
</select>
<label v-if="tab === 'new'" class="jl-check"> <label v-if="tab === 'new'" class="jl-check">
<input v-model="showLowScores" type="checkbox" /> <input v-model="showLowScores" type="checkbox" />
Below {{ minScore }}<template v-if="hiddenLow"> ({{ hiddenLow }} hidden)</template> Below {{ minScore }}<template v-if="hiddenLow"> ({{ hiddenLow }} hidden)</template>
@@ -282,7 +327,7 @@ onBeforeUnmount(stopPolling);
class="jl-lead" class="jl-lead"
:class="{ 'jl-lead-unmatched': !lead.matched && lead.state === 'new' }" :class="{ 'jl-lead-unmatched': !lead.matched && lead.state === 'new' }"
> >
<div class="jl-score" :class="scoreClass(lead)" :title="lead.score == null ? 'Not scored' : `Fit score ${lead.score} out of 100`"> <div class="jl-score" :class="scoreClass(lead)" :title="scoreTitle(lead)">
{{ lead.score ?? "–" }} {{ lead.score ?? "–" }}
</div> </div>
<div class="jl-lead-body"> <div class="jl-lead-body">
@@ -468,6 +513,10 @@ onBeforeUnmount(stopPolling);
margin-bottom: 0.75rem; margin-bottom: 0.75rem;
} }
.jl-sort {
flex: 0 0 auto;
}
.jl-check { .jl-check {
display: flex; display: flex;
align-items: center; align-items: center;