package main import ( "bytes" "context" _ "embed" "encoding/json" "errors" "fmt" "log/slog" "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"` SalarySuggestion string `json:"salary_suggestion"` 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") // errBadAnswer means Claude answered, but not with the JSON object asked for. // It is worth one more try: the same posting usually comes out fine. var errBadAnswer = errors.New("claude's answer is not the expected JSON") // around quotes the part of the answer a JSON error points at, so the log // shows what went wrong instead of only where. func around(s string, err error) string { var syn *json.SyntaxError if !errors.As(err, &syn) { return truncate(s, 160) } at := int(min(max(syn.Offset, 0), int64(len(s)))) return strings.ToValidUTF8(s[max(0, at-120):min(len(s), at+60)], "") } // 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>", "", "< cv>", "", "< /cv>").Replace(p.Text) var b strings.Builder fmt.Fprintf(&b, "\n%s\n\n\n", strings.TrimSpace(cv)) fmt.Fprintf(&b, "\n%s\n\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("%w: %v, near %q", errBadAnswer, err, around(envelope.Result[start:end+1], 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) { pkg, err := a.assessOnce(ctx, p) if errors.Is(err, errBadAnswer) { slog.Warn("malformed answer, asking once more", "err", err) pkg, err = a.assessOnce(ctx, p) } return pkg, err } func (a *Assessor) assessOnce(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) }