fix: retry a malformed answer once and log the text around the fault

This commit is contained in:
2026-11-25 09:27:54 +01:00
parent 3b66030413
commit 44bb3fd46a
2 changed files with 37 additions and 1 deletions
+26 -1
View File
@@ -7,6 +7,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"os/exec"
"strings"
@@ -42,6 +43,21 @@ type Package struct {
// 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
@@ -78,7 +94,7 @@ func parsePackage(stdout []byte) (*Package, error) {
}
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)
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 != "" {
@@ -93,6 +109,15 @@ func parsePackage(stdout []byte) (*Package, error) {
// 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)