Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ unless you turn it on: `/plugin` → Marketplaces → refetch → Enable
auto-update. New versions load on the next launch or `/reload-plugins`. To
update by hand, run `claude plugin update refetch@refetch`.

A session that was open during an update keeps running the version it
started with. refetch says so when that session starts a new conversation
and when a fetch fails, and `refetch doctor` reports it. `refetch stats`
splits fetches by refetch version when more than one shows up.

### Check the setup

Ask Claude to run `refetch doctor`, or run it yourself. It checks the
Expand Down
3 changes: 3 additions & 0 deletions cmd/refetch/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ func (fr *fetcher) snapshot(ctx context.Context, url string) (fetch.Page, time.T
}
if strings.Contains(got.ContentType, "html") {
switch {
case fetch.BlockPage(got.Body):
got.Last.Outcome = fetch.OutcomeRefused
return got, ts, errors.New("the snapshot is a block page")
case fetch.Challenge(http.StatusOK, got.Body):
got.Last.Outcome = fetch.OutcomeChallenge
return got, ts, errors.New("the snapshot is a challenge page")
Expand Down
30 changes: 6 additions & 24 deletions cmd/refetch/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,16 @@ func archiveCheck(cfg config.Config) check {

func versionCheck() check {
bin := buildVersion()
plugin := os.Getenv("REFETCH_PLUGIN_VERSION")
plugin, newer := os.Getenv("REFETCH_PLUGIN_VERSION"), newerPlugin()
switch {
case plugin == "":
return check{true, "version", "refetch " + bin + " (not run through the plugin)"}
case plugin == "0.0.0":
return check{true, "version", "refetch " + bin + ", with the plugin files of a development checkout"}
case strings.TrimPrefix(bin, "v") != plugin:
return check{false, "version", fmt.Sprintf("binary %s, plugin %s: run /reload-plugins, or check REFETCH_BIN", bin, plugin)}
case newer != "":
return check{false, "version", fmt.Sprintf("this session runs refetch %s, but %s is installed: run /reload-plugins or restart Claude Code", plugin, newer)}
}
return check{true, "version", "refetch " + bin + ", same as the plugin"}
}
Expand All @@ -103,15 +105,15 @@ var (
// GitHub is not a setup problem, so it never fails the check.
func updateCheck(ctx context.Context) check {
current := cmp.Or(os.Getenv("REFETCH_PLUGIN_VERSION"), strings.TrimPrefix(buildVersion(), "v"))
cur, ok := minorVersion(current)
if !ok || current == "0.0.0" { // a checkout of main; only releases set a version
cur, ok := releaseVersion(current)
if !ok { // a checkout of main; only releases set a version
return check{true, "updates", "not checked for a development build"}
}
latest, err := latestRelease(ctx)
if err != nil {
return check{true, "updates", "could not check for a newer release: " + err.Error()}
}
lat, ok := minorVersion(latest)
lat, ok := releaseVersion(latest)
switch {
case !ok:
return check{true, "updates", "could not read the latest release " + strconv.Quote(latest)}
Expand Down Expand Up @@ -148,26 +150,6 @@ func latestRelease(ctx context.Context) (string, error) {
return strings.TrimPrefix(rel.Tag, "v"), nil
}

// minorVersion parses the major and minor numbers of a release version
// such as 1.2.3; development and snapshot builds do not parse.
func minorVersion(v string) ([2]int, bool) {
parts := strings.Split(v, ".")
if len(parts) != 3 {
return [2]int{}, false
}
var out [2]int
for i, p := range parts {
n, err := strconv.Atoi(p)
if err != nil || n < 0 {
return [2]int{}, false
}
if i < 2 {
out[i] = n
}
}
return out, true
}

func configCheck() check {
path := config.Path()
if _, err := os.Stat(path); err != nil {
Expand Down
40 changes: 35 additions & 5 deletions cmd/refetch/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/json/v2"
"fmt"
"io"
neturl "net/url"
"os"
"regexp"
"strconv"
Expand Down Expand Up @@ -109,6 +110,9 @@ func (h *hooker) handle(ctx context.Context, in hookInput) string {
h.debug(h.st.Rollup(ctx, h.now.Add(-store.Retention)))
}
prunePages(config.DataDir(), savedPagesAge)
if note := staleNote(); note != "" {
return standingGuidance + "\n" + note
}
return standingGuidance
case "PreToolUse":
if isRead(in.Tool) {
Expand All @@ -121,6 +125,15 @@ func (h *hooker) handle(ctx context.Context, in hookInput) string {
default:
return ""
}
if !stats.IsFetchPage(in.Tool) && !isRead(in.Tool) {
return ""
}
if in.Event == "PostToolUseFailure" && harnessError.MatchString(in.Error) {
for id, u := range readURLs(in) {
h.record(ctx, in, id, u, store.CallDenied, in.Error)
}
return ""
}
if stats.IsFetchPage(in.Tool) {
outcome, why := store.CallOK, ""
if in.Event == "PostToolUseFailure" {
Expand All @@ -129,9 +142,6 @@ func (h *hooker) handle(ctx context.Context, in hookInput) string {
h.record(ctx, in, in.ToolUseID, in.Input.URL, outcome, why)
return ""
}
if !isRead(in.Tool) {
return ""
}
failed := detect(in)
for id, u := range readURLs(in) {
outcome, why := store.CallOK, ""
Expand Down Expand Up @@ -160,7 +170,7 @@ func (h *hooker) recordAs(ctx context.Context, tool string, in hookInput, id, ur
return
}
h.debug(h.st.RecordCall(ctx, store.ToolCall{
Time: h.now, SessionID: in.SessionID, ToolUseID: id, Tool: tool, URL: url, Outcome: outcome, Error: why,
Time: h.now, SessionID: in.SessionID, ToolUseID: id, Tool: tool, URL: url, Outcome: outcome, Error: why, Version: strings.TrimPrefix(buildVersion(), "v"),
}))
}

Expand All @@ -179,6 +189,12 @@ func readURLs(in hookInput) map[string]string {
return out
}

// harnessError matches a tool error from Claude Code itself (a usage limit,
// a permission prompt the user declined, the auto mode classifier), which
// says nothing about the page and is no failure for refetch to pick up.
var harnessError = regexp.MustCompile(`(?i)hit your [^.]{0,30}limit|usage limit|auto mode classifier|` +
`doesn't want to proceed|tool use was rejected|permission to use|interrupted by (the )?user`)

// summaryBlock matches the wording of a challenge or refusal page in the
// text a read returned (WebFetch's summary or context-mode's preview).
var summaryBlock = regexp.MustCompile(`(?i)just a moment|checking your browser|verify(ing)? (that )?you are (a )?human|` +
Expand Down Expand Up @@ -245,7 +261,7 @@ func detect(in hookInput) []failure {
return []failure{{in.Input.URL, "HTTP 202, likely a bot challenge"}}
case r.Bytes < 128<<10 && summaryBlock.MatchString(r.Result):
return []failure{{in.Input.URL, "challenge or block page"}}
case r.Bytes > 0 && (r.Bytes < 256 || (r.Bytes < 16<<10 && summaryNeedsJS.MatchString(r.Result))):
case r.Bytes > 0 && (r.Bytes < 256 && !apiURL(in.Input.URL) || (r.Bytes < 16<<10 && summaryNeedsJS.MatchString(r.Result))):
return []failure{{in.Input.URL, "page needs JavaScript"}}
case r.Bytes < 64<<10 && summaryEmpty.MatchString(r.Result):
return []failure{{in.Input.URL, "page came back empty"}}
Expand Down Expand Up @@ -277,6 +293,20 @@ func detect(in hookInput) []failure {
return nil
}

// apiURL reports an address that answers with data rather than a page (an
// api host or path, a .json or .xml file, format=json): a reply of a few
// bytes there is an empty result, not a JavaScript-only page.
func apiURL(raw string) bool {
u, err := neturl.Parse(raw)
if err != nil {
return false
}
path := strings.ToLower(u.Path)
return strings.HasPrefix(strings.ToLower(u.Hostname()), "api.") || strings.Contains(path, "/api") ||
strings.HasSuffix(path, ".json") || strings.HasSuffix(path, ".xml") ||
strings.EqualFold(u.Query().Get("format"), "json")
}

func tinyIndex(text string) bool {
m := ctxSize.FindStringSubmatch(text)
if m == nil {
Expand Down
17 changes: 16 additions & 1 deletion cmd/refetch/hook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,16 @@ const (
"tool_input":{"url":"https://news.example.com/a"},"tool_response":[{"type":"text","text":"Source: ..."}]}`
fetchPageFail = `{"session_id":"s1","hook_event_name":"PostToolUseFailure","tool_name":"mcp__plugin_refetch_refetch__fetch_page","tool_use_id":"t12",
"tool_input":{"url":"https://c.example.com/"},"error":"could not read https://c.example.com/: refused (HTTP 403, chrome_like client)"}`
webFetchLimit = `{"session_id":"s1","hook_event_name":"PostToolUseFailure","tool_name":"WebFetch","tool_use_id":"t17",
"tool_input":{"url":"https://commons.example.org/wiki/File:Logo.svg"},"error":"You've hit your 5-hour limit · resets 11pm (Asia/Tbilisi)"}`
webFetchClassifier = `{"session_id":"s1","hook_event_name":"PostToolUseFailure","tool_name":"WebFetch","tool_use_id":"t18",
"tool_input":{"url":"https://www.example.co.il/"},"error":"The server-side auto mode classifier gave no verdict for WebFetch: another call in this response was changed."}`
webFetchTinyJSON = `{"session_id":"s1","hook_event_name":"PostToolUse","tool_name":"WebFetch","tool_use_id":"t19",
"tool_input":{"url":"https://commons.example.org/w/api.php?action=query&list=search&format=json&srsearch=x"},
"tool_response":{"bytes":120,"code":200,"codeText":"OK","result":"The search returned no results.","durationMs":300,"url":"https://commons.example.org/w/api.php"}}`
webFetchTinyHTML = `{"session_id":"s1","hook_event_name":"PostToolUse","tool_name":"WebFetch","tool_use_id":"t20",
"tool_input":{"url":"https://shell.example.com/"},
"tool_response":{"bytes":120,"code":200,"codeText":"OK","result":"There is nothing on the page.","durationMs":300,"url":"https://shell.example.com/"}}`
sessionStart = `{"session_id":"s1","hook_event_name":"SessionStart","source":"startup"}`
bashPost = `{"session_id":"s1","hook_event_name":"PostToolUse","tool_name":"Bash","tool_use_id":"t13","tool_input":{"command":"ls"},"tool_response":{"stdout":"x"}}`
)
Expand Down Expand Up @@ -94,6 +104,10 @@ func TestHookNudges(t *testing.T) {
{"WebFetch empty summary", webFetchEmpty, []string{"page came back empty"}},
{"WebFetch timeout", webFetchTimeout, []string{"(timeout of 60000ms exceeded)"}},
{"WebFetch pre", webFetchPre, nil},
{"WebFetch usage limit", webFetchLimit, nil},
{"WebFetch auto mode classifier", webFetchClassifier, nil},
{"WebFetch tiny JSON", webFetchTinyJSON, nil},
{"WebFetch tiny HTML", webFetchTinyHTML, []string{"page needs JavaScript"}},
{"ctx 403", ctx403, []string{"ctx_fetch_and_index could not read https://c.example.com/ (HTTP 403)", "save: true"}},
{"ctx challenge preview", ctxChallenge, []string{"https://d.example.com/ (challenge or block page)"}},
{"ctx empty page", ctxJS, []string{"nearly empty"}},
Expand Down Expand Up @@ -130,6 +144,7 @@ func TestHookNudges(t *testing.T) {
"t1": store.CallFailed, "t2": store.CallFailed, "t3": store.CallFailed, "t4": store.CallOK, "t5": store.CallFailed,
"t6": store.CallStarted, "t7": store.CallFailed, "t10#0": store.CallOK, "t10#1": store.CallFailed,
"t11": store.CallOK, "t12": store.CallFailed, "t14": store.CallOK,
"t17": store.CallDenied, "t18": store.CallDenied, "t19": store.CallOK, "t20": store.CallFailed,
}
for id, want := range checks {
if byID[id].Outcome != want {
Expand All @@ -143,7 +158,7 @@ func TestHookNudges(t *testing.T) {
t.Error("Bash must not be recorded")
}
r := stats.Build(calls, nil, stats.Options{}, time.Now())
if r.Failed != 10 || r.PickedUp != 2 || r.Resolved != 1 || r.StillFailed != 1 {
if r.Failed != 11 || r.PickedUp != 2 || r.Resolved != 1 || r.StillFailed != 1 {
t.Errorf("funnel from hook rows: %+v", r)
}
}
Expand Down
4 changes: 3 additions & 1 deletion cmd/refetch/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ func (fr *fetcher) get(ctx context.Context, url string, mode renderMode) (fetch.
for _, a := range p.Attempts {
err := fr.st.RecordAttempt(context.WithoutCancel(ctx), store.Attempt{
Time: time.Now(), FetchID: id, Via: fr.via, URL: a.URL, Client: a.Client, Outcome: a.Outcome,
Status: a.Status, Bytes: a.Bytes, Duration: a.Duration, Error: a.Err,
Status: a.Status, Bytes: a.Bytes, Duration: a.Duration, Error: a.Err, Version: strings.TrimPrefix(buildVersion(), "v"),
})
if err != nil && fr.stderr != nil {
_, _ = fmt.Fprintln(fr.stderr, "refetch: could not record a fetch step:", err)
Expand Down Expand Up @@ -450,6 +450,8 @@ func (fr *fetcher) renderAttempt(ctx context.Context, url, host string) (fetch.A
a.Outcome, a.Err = fetch.OutcomeTimeout, err.Error()
case err != nil:
a.Outcome, a.Err = fetch.OutcomeError, err.Error()
case fetch.BlockPage(rp.DOM):
a.Outcome, a.Err = fetch.OutcomeRefused, "headless Chrome got the site's block page"
case fetch.Challenge(http.StatusOK, rp.DOM):
a.Outcome, a.Err = fetch.OutcomeChallenge, "headless Chrome got the challenge page too"
case fetch.EmptyRendered(rp.DOM):
Expand Down
6 changes: 5 additions & 1 deletion cmd/refetch/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ func newServer(fr *fetcher, dataDir string) *mcp.Server {
}, func(ctx context.Context, _ *mcp.CallToolRequest, in fetchInput) (*mcp.CallToolResult, any, error) {
text, err := fetchPage(ctx, fr, dataDir, in)
if err != nil {
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: err.Error()}}}, nil, nil //nolint:nilerr // a tool error result for Claude, not a protocol error
msg := err.Error()
if note := staleNote(); note != "" {
msg += "\n" + note
}
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: msg}}}, nil, nil
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: text}}}, nil, nil
})
Expand Down
70 changes: 70 additions & 0 deletions cmd/refetch/stale.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package main

import (
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
)

// newerPlugin returns the newest refetch version installed next to the
// plugin this process runs from, when it is newer than this one; else "".
// Claude Code keeps a session's plugin, MCP server and hooks on the version
// it started with, so a long session goes on running an old refetch after
// an update (Nov 2026: 0.3.0 for days after 0.5.0 came out). Only the
// versioned plugin cache (…/refetch/<version>) has versions side by side.
func newerPlugin() string {
root, current := os.Getenv("REFETCH_PLUGIN_ROOT"), os.Getenv("REFETCH_PLUGIN_VERSION")
cur, ok := releaseVersion(current)
if !ok || root == "" || filepath.Base(root) != current {
return ""
}
cache := os.DirFS(filepath.Dir(root))
entries, err := fs.ReadDir(cache, ".")
if err != nil {
return ""
}
best, bestV := "", cur
for _, e := range entries {
v, ok := releaseVersion(e.Name())
if !ok || slices.Compare(v[:], bestV[:]) <= 0 {
continue
}
if _, err := fs.Stat(cache, e.Name()+"/.claude-plugin/plugin.json"); err == nil {
best, bestV = e.Name(), v
}
}
return best
}

// staleNote tells Claude, and through it the user, that this session runs
// an older refetch than the one installed; "" when it does not.
func staleNote() string {
v := newerPlugin()
if v == "" {
return ""
}
return fmt.Sprintf("refetch %s is installed, but this Claude Code session still runs refetch %s, which it started with. "+
"Tell the user to run /reload-plugins or restart Claude Code to use the new version.", v, os.Getenv("REFETCH_PLUGIN_VERSION"))
}

// releaseVersion parses a release version such as 1.2.3; development and
// snapshot builds do not parse, and neither does main's 0.0.0.
func releaseVersion(v string) ([3]int, bool) {
parts := strings.Split(v, ".")
if len(parts) != 3 || v == "0.0.0" {
return [3]int{}, false
}
var out [3]int
for i, p := range parts {
n, err := strconv.Atoi(p)
if err != nil || n < 0 {
return [3]int{}, false
}
out[i] = n
}
return out, true
}
66 changes: 66 additions & 0 deletions cmd/refetch/stale_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package main

import (
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/samgozman/refetch/config"
)

// pluginCache lays out Claude Code's versioned plugin cache with the given
// versions installed, and returns its directory.
func pluginCache(t *testing.T, versions ...string) string {
t.Helper()
dir := filepath.Join(t.TempDir(), "cache", "refetch", "refetch")
for _, v := range versions {
if err := os.MkdirAll(filepath.Join(dir, v, ".claude-plugin"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, v, ".claude-plugin", "plugin.json"), []byte(`{"version":"`+v+`"}`), 0o600); err != nil {
t.Fatal(err)
}
}
return dir
}

func TestNewerPlugin(t *testing.T) {
dir := pluginCache(t, "0.3.0", "0.5.0", "0.10.0")
if err := os.MkdirAll(filepath.Join(dir, "0.11.0"), 0o700); err != nil { // a half-installed version
t.Fatal(err)
}
for _, tc := range []struct{ root, version, want string }{
{filepath.Join(dir, "0.3.0"), "0.3.0", "0.10.0"},
{filepath.Join(dir, "0.10.0"), "0.10.0", ""},
{filepath.Join(dir, "0.5.0"), "0.0.0", ""}, // a checkout of main
{t.TempDir(), "0.3.0", ""}, // a plugin outside the versioned cache
{"", "0.3.0", ""}, // not run through the plugin
{filepath.Join(dir, "0.3.0"), "0.3.0-rc.1", ""}, // not a release
} {
t.Setenv("REFETCH_PLUGIN_ROOT", tc.root)
t.Setenv("REFETCH_PLUGIN_VERSION", tc.version)
if got := newerPlugin(); got != tc.want {
t.Errorf("root %s, version %s: newerPlugin = %q, want %q", tc.root, tc.version, got, tc.want)
}
}
}

func TestStaleSessionIsTold(t *testing.T) {
dir := pluginCache(t, "0.3.0", "0.5.0")
t.Setenv("REFETCH_PLUGIN_ROOT", filepath.Join(dir, "0.3.0"))
t.Setenv("REFETCH_PLUGIN_VERSION", "0.3.0")
t.Setenv("REFETCH_DATA", t.TempDir())
h := hooker{cfg: config.Default(), now: time.Now(), debug: func(error) {}}
got := h.handle(t.Context(), parse(t, sessionStart))
if !strings.Contains(got, "refetch 0.5.0 is installed") || !strings.Contains(got, "/reload-plugins") || !strings.Contains(got, "fetch_page") {
t.Errorf("SessionStart in a stale session: %q", got)
}
old := version
version = "0.3.0"
t.Cleanup(func() { version = old })
if c := versionCheck(); c.ok || !strings.Contains(c.detail, "0.5.0 is installed") {
t.Errorf("doctor's version check: %+v", c)
}
}
Loading