Files
jobhunt/assess.go
T

125 lines
4.3 KiB
Go

package main
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"time"
)
//go:embed prompt.md
var systemPrompt string
// Package is the "target package" Claude returns for one posting.
type Package struct {
Company string `json:"company"`
Title string `json:"title"`
Location string `json:"location"`
WorkMode string `json:"work_mode"`
Seniority string `json:"seniority"`
Salary string `json:"salary"`
PostingLanguage string `json:"posting_language"`
DutchRequirement string `json:"dutch_requirement"`
LanguageBlocker bool `json:"language_blocker"`
Summary string `json:"summary"`
Requirements []string `json:"requirements"`
Strengths []string `json:"strengths"`
Gaps []string `json:"gaps"`
FitScore int `json:"fit_score"`
Verdict string `json:"verdict"`
VerdictReason string `json:"verdict_reason"`
CVTweaks []string `json:"cv_tweaks"`
Questions []string `json:"questions"`
CoverLetter string `json:"cover_letter"`
}
// errNotAPosting is returned when Claude says the text is not a job posting.
var errNotAPosting = errors.New("that does not look like a job posting")
// Assessor runs the claude CLI.
type Assessor struct {
Config
}
// buildInput frames the CV and the posting for the prompt. The closing tags
// are neutralised inside the posting so its text cannot end its own block.
func buildInput(cv string, p Posting) string {
text := strings.NewReplacer("</posting>", "< /posting>", "<cv>", "< cv>", "</cv>", "< /cv>").Replace(p.Text)
var b strings.Builder
fmt.Fprintf(&b, "<cv>\n%s\n</cv>\n\n", strings.TrimSpace(cv))
fmt.Fprintf(&b, "<posting url=%q>\n%s\n</posting>\n\n", p.URL, strings.TrimSpace(text))
b.WriteString("Return the JSON object for this posting.")
return b.String()
}
// parsePackage reads the CLI's --output-format json envelope and then the
// JSON object inside its result text.
func parsePackage(stdout []byte) (*Package, error) {
var envelope struct {
IsError bool `json:"is_error"`
Result string `json:"result"`
}
if err := json.Unmarshal(stdout, &envelope); err != nil {
return nil, fmt.Errorf("claude output is not JSON: %w", err)
}
if envelope.IsError {
return nil, fmt.Errorf("claude reported an error: %s", truncate(envelope.Result, 300))
}
// Tolerate a code fence or a stray sentence around the object.
start, end := strings.Index(envelope.Result, "{"), strings.LastIndex(envelope.Result, "}")
if start < 0 || end < start {
return nil, fmt.Errorf("no JSON object in claude's answer: %s", truncate(envelope.Result, 300))
}
var pkg Package
if err := json.Unmarshal([]byte(envelope.Result[start:end+1]), &pkg); err != nil {
return nil, fmt.Errorf("claude's answer is not the expected JSON: %w", err)
}
if strings.TrimSpace(pkg.Title) == "" {
if pkg.VerdictReason != "" {
return nil, fmt.Errorf("%w: %s", errNotAPosting, pkg.VerdictReason)
}
return nil, errNotAPosting
}
pkg.FitScore = max(0, min(100, pkg.FitScore))
return &pkg, nil
}
// Assess asks Claude for the package. Claude gets no tools (--tools ""), so
// whatever a posting says, the worst outcome is a strange note.
func (a *Assessor) Assess(ctx context.Context, p Posting) (*Package, error) {
cv, err := os.ReadFile(a.CVPath)
if err != nil {
return nil, fmt.Errorf("reading the CV: %w", err)
}
ctx, cancel := context.WithTimeout(ctx, 8*time.Minute)
defer cancel()
args := []string{"-p", "--tools", "", "--output-format", "json", "--system-prompt", systemPrompt}
if a.Model != "" {
args = append(args, "--model", a.Model)
}
cmd := exec.CommandContext(ctx, a.ClaudeBin, args...)
cmd.Dir = a.StateDir // not the vault: no project files for the CLI to pick up
cmd.Stdin = strings.NewReader(buildInput(string(cv), p))
var stderr bytes.Buffer
cmd.Stderr = &stderr
cmd.WaitDelay = 5 * time.Second
stdout, err := cmd.Output()
if err != nil {
// The CLI prints its JSON envelope even on failure; prefer its message.
if _, perr := parsePackage(stdout); perr != nil && len(stdout) > 0 {
return nil, fmt.Errorf("claude failed: %w", perr)
}
return nil, fmt.Errorf("running claude: %w: %s", err, truncate(strings.TrimSpace(stderr.String()), 300))
}
return parsePackage(stdout)
}