Skip to content

[codex] Add IntroDB marker integration and dialogue-aware Chromaprint refinement - #57

Merged
Quick104 merged 14 commits into
mainfrom
feat/introdb-marker-integration
Jun 7, 2026
Merged

Quick104 merged 14 commits into
mainfrom
feat/introdb-marker-integration

Conversation

@Quick104

@Quick104 Quick104 commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add multi-source marker plumbing for IntroDB read/write paths, provider configuration, contribution audit storage, and the daily local-marker contribution task.
  • Add admin marker/provider API surface and provenance-aware marker writes for intro/credits/recap/preview segments.
  • Add the web marker editor, Intro Markers settings page, and player seek-bar marker editing controls.
  • Improve local Chromaprint intro detection with a subtitle-backed dialogue boundary refiner so shared intro music under active dialogue does not become the skip start.

Root Cause

Chromaprint correctly finds shared audio, but some episodes start the intro music bed before the actual title sequence while dialogue is still active. The local detector was treating that shared music onset as the user-facing intro start. The new refinement keeps Chromaprint as the coarse audio detector and moves only the start boundary forward to the last early dialogue cue when a matching non-SDH text subtitle sidecar is available.

Validation

  • go test ./internal/api/handlers ./internal/markers ./internal/markers/introdb ./internal/scanner ./internal/taskmanager/tasks ./internal/intromarkers ./internal/subtitles ./internal/subtitles/ai
  • cd web && pnpm exec prettier --check src/api/types.ts src/hooks/queries/keys.ts src/hooks/queries/markers.ts src/hooks/queries/admin/markers.ts src/lib/markers.ts src/components/markers/MarkerEditor.tsx src/pages/ItemDetail/EpisodeContent.tsx src/pages/ItemDetail/MovieContent.tsx src/pages/ItemDetail/components/ActionBar.tsx src/pages/admin-settings/AdminSettingsLayout.tsx src/pages/admin-settings/IntegrationsSettings.tsx src/pages/admin-settings/ScannerSettings.tsx src/pages/admin-settings/IntroSettings.tsx src/player/components/PlayerControls.tsx src/player/components/SeekBar.tsx src/player/components/VideoPlayer.tsx src/player/components/WatchPage.tsx src/player/components/MarkerEditPanel.tsx src/player/hooks/useMarkerEditor.ts src/player/types.ts
  • cd web && pnpm run lint exits 0 with existing warnings.
  • Full cd web && pnpm run format:check still fails on 18 pre-existing frontend files outside this PR diff.
  • Validated the S.W.A.T. S05E02 file metadata/cues on the dev host: file 636600 has English audio plus an English non-SDH SRT sidecar, and the bad 322.014s Chromaprint start refines to 330.852s after the final early dialogue cue.

Commit Grouping

  • fix(intromarkers): refine chromaprint starts with dialogue cues
  • feat(markers): finish marker management backend
  • feat(web): add marker editing UI

Notes

  • AI-assisted implementation: Codex.

Summary by CodeRabbit

  • New Features

    • In-player and item-detail marker editing (intro/credits/recap/preview) with seekbar drag UI, modal editor, and save/clear behavior.
    • Admin UI for marker providers: list, validate, configure fetch/contribute/priority, and run marker tasks.
    • Background task to auto-contribute eligible local markers and on-demand contribution flow to online providers.
    • Marker edit history/audit views and new marker-edit permission.
  • Bug Fixes

    • Playback now reliably broadcasts cleared/updated marker states.
  • Documentation

    • Added design and phased implementation plans for marker sources, IntroDB fixes, and contribution workflow.

Quick104 and others added 7 commits June 6, 2026 10:08
…, best candidate)

Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first
libraries got no markers), decode and use the real per-segment confidence and
submission_count instead of a hardcoded 0.9, and pick the most-submitted /
highest-confidence candidate when several are returned. Adds httptest coverage
for the introdb client and provider.

Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…t provenance

Add marker_provider_config (per-provider fetch enable/priority + contribute
gates, contribution off by default) and a cached ProviderConfigStore. Add
Registry.FetchMerged: query all fetch-enabled providers concurrently and keep
the best candidate per segment (submission_count, then confidence, then fetch
priority), stamping each winning marker with its provider/algorithm. Thread
per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate
(additive SegmentProvenance overrides) so a merged result writes correct
per-segment provider/confidence/algorithm; the legacy shared columns keep a
summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB
enabled, behavior is unchanged.

Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ice engine

Add a markers.Submitter capability and implement it on the introdb provider
(POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies
the null start/end conventions). Add the marker_contributions audit table and a
value-hash-keyed ContributionStore for idempotency. Add ContributionService:
resolves enabled submitter providers, gates eligibility (never re-submit
online-sourced markers; auto runs require contribute_auto_local + scanner-intro
above the per-provider confidence threshold), checks idempotency, submits, and
records. Wired in main.go; no trigger yet (admin API and task follow).

Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…dpoints

Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with
provenance; manual upsert where a segment object sets and null clears),
DELETE .../markers/{segment}, POST .../contribute and GET .../contributions,
plus GET/PUT /admin/markers/providers[/{provider}] and a
.../validate key-check returning user stats. Manual writes go through the
priority-gated UpsertMarkers (source=manual) and notify live sessions; a new
FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the
contribution rules.

Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add ContributeMarkersTask (daily 04:00, after local detection): when a provider
has contribute_enabled + contribute_auto_local, page through episode files with
a scanner intro marker at/above the provider's confidence threshold (new
ContributionStore.CandidateLocalIntroFiles keyset query) and run them through
ContributionService with Auto=true. No-op when no provider opts in; idempotent
and resumable across runs.

Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds provider-configured merged marker fetch, plugin-backed providers, per-segment provenance and write-path, contribution service/store/admin APIs and background task, chromaprint dialogue refinement with subtitle parsing, router/main wiring, migrations, and web UI/editor/player changes.

Changes

Markers platform end-to-end

Layer / File(s) Summary
Design docs and plans
docs/...
Design and phased implementation plans for marker sources, TheIntroDB correctness, contribution pipeline, and rollout verification.
Intro analysis & dialogue refinement
internal/intromarkers/...
Adds chromaprint dialogue-boundary refiner, subtitle-aware selection, config hashing, and tests asserting refinement persistence and counters.
Subtitle parsing shared lib
internal/subtitles/*, internal/subtitles/ai/*
New shared subtitle parser/serializer used by AI and refinement logic with wrapper adapters.
Provider config & registry
internal/markers/provider_config.go, internal/markers/types.go, tests
DB-backed ProviderConfigStore, registry concurrency and UseConfigStore wiring, and FetchMerged merging semantics plus tests and migration.
Plugin provider & host integration
internal/markers/plugin_provider.go, internal/pluginhost/*, internal/plugins/*, cmd/silo/main.go
Plugin-backed marker provider adapter, marker-provider client wrapper, plugin lifecycle hooks, discovery/reload wiring, startup reload and legacy introdb migration logic.
Contribution service & store
internal/markers/contribute.go, internal/markers/contribution_repo.go, internal/taskmanager/tasks/*, migrations, tests
ContributionService, ContributionStore with ContentHash idempotency, ContributeMarkersTask, unit tests, and DB migrations for provider config and contributions.
Scanner write-path & per-segment provenance
internal/scanner/*, internal/markers/write.go, tests
Per-segment provenance in MarkerUpdate and SegmentProvenance, UpsertAndClearMarkers/ClearMarkers API, recomputeSharedMarkerAttribution, CanWriteMarker manual-wins semantics, and tests.
API handlers & router
internal/api/handlers/*, internal/api/router.go
Admin provider management handler, markers handler (get/set/clear/contribute/list/history), router wiring, playback notifier behavior, and handler tests.
Web UI & player editor
web/src/...
API types, React hooks, MarkerEditor dialog, in-player editor/panels/seekbar integration, admin Intro Settings page, admin marker history, and related hooks/tests.
Startup wiring, migrations & misc tests
cmd/silo/main.go, migrations/*, misc tests
Startup provider-config reload and plugin provider migration/copy logic, task registration, migrations for provider configs, contributions, marker edit audit, and lifecycle/migration tests.

Estimated code review effort
🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • Silo-Server/silo-server#11: Related changes to permissions and admin gating that overlap with marker_edit permission wiring.
  • Silo-Server/silo-server#2: Prior IntroDB/marker wiring and lazy-fetch flow that this PR replaces with provider-configured registry and merged provenance handling.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/introdb-marker-integration

@Quick104
Quick104 marked this pull request as ready for review June 6, 2026 21:02
@Quick104

Quick104 commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

@codex @CodeRabbit

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create an environment for this repo.

@coderabbitai

coderabbitai Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

@Quick104 It looks like you've tagged me without a specific request. I'll go ahead and kick off a review of this PR for you!

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 399de77b50

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/api/handlers/markers.go Outdated
// Re-validate the resolved primary file through the authorizer so item-id
// edits are access-checked the same way file-id edits are.
if h.Authorizer != nil {
return h.authorizeFile(w, r, files[0].ID)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Choose an accessible file for item marker edits

When a visible movie/episode has multiple file versions and the first media_files row is outside the current viewer scope (for example due to a profile quality ceiling or disabled library), the new /markers/items/{id} path authorizes only files[0] and returns 404 even though another version of the same item is accessible. This breaks the detail-page marker editor for otherwise playable items; iterate the resolved files and use the first one that authorizes (or filter before selecting) instead of failing on the inaccessible first row.

Useful? React with 👍 / 👎.

return &models.MediaFile{ID: fileID}
}
if h.Notifier != nil {
h.Notifier.MarkersUpdated(ctx, refreshed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Notify players when the last marker is cleared

When this path clears the final remaining marker for a file, MarkersUpdated currently drops the update because all four ranges are nil, so other active playback sessions keep showing stale skip regions until they reload. The realtime protocol and client already accept null ranges, so the manual clear path needs to emit an update even for the all-cleared state.

Useful? React with 👍 / 👎.

// correction hashes differently (submitted as a new value).
func ContentHash(segmentKind string, startMs, endMs, durationMs *int64) string {
h := sha256.New()
fmt.Fprintf(h, "%s|%s|%s|%s", segmentKind, ptrIntStr(startMs), ptrIntStr(endMs), ptrIntStr(durationMs))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the target identity in contribution idempotency

Because the idempotency hash excludes the external IDs being submitted to, a file that was previously contributed while matched to the wrong TMDB item will be treated as already submitted after it is rematched if the marker bounds are unchanged. In that rematch scenario AlreadySubmitted skips the corrected contribution for the new target content; include the resolved provider identity (at least TMDB/season/episode or movie kind) in the hash/key or stored row used for de-duplication.

Useful? React with 👍 / 👎.

); err != nil {
return fmt.Errorf("update marker provider config: %w", err)
}
return s.Reload(ctx)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate provider config changes to other nodes

In a multi-instance deployment this update only refreshes the in-process cache on the node that handled the admin request; other API/worker nodes keep their old fetch/contribute flags until restart. That means disabling contribution or online fetch can still leave requests/tasks on another node using the stale enabled config, so this needs the same kind of cross-node invalidation/reload path used for settings or a non-stale read strategy.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 15

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/scanner/file_repo.go (1)

1167-1168: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Recompute shared marker attribution from the post-patch segment state.

This still uses the legacy update-level summary, so adding a lower-confidence segment can downgrade markers_confidence even when a higher-confidence segment of the same source remains on the row. That leaves the shared metadata wrong and can weaken later same-source overwrite gating for segments that still fall back to the legacy fields.

Suggested fix
-	anyApplied := introApplied || creditsApplied || recapApplied || previewApplied
-	nextSource, nextConfidence := nextSharedMarkerAttribution(existingSource, existingConfidence, update, anyApplied)
+	anyApplied := introApplied || creditsApplied || recapApplied || previewApplied
+	nextSource, nextConfidence := existingSource, existingConfidence
+	if anyApplied {
+		nextSource, nextConfidence = recomputeSharedMarkerAttribution(
+			existingSource,
+			existingConfidence,
+			intro,
+			credits,
+			recap,
+			preview,
+		)
+	}
🤖 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/scanner/file_repo.go` around lines 1167 - 1168, The shared marker
attribution call uses the legacy `update` summary and can be downgraded by a
low-confidence segment; change `nextSharedMarkerAttribution(existingSource,
existingConfidence, update, anyApplied)` to recompute the source-level state
from the post-patch segments instead of the `update` object: derive the
effective source and highest confidence for that source by scanning the row's
segments after applying the patch (e.g. compute max confidence and presence for
the same `existingSource` across remaining segments or use the segment-level
metadata instead of `update`), then pass those recomputed values into
`nextSharedMarkerAttribution` (keep `anyApplied` logic intact).
🧹 Nitpick comments (6)
internal/markers/contribute.go (1)

189-191: 💤 Low value

Consider adding a comment explaining the TMDB requirement.

The code enforces TMDB ID presence (line 189), but the reason isn't immediately clear to future maintainers. A brief comment would help:

// IntroDB and other providers require TMDB as the canonical external ID.
if strings.TrimSpace(ids.TmdbID) == "" {
    return ContributionOutcome{...}, true
}
🤖 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/markers/contribute.go` around lines 189 - 191, Add a brief
clarifying comment above the TMDB check (the if using ids.TmdbID) explaining why
TMDB is required (e.g., "IntroDB and other providers treat TMDB as the canonical
external ID used for matching/contributions"), then keep the existing early
return (returning ContributionOutcome with Provider: providerID, Segment:
seg.kind, Status: OutcomeStatusSkipped, Reason: "tmdb id required"); place the
comment immediately above the ids.TmdbID check so future maintainers understand
the constraint without changing logic.
internal/markers/introdb/submit_test.go (1)

55-56: Clarify zero-start normalization in IntroDB JSON

The expectation that Start: ptrDur(0) results in gotBody.StartMs == nil is aligned with IntroDB behavior: null and 0 start times are treated equivalently (both mean “start at the beginning”), so this shouldn’t be misinterpreted as anything else. Add a short comment in the test to document this normalization intent for future readers.

🤖 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/markers/introdb/submit_test.go` around lines 55 - 56, Add a brief
inline comment in the test near the assertion that checks gotBody.StartMs (the
block that expects gotBody.StartMs == nil when Start: ptrDur(0) is used)
explaining that IntroDB normalizes zero start times to null (i.e., Start:
ptrDur(0) and explicit null are treated equivalently as "start at the
beginning"), so the test intentionally expects nil; place the comment next to
the assertion referencing gotBody.StartMs and the test input Start: ptrDur(0).
internal/markers/introdb/client_test.go (1)

20-21: ⚡ Quick win

Close the test clients.

NewClient() starts the cache sweeper goroutine. These tests never call Close(), so the goroutines live until process exit and can start tripping leak detectors as the suite grows. Add defer c.Close() after each client is created.

Also applies to: 44-45, 65-66, 83-84

🤖 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/markers/introdb/client_test.go` around lines 20 - 21, Tests create
clients with NewClient("") which spawn a cache sweeper goroutine but never call
Close(), leaking goroutines; after each client creation (calls to NewClient("")
assigned to variable c in client_test.go, e.g. the instances at the locations
corresponding to the code around NewClient("") / c.SetBaseURL(...)) add a defer
c.Close() immediately after creating and configuring the client to ensure its
goroutine is stopped; apply this change to the four occurrences mentioned so
each test defers c.Close().
internal/markers/types_test.go (1)

87-146: ⚡ Quick win

Add tie-break coverage for confidence and configured fetch priority.

These tests only exercise the submission-count branch. Regressions in the other two ranking rules would still pass, especially the provider-priority path that depends on UseConfigStore.

🤖 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/markers/types_test.go` around lines 87 - 146, Tests only cover
submission-count tie-break; add cases exercising the other ranking rules by
creating providers (fakeProvider with Result/Markers) that tie on
SubmissionCount but differ in Confidence and by configured fetch priority, then
call Registry.FetchMerged and assert the chosen Marker comes from the provider
with higher Confidence and, separately, from the higher-priority provider when
UseConfigStore is enabled. Concretely, extend or add tests alongside
TestRegistryFetchMergedKeepsBestPerSegment that: (1) create two providers with
equal SubmissionCount but Confidence 0.9 vs 0.7 and verify MarkerKindIntro picks
the 0.9 provider; and (2) create two providers with equal Confidence and
SubmissionCount, enable the config-based priority path
(UseConfigStore/NewRegistry configured to use a config store) and set provider
fetch priorities so FetchMerged picks the configured higher-priority provider;
assert provider IDs on the merged result accordingly. Ensure the tests reference
fakeProvider, Result, MarkerKindIntro/MarkerKindCredits, NewRegistry,
UseConfigStore (or the registry constructor flag), Request and ItemKindEpisode
so they exercise the intended tie-break branches.
web/src/components/markers/MarkerEditor.tsx (1)

135-179: ⚡ Quick win

Wrap inputs in a <form> element for better keyboard accessibility.

The input fields are not wrapped in a <form> element, so pressing Enter in a text field won't trigger submission. Adding a form with onSubmit={handleSave} would improve accessibility (screen reader announcements, keyboard navigation) and user experience (Enter key submit).

♻️ Suggested refactor
   return (
-    <>
+    <form onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
       <div className="grid gap-3 py-1">
         {MARKER_KINDS.map((kind) => (
           <div key={kind} className="grid grid-cols-[5.5rem_1fr_1fr_auto] items-center gap-2">
             <span className="text-sm font-medium">{MARKER_LABELS[kind]}</span>
             <Input
               aria-label={`${MARKER_LABELS[kind]} start`}
               placeholder="start"
               value={fields[kind].start}
               onChange={(e) => setField(kind, "start", e.target.value)}
             />
             <Input
               aria-label={`${MARKER_LABELS[kind]} end`}
               placeholder="end"
               value={fields[kind].end}
               onChange={(e) => setField(kind, "end", e.target.value)}
             />
             <Button
               type="button"
               variant="ghost"
               size="icon"
               aria-label={`Clear ${MARKER_LABELS[kind]}`}
               onClick={() => clearKind(kind)}
             >
               <Trash2 className="size-4" />
             </Button>
           </div>
         ))}
       </div>

       {error && <p className="text-destructive text-sm">{error}</p>}

       <DialogFooter>
         <Button variant="outline" onClick={onClose}>
           Cancel
         </Button>
-        <Button onClick={handleSave} disabled={setMarkers.isPending}>
+        <Button type="submit" disabled={setMarkers.isPending}>
           {setMarkers.isPending && <Loader2 className="size-4 animate-spin" />}
           Save
         </Button>
       </DialogFooter>
-    </>
+    </form>
   );
🤖 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/components/markers/MarkerEditor.tsx` around lines 135 - 179, The
inputs in MarkerEditor are not wrapped in a form so Enter won't submit; wrap the
area containing MARKER_KINDS inputs and the error message inside a <form> with
onSubmit={handleSave} and ensure the Save button remains type="submit" (or
remove its onClick) while keeping Cancel (onClose) as type="button"; also
prevent duplicate action by keeping handleSave idempotent or returning false on
invalid data and ensure setMarkers.isPending still disables the submit and
renders the Loader2 as before.
migrations/182_marker_contributions.up.sql (1)

4-21: ⚡ Quick win

Consider adding CHECK constraints for enumerated text fields.

The provider, segment_kind, source, and status columns are documented as having specific allowed values (e.g., status is pending | accepted | rejected | error), but the schema uses unconstrained TEXT. Adding CHECK constraints would prevent invalid values from being inserted if application-layer validation is bypassed or has bugs.

🛡️ Proposed constraints
 CREATE TABLE public.marker_contributions (
     id                 uuid PRIMARY KEY DEFAULT gen_random_uuid(),
     media_file_id      integer NOT NULL REFERENCES media_files(id) ON DELETE CASCADE,
     provider           text    NOT NULL,
-    segment_kind       text    NOT NULL,                -- intro | recap | credits | preview
-    source             text    NOT NULL,                -- what we contributed: scanner | manual
+    segment_kind       text    NOT NULL CHECK (segment_kind IN ('intro', 'recap', 'credits', 'preview')),
+    source             text    NOT NULL CHECK (source IN ('scanner', 'manual')),
     submitted_start_ms bigint,
     submitted_end_ms   bigint,
     video_duration_ms  bigint,
     content_hash       text    NOT NULL,                -- hash(segment_kind, start_ms, end_ms, duration_ms)
     submission_id      text,                            -- id returned by the provider
-    status             text    NOT NULL,                -- pending | accepted | rejected | error
+    status             text    NOT NULL CHECK (status IN ('pending', 'accepted', 'rejected', 'error')),
     http_status        integer,
🤖 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 `@migrations/182_marker_contributions.up.sql` around lines 4 - 21, Add CHECK
constraints to the marker_contributions table to enforce allowed values for the
enumerated text columns: add checks on provider (allowed provider values),
segment_kind (intro, recap, credits, preview), source (scanner, manual), and
status (pending, accepted, rejected, error); implement these either by updating
the CREATE TABLE to include column-level CHECK clauses or by issuing ALTER TABLE
... ADD CONSTRAINT statements with explicit constraint names (e.g.,
marker_contributions_segment_kind_check, marker_contributions_status_check) and
ensure the constraints and names reference the existing columns media_file_id,
provider, segment_kind, source, status so the migration fails fast on invalid
inserts.
🤖 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 `@docs/superpowers/plans/2026-06-06-marker-introdb-readpath-correctness.md`:
- Line 618: Remove the dangling untyped fenced code block marker ``` at the end
of the file: either delete the trailing backticks or convert them to a properly
typed/closed fenced block (e.g., ```md or ```text plus matching closing fence)
so the file no longer ends with an open/untyped ``` that triggers MD040 and
breaks rendering.

In
`@docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md`:
- Line 75: The Task headings like "### Task 1.1 — Type plumbing" are jumping a
level and violating markdownlint MD001; update these to use a single-level
increment (e.g., change "### Task 1.1 — Type plumbing" to "## Task 1.1 — Type
plumbing") or alternatively demote the surrounding phase headers so the relative
depth is consistent; apply the same fix to the other occurrences mentioned (the
headings at the other noted locations) so all task headings follow the same
h2/h3 scheme.
- Line 483: There is an unterminated/empty fenced code block (a bare "```" at
the end of the file) causing MD040; either remove that trailing "```" entirely
or replace it with a properly typed/closed fenced block by adding a language
identifier (e.g., "```text" or "```json") and a matching closing fence so the
block is valid.

In `@internal/api/handlers/markers.go`:
- Around line 406-414: reloadAndNotify currently fabricates an empty
models.MediaFile on reload failure which leads callers to treat the operation as
successful; change reloadAndNotify to return (nil, error) by propagating the
error from h.Files.GetByID (or a wrapped error if refreshed==nil), update its
signature from func (h *MarkersHandler) reloadAndNotify(ctx context.Context,
fileID int) *models.MediaFile to return (*models.MediaFile, error), and ensure
callers that invoked reloadAndNotify handle the error path and avoid calling
h.Notifier.MarkersUpdated or returning 200 on failure; reference
functions/fields: reloadAndNotify, h.Files.GetByID, h.Notifier.MarkersUpdated,
and models.MediaFile.
- Around line 305-318: The handler currently calls h.Writer.UpsertMarkers and
h.Writer.ClearMarkers separately so a failure in ClearMarkers can leave a
partial successful UpsertMarkers and still return 500; make the mutation atomic
by adding and using a single combined operation on the writer (e.g., add a
method like UpsertAndClearMarkers(ctx, fileID, upsertUpdate, clearSegments) or
WrapMarkersInTx that performs both UpsertMarkers and ClearMarkers in one DB
transaction) and replace the two independent calls in the markers handler with
one call to that new atomic method (referencing UpsertMarkers, ClearMarkers, and
h.Writer to locate where to implement the combined operation).
- Around line 363-368: In HandleContributeFile in markers.go, stop gating JSON
decoding on r.ContentLength; always attempt
json.NewDecoder(r.Body).Decode(&body) and treat io.EOF as the only “no body”
case (leave body at zero values), but return a BadRequest on any other decode
error; this prevents skipping decoding for chunked/unknown-length requests and
avoids mistakenly interpreting nil/empty opts.Segments as “all segments.” Ensure
you reference the variables body, opts.Segments and the function
markers.ContributeFile when making the change.

In `@internal/intromarkers/repository.go`:
- Around line 596-621: The current logic compares patch.Confidence vs
*row.IntroMarkersConfidence before considering scannerAlgorithmPriority, causing
high-confidence low-priority markers to block higher-priority algorithms; change
the ordering to compute existingAlgorithm (from row.IntroMarkersAlgorithm), call
scannerAlgorithmPriority for patch.Algorithm and existingAlgorithm first and
compare patchPriority vs existingPriority, returning when priorities differ,
then if priorities are equal compare confidences (and finally handle the special
case when patchPriority == 0 and algorithms differ, and the introRangeDiffers
check). Ensure the same reordered logic is applied in the duplicate block around
lines 627-642 that mirrors this logic.

In `@internal/markers/introdb/client.go`:
- Around line 280-286: When handling HTTP 429 in submitSegment(), don't return a
RetryAfterError with RetryAfter == 0 when usageResetSeconds(resp) yields 0;
instead apply the same positive fallback used in fetch() so callers back off.
Update the block that builds &markers.RetryAfterError (in submitSegment) to
compute after := time.Duration(usageResetSeconds(resp)) * time.Second and if
after == 0 set after = the same non-zero fallback value used by fetch(); then
pass that adjusted after into RetryAfter and the log/message (keeping ProviderID
and Message formatting intact). Ensure the same change is also applied to the
analogous 429 handling at the other site (lines ~343-352) so both paths use the
positive fallback.

In `@internal/markers/introdb/provider.go`:
- Around line 184-202: The current logic in provider.go that normalizes
req.Start/req.End (used when building body.StartMs/body.EndMs) silently converts
out-of-range values like start < 0 or end > req.Duration into boundary
submissions; instead, update the validation to only canonicalize exact
boundaries (treat start == 0 as nil for "beginning" and end == req.Duration as
nil for "to EOF") and otherwise return a validation error (fail fast) when start
< 0 or end > req.Duration or when start > end; specifically, in the block
handling req.Segment (and before assigning body.StartMs/body.EndMs), add
explicit checks on req.Start and req.End for negativity/overshoot and reject
invalid ranges rather than setting them to nil, preserving the conversion to
milliseconds only for valid, non-boundary values.

In `@web/src/hooks/queries/admin/markers.ts`:
- Around line 34-41: The onSuccess handler for the provider-save mutation fails
to evict the cached validation entry, so markerProviderValidation(...) can
remain stale; update the onSuccess in the mutation (the async handler that
currently calls queryClient.invalidateQueries for adminKeys.markerProviders()
and adminKeys.markerProvider(variables.provider)) to also call
queryClient.invalidateQueries for
adminKeys.markerProviderValidation(variables.provider) (or the correct
markerProviderValidation key shape) as part of the Promise.all so the validation
cache is invalidated whenever provider settings change.

In `@web/src/player/components/MarkerEditPanel.tsx`:
- Around line 34-66: The handleDragStart adds document-level listeners
(onMove/onUp) but doesn't guarantee they are removed if the component unmounts
during a drag; update the component to track the active listeners (e.g., store
onMove and onUp in refs or a single "isDragging" ref) and add a useEffect
cleanup that removes document.removeEventListener("pointermove", onMove) and
document.removeEventListener("pointerup", onUp) on unmount; ensure you still
remove them in the existing onUp handler and reference the same handler
instances (from refs) so removal succeeds; relevant symbols: handleDragStart,
onMove, onUp, panelRef, setOffset.

In `@web/src/player/components/PlayerControls.tsx`:
- Around line 346-356: The marker-edit button currently only updates data-active
but isn't exposed as a toggled control to assistive tech; update the button
rendered when markerEditAvailable && onToggleMarkerEdit to include
aria-pressed={markerEditActive} (use the boolean markerEditActive, not a string)
alongside the existing attributes so screen readers can announce its on/off
state (refer to the button that uses markerEditActive, onToggleMarkerEdit and
Tags in PlayerControls).

In `@web/src/player/components/SeekBar.tsx`:
- Around line 418-440: MarkerHandle currently exposes slider semantics but lacks
focus/keyboard support; remove the misleading interactive attributes instead of
faking a slider. In the MarkerHandle component remove role="slider",
aria-valuenow and tabIndex={-1} (and any other slider-specific ARIA attributes)
so it is not announced as a slider; keep aria-label or convert it to a
non-interactive attribute (or use aria-hidden if purely decorative). This change
touches the MarkerHandle function and its root div element.

In `@web/src/player/hooks/useMarkerEditor.ts`:
- Around line 155-182: The save() function currently calls onSaved?.(draft)
inside the try block so any exception from the callback or timing of parent
refresh can be treated as a failed save and leave originalRef stale; instead,
after the playerFetch resolves but before invoking any external callbacks,
update the local baseline by committing the draft into originalRef.current (and
clear editing state via setEditing(false)), then call onSaved?.(draft) outside
the request-failure path and guard it with its own try/catch so callback errors
do not flip setError or setSaving; keep playerFetch, draft, originalRef,
onSaved, setEditing, setSaving, and setError as the referenced symbols to locate
where to apply the change.
- Around line 107-123: The setEdge callback can produce starts/ends outside [0,
duration] after enforcing MIN_GAP (e.g., when duration < MIN_GAP); update
setEdge (used with setDraft and PlayerTimeRange) to re-clamp the computed
next.start and next.end to the valid range after applying the MIN_GAP adjustment
(or early-return/short-circuit when duration <= MIN_GAP) so final values are
always bounded by 0 and duration; ensure you reference MIN_GAP, NEW_MARKER_SPAN
and duration when computing the corrected clamped range.

---

Outside diff comments:
In `@internal/scanner/file_repo.go`:
- Around line 1167-1168: The shared marker attribution call uses the legacy
`update` summary and can be downgraded by a low-confidence segment; change
`nextSharedMarkerAttribution(existingSource, existingConfidence, update,
anyApplied)` to recompute the source-level state from the post-patch segments
instead of the `update` object: derive the effective source and highest
confidence for that source by scanning the row's segments after applying the
patch (e.g. compute max confidence and presence for the same `existingSource`
across remaining segments or use the segment-level metadata instead of
`update`), then pass those recomputed values into `nextSharedMarkerAttribution`
(keep `anyApplied` logic intact).

---

Nitpick comments:
In `@internal/markers/contribute.go`:
- Around line 189-191: Add a brief clarifying comment above the TMDB check (the
if using ids.TmdbID) explaining why TMDB is required (e.g., "IntroDB and other
providers treat TMDB as the canonical external ID used for
matching/contributions"), then keep the existing early return (returning
ContributionOutcome with Provider: providerID, Segment: seg.kind, Status:
OutcomeStatusSkipped, Reason: "tmdb id required"); place the comment immediately
above the ids.TmdbID check so future maintainers understand the constraint
without changing logic.

In `@internal/markers/introdb/client_test.go`:
- Around line 20-21: Tests create clients with NewClient("") which spawn a cache
sweeper goroutine but never call Close(), leaking goroutines; after each client
creation (calls to NewClient("") assigned to variable c in client_test.go, e.g.
the instances at the locations corresponding to the code around NewClient("") /
c.SetBaseURL(...)) add a defer c.Close() immediately after creating and
configuring the client to ensure its goroutine is stopped; apply this change to
the four occurrences mentioned so each test defers c.Close().

In `@internal/markers/introdb/submit_test.go`:
- Around line 55-56: Add a brief inline comment in the test near the assertion
that checks gotBody.StartMs (the block that expects gotBody.StartMs == nil when
Start: ptrDur(0) is used) explaining that IntroDB normalizes zero start times to
null (i.e., Start: ptrDur(0) and explicit null are treated equivalently as
"start at the beginning"), so the test intentionally expects nil; place the
comment next to the assertion referencing gotBody.StartMs and the test input
Start: ptrDur(0).

In `@internal/markers/types_test.go`:
- Around line 87-146: Tests only cover submission-count tie-break; add cases
exercising the other ranking rules by creating providers (fakeProvider with
Result/Markers) that tie on SubmissionCount but differ in Confidence and by
configured fetch priority, then call Registry.FetchMerged and assert the chosen
Marker comes from the provider with higher Confidence and, separately, from the
higher-priority provider when UseConfigStore is enabled. Concretely, extend or
add tests alongside TestRegistryFetchMergedKeepsBestPerSegment that: (1) create
two providers with equal SubmissionCount but Confidence 0.9 vs 0.7 and verify
MarkerKindIntro picks the 0.9 provider; and (2) create two providers with equal
Confidence and SubmissionCount, enable the config-based priority path
(UseConfigStore/NewRegistry configured to use a config store) and set provider
fetch priorities so FetchMerged picks the configured higher-priority provider;
assert provider IDs on the merged result accordingly. Ensure the tests reference
fakeProvider, Result, MarkerKindIntro/MarkerKindCredits, NewRegistry,
UseConfigStore (or the registry constructor flag), Request and ItemKindEpisode
so they exercise the intended tie-break branches.

In `@migrations/182_marker_contributions.up.sql`:
- Around line 4-21: Add CHECK constraints to the marker_contributions table to
enforce allowed values for the enumerated text columns: add checks on provider
(allowed provider values), segment_kind (intro, recap, credits, preview), source
(scanner, manual), and status (pending, accepted, rejected, error); implement
these either by updating the CREATE TABLE to include column-level CHECK clauses
or by issuing ALTER TABLE ... ADD CONSTRAINT statements with explicit constraint
names (e.g., marker_contributions_segment_kind_check,
marker_contributions_status_check) and ensure the constraints and names
reference the existing columns media_file_id, provider, segment_kind, source,
status so the migration fails fast on invalid inserts.

In `@web/src/components/markers/MarkerEditor.tsx`:
- Around line 135-179: The inputs in MarkerEditor are not wrapped in a form so
Enter won't submit; wrap the area containing MARKER_KINDS inputs and the error
message inside a <form> with onSubmit={handleSave} and ensure the Save button
remains type="submit" (or remove its onClick) while keeping Cancel (onClose) as
type="button"; also prevent duplicate action by keeping handleSave idempotent or
returning false on invalid data and ensure setMarkers.isPending still disables
the submit and renders the Loader2 as before.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1017d515-404e-43eb-970d-77534cfa22b8

📥 Commits

Reviewing files that changed from the base of the PR and between 69c1e6c and 399de77.

📒 Files selected for processing (64)
  • cmd/silo/main.go
  • docs/superpowers/plans/2026-06-06-marker-introdb-readpath-correctness.md
  • docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md
  • docs/superpowers/specs/2026-06-06-marker-sources-and-contribution-design.md
  • internal/api/handlers/admin_marker_providers.go
  • internal/api/handlers/admin_marker_providers_test.go
  • internal/api/handlers/markers.go
  • internal/api/handlers/markers_test.go
  • internal/api/handlers/playback_lazy_markers.go
  • internal/api/router.go
  • internal/intromarkers/analyzer.go
  • internal/intromarkers/analyzer_test.go
  • internal/intromarkers/dialogue.go
  • internal/intromarkers/dialogue_test.go
  • internal/intromarkers/repository.go
  • internal/intromarkers/repository_test.go
  • internal/intromarkers/types.go
  • internal/markers/contribute.go
  • internal/markers/contribute_test.go
  • internal/markers/contribution_repo.go
  • internal/markers/introdb/client.go
  • internal/markers/introdb/client_test.go
  • internal/markers/introdb/provider.go
  • internal/markers/introdb/provider_test.go
  • internal/markers/introdb/submit_test.go
  • internal/markers/introdb/types.go
  • internal/markers/provider_config.go
  • internal/markers/provider_config_test.go
  • internal/markers/types.go
  • internal/markers/types_test.go
  • internal/markers/write.go
  • internal/markers/write_test.go
  • internal/scanner/file_repo.go
  • internal/scanner/file_repo_test.go
  • internal/scanner/types.go
  • internal/subtitles/ai/engine.go
  • internal/subtitles/ai/srt.go
  • internal/subtitles/cues.go
  • internal/taskmanager/tasks/contribute_markers.go
  • internal/taskmanager/tasks/contribute_markers_test.go
  • migrations/181_marker_provider_config.down.sql
  • migrations/181_marker_provider_config.up.sql
  • migrations/182_marker_contributions.down.sql
  • migrations/182_marker_contributions.up.sql
  • web/src/api/types.ts
  • web/src/components/markers/MarkerEditor.tsx
  • web/src/hooks/queries/admin/markers.ts
  • web/src/hooks/queries/keys.ts
  • web/src/hooks/queries/markers.ts
  • web/src/lib/markers.ts
  • web/src/pages/ItemDetail/EpisodeContent.tsx
  • web/src/pages/ItemDetail/MovieContent.tsx
  • web/src/pages/ItemDetail/components/ActionBar.tsx
  • web/src/pages/admin-settings/AdminSettingsLayout.tsx
  • web/src/pages/admin-settings/IntegrationsSettings.tsx
  • web/src/pages/admin-settings/IntroSettings.tsx
  • web/src/pages/admin-settings/ScannerSettings.tsx
  • web/src/player/components/MarkerEditPanel.tsx
  • web/src/player/components/PlayerControls.tsx
  • web/src/player/components/SeekBar.tsx
  • web/src/player/components/VideoPlayer.tsx
  • web/src/player/components/WatchPage.tsx
  • web/src/player/hooks/useMarkerEditor.ts
  • web/src/player/types.ts
💤 Files with no reviewable changes (2)
  • web/src/pages/admin-settings/IntegrationsSettings.tsx
  • web/src/pages/admin-settings/ScannerSettings.tsx

`internal/markers/types.go` (modify, add `Marker.SubmissionCount`),
`internal/markers/introdb/{client_test.go,provider_test.go}` (create).

### Task 1.1 — Type plumbing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix heading depth progression to satisfy markdownlint MD001.

These task headings jump levels (expected h2, found h3). Use a single-level increment strategy (e.g., make these ##, or demote phase headers and keep these as ###) so lint passes consistently.

Also applies to: 124-124, 251-251, 365-365, 411-411

🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 75-75: Heading levels should only increment by one level at a time
Expected: h2; Actual: h3

(MD001, heading-increment)

🤖 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-06-marker-sources-and-contribution-implementation.md`
at line 75, The Task headings like "### Task 1.1 — Type plumbing" are jumping a
level and violating markdownlint MD001; update these to use a single-level
increment (e.g., change "### Task 1.1 — Type plumbing" to "## Task 1.1 — Type
plumbing") or alternatively demote the surrounding phase headers so the relative
depth is consistent; apply the same fix to the other occurrences mentioned (the
headings at the other noted locations) so all task headings follow the same
h2/h3 scheme.

Source: Linters/SAST tools

Comment thread internal/api/handlers/markers.go Resolved
Comment thread internal/api/handlers/markers.go Resolved
Comment thread web/src/player/components/SeekBar.tsx Resolved
Comment thread web/src/player/hooks/useMarkerEditor.ts Resolved
Comment thread web/src/player/hooks/useMarkerEditor.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/markers/types.go (1)

369-375: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

FetchMerged drops single-provider result metadata.

This path always returns a fresh Result{SourceClass: ...} without restoring top-level ProviderID or Algorithm. With one enabled provider, that no longer matches FetchFirstHit, despite the documented contract on Lines 317-319. Any caller still reading Result.ProviderID, Result.Algorithm, or the original SourceClass will regress even though the per-marker fields are stamped correctly.

🤖 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/markers/types.go` around lines 369 - 375, FetchMerged currently
constructs a fresh Result (merged := Result{SourceClass:
models.MarkerSourceOnline}) and returns that, which drops top-level metadata
such as ProviderID and Algorithm and can misrepresent SourceClass; instead,
preserve the original result metadata when merging. Locate FetchMerged and the
merged variable, and copy ProviderID, Algorithm and the original SourceClass
from the input Result (or from the single-provider winner in best[kind]) into
merged before returning (or initialize merged by cloning the original Result and
then replace/append Markers), ensuring per-marker fields remain stamped but
top-level ProviderID, Algorithm and SourceClass are retained.
internal/api/handlers/admin_marker_providers_test.go (1)

46-48: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Parse the response JSON instead of matching raw fragments.

This assertion is brittle against harmless encoder changes like float rendering or spacing, and it does not verify the field in its actual object location. Unmarshal the body and assert the acceptance_rate key/value directly.

🤖 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/api/handlers/admin_marker_providers_test.go` around lines 46 - 48,
The test currently checks rec.Body.String() with brittle string matching for
`"acceptance_rate":0.7`; instead, unmarshal the response JSON body (e.g., into a
map[string]interface{} or a small struct) and assert the acceptance_rate field
value directly; in the test around variables rec and body, replace the raw
string Contains check with json.Unmarshal(bodyBytes, &m) and then check
m["acceptance_rate"] (or struct.AcceptanceRate) equals the expected numeric
value, failing the test if the key is missing or the value mismatches.
🤖 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 2047-2049: The sort comparators currently dereference slice
elements (e.g., installations[i].ID in the sort.Slice comparator) without
checking for nil, which can panic if a nil entry exists; update the
comparator(s) to first guard against nils (e.g., if installations[i] == nil &&
installations[j] == nil { return false } if installations[i] == nil { return
false } if installations[j] == nil { return true }) so nils are consistently
ordered (typically after non-nils), or pre-filter nil entries out of the slice
before calling sort.Slice; apply the same nil-guard pattern to the other
provider/capability comparator that dereferences elements to avoid nil-pointer
panics.

In `@internal/api/handlers/admin_marker_providers_test.go`:
- Around line 56-68: The test in admin_marker_providers_test.go currently
verifies DisplayName, SourceType, PluginInstallationID, CapabilityID and
IsSubmitter but omits PluginID; update the assertions after calling
toProviderConfigResponse (or wherever resp is produced) to also assert
resp.PluginID == "silo.plugin.markers" so the test ensures
toProviderConfigResponse preserves the PluginID field from
markers.ProviderDescriptor.

In `@internal/markers/plugin_provider.go`:
- Around line 244-271: The markerFromPluginSegment function currently accepts
negative start times and end times beyond the media duration; update
markerFromPluginSegment to validate and reject segments with start < 0 or end >
duration (in addition to the existing end <= start check) — use
secondsDuration(segment.GetStartSeconds()) and
secondsDuration(segment.GetEndSeconds()) to compute start/end, then if start < 0
or end > duration return (Marker{}, false); alternatively clamp to [0,duration]
only if you want to accept corrected values, but be explicit in code (refer to
markerFromPluginSegment, start, end, duration, secondsDuration and the end <=
start check) so invalid external plugin ranges cannot propagate.

In `@internal/markers/types.go`:
- Around line 248-270: SetProviders currently validates and builds the
replacement slice before taking r.mu, allowing a concurrent writer like Register
to mutate r.providers and be lost; fix by acquiring the registry write lock
(r.mu.Lock()) at the start of SetProviders (after the nil-receiver check),
perform the validation/build of next while holding the lock, assign r.providers
= next, then unlock (defer r.mu.Unlock() is fine). This serializes SetProviders
with Register and any other writers so updates are not lost.

In `@internal/plugins/service.go`:
- Around line 90-99: OnLifecycleChange currently runs lifecycleHooks directly so
a panic in any hook can escape; update the loop that iterates over hooks (the
hook variable in OnLifecycleChange) to invoke each hook inside a panic-safe
wrapper: defer a recover() for each call so a panic is caught and does not
propagate, and, if the Service exposes a logger (e.g., s.logger or similar), log
the recovered panic and stack trace; otherwise silently swallow the panic and
continue to the next hook to preserve the best-effort behavior.

In `@web/src/pages/admin-settings/IntroSettings.tsx`:
- Around line 94-95: Replace the loose parseInt logic for fetchPriority: stop
using Number.parseInt(fetchPriority, 10) and instead perform strict numeric
validation (e.g. test the raw string with a digits-only regex like /^[+-]?\d+$/
to reject scientific notation such as "1e2", then parse with Number or parseInt
once validated). Update the constants parsedFetchPriority and priorityValid in
IntroSettings.tsx so parsedFetchPriority = Number(fetchPriority) (or parseInt
after the regex check) and priorityValid = Number.isInteger(parsedFetchPriority)
&& /^[+-]?\d+$/.test(fetchPriority), ensuring the component only accepts real
integer strings before sending fetch_priority.

---

Outside diff comments:
In `@internal/api/handlers/admin_marker_providers_test.go`:
- Around line 46-48: The test currently checks rec.Body.String() with brittle
string matching for `"acceptance_rate":0.7`; instead, unmarshal the response
JSON body (e.g., into a map[string]interface{} or a small struct) and assert the
acceptance_rate field value directly; in the test around variables rec and body,
replace the raw string Contains check with json.Unmarshal(bodyBytes, &m) and
then check m["acceptance_rate"] (or struct.AcceptanceRate) equals the expected
numeric value, failing the test if the key is missing or the value mismatches.

In `@internal/markers/types.go`:
- Around line 369-375: FetchMerged currently constructs a fresh Result (merged
:= Result{SourceClass: models.MarkerSourceOnline}) and returns that, which drops
top-level metadata such as ProviderID and Algorithm and can misrepresent
SourceClass; instead, preserve the original result metadata when merging. Locate
FetchMerged and the merged variable, and copy ProviderID, Algorithm and the
original SourceClass from the input Result (or from the single-provider winner
in best[kind]) into merged before returning (or initialize merged by cloning the
original Result and then replace/append Markers), ensuring per-marker fields
remain stamped but top-level ProviderID, Algorithm and SourceClass are retained.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: aed4f449-a156-4bae-ad62-335ee5c410d2

📥 Commits

Reviewing files that changed from the base of the PR and between 399de77 and bfc5a08.

📒 Files selected for processing (28)
  • cmd/silo/main.go
  • cmd/silo/marker_plugin_migration_test.go
  • internal/api/handlers/admin_marker_providers.go
  • internal/api/handlers/admin_marker_providers_test.go
  • internal/api/handlers/playback_lazy_markers.go
  • internal/markers/contribute.go
  • internal/markers/contribute_test.go
  • internal/markers/introdb/client.go
  • internal/markers/introdb/provider.go
  • internal/markers/introdb/types.go
  • internal/markers/plugin_provider.go
  • internal/markers/plugin_provider_test.go
  • internal/markers/provider_config.go
  • internal/markers/types.go
  • internal/markers/types_test.go
  • internal/markers/write.go
  • internal/markers/write_test.go
  • internal/pluginhost/client.go
  • internal/pluginhost/client_test.go
  • internal/pluginhost/handshake.go
  • internal/plugins/service.go
  • internal/plugins/service_hot_reload_test.go
  • internal/scanner/file_repo.go
  • internal/scanner/file_repo_test.go
  • internal/scanner/types.go
  • web/src/api/types.ts
  • web/src/hooks/queries/admin/markers.ts
  • web/src/pages/admin-settings/IntroSettings.tsx
💤 Files with no reviewable changes (3)
  • internal/markers/introdb/types.go
  • internal/markers/introdb/provider.go
  • internal/markers/introdb/client.go
✅ Files skipped from review due to trivial changes (1)
  • internal/pluginhost/handshake.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/scanner/types.go
  • internal/markers/write_test.go
  • web/src/api/types.ts
  • web/src/hooks/queries/admin/markers.ts
  • internal/markers/contribute_test.go

Comment thread cmd/silo/main.go Resolved
Comment thread internal/markers/plugin_provider.go Resolved
Comment thread internal/markers/types.go Resolved
Comment thread internal/plugins/service.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
internal/markers/plugin_provider_test.go (1)

88-127: ⚡ Quick win

Consider adding test case for start >= duration.

The implementation rejects segments where start >= duration, but this edge case isn't covered. Adding a test case like {name: "start at duration", segment: &pluginv1.MarkerSegment{Segment: "intro", StartSeconds: &sixtySeconds}, wantOK: false} would complete the out-of-bounds coverage.

🧪 Suggested test case addition
 	validStart := 50.0
 	duration := time.Minute
+	atDuration := 60.0

 	tests := []struct {
 		name    string
 		segment *pluginv1.MarkerSegment
 		wantOK  bool
 		wantEnd time.Duration
 	}{
 		{
 			name:    "negative start",
 			segment: &pluginv1.MarkerSegment{Segment: "intro", StartSeconds: &negativeStart},
 		},
 		{
 			name:    "end past duration",
 			segment: &pluginv1.MarkerSegment{Segment: "intro", StartSeconds: &start10, EndSeconds: &end61},
 		},
+		{
+			name:    "start at duration",
+			segment: &pluginv1.MarkerSegment{Segment: "intro", StartSeconds: &atDuration},
+		},
 		{
 			name:    "default end uses duration",
 			segment: &pluginv1.MarkerSegment{Segment: "credits", StartSeconds: &validStart},
 			wantOK:  true,
 			wantEnd: duration,
 		},
 	}
🤖 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/markers/plugin_provider_test.go` around lines 88 - 127, Add a test
for the "start >= duration" boundary inside
TestPluginProviderRejectsOutOfBoundsSegments: create a new test case (e.g., name
"start at duration") that supplies a MarkerSegment with StartSeconds equal to
the duration (e.g., 60s) and expect wantOK false, then run the existing
markerFromPluginSegment(duration) assertions as in the other cases to validate
the implementation rejects this segment; update the tests slice in
TestPluginProviderRejectsOutOfBoundsSegments accordingly so the loop exercises
this edge case.
🤖 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.

Nitpick comments:
In `@internal/markers/plugin_provider_test.go`:
- Around line 88-127: Add a test for the "start >= duration" boundary inside
TestPluginProviderRejectsOutOfBoundsSegments: create a new test case (e.g., name
"start at duration") that supplies a MarkerSegment with StartSeconds equal to
the duration (e.g., 60s) and expect wantOK false, then run the existing
markerFromPluginSegment(duration) assertions as in the other cases to validate
the implementation rejects this segment; update the tests slice in
TestPluginProviderRejectsOutOfBoundsSegments accordingly so the loop exercises
this edge case.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6d5564ff-22dd-44f9-91ff-a597edc50b76

📥 Commits

Reviewing files that changed from the base of the PR and between bfc5a08 and dc26c1d.

📒 Files selected for processing (29)
  • cmd/silo/main.go
  • docs/superpowers/plans/2026-06-06-marker-introdb-readpath-correctness.md
  • docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md
  • internal/api/handlers/admin_marker_providers.go
  • internal/api/handlers/admin_marker_providers_test.go
  • internal/api/handlers/markers.go
  • internal/api/handlers/markers_test.go
  • internal/api/router.go
  • internal/cache/redis.go
  • internal/intromarkers/repository.go
  • internal/intromarkers/repository_test.go
  • internal/markers/contribute.go
  • internal/markers/contribute_test.go
  • internal/markers/contribution_repo.go
  • internal/markers/plugin_provider.go
  • internal/markers/plugin_provider_test.go
  • internal/markers/types.go
  • internal/playback/marker_update_notifier.go
  • internal/playback/marker_update_notifier_test.go
  • internal/plugins/service.go
  • internal/plugins/service_lifecycle_test.go
  • internal/scanner/file_repo.go
  • migrations/182_marker_contributions.up.sql
  • web/src/hooks/queries/admin/markers.ts
  • web/src/pages/admin-settings/IntroSettings.tsx
  • web/src/player/components/MarkerEditPanel.tsx
  • web/src/player/components/PlayerControls.tsx
  • web/src/player/components/SeekBar.tsx
  • web/src/player/hooks/useMarkerEditor.ts
💤 Files with no reviewable changes (3)
  • internal/playback/marker_update_notifier.go
  • web/src/player/components/SeekBar.tsx
  • docs/superpowers/plans/2026-06-06-marker-introdb-readpath-correctness.md
✅ Files skipped from review due to trivial changes (1)
  • docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md
🚧 Files skipped from review as they are similar to previous changes (16)
  • migrations/182_marker_contributions.up.sql
  • internal/api/router.go
  • web/src/hooks/queries/admin/markers.ts
  • internal/markers/contribution_repo.go
  • internal/plugins/service.go
  • internal/intromarkers/repository.go
  • internal/api/handlers/markers_test.go
  • web/src/player/hooks/useMarkerEditor.ts
  • internal/markers/contribute_test.go
  • web/src/player/components/PlayerControls.tsx
  • cmd/silo/main.go
  • web/src/player/components/MarkerEditPanel.tsx
  • internal/api/handlers/admin_marker_providers.go
  • internal/markers/types.go
  • web/src/pages/admin-settings/IntroSettings.tsx
  • internal/markers/plugin_provider.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/scanner/file_repo.go (2)

1143-1189: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Compute changed from the final state diff, not from the requested operation.

This path currently marks every accepted patch and every clear as a write, even when the segment is byte-for-byte identical to what is already stored. That makes idempotent retries rewrite updated_at, and the CASE ... NOW() logic in writeMarkerMutationState will also bump *_markers_detected_at on unchanged markers. Snapshot the original segment states and derive changed with segmentEqual after all mutations are applied.

Suggested fix
 	state, err := loadMarkerMutationState(ctx, tx, fileID)
 	if err != nil {
 		return false, err
 	}
-	changed := markerSegmentFlags{}
+	original := state

 	if hasUpdate {
-		applied, err := applyMarkerUpdateToMutationState(update, &state)
+		_, err := applyMarkerUpdateToMutationState(update, &state)
 		if err != nil {
 			return false, err
 		}
-		changed.intro = changed.intro || applied.intro
-		changed.credits = changed.credits || applied.credits
-		changed.recap = changed.recap || applied.recap
-		changed.preview = changed.preview || applied.preview
 	}
 	if clearFlags.intro {
 		clearSegmentState(&state.intro)
-		changed.intro = true
 	}
 	if clearFlags.credits {
 		clearSegmentState(&state.credits)
-		changed.credits = true
 	}
 	if clearFlags.recap {
 		clearSegmentState(&state.recap)
-		changed.recap = true
 	}
 	if clearFlags.preview {
 		clearSegmentState(&state.preview)
-		changed.preview = true
 	}
+	changed := markerSegmentFlags{
+		intro:   !segmentEqual(original.intro, state.intro),
+		credits: !segmentEqual(original.credits, state.credits),
+		recap:   !segmentEqual(original.recap, state.recap),
+		preview: !segmentEqual(original.preview, state.preview),
+	}
 	if !changed.any() {
 		if err := tx.Commit(ctx); err != nil {
 			return false, fmt.Errorf("commit marker no-op transaction: %w", err)
 		}
🤖 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/scanner/file_repo.go` around lines 1143 - 1189, Snapshot the
original segment states immediately after loadMarkerMutationState (store copies
of state.intro, state.credits, state.recap, state.preview), then apply
applyMarkerUpdateToMutationState and clearSegmentState as before, but DO NOT set
markerSegmentFlags based on the requested ops; after all mutations compute each
changed flag by comparing the original snapshot to the final state using
segmentEqual (e.g. changed.intro = !segmentEqual(originalIntro, state.intro),
etc.), and only call writeMarkerMutationState / commit when changed.any() is
true so unchanged, idempotent operations do not update timestamps or write.

1026-1031: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Carry forward the legacy shared confidence in the priority check.

When a pre-segment-provenance row falls back to legacySharedSource, it still passes state.confidence into CanWriteMarker. That drops the existing shared confidence on the floor, so a lower-confidence write from the same source can overwrite a stronger legacy marker because the current confidence looks nil.

Suggested fix
 func applySegmentPatch(
 	state *segmentState,
 	legacySharedSource *string,
+	legacySharedConfidence *float64,
 	source string,
 	provider *string,
 	confidence *float64,
 	algorithm string,
@@
-	effectiveSource := state.source
+	effectiveSource := state.source
+	effectiveConfidence := state.confidence
 	if effectiveSource == nil && state.start != nil && state.end != nil {
 		effectiveSource = legacySharedSource
+		if effectiveConfidence == nil {
+			effectiveConfidence = legacySharedConfidence
+		}
 	}
-	if !markers.CanWriteMarker(effectiveSource, state.confidence, source, confidence) {
+	if !markers.CanWriteMarker(effectiveSource, effectiveConfidence, source, confidence) {
 		return false, nil
 	}

and pass state.existingConfidence from applyMarkerUpdateToMutationState.

🤖 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/scanner/file_repo.go` around lines 1026 - 1031, The priority check
is using state.confidence even when effectiveSource is set to
legacySharedSource, which drops the legacy shared confidence; change the
CanWriteMarker call to pass state.existingConfidence when effectiveSource ==
legacySharedSource (i.e. preserve the carried-forward legacy confidence), and
ensure applyMarkerUpdateToMutationState populates state.existingConfidence
appropriately so markers.CanWriteMarker(effectiveSource, appropriateConfidence,
source, confidence) receives the legacy confidence instead of nil.
🤖 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 `@web/src/player/components/SeekBar.tsx`:
- Around line 43-48: Replace the duplicated MARKER_LABELS in SeekBar.tsx with a
single shared source: move the label map currently defined in useMarkerEditor.ts
(the map keyed by MarkerKind) into a new utility under web/src/lib or
web/src/utils (e.g., export getMarkerLabels or MARKER_LABELS constant), then
import and use that shared symbol in both useMarkerEditor (where it currently
lives) and SeekBar.tsx (replace the local MARKER_LABELS), and also update the
live-drag tooltip rendering path to consume the same label map so both hover
tooltip and drag tooltip show identical, centralized labels.

---

Outside diff comments:
In `@internal/scanner/file_repo.go`:
- Around line 1143-1189: Snapshot the original segment states immediately after
loadMarkerMutationState (store copies of state.intro, state.credits,
state.recap, state.preview), then apply applyMarkerUpdateToMutationState and
clearSegmentState as before, but DO NOT set markerSegmentFlags based on the
requested ops; after all mutations compute each changed flag by comparing the
original snapshot to the final state using segmentEqual (e.g. changed.intro =
!segmentEqual(originalIntro, state.intro), etc.), and only call
writeMarkerMutationState / commit when changed.any() is true so unchanged,
idempotent operations do not update timestamps or write.
- Around line 1026-1031: The priority check is using state.confidence even when
effectiveSource is set to legacySharedSource, which drops the legacy shared
confidence; change the CanWriteMarker call to pass state.existingConfidence when
effectiveSource == legacySharedSource (i.e. preserve the carried-forward legacy
confidence), and ensure applyMarkerUpdateToMutationState populates
state.existingConfidence appropriately so
markers.CanWriteMarker(effectiveSource, appropriateConfidence, source,
confidence) receives the legacy confidence instead of nil.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0a24e6b2-eae9-4d10-a8c0-1cf3d11f6575

📥 Commits

Reviewing files that changed from the base of the PR and between dc26c1d and 0cec001.

📒 Files selected for processing (2)
  • internal/scanner/file_repo.go
  • web/src/player/components/SeekBar.tsx

Comment on lines +43 to +48
const MARKER_LABELS: Record<MarkerKind, string> = {
intro: "Intro",
recap: "Recap",
credits: "Credits / Outro",
preview: "Preview",
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use one shared label source for marker kinds.

This adds a second MARKER_LABELS map even though web/src/player/hooks/useMarkerEditor.ts:10-15 already defines the same labels, and only this hover tooltip uses it. The live drag tooltip still renders the raw enum (credits, preview, etc.), so the same marker kind already shows different copy within the editor. Please centralize the labels and consume that shared source in both tooltip paths.

As per coding guidelines, "keep shared utilities in web/src/lib or web/src/utils".

Also applies to: 311-323

🤖 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/player/components/SeekBar.tsx` around lines 43 - 48, Replace the
duplicated MARKER_LABELS in SeekBar.tsx with a single shared source: move the
label map currently defined in useMarkerEditor.ts (the map keyed by MarkerKind)
into a new utility under web/src/lib or web/src/utils (e.g., export
getMarkerLabels or MARKER_LABELS constant), then import and use that shared
symbol in both useMarkerEditor (where it currently lives) and SeekBar.tsx
(replace the local MARKER_LABELS), and also update the live-drag tooltip
rendering path to consume the same label map so both hover tooltip and drag
tooltip show identical, centralized labels.

Source: Coding guidelines

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/api/handlers/markers.go (1)

374-410: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Reject unknown marker keys instead of silently no-oping them.

This loop only processes the four known segment names, so a body like {"outtro": {...}} returns 200 with no mutation. That makes client typos look successful.

Suggested fix
 	var raw map[string]json.RawMessage
 	if err := json.NewDecoder(r.Body).Decode(&raw); err != nil {
 		writeError(w, http.StatusBadRequest, "bad_request", "Invalid request body")
 		return
 	}
+	for key := range raw {
+		if !isMarkerSegment(key) {
+			writeError(w, http.StatusBadRequest, "bad_request", "Unknown marker segment "+key)
+			return
+		}
+	}
 
 	duration := float64(file.Duration)
🤖 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/api/handlers/markers.go` around lines 374 - 410, The handler
currently decodes the request into raw (map[string]json.RawMessage) and only
iterates known markerSegmentNames, silently ignoring any unknown keys; change
the validation so after decoding raw you iterate the keys in raw and reject
(writeError 400) any key that is not in markerSegmentNames (or allowed keys like
other known fields), before proceeding to parse segments and using
normalizeManualSegment/applyManualSegment; reference raw, markerSegmentNames,
normalizeManualSegment, and applyManualSegment to locate where to add the
unknown-key check and return a bad_request when an unexpected key is present.
🧹 Nitpick comments (1)
migrations/183_marker_edit_audit.up.sql (1)

1-2: permissions column DEFAULT is overwritten by migration 183 (not extended).

ALTER COLUMN permissions SET DEFAULT ARRAY['marker_edit']::text[] replaces the entire default. In this repo the prior default was '{}'::text[] (migrations/001_schema.up.sql, migrations/140_user_permissions.up.sql), and the down migration resets it back to '{}'::text[]. If future migrations need the default to include additional permissions, this will override that baseline—consider concatenating/preserving existing defaults if that’s the intent.

🤖 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 `@migrations/183_marker_edit_audit.up.sql` around lines 1 - 2, The migration
overwrites the users.permissions default (ALTER COLUMN permissions SET DEFAULT
ARRAY['marker_edit']::text[]) instead of extending it; update
migrations/183_marker_edit_audit.up.sql so the default preserves existing
entries and appends 'marker_edit' (use array concatenation/array_cat with
COALESCE to handle NULL or '{}' defaults) rather than replacing the whole
default, and ensure the down migration restores the previous baseline default
('{}'::text[]) as intended.
🤖 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 `@internal/api/handlers/markers.go`:
- Around line 298-300: The current permission check collapses GetByID errors
into a 403; change the logic in the markers handler so that when
h.Users.GetByID(ctx, claims.UserID) returns a non-nil err you return a 500 via
writeError (internal server error) and only treat user == nil or
!auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) as a 403;
specifically update the block that calls h.Users.GetByID,
auth.HasEffectivePermission, and writeError so errors from GetByID are handled
and logged/returned as a 500 while real permission failures remain 403.

In `@web/src/components/markers/MarkerEditor.tsx`:
- Around line 76-79: The current MarkerEditor passes history={isAdmin ?
(history.data ?? []) : []} which masks fetch errors from useItemMarkerHistory
and shows a false empty audit log; update MarkerEditor to detect history.error
(from useItemMarkerHistory) and avoid passing an empty array on error—e.g., pass
undefined or null for history and set historyLoading/showHistory appropriately,
and surface an error prop or conditional UI for MarkerHistory so 403/500
responses are shown as an error state instead of "No marker edits recorded.";
ensure updates reference the useItemMarkerHistory return (history.data,
history.isLoading, history.error) and the MarkerHistory props (history,
historyLoading, showHistory, and/or add an error prop).

In `@web/src/pages/AdminUserDetail.tsx`:
- Around line 284-291: The UI is using hasAssignedPermission(user.permissions,
PERMISSION_MARKER_EDIT) which only checks explicit assignment and can show
admins as "Not allowed"; replace that check with the effective-permission helper
(e.g. hasEffectivePermission or userHasEffectivePermission) so the Marker
Editing row uses hasEffectivePermission(user, PERMISSION_MARKER_EDIT) (or the
equivalent app utility) instead of hasAssignedPermission, and update the other
similar rows (lines ~1011-1027) to use the same effective-permission function.

---

Outside diff comments:
In `@internal/api/handlers/markers.go`:
- Around line 374-410: The handler currently decodes the request into raw
(map[string]json.RawMessage) and only iterates known markerSegmentNames,
silently ignoring any unknown keys; change the validation so after decoding raw
you iterate the keys in raw and reject (writeError 400) any key that is not in
markerSegmentNames (or allowed keys like other known fields), before proceeding
to parse segments and using normalizeManualSegment/applyManualSegment; reference
raw, markerSegmentNames, normalizeManualSegment, and applyManualSegment to
locate where to add the unknown-key check and return a bad_request when an
unexpected key is present.

---

Nitpick comments:
In `@migrations/183_marker_edit_audit.up.sql`:
- Around line 1-2: The migration overwrites the users.permissions default (ALTER
COLUMN permissions SET DEFAULT ARRAY['marker_edit']::text[]) instead of
extending it; update migrations/183_marker_edit_audit.up.sql so the default
preserves existing entries and appends 'marker_edit' (use array
concatenation/array_cat with COALESCE to handle NULL or '{}' defaults) rather
than replacing the whole default, and ensure the down migration restores the
previous baseline default ('{}'::text[]) as intended.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6de207e6-0844-41da-811d-bf1e7d33df64

📥 Commits

Reviewing files that changed from the base of the PR and between 0cec001 and a8bf4f9.

📒 Files selected for processing (35)
  • internal/api/handlers/admin.go
  • internal/api/handlers/markers.go
  • internal/api/handlers/markers_test.go
  • internal/api/router.go
  • internal/auth/permissions.go
  • internal/auth/permissions_test.go
  • internal/auth/repository.go
  • internal/scanner/file_repo.go
  • internal/scanner/file_repo_test.go
  • internal/scanner/marker_audit.go
  • migrations/183_marker_edit_audit.down.sql
  • migrations/183_marker_edit_audit.up.sql
  • web/src/App.tsx
  • web/src/api/types.ts
  • web/src/components/AdminSidebar.test.tsx
  • web/src/components/AdminSidebar.tsx
  • web/src/components/markers/MarkerEditor.tsx
  • web/src/hooks/queries/admin/markers.ts
  • web/src/hooks/queries/keys.ts
  • web/src/hooks/queries/markers.ts
  • web/src/lib/documentTitle.ts
  • web/src/lib/permissions.test.ts
  • web/src/lib/permissions.ts
  • web/src/pages/AdminMarkerHistory.tsx
  • web/src/pages/AdminUserDetail.tsx
  • web/src/pages/AdminUsers.tsx
  • web/src/pages/ItemDetail/EpisodeContent.tsx
  • web/src/pages/ItemDetail/MovieContent.test.tsx
  • web/src/pages/ItemDetail/MovieContent.tsx
  • web/src/playback/WatchPlaybackChrome.tsx
  • web/src/player/components/PlayerControls.test.tsx
  • web/src/player/components/VideoPlayer.tsx
  • web/src/player/components/WatchPage.tsx
  • web/src/player/hooks/useMarkerEditor.ts
  • web/src/player/types.ts
✅ Files skipped from review due to trivial changes (3)
  • web/src/lib/permissions.test.ts
  • migrations/183_marker_edit_audit.down.sql
  • web/src/api/types.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • web/src/pages/ItemDetail/EpisodeContent.tsx
  • web/src/player/types.ts
  • web/src/player/components/WatchPage.tsx
  • web/src/hooks/queries/admin/markers.ts
  • web/src/player/components/VideoPlayer.tsx
  • internal/api/router.go

Comment on lines +298 to +300
user, err := h.Users.GetByID(r.Context(), claims.UserID)
if err != nil || user == nil || !auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) {
writeError(w, http.StatusForbidden, "forbidden", "Marker editing permission required")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Return 500 when the permission lookup itself fails.

Line 298 collapses h.Users.GetByID(...) failures into the same 403 path as a real permission miss. A transient user-store error will deny valid editors with a misleading auth response.

Suggested fix
 	user, err := h.Users.GetByID(r.Context(), claims.UserID)
-	if err != nil || user == nil || !auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) {
+	if err != nil {
+		h.logger.Error("markers: load permission user failed", "user_id", claims.UserID, "error", err)
+		writeError(w, http.StatusInternalServerError, "internal_error", "Failed to verify marker editing permission")
+		return false
+	}
+	if user == nil || !auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) {
 		writeError(w, http.StatusForbidden, "forbidden", "Marker editing permission required")
 		return false
 	}
📝 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.

Suggested change
user, err := h.Users.GetByID(r.Context(), claims.UserID)
if err != nil || user == nil || !auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) {
writeError(w, http.StatusForbidden, "forbidden", "Marker editing permission required")
user, err := h.Users.GetByID(r.Context(), claims.UserID)
if err != nil {
h.logger.Error("markers: load permission user failed", "user_id", claims.UserID, "error", err)
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to verify marker editing permission")
return false
}
if user == nil || !auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) {
writeError(w, http.StatusForbidden, "forbidden", "Marker editing permission required")
return false
}
🤖 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/api/handlers/markers.go` around lines 298 - 300, The current
permission check collapses GetByID errors into a 403; change the logic in the
markers handler so that when h.Users.GetByID(ctx, claims.UserID) returns a
non-nil err you return a 500 via writeError (internal server error) and only
treat user == nil or !auth.HasEffectivePermission(user,
auth.PermissionMarkerEdit) as a 403; specifically update the block that calls
h.Users.GetByID, auth.HasEffectivePermission, and writeError so errors from
GetByID are handled and logged/returned as a 500 while real permission failures
remain 403.

Comment on lines +76 to +79
history={isAdmin ? (history.data ?? []) : []}
historyLoading={isAdmin && history.isLoading}
showHistory={isAdmin}
onClose={() => onOpenChange(false)}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Don't render history fetch failures as an empty audit log.

If useItemMarkerHistory errors, this falls back to [] and MarkerHistory shows No marker edits recorded. Admins will see a false empty state for 403/500s.

Suggested fix
           <MarkerEditorForm
             key={data.file_id}
             itemId={itemId}
             data={data}
             history={isAdmin ? (history.data ?? []) : []}
             historyLoading={isAdmin && history.isLoading}
+            historyError={isAdmin && history.isError}
             showHistory={isAdmin}
             onClose={() => onOpenChange(false)}
           />
@@
   history,
   historyLoading,
+  historyError,
   showHistory,
   onClose,
 }: {
   itemId: string;
   data: FileMarkersResponse;
   history: MarkerEditAuditEntry[];
   historyLoading: boolean;
+  historyError: boolean;
   showHistory: boolean;
   onClose: () => void;
 }) {
@@
-      {showHistory && <MarkerHistory rows={history} isLoading={historyLoading} />}
+      {showHistory && (
+        <MarkerHistory rows={history} isLoading={historyLoading} isError={historyError} />
+      )}
@@
-function MarkerHistory({ rows, isLoading }: { rows: MarkerEditAuditEntry[]; isLoading: boolean }) {
+function MarkerHistory({
+  rows,
+  isLoading,
+  isError,
+}: {
+  rows: MarkerEditAuditEntry[];
+  isLoading: boolean;
+  isError: boolean;
+}) {
   return (
     <div className="border-border mt-2 border-t pt-3">
@@
-      {rows.length === 0 && !isLoading ? (
+      {isError ? (
+        <p className="text-destructive text-sm">Failed to load recent marker changes.</p>
+      ) : rows.length === 0 && !isLoading ? (
         <p className="text-muted-foreground text-sm">No marker edits recorded.</p>
       ) : (

Also applies to: 202-235

🤖 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/components/markers/MarkerEditor.tsx` around lines 76 - 79, The
current MarkerEditor passes history={isAdmin ? (history.data ?? []) : []} which
masks fetch errors from useItemMarkerHistory and shows a false empty audit log;
update MarkerEditor to detect history.error (from useItemMarkerHistory) and
avoid passing an empty array on error—e.g., pass undefined or null for history
and set historyLoading/showHistory appropriately, and surface an error prop or
conditional UI for MarkerHistory so 403/500 responses are shown as an error
state instead of "No marker edits recorded."; ensure updates reference the
useItemMarkerHistory return (history.data, history.isLoading, history.error) and
the MarkerHistory props (history, historyLoading, showHistory, and/or add an
error prop).

Comment on lines +284 to +291
<DetailRow
label="Marker Editing"
value={
hasAssignedPermission(user.permissions, PERMISSION_MARKER_EDIT)
? "Allowed"
: "Not allowed"
}
/>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use effective marker-edit permission semantics for admin users.

Backend auth grants marker_edit to every admin via HasEffectivePermission, but these branches only check explicit assignment. Admins can therefore show as Not allowed here and get a toggle that doesn't reflect runtime behavior.

Suggested fix
-          <DetailRow
-            label="Marker Editing"
-            value={
-              hasAssignedPermission(user.permissions, PERMISSION_MARKER_EDIT)
-                ? "Allowed"
-                : "Not allowed"
-            }
-          />
+          <DetailRow
+            label="Marker Editing"
+            value={
+              user.role === "admin" ||
+              hasAssignedPermission(user.permissions, PERMISSION_MARKER_EDIT)
+                ? "Allowed"
+                : "Not allowed"
+            }
+          />
+  const markerEditAllowed =
+    role === "admin" || hasAssignedPermission(permissions, PERMISSION_MARKER_EDIT);
+
             <div className="border-border flex items-center justify-between rounded-md border px-3 py-2">
               <div>
                 <Label htmlFor={markerEditId}>Marker Editing</Label>
                 <p className="text-muted-foreground text-xs">
                   Edit intro, recap, credits, and preview markers within assigned libraries.
                 </p>
               </div>
               <Switch
                 id={markerEditId}
-                checked={hasAssignedPermission(permissions, PERMISSION_MARKER_EDIT)}
+                checked={markerEditAllowed}
+                disabled={role === "admin"}
                 onCheckedChange={(checked) =>
                   setPermissions((current) =>
                     setAssignedPermission(current, PERMISSION_MARKER_EDIT, checked),
                   )
                 }
               />
             </div>

Also applies to: 1011-1027

🤖 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/AdminUserDetail.tsx` around lines 284 - 291, The UI is using
hasAssignedPermission(user.permissions, PERMISSION_MARKER_EDIT) which only
checks explicit assignment and can show admins as "Not allowed"; replace that
check with the effective-permission helper (e.g. hasEffectivePermission or
userHasEffectivePermission) so the Marker Editing row uses
hasEffectivePermission(user, PERMISSION_MARKER_EDIT) (or the equivalent app
utility) instead of hasAssignedPermission, and update the other similar rows
(lines ~1011-1027) to use the same effective-permission function.

@Quick104
Quick104 merged commit b6e4027 into main Jun 7, 2026
5 checks passed
@Quick104
Quick104 deleted the feat/introdb-marker-integration branch June 7, 2026 02:29
Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
… refinement (Silo-Server#57)

* docs(markers): design + implementation plans for multi-source markers & TheIntroDB contribution

* fix(markers): TheIntroDB read-path correctness (TVDB, real confidence, best candidate)

Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first
libraries got no markers), decode and use the real per-segment confidence and
submission_count instead of a hardcoded 0.9, and pick the most-submitted /
highest-confidence candidate when several are returned. Adds httptest coverage
for the introdb client and provider.

Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): multi-source dispatch, per-provider config, per-segment provenance

Add marker_provider_config (per-provider fetch enable/priority + contribute
gates, contribution off by default) and a cached ProviderConfigStore. Add
Registry.FetchMerged: query all fetch-enabled providers concurrently and keep
the best candidate per segment (submission_count, then confidence, then fetch
priority), stamping each winning marker with its provider/algorithm. Thread
per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate
(additive SegmentProvenance overrides) so a merged result writes correct
per-segment provider/confidence/algorithm; the legacy shared columns keep a
summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB
enabled, behavior is unchanged.

Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): TheIntroDB submission client, contribution audit, service engine

Add a markers.Submitter capability and implement it on the introdb provider
(POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies
the null start/end conventions). Add the marker_contributions audit table and a
value-hash-keyed ContributionStore for idempotency. Add ContributionService:
resolves enabled submitter providers, gates eligibility (never re-submit
online-sourced markers; auto runs require contribute_auto_local + scanner-intro
above the per-provider confidence threshold), checks idempotency, submits, and
records. Wired in main.go; no trigger yet (admin API and task follow).

Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(api): admin marker editing, contribution, and provider config endpoints

Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with
provenance; manual upsert where a segment object sets and null clears),
DELETE .../markers/{segment}, POST .../contribute and GET .../contributions,
plus GET/PUT /admin/markers/providers[/{provider}] and a
.../validate key-check returning user stats. Manual writes go through the
priority-gated UpsertMarkers (source=manual) and notify live sessions; a new
FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the
contribution rules.

Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): daily auto-contribution task for local intro markers

Add ContributeMarkersTask (daily 04:00, after local detection): when a provider
has contribute_enabled + contribute_auto_local, page through episode files with
a scanner intro marker at/above the provider's confidence threshold (new
ContributionStore.CandidateLocalIntroFiles keyset query) and run them through
ContributionService with Auto=true. No-op when no provider opts in; idempotent
and resumable across runs.

Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(intromarkers): refine chromaprint starts with dialogue cues

* feat(markers): finish marker management backend

* feat(web): add marker editing UI

* feat(markers): use plugin marker providers

* fix(markers): address PR review feedback

* feat(player): show marker labels on seek hover

* fix(markers): type nullable marker mutation params

* feat(markers): audit marker edits and add permission

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Quick104 added a commit that referenced this pull request Jun 11, 2026
… refinement (#57)

* docs(markers): design + implementation plans for multi-source markers & TheIntroDB contribution

* fix(markers): TheIntroDB read-path correctness (TVDB, real confidence, best candidate)

Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first
libraries got no markers), decode and use the real per-segment confidence and
submission_count instead of a hardcoded 0.9, and pick the most-submitted /
highest-confidence candidate when several are returned. Adds httptest coverage
for the introdb client and provider.

Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): multi-source dispatch, per-provider config, per-segment provenance

Add marker_provider_config (per-provider fetch enable/priority + contribute
gates, contribution off by default) and a cached ProviderConfigStore. Add
Registry.FetchMerged: query all fetch-enabled providers concurrently and keep
the best candidate per segment (submission_count, then confidence, then fetch
priority), stamping each winning marker with its provider/algorithm. Thread
per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate
(additive SegmentProvenance overrides) so a merged result writes correct
per-segment provider/confidence/algorithm; the legacy shared columns keep a
summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB
enabled, behavior is unchanged.

Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): TheIntroDB submission client, contribution audit, service engine

Add a markers.Submitter capability and implement it on the introdb provider
(POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies
the null start/end conventions). Add the marker_contributions audit table and a
value-hash-keyed ContributionStore for idempotency. Add ContributionService:
resolves enabled submitter providers, gates eligibility (never re-submit
online-sourced markers; auto runs require contribute_auto_local + scanner-intro
above the per-provider confidence threshold), checks idempotency, submits, and
records. Wired in main.go; no trigger yet (admin API and task follow).

Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(api): admin marker editing, contribution, and provider config endpoints

Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with
provenance; manual upsert where a segment object sets and null clears),
DELETE .../markers/{segment}, POST .../contribute and GET .../contributions,
plus GET/PUT /admin/markers/providers[/{provider}] and a
.../validate key-check returning user stats. Manual writes go through the
priority-gated UpsertMarkers (source=manual) and notify live sessions; a new
FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the
contribution rules.

Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): daily auto-contribution task for local intro markers

Add ContributeMarkersTask (daily 04:00, after local detection): when a provider
has contribute_enabled + contribute_auto_local, page through episode files with
a scanner intro marker at/above the provider's confidence threshold (new
ContributionStore.CandidateLocalIntroFiles keyset query) and run them through
ContributionService with Auto=true. No-op when no provider opts in; idempotent
and resumable across runs.

Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(intromarkers): refine chromaprint starts with dialogue cues

* feat(markers): finish marker management backend

* feat(web): add marker editing UI

* feat(markers): use plugin marker providers

* fix(markers): address PR review feedback

* feat(player): show marker labels on seek hover

* fix(markers): type nullable marker mutation params

* feat(markers): audit marker edits and add permission

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Quick104 added a commit that referenced this pull request Jun 17, 2026
… refinement (#57)

* docs(markers): design + implementation plans for multi-source markers & TheIntroDB contribution

* fix(markers): TheIntroDB read-path correctness (TVDB, real confidence, best candidate)

Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first
libraries got no markers), decode and use the real per-segment confidence and
submission_count instead of a hardcoded 0.9, and pick the most-submitted /
highest-confidence candidate when several are returned. Adds httptest coverage
for the introdb client and provider.

Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): multi-source dispatch, per-provider config, per-segment provenance

Add marker_provider_config (per-provider fetch enable/priority + contribute
gates, contribution off by default) and a cached ProviderConfigStore. Add
Registry.FetchMerged: query all fetch-enabled providers concurrently and keep
the best candidate per segment (submission_count, then confidence, then fetch
priority), stamping each winning marker with its provider/algorithm. Thread
per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate
(additive SegmentProvenance overrides) so a merged result writes correct
per-segment provider/confidence/algorithm; the legacy shared columns keep a
summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB
enabled, behavior is unchanged.

Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): TheIntroDB submission client, contribution audit, service engine

Add a markers.Submitter capability and implement it on the introdb provider
(POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies
the null start/end conventions). Add the marker_contributions audit table and a
value-hash-keyed ContributionStore for idempotency. Add ContributionService:
resolves enabled submitter providers, gates eligibility (never re-submit
online-sourced markers; auto runs require contribute_auto_local + scanner-intro
above the per-provider confidence threshold), checks idempotency, submits, and
records. Wired in main.go; no trigger yet (admin API and task follow).

Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(api): admin marker editing, contribution, and provider config endpoints

Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with
provenance; manual upsert where a segment object sets and null clears),
DELETE .../markers/{segment}, POST .../contribute and GET .../contributions,
plus GET/PUT /admin/markers/providers[/{provider}] and a
.../validate key-check returning user stats. Manual writes go through the
priority-gated UpsertMarkers (source=manual) and notify live sessions; a new
FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the
contribution rules.

Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): daily auto-contribution task for local intro markers

Add ContributeMarkersTask (daily 04:00, after local detection): when a provider
has contribute_enabled + contribute_auto_local, page through episode files with
a scanner intro marker at/above the provider's confidence threshold (new
ContributionStore.CandidateLocalIntroFiles keyset query) and run them through
ContributionService with Auto=true. No-op when no provider opts in; idempotent
and resumable across runs.

Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(intromarkers): refine chromaprint starts with dialogue cues

* feat(markers): finish marker management backend

* feat(web): add marker editing UI

* feat(markers): use plugin marker providers

* fix(markers): address PR review feedback

* feat(player): show marker labels on seek hover

* fix(markers): type nullable marker mutation params

* feat(markers): audit marker edits and add permission

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Quick104 added a commit that referenced this pull request Jun 17, 2026
… refinement (#57)

* docs(markers): design + implementation plans for multi-source markers & TheIntroDB contribution

* fix(markers): TheIntroDB read-path correctness (TVDB, real confidence, best candidate)

Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first
libraries got no markers), decode and use the real per-segment confidence and
submission_count instead of a hardcoded 0.9, and pick the most-submitted /
highest-confidence candidate when several are returned. Adds httptest coverage
for the introdb client and provider.

Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): multi-source dispatch, per-provider config, per-segment provenance

Add marker_provider_config (per-provider fetch enable/priority + contribute
gates, contribution off by default) and a cached ProviderConfigStore. Add
Registry.FetchMerged: query all fetch-enabled providers concurrently and keep
the best candidate per segment (submission_count, then confidence, then fetch
priority), stamping each winning marker with its provider/algorithm. Thread
per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate
(additive SegmentProvenance overrides) so a merged result writes correct
per-segment provider/confidence/algorithm; the legacy shared columns keep a
summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB
enabled, behavior is unchanged.

Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): TheIntroDB submission client, contribution audit, service engine

Add a markers.Submitter capability and implement it on the introdb provider
(POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies
the null start/end conventions). Add the marker_contributions audit table and a
value-hash-keyed ContributionStore for idempotency. Add ContributionService:
resolves enabled submitter providers, gates eligibility (never re-submit
online-sourced markers; auto runs require contribute_auto_local + scanner-intro
above the per-provider confidence threshold), checks idempotency, submits, and
records. Wired in main.go; no trigger yet (admin API and task follow).

Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(api): admin marker editing, contribution, and provider config endpoints

Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with
provenance; manual upsert where a segment object sets and null clears),
DELETE .../markers/{segment}, POST .../contribute and GET .../contributions,
plus GET/PUT /admin/markers/providers[/{provider}] and a
.../validate key-check returning user stats. Manual writes go through the
priority-gated UpsertMarkers (source=manual) and notify live sessions; a new
FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the
contribution rules.

Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(markers): daily auto-contribution task for local intro markers

Add ContributeMarkersTask (daily 04:00, after local detection): when a provider
has contribute_enabled + contribute_auto_local, page through episode files with
a scanner intro marker at/above the provider's confidence threshold (new
ContributionStore.CandidateLocalIntroFiles keyset query) and run them through
ContributionService with Auto=true. No-op when no provider opts in; idempotent
and resumable across runs.

Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(intromarkers): refine chromaprint starts with dialogue cues

* feat(markers): finish marker management backend

* feat(web): add marker editing UI

* feat(markers): use plugin marker providers

* fix(markers): address PR review feedback

* feat(player): show marker labels on seek hover

* fix(markers): type nullable marker mutation params

* feat(markers): audit marker edits and add permission

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Quick104 added a commit that referenced this pull request Nov 5, 2026
…changes

The SDK commit merges the final heads of Silo-Server/silo-plugin-sdk
#57-#62: the event catalog, scoped host API keys, notification channels,
conditional instance state writes, default task schedules and host
viewer headers. Plugin event names now need a publisher and an event
name; every name the server uses already has both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant