Repository navigation
Conversation
📝 WalkthroughWalkthroughThis pull request implements autoscan polling and rewrite suggestions for Silo. It adds a new ChangesAutoscan polling and rewrite sync
🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
Periodic poller over autoscan-enabled Radarr/Sonarr instances (reusing request_integrations) that maps import paths to Silo media folders and enqueues targeted scans via the existing scantrigger + scanqueue. Lean single-service model: no cross-node fan-out guard or retry queue. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Adds ErrIntegrationNotFound sentinel (errors.Is) instead of string matching. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ure trigger on interval change; skip source on key-resolution error Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…p, boundary-safe rewrites, GREATEST cursor guard, async trigger, quiet unresolved-path skip, FK->404 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rs, re-seed source editor on save Addresses minor code-review findings: Windows backslash paths now normalized before rewrite/dedupe; HandleStatus returns repository errors instead of 200; the per-source editor re-seeds from server data after a save. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add suggestRewrites / commonSuffixLen for Task 1 of the autoscan arr-polling feature. Pure function: matches arr root-folder paths to Silo media folder paths by longest common trailing segment count, adjusted for depth-delta so coincidental same-named segments at different structural levels don't inflate confidence. Categorises each arr root as Proposed, Ambiguous, Unmatched, or Covered by an existing PathRewrite rule. TDD: test file written first, verified failing, then implementation added. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Add GET /autoscan/sources/{id}/rewrite-suggestions admin endpoint: extend
the autoscanTriggerer interface with SuggestRewrites, wire SetRewriteResolvers
in the router, and add handler + test.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…p no-op suggestions Addresses final-review edge cases: coveredBy normalizes the existing rewrite's From (so a stored Windows/dup-slash rule still covers a root); duplicate arr roots and duplicate Silo folder paths are de-duplicated; an arr path that already equals its Silo path is not proposed as a no-op rewrite. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- suggestRewrites initializes Proposed/Unmatched/Ambiguous/Covered to empty slices so the JSON response is [] not null — fixes the 'Something went wrong' crash when every root is already covered (frontend mapped over null). - Move the sync button into the Path rewrites card beside 'Add rewrite' and rename it 'Sync rewrites'; guard the proposed map with ?? []. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rites on load - Root-folder fetch for sync uses a 2-min timeout: Radarr/Sonarr compute unmappedFolders by scanning all roots, so a large library's /rootfolder takes 20-30s+ and tripped arrclient's 30s default (Sonarr 502'd at exactly 30s). - Spin the sync icon + show 'Syncing…' while the request is in flight. - Path rewrites card starts collapsed on page load. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
History polling previously only tracked downloadFolderImported events. A rename in Sonarr/Radarr (episodeFileRenamed / movieFileRenamed) moves a file without an import event, leaving the library folder stale until the next full scan. Extend the history client to also surface renamed paths: both the new path and the old sourcePath, since a rename can move a file between folders and both parents may need rescanning. Delete events are still skipped — upgrade-deletes are covered by the paired import, and standalone deletes carry no file path in arr history. Renames the interface method ImportedPaths -> ChangedPaths to reflect the broader scope. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tine HandleTrigger dispatches PollOnce on a detached goroutine and responds 202 immediately. The test read trig.called straight after the handler returned, racing the goroutine (usually 'PollOnce was not invoked') and reading the field without synchronization (a data race under -race). Signal completion through a channel the fake sends on when PollOnce runs; the test waits on it (bounded) before asserting. The channel send happens-before the receive, so the subsequent read of called is race-free. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
d3ee373 to
98251d0
Compare
There was a problem hiding this comment.
Actionable comments posted: 16
🧹 Nitpick comments (2)
internal/autoscan/rewrite_test.go (1)
5-35: ⚡ Quick winAdd test coverage for trailing slashes in
Tofield.The current tests don't cover the scenario where
PathRewrite.Tocontains a trailing slash. This would help catch the potential double-slash issue flagged inrewrite.go.🧪 Suggested test case
// Test trailing slash in To field trailing := []PathRewrite{{From: "/data/media", To: "/mnt/media/"}} if got := applyRewrites("/data/media/x", trailing); got != "/mnt/media/x" { t.Fatalf("trailing slash: got %q, want %q", got, "/mnt/media/x") }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/autoscan/rewrite_test.go` around lines 5 - 35, Add a unit test to cover trailing slashes in PathRewrite.To: update internal/autoscan/rewrite_test.go to include a case where PathRewrite{From: "/data/media", To: "/mnt/media/"} (note trailing slash) is applied via applyRewrites and assert that applyRewrites("/data/media/x", trailing) returns "/mnt/media/x" (no double slash). Place this alongside existing cases (e.g., the "boundary" tests) so we validate trimming/concatenation behavior for applyRewrites and ensure the function handles trailing slashes in PathRewrite.To correctly.internal/autoscan/service_test.go (1)
83-111: ⚡ Quick winAdd a first-enable regression test.
The suite never covers
LastPollAt == nil, so it won't catch a poll window that replays history on initial opt-in. A small test double that records thesincepassed toChangedPathswould lock in the intended “start at now on first enable” behavior.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/autoscan/service_test.go` around lines 83 - 111, Add a test that covers the initial-enable case where LastPollAt is nil so we verify PollOnce uses "now" as the since parameter: create a fakeHistory that records the time argument passed to ChangedPaths, set up a store/advanced entry for an integration (e.g., "i1") with LastPollAt == nil, call svc.PollOnce, and assert the recorded since is non-nil and within a small delta of time.Now; reference the test harness symbols TestPollOnceEnqueuesDedupedFolders (or add TestPollOnceFirstEnableUsesNow), fakeHistory.ChangedPaths, LastPollAt, NewService and PollOnce to locate and implement the check.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@cmd/silo/main.go`:
- Around line 1335-1344: The autoscan service is being constructed with a nil
debounce/suppressor because deps.RedisClient is not initialized; initialize and
pass the real Redis client into autoscan.NewRedisSuppressor before creating
autoscan.NewService (or replace deps.RedisClient with the existing initialized
Redis client instance used elsewhere), ensuring the symbol chain
autoscan.NewRedisSuppressor(deps.RedisClient) receives a live client prior to
taskMgr.Register(tasks.NewAutoscanPollTask(...)); update the startup sequence so
the Redis client is created/assigned on deps (or use the global/factory helper
that builds the Redis client) before constructing autoscanSvc.
In `@docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md`:
- Line 1019: This line still includes the absolute path /tmp/go/bin (fourth
occurrence); search for and remove any hardcoded /tmp/go/bin usages and replace
them with a non-absolute alternative (e.g., rely on go build ./... without a
hardcoded bin path or use the environment-aware GOBIN/GOPATH via go env) so the
"go build ./..." line and any other occurrences no longer contain an absolute
filesystem path.
- Line 13: Replace the absolute path "/tmp/go/bin" with an environment-agnostic
phrasing: update the sentence that currently reads "The Go toolchain may be at
`/tmp/go/bin` — prepend it to `PATH` if `go` is not found." to something like
"The Go toolchain location may need to be added to PATH if `go` is not found."
so the doc (in docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md) no
longer includes any local absolute filesystem paths and remains
environment-agnostic.
- Line 568: Replace the absolute filesystem path "/tmp/go/bin" used in this
document with a generic placeholder or environment variable reference (e.g.
$GOBIN or <gobin-path>) everywhere it appears; locate the occurrence referenced
alongside the SQL snippet containing "VALUES ($1, $2, $3, now())" and update
that literal path to the placeholder to comply with the docs/superpowers
guidelines.
In `@docs/superpowers/plans/2026-06-02-autoscan-rewrite-sync.md`:
- Line 662: The line "export PATH=$PATH:/tmp/go/bin" contains a local absolute
filesystem path; replace it with a generic placeholder or environment variable
(e.g., export PATH=$PATH:$GOBIN or export PATH=$PATH:<your-go-bin-path>) so the
docs do not include an absolute local path and follow the guideline for docs in
specs/plans.
- Line 13: Remove the local absolute path referenced in the sentence "The Go
toolchain may be at `/tmp/go/bin` — prepend to `PATH` if `go` is missing." and
replace it with environment-agnostic guidance: state that the Go toolchain must
be available on PATH and, if installed in a non-standard location, users should
add its bin directory to PATH or install Go via their platform's package
manager; update the sentence in the docs/superpowers/plans file accordingly
(look for the sentence containing `/tmp/go/bin`) so no absolute filesystem paths
remain.
In `@internal/api/handlers/autoscan_test.go`:
- Around line 154-157: The test creates a request without a chi route context so
HandleUpsertSource’s call to chi.URLParam("id") isn’t exercised; fix the test by
creating a chi RouteContext, calling ctx.URLParams.Add("id","missing") (or
equivalent), and attaching it to the request context before calling
HandleUpsertSource so the handler reads the intended id via chi.URLParam; update
the existing test snippet around httptest.NewRequest/rec to set the route
context on req's context prior to invoking HandleUpsertSource.
In `@internal/api/handlers/autoscan.go`:
- Around line 76-82: The handler currently ignores failures from
h.triggers.UpdateTriggers("autoscan_poll", ...) and returns success even though
the persisted updated.PollIntervalMinutes may not be applied; change this to
either roll back the stored poll interval to the previous value or return an
error to the client. Concretely: capture the previous poll interval before
persisting, call h.triggers.UpdateTriggers(...) and if it returns an error,
attempt to restore the previous value in the same storage/update path you used
earlier (or call the same repo/save method with the previous interval), log the
rollback error if that fails, and return a non-200 error response (e.g., HTTP
500) instead of success; if you cannot implement rollback, immediately return an
error response after logging the UpdateTriggers error so stored config and live
schedule cannot diverge. Ensure you update the code around
h.triggers.UpdateTriggers, autoscan_poll and use updated.PollIntervalMinutes and
the captured previous value to perform the rollback or error response.
In `@internal/api/router.go`:
- Around line 422-436: The autoscan handler is being created even when
deps.TaskManager is nil; update the wiring to require the scheduler by adding a
check for deps.TaskManager != nil to the existing condition that checks
deps.FolderRepo and deps.LibraryScanQueue so autoscan.NewService(...),
autoscanSvc.SetRewriteResolvers(...), and handlers.NewAutoscanHandler(...) only
run when a TaskManager is present; ensure autoscanHandler remains nil when
TaskManager is absent so the admin/polling UI won’t expose periodic features it
cannot configure.
In `@internal/autoscan/repository.go`:
- Around line 159-168: AdvanceLastPoll currently returns a generic error when
Exec fails; mirror GetSource/UpsertSource behavior by mapping a
foreign-key/foreign key violation on integration_id to ErrIntegrationNotFound.
After the r.pool.Exec call in Repository.AdvanceLastPoll, inspect the returned
error (e.g., via errors.As into *pgconn.PgError or by checking SQLSTATE
"23503"/FK constraint name) and if it indicates a FK violation for the
integration_id, return ErrIntegrationNotFound instead of wrapping the original
error; otherwise wrap/return the original error as before. Ensure you reference
Repository.AdvanceLastPoll, r.pool.Exec and ErrIntegrationNotFound so the change
is easy to locate.
- Around line 46-50: The SQL fragment in sourceSelect currently returns all
request_integrations rows; restrict it to supported integration kinds by adding
a WHERE clause filtering ri.kind to the allowed set (e.g., 'radarr' and
'sonarr') in the sourceSelect constant so only those integrations are selected
for the autoscan read path, and ensure any write/update code that creates or
updates autoscan_sources uses the same allowed-kind whitelist so the read and
write boundaries remain consistent (refer to the sourceSelect constant and the
code paths that insert/update autoscan_sources/integration rows).
In `@internal/autoscan/rewrite.go`:
- Around line 14-28: applyRewrites can produce a double slash when rw.To ends
with '/' because the code returns strings.TrimSpace(rw.To) +
strings.TrimPrefix(path, trimmed); normalize rw.To before concatenation by
trimming trailing slashes (e.g., use strings.TrimRight(strings.TrimSpace(rw.To),
"/")) and then concatenate with a single '/' delimiter when needed (or ensure
the trimmed suffix of path has its leading '/' preserved via strings.TrimPrefix
and add '/' only if the normalized rw.To is non-empty and does not already end
with '/'); update the logic in applyRewrites to use the normalized rw.To to
avoid producing "//".
In `@internal/autoscan/service.go`:
- Around line 77-83: The current logic always subtracts pollOverlap from since
even when src.LastPollAt is nil, causing newly-enabled sources to backdate the
first poll; change the logic so that the overlap subtraction only happens when
src.LastPollAt is non-nil: set since = cycleStart by default, and if
src.LastPollAt != nil set since = src.LastPollAt and then apply since =
since.Add(-pollOverlap) (i.e., move the Add(-pollOverlap) inside the LastPollAt
!= nil branch) while keeping the same variable names (since, cycleStart,
pollOverlap, src.LastPollAt) so a newly enabled source won’t replay history.
- Around line 186-191: In SuggestRewrites, secret resolution currently ignores
errors and proceeds with the unresolved APIKeyRef; update the block around
s.secrets.Get to fail fast: when s.secrets != nil and apiKey != "" call
s.secrets.Get(ctx, apiKey) and if rerr != nil return the error (or wrap with
context) instead of treating it as success, otherwise use resolved when
non-empty; this mirrors the behavior in PollOnce and prevents probing Arr with
an unresolved reference (refer to SuggestRewrites and s.secrets.Get).
In `@web/src/hooks/queries/useAutoscan.ts`:
- Around line 87-99: useTriggerAutoscan currently only shows a toast on success
but doesn’t refresh cached autoscan data; inject a QueryClient by calling
useQueryClient() inside useTriggerAutoscan and in the onSuccess handler call
queryClient.invalidateQueries(...) for the same query key used by the autoscan
query (the key used by your useAutoscan / autoscan-related useQuery) so the
admin screen is refetched immediately after a successful trigger.
In `@web/src/pages/AdminRequests.tsx`:
- Around line 1471-1475: handleSave currently filters path_rewrites with a
predicate that allows entries where only one side is filled; update the filter
so only fully-specified mappings are saved by requiring both trimmed fields to
be non-empty (i.e. change the predicate on rewrites.map(...) from
"rewrite.from.length > 0 || rewrite.to.length > 0" to require both non-empty),
keeping the existing trim and then call updateSource.mutate(...) as before
(referencing handleSave, path_rewrites, rewrites, and
updateSource.mutate/source.integration_id).
---
Nitpick comments:
In `@internal/autoscan/rewrite_test.go`:
- Around line 5-35: Add a unit test to cover trailing slashes in PathRewrite.To:
update internal/autoscan/rewrite_test.go to include a case where
PathRewrite{From: "/data/media", To: "/mnt/media/"} (note trailing slash) is
applied via applyRewrites and assert that applyRewrites("/data/media/x",
trailing) returns "/mnt/media/x" (no double slash). Place this alongside
existing cases (e.g., the "boundary" tests) so we validate
trimming/concatenation behavior for applyRewrites and ensure the function
handles trailing slashes in PathRewrite.To correctly.
In `@internal/autoscan/service_test.go`:
- Around line 83-111: Add a test that covers the initial-enable case where
LastPollAt is nil so we verify PollOnce uses "now" as the since parameter:
create a fakeHistory that records the time argument passed to ChangedPaths, set
up a store/advanced entry for an integration (e.g., "i1") with LastPollAt ==
nil, call svc.PollOnce, and assert the recorded since is non-nil and within a
small delta of time.Now; reference the test harness symbols
TestPollOnceEnqueuesDedupedFolders (or add TestPollOnceFirstEnableUsesNow),
fakeHistory.ChangedPaths, LastPollAt, NewService and PollOnce to locate and
implement the check.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 59afd7ab-a07d-4de0-ad2f-bbbea3ae3c37
📒 Files selected for processing (31)
cmd/silo/main.godocs/superpowers/plans/2026-06-02-autoscan-arr-polling.mddocs/superpowers/plans/2026-06-02-autoscan-rewrite-sync.mddocs/superpowers/specs/2026-06-02-autoscan-arr-polling-design.mddocs/superpowers/specs/2026-06-02-autoscan-rewrite-sync-design.mdinternal/api/handlers/autoscan.gointernal/api/handlers/autoscan_test.gointernal/api/router.gointernal/autoscan/dedupe.gointernal/autoscan/dedupe_test.gointernal/autoscan/errors.gointernal/autoscan/history.gointernal/autoscan/history_test.gointernal/autoscan/repository.gointernal/autoscan/rewrite.gointernal/autoscan/rewrite_test.gointernal/autoscan/service.gointernal/autoscan/service_test.gointernal/autoscan/suggest.gointernal/autoscan/suggest_deps.gointernal/autoscan/suggest_test.gointernal/autoscan/suppress.gointernal/autoscan/types.gointernal/taskmanager/tasks/autoscan_poll.gomigrations/171_autoscan.down.sqlmigrations/171_autoscan.up.sqlweb/src/api/types.tsweb/src/hooks/queries/keys.tsweb/src/hooks/queries/useAutoscan.tsweb/src/lib/recipes.test.tsweb/src/pages/AdminRequests.tsx
|
|
||
| **Spec:** `docs/superpowers/specs/2026-06-02-autoscan-arr-polling-design.md` | ||
|
|
||
| **Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Full lint: `make lint`. Frontend: `cd web && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend it to `PATH` if `go` is not found. Use the project's disposable test DB for migrations; never touch a live database. |
There was a problem hiding this comment.
Remove the absolute filesystem path.
The reference to /tmp/go/bin violates the guideline for these documents. As per coding guidelines, docs in docs/superpowers/{specs,plans}/ should never include local absolute filesystem paths. Consider rewording to be environment-agnostic, such as: "The Go toolchain location may need to be added to PATH if go is not found."
Suggested rewording
-**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Full lint: `make lint`. Frontend: `cd web && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend it to `PATH` if `go` is not found. Use the project's disposable test DB for migrations; never touch a live database.
+**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Full lint: `make lint`. Frontend: `cd web && pnpm run lint`. The Go toolchain location may need to be added to `PATH` if `go` is not found. Use the project's disposable test DB for migrations; never touch a live database.As per coding guidelines: When creating or editing docs/superpowers/specs/ or docs/superpowers/plans/, never include local absolute filesystem paths or transient worktree IDs.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| **Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Full lint: `make lint`. Frontend: `cd web && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend it to `PATH` if `go` is not found. Use the project's disposable test DB for migrations; never touch a live database. | |
| **Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Full lint: `make lint`. Frontend: `cd web && pnpm run lint`. The Go toolchain location may need to be added to `PATH` if `go` is not found. Use the project's disposable test DB for migrations; never touch a live database. |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md` at line 13,
Replace the absolute path "/tmp/go/bin" with an environment-agnostic phrasing:
update the sentence that currently reads "The Go toolchain may be at
`/tmp/go/bin` — prepend it to `PATH` if `go` is not found." to something like
"The Go toolchain location may need to be added to PATH if `go` is not found."
so the doc (in docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md) no
longer includes any local absolute filesystem paths and remains
environment-agnostic.
| } | ||
| if _, err := r.pool.Exec(ctx, ` | ||
| INSERT INTO autoscan_sources (integration_id, enabled, path_rewrites, updated_at) | ||
| VALUES ($1, $2, $3, now()) |
There was a problem hiding this comment.
Remove the absolute filesystem path.
Same issue as line 13—the /tmp/go/bin reference violates the guideline. Consider using a generic placeholder or environment variable. As per coding guidelines, never include local absolute filesystem paths in docs/superpowers/{specs,plans}/ documents.
Suggested fix
-export PATH=$PATH:/tmp/go/bin
+# Add the Go toolchain to PATH if needed:
+# export PATH=$PATH:<go-toolchain-location>As per coding guidelines: When creating or editing docs/superpowers/specs/ or docs/superpowers/plans/, never include local absolute filesystem paths.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md` at line 568,
Replace the absolute filesystem path "/tmp/go/bin" used in this document with a
generic placeholder or environment variable reference (e.g. $GOBIN or
<gobin-path>) everywhere it appears; locate the occurrence referenced alongside
the SQL snippet containing "VALUES ($1, $2, $3, now())" and update that literal
path to the placeholder to comply with the docs/superpowers guidelines.
| - [ ] **Step 9.3: Build the whole server** | ||
|
|
||
| ```bash | ||
| go build ./... # requires libvips locally; if unavailable, build ./internal/... ./cmd/... minus the bimg-dependent packages, and rely on CI/Docker for the full build |
There was a problem hiding this comment.
Remove the absolute filesystem path.
Fourth occurrence of /tmp/go/bin. Apply the same fix as previous comments to maintain consistency. As per coding guidelines, avoid absolute filesystem paths in these documents.
As per coding guidelines: When creating or editing docs/superpowers/specs/ or docs/superpowers/plans/, never include local absolute filesystem paths.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md` at line 1019, This
line still includes the absolute path /tmp/go/bin (fourth occurrence); search
for and remove any hardcoded /tmp/go/bin usages and replace them with a
non-absolute alternative (e.g., rely on go build ./... without a hardcoded bin
path or use the environment-aware GOBIN/GOPATH via go env) so the "go build
./..." line and any other occurrences no longer contain an absolute filesystem
path.
|
|
||
| **Spec:** `docs/superpowers/specs/2026-06-02-autoscan-rewrite-sync-design.md` | ||
|
|
||
| **Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Frontend: `cd web && pnpm exec tsc -b && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend to `PATH` if `go` is missing. `internal/api`/`internal/api/handlers` cannot be compiled without libvips; verify those via `gofmt` + the Docker build. |
There was a problem hiding this comment.
Remove the absolute filesystem path.
The reference to /tmp/go/bin violates the guideline. As per coding guidelines, docs in docs/superpowers/{specs,plans}/ should never include local absolute filesystem paths. Use environment-agnostic wording instead.
Suggested rewording
-**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Frontend: `cd web && pnpm exec tsc -b && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend to `PATH` if `go` is missing. `internal/api`/`internal/api/handlers` cannot be compiled without libvips; verify those via `gofmt` + the Docker build.
+**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Frontend: `cd web && pnpm exec tsc -b && pnpm run lint`. The Go toolchain location may need to be added to `PATH` if `go` is missing. `internal/api`/`internal/api/handlers` cannot be compiled without libvips; verify those via `gofmt` + the Docker build.As per coding guidelines: When creating or editing docs/superpowers/specs/ or docs/superpowers/plans/, never include local absolute filesystem paths or transient worktree IDs.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| **Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Frontend: `cd web && pnpm exec tsc -b && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend to `PATH` if `go` is missing. `internal/api`/`internal/api/handlers` cannot be compiled without libvips; verify those via `gofmt` + the Docker build. | |
| **Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Frontend: `cd web && pnpm exec tsc -b && pnpm run lint`. The Go toolchain location may need to be added to `PATH` if `go` is missing. `internal/api`/`internal/api/handlers` cannot be compiled without libvips; verify those via `gofmt` + the Docker build. |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/superpowers/plans/2026-06-02-autoscan-rewrite-sync.md` at line 13,
Remove the local absolute path referenced in the sentence "The Go toolchain may
be at `/tmp/go/bin` — prepend to `PATH` if `go` is missing." and replace it with
environment-agnostic guidance: state that the Go toolchain must be available on
PATH and, if installed in a non-standard location, users should add its bin
directory to PATH or install Go via their platform's package manager; update the
sentence in the docs/superpowers/plans file accordingly (look for the sentence
containing `/tmp/go/bin`) so no absolute filesystem paths remain.
| func applyRewrites(path string, rewrites []PathRewrite) string { | ||
| for _, rw := range rewrites { | ||
| from := strings.TrimSpace(rw.From) | ||
| if from == "" { | ||
| continue | ||
| } | ||
| // Match only at a path-segment boundary: exact, or prefix followed by '/'. | ||
| // This prevents From="/data/media" from rewriting "/data/media2/x". | ||
| trimmed := strings.TrimSuffix(from, "/") | ||
| if path == trimmed || strings.HasPrefix(path, trimmed+"/") { | ||
| return strings.TrimSpace(rw.To) + strings.TrimPrefix(path, trimmed) | ||
| } | ||
| } | ||
| return path | ||
| } |
There was a problem hiding this comment.
Potential double-slash in rewritten paths when To has a trailing slash.
Line 24 trims whitespace from rw.To but does not trim trailing slashes. When To ends with / and the path has a prefix match, the result will contain a double slash.
Example:
- From:
/data/media, To:/mnt/media/, path:/data/media/Movies/file.mkv - Result:
/mnt/media//Movies/file.mkv(double slash)
🔧 Proposed fix to normalize trailing slashes
func applyRewrites(path string, rewrites []PathRewrite) string {
for _, rw := range rewrites {
from := strings.TrimSpace(rw.From)
if from == "" {
continue
}
+ to := strings.TrimSpace(strings.TrimSuffix(rw.To, "/"))
// Match only at a path-segment boundary: exact, or prefix followed by '/'.
// This prevents From="/data/media" from rewriting "/data/media2/x".
trimmed := strings.TrimSuffix(from, "/")
if path == trimmed || strings.HasPrefix(path, trimmed+"/") {
- return strings.TrimSpace(rw.To) + strings.TrimPrefix(path, trimmed)
+ return to + strings.TrimPrefix(path, trimmed)
}
}
return path
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/autoscan/rewrite.go` around lines 14 - 28, applyRewrites can produce
a double slash when rw.To ends with '/' because the code returns
strings.TrimSpace(rw.To) + strings.TrimPrefix(path, trimmed); normalize rw.To
before concatenation by trimming trailing slashes (e.g., use
strings.TrimRight(strings.TrimSpace(rw.To), "/")) and then concatenate with a
single '/' delimiter when needed (or ensure the trimmed suffix of path has its
leading '/' preserved via strings.TrimPrefix and add '/' only if the normalized
rw.To is non-empty and does not already end with '/'); update the logic in
applyRewrites to use the normalized rw.To to avoid producing "//".
| // First enable: last_poll_at null -> floor at cycleStart (don't replay history). | ||
| since := cycleStart | ||
| if src.LastPollAt != nil { | ||
| since = *src.LastPollAt | ||
| } | ||
| // Overlap buffer absorbs clock skew so boundary events aren't missed. | ||
| since = since.Add(-pollOverlap) |
There was a problem hiding this comment.
Don't backdate the first poll window.
When LastPollAt is nil, this still subtracts pollOverlap, so a newly enabled source replays the last two minutes of Arr history despite the comment saying “don't replay history.” That can enqueue stale imports immediately after opt-in.
Suggested fix
// First enable: last_poll_at null -> floor at cycleStart (don't replay history).
since := cycleStart
if src.LastPollAt != nil {
- since = *src.LastPollAt
+ since = *src.LastPollAt
+ // Overlap buffer absorbs clock skew so boundary events aren't missed.
+ since = since.Add(-pollOverlap)
}
- // Overlap buffer absorbs clock skew so boundary events aren't missed.
- since = since.Add(-pollOverlap)
// Floor the window so a long outage can't produce an oversized history
// response that arrclient truncates (permanent stall otherwise).
if floor := cycleStart.Add(-maxLookback); since.Before(floor) {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // First enable: last_poll_at null -> floor at cycleStart (don't replay history). | |
| since := cycleStart | |
| if src.LastPollAt != nil { | |
| since = *src.LastPollAt | |
| } | |
| // Overlap buffer absorbs clock skew so boundary events aren't missed. | |
| since = since.Add(-pollOverlap) | |
| // First enable: last_poll_at null -> floor at cycleStart (don't replay history). | |
| since := cycleStart | |
| if src.LastPollAt != nil { | |
| since = *src.LastPollAt | |
| // Overlap buffer absorbs clock skew so boundary events aren't missed. | |
| since = since.Add(-pollOverlap) | |
| } | |
| // Floor the window so a long outage can't produce an oversized history | |
| // response that arrclient truncates (permanent stall otherwise). | |
| if floor := cycleStart.Add(-maxLookback); since.Before(floor) { |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/autoscan/service.go` around lines 77 - 83, The current logic always
subtracts pollOverlap from since even when src.LastPollAt is nil, causing
newly-enabled sources to backdate the first poll; change the logic so that the
overlap subtraction only happens when src.LastPollAt is non-nil: set since =
cycleStart by default, and if src.LastPollAt != nil set since = src.LastPollAt
and then apply since = since.Add(-pollOverlap) (i.e., move the Add(-pollOverlap)
inside the LastPollAt != nil branch) while keeping the same variable names
(since, cycleStart, pollOverlap, src.LastPollAt) so a newly enabled source won’t
replay history.
| apiKey := src.APIKeyRef | ||
| if s.secrets != nil && apiKey != "" { | ||
| if resolved, rerr := s.secrets.Get(ctx, apiKey); rerr == nil && resolved != "" { | ||
| apiKey = resolved | ||
| } | ||
| } |
There was a problem hiding this comment.
Fail fast when secret resolution breaks in SuggestRewrites.
Unlike PollOnce, this silently ignores SecretResolver.Get failures and continues with APIKeyRef as the Arr API key. That turns a secret-resolution failure into a misleading “Arr unreachable” path and can probe Arr with the unresolved reference string.
Suggested fix
apiKey := src.APIKeyRef
if s.secrets != nil && apiKey != "" {
- if resolved, rerr := s.secrets.Get(ctx, apiKey); rerr == nil && resolved != "" {
- apiKey = resolved
- }
+ resolved, rerr := s.secrets.Get(ctx, apiKey)
+ if rerr != nil {
+ return RewriteSuggestions{}, fmt.Errorf("autoscan: resolve api key: %w", rerr)
+ }
+ if resolved != "" {
+ apiKey = resolved
+ }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| apiKey := src.APIKeyRef | |
| if s.secrets != nil && apiKey != "" { | |
| if resolved, rerr := s.secrets.Get(ctx, apiKey); rerr == nil && resolved != "" { | |
| apiKey = resolved | |
| } | |
| } | |
| apiKey := src.APIKeyRef | |
| if s.secrets != nil && apiKey != "" { | |
| resolved, rerr := s.secrets.Get(ctx, apiKey) | |
| if rerr != nil { | |
| return RewriteSuggestions{}, fmt.Errorf("autoscan: resolve api key: %w", rerr) | |
| } | |
| if resolved != "" { | |
| apiKey = resolved | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/autoscan/service.go` around lines 186 - 191, In SuggestRewrites,
secret resolution currently ignores errors and proceeds with the unresolved
APIKeyRef; update the block around s.secrets.Get to fail fast: when s.secrets !=
nil and apiKey != "" call s.secrets.Get(ctx, apiKey) and if rerr != nil return
the error (or wrap with context) instead of treating it as success, otherwise
use resolved when non-empty; this mirrors the behavior in PollOnce and prevents
probing Arr with an unresolved reference (refer to SuggestRewrites and
s.secrets.Get).
| export function useTriggerAutoscan() { | ||
| return useMutation({ | ||
| mutationFn: () => | ||
| api<{ status: string }>("/admin/autoscan/trigger", { | ||
| method: "POST", | ||
| }), | ||
| onSuccess: () => { | ||
| toast.success("Autoscan triggered"); | ||
| }, | ||
| onError: (err) => { | ||
| toast.error(err instanceof Error ? err.message : "Failed to trigger autoscan"); | ||
| }, | ||
| }); |
There was a problem hiding this comment.
Invalidate autoscan queries after a manual trigger.
A successful trigger changes autoscan state immediately, but this hook only shows a toast. The admin screen will keep showing stale source data until the 30s stale window expires or the user refreshes.
Suggested fix
export function useTriggerAutoscan() {
+ const queryClient = useQueryClient();
return useMutation({
mutationFn: () =>
api<{ status: string }>("/admin/autoscan/trigger", {
method: "POST",
}),
onSuccess: () => {
toast.success("Autoscan triggered");
+ queryClient.invalidateQueries({ queryKey: adminKeys.autoscanSources() });
+ queryClient.invalidateQueries({ queryKey: adminKeys.autoscanSettings() });
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : "Failed to trigger autoscan");
},
});
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function useTriggerAutoscan() { | |
| return useMutation({ | |
| mutationFn: () => | |
| api<{ status: string }>("/admin/autoscan/trigger", { | |
| method: "POST", | |
| }), | |
| onSuccess: () => { | |
| toast.success("Autoscan triggered"); | |
| }, | |
| onError: (err) => { | |
| toast.error(err instanceof Error ? err.message : "Failed to trigger autoscan"); | |
| }, | |
| }); | |
| export function useTriggerAutoscan() { | |
| const queryClient = useQueryClient(); | |
| return useMutation({ | |
| mutationFn: () => | |
| api<{ status: string }>("/admin/autoscan/trigger", { | |
| method: "POST", | |
| }), | |
| onSuccess: () => { | |
| toast.success("Autoscan triggered"); | |
| queryClient.invalidateQueries({ queryKey: adminKeys.autoscanSources() }); | |
| queryClient.invalidateQueries({ queryKey: adminKeys.autoscanSettings() }); | |
| }, | |
| onError: (err) => { | |
| toast.error(err instanceof Error ? err.message : "Failed to trigger autoscan"); | |
| }, | |
| }); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/hooks/queries/useAutoscan.ts` around lines 87 - 99,
useTriggerAutoscan currently only shows a toast on success but doesn’t refresh
cached autoscan data; inject a QueryClient by calling useQueryClient() inside
useTriggerAutoscan and in the onSuccess handler call
queryClient.invalidateQueries(...) for the same query key used by the autoscan
query (the key used by your useAutoscan / autoscan-related useQuery) so the
admin screen is refetched immediately after a successful trigger.
| function handleSave() { | ||
| const path_rewrites = rewrites | ||
| .map((rewrite) => ({ from: rewrite.from.trim(), to: rewrite.to.trim() })) | ||
| .filter((rewrite) => rewrite.from.length > 0 || rewrite.to.length > 0); | ||
| updateSource.mutate({ id: source.integration_id, body: { enabled, path_rewrites } }); |
There was a problem hiding this comment.
Don't submit half-filled path rewrites.
The current filter keeps rows when either side is non-empty, so entries like from="/arr", to="" still get saved. Those cannot map paths correctly and are easy to create from the blank-row editor.
🧩 Minimal fix
const path_rewrites = rewrites
.map((rewrite) => ({ from: rewrite.from.trim(), to: rewrite.to.trim() }))
- .filter((rewrite) => rewrite.from.length > 0 || rewrite.to.length > 0);
+ .filter((rewrite) => rewrite.from.length > 0 && rewrite.to.length > 0);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| function handleSave() { | |
| const path_rewrites = rewrites | |
| .map((rewrite) => ({ from: rewrite.from.trim(), to: rewrite.to.trim() })) | |
| .filter((rewrite) => rewrite.from.length > 0 || rewrite.to.length > 0); | |
| updateSource.mutate({ id: source.integration_id, body: { enabled, path_rewrites } }); | |
| function handleSave() { | |
| const path_rewrites = rewrites | |
| .map((rewrite) => ({ from: rewrite.from.trim(), to: rewrite.to.trim() })) | |
| .filter((rewrite) => rewrite.from.length > 0 && rewrite.to.length > 0); | |
| updateSource.mutate({ id: source.integration_id, body: { enabled, path_rewrites } }); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/AdminRequests.tsx` around lines 1471 - 1475, handleSave
currently filters path_rewrites with a predicate that allows entries where only
one side is filled; update the filter so only fully-specified mappings are saved
by requiring both trimmed fields to be non-empty (i.e. change the predicate on
rewrites.map(...) from "rewrite.from.length > 0 || rewrite.to.length > 0" to
require both non-empty), keeping the existing trim and then call
updateSource.mutate(...) as before (referencing handleSave, path_rewrites,
rewrites, and updateSource.mutate/source.integration_id).
Summary
Adds Autoscan: a periodic poller that watches each configured Radarr/Sonarr instance's history for changes and triggers targeted Silo library rescans, so newly-imported or renamed files appear without waiting for a full scan.
The feature reuses the existing
request_integrationsrows as its arr sources (no second place to configure server URLs/keys) and is off by default — operators opt in per instance from the Requests admin surface.Three layers, built bottom-up:
/api/v3/history/since, map arr-side paths to Silo paths via per-instance path rewrites, dedup to parent folders, and enqueue scans through the existingscantrigger→scanqueuepipeline. Redis-backed debounce suppresses repeat scans of the same(folder, path)within a TTL.episodeFileRenamed/movieFileRenamedevents (both the new path and the oldsourcePath), since a rename moves a file with no import event and can cross folders.Why this approach
request_integrations; Autoscan references them by FK (ON DELETE CASCADE) instead of duplicating credential storage.MediaFolderand enqueueing a subtree/file scan keeps the feature cheap under load — consistent with the repo's performance-first priority.Schema
migrations/171_autoscan.{up,down}.sql(no collision —maintops out at 170):autoscan_settings— singleton row (id boolean PRIMARY KEY CHECK (id)):enabled,poll_interval_minutes(CHECK > 0),debounce_seconds(CHECK >= 0). Seeded disabled.autoscan_sources—integration_idPK/FK →request_integrations(id)ON DELETE CASCADE;enabled,path_rewrites jsonb,last_poll_at.API (admin-gated, under
/admin)/admin/autoscan/settings/admin/autoscan/settings/admin/autoscan/sources/admin/autoscan/sources/{id}/admin/autoscan/trigger/admin/autoscan/status/admin/autoscan/sources/{id}/rewrite-suggestionsFrontend
New Autoscan tab in the Requests admin page (
AdminRequests.tsx): global enable + interval/debounce, per-source enable, and a collapsible path-rewrite editor with a "Sync rewrites" action that previews proposed / unmatched / ambiguous / already-covered matches before applying. Types + React Query hooks inweb/src/api/types.tsandweb/src/hooks/queries/useAutoscan.ts.Testing
internal/autoscan: poll cycle (dedup, distinct-paths-same-folder, disabled no-op, source-failure-doesn't-advance, release-claim-on-enqueue-failure), history parsing (imports + renames, ignores unrelated events), suffix-match suggester (unique/ambiguous/covered/no-op/normalization), rewrite + dedupe helpers, and handler tests (FK → 404, trigger dispatch).-race. Note: the autoscan handler tests live ininternal/api/handlers, which links libvips via CGO; run tests in an environment withlibvips-dev(CI / the Dockergolang:1.26build stage). A bare host without it reports[build failed]for those packages and skips their tests.go vet+gofmtclean.Risks / follow-ups
silo-android,silo-apple) need no changes — admin-only server feature, no client-visible API surface.Note on the diff
This branch was cut before the vitest-4 hotfix (#42) merged, so the diff includes one unrelated file,
web/src/lib/recipes.test.ts. That is the exact change in #42; once #42 merges and this branch is rebased ontomain, git drops it as a duplicate. It does not double-apply.🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes