Skip to content

feat(policy): access groups + embedded OPA policy engine with decision audit log - #282

Merged
Quick104 merged 46 commits into
mainfrom
claude/wizardly-jepsen-f6f5ea
Jul 5, 2026
Merged

Quick104 merged 46 commits into
mainfrom
claude/wizardly-jepsen-f6f5ea

Conversation

@Quick104

@Quick104 Quick104 commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Part of #272

Problem

Silo's authorization logic is scattered across hand-rolled Go: access.Resolver for viewer scope, ad hoc middleware for admin/permission gates, inline checks for downloads and playback admission — with the library/rating predicate logic duplicated and no way for admins to express rules beyond the fixed schema (schedules, per-collection exceptions, device rules), and no audit trail of authorization decisions.

Approach

Embed OPA (github.com/open-policy-agent/opa/v1/rego, no sidecar) as the single policy engine. The full design rationale, contracts, and rollout strategy are in the committed docs:

  • Spec: docs/superpowers/specs/2026-07-02-opa-policy-engine-design.md
  • Plan: docs/superpowers/plans/2026-07-02-opa-policy-engine.md

Highlights:

  • Vendor Rego ships in the binary (go:embed) and reproduces today's behavior exactly; admin-authored policies live in Postgres as immutable versions with activate/rollback and compile-check-before-persist.
  • Narrowing-only override contract: vendor rules consult data.silo_custom.<domain>.override(base_decision, input) and merge only in the tightening direction (intersect libraries, min ceilings, AND booleans) — a custom policy can restrict, never widen. Sandbox: capabilities lockdown (no http.send/net.*/opa.runtime), 25ms eval timeout, enforced package namespace, one enabled document per domain.
  • Three surfaces cut over (direct replacement, per the approved plan): viewer scope resolution (all five resolver construction sites incl. jellycompat + ABS), acting-admin + marker_edit/metadata_curation gates, and download/transcode/playback-admission decisions. PIN crypto, session counting, config loading, and preset enumeration stay in Go — the policy decides given facts.
  • Admin Policy workspace (/admin/policy): CodeMirror Rego editor with inline compile diagnostics, explicit save-version vs activate flow, vendor viewer, simulate panel, version history with rollback, decision-log browser. Capability endpoint GET /api/v1/policy/capability.
  • Decision audit log: partitioned policy_decisions (partman daily), async batched writer that never blocks a decision, 1-in-50 scope sampling with denials/errors always logged, retention task.
  • Multi-node: EventPolicyChanged on the existing admin channel + a generation-poll fallback; activation reloads the local engine synchronously and converges other nodes.

Verification

  • Parity is the gate for the direct replacement: 1368-case dual-execution battery for scope (incl. the nil-vs-empty AllowedLibraryIDs boundary and quality/rating variation), dual-middleware tests asserting byte-equal HTTP responses for the permission gates, and combination tables against the real downloads/playback logic. Legacy implementations stay compiled as the reference; deletion is a follow-up after bake (plan Phase 10).
  • Full go test ./... green except two documented pre-existing failures (jellycompat TestBeginWebOperation*, one playback GPU probe) — confirmed identical on main.
  • DB-backed suites (store atomicity, decision-log pagination, cross-node convergence incl. poll fallback, degraded vendor-only boot, last-known-good reload) run against a migrated Postgres.
  • make lint-equivalent (golangci v2) clean on all touched packages; cd web && pnpm run lint && pnpm run format:check && pnpm run build green; make verify-local-paths green.
  • Live end-to-end exercise against a running server: capability → create document → validate (caught a real Rego error with row/col) → save version → activate (generation bump + engine reload) → authenticated requests green with the custom policy active → simulate day/night schedule behavior.
  • Scope decision benchmark: ~106µs/op including input marshaling (budget: 200µs).

Screenshots

The admin UI is fully test-covered (vitest) and was exercised against the live API, but browser screenshots are pending — the local Docker VM wedged (disk pressure) at the end of the run. Will follow up with screenshots in a comment.

Risks / follow-ups

  • Direct replacement has no runtime fallback by design; the per-surface cutover commits are individually revertable and legacy code paths still exist for policy-less wiring (proxy modes).
  • Follow-ups (tracked in the spec's Deferred section): delete legacy implementations after a release of bake, repeated-eval-timeout circuit breaker, persisted policy test suites, elevated (widening) override path, compile-to-SQL list filtering, plugin route gating.
  • Client repos need no changes (server-side enforcement only; capability endpoint exists for future client awareness).

AI-use disclosure

Implementation diffs were written by OpenAI Codex (GPT-5.5) via codex exec, orchestrated phase-by-phase from the committed plan by Claude (Fable 5), which authored the spec/plan/briefs, reviewed every diff line-by-line, rejected and redirected one design deviation (a reflection-based hot-path adapter), fixed several issues directly (module tidy ordering, lint findings, a tsc -b type error, test seeding), and ran all verification. Commit messages note per-commit attribution.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added an Admin Policy area to view, edit, validate, simulate, and browse policy decisions and logs.
    • Introduced policy-driven authorization for viewer scope, metadata curation, download access, and playback admission (fail-closed on evaluation issues).
    • Added Admin Access Groups management with group-aware policy layering.
    • Added policy decision logging controls (verbosity, sampling, retention) plus scheduled cleanup.
  • Bug Fixes
    • Improved parity between legacy and policy-backed authorization flows, including consistent permission/validation behavior and session admission limits.

Update — Access Groups become the everyday surface

Review feedback (rightly) found the Rego editor too low-level to be the primary admin interface — asking a household admin to write policy code to cap a kid's rating is the wrong altitude. The OPA engine was the right infrastructure call and the wrong interface call. This PR now ships the interface most admins actually want, on top of the same engine:

  • Access Groups (/admin/access-groups): named groups ("Users", "Kids", "Guests") carrying shared defaults — library access, playback-quality ceiling, downloads, transcoded downloads, concurrent-stream/transcode limits, an assignable-permissions mask, and media requests. Users get a Group picker on their profile.
  • Restriction-only composition: a group grants the most a member can do; the member's own settings still apply on top and can only tighten further (library intersection, MinQuality, AND'd booleans, strictest positive limits, permission-mask intersection). This is the same "strictest layer wins" rule the account/profile merge already used, extended one layer up — no confusing inherit-vs-override tri-state. No group = exactly today's behavior; existing users are untouched.
  • The merge happens in Go (access.ApplyGroupPolicy) before policy inputs are built, so the vendor Rego, the parity suites, and the decision-log pipeline are all unchanged — groups are just data flowing into the existing engine. Every enforcement surface (both resolvers, permission gates, downloads, playback admission, and now request creation) consumes the effective policy and fails closed on provider errors.
  • The Rego editor is demoted to advanced: a new policy.editor_enabled server setting (default off, hot-reloaded) hides the Policy page and 403-gates its editor endpoints. The engine and decision logging keep running regardless. It stays available for the rare power user who wants time-of-day or per-collection rules the group toggles can't express.

Design addendum: docs/superpowers/specs/2026-07-02-access-groups-design.md.

Verification (groups)

Composition core has table-driven unit tests including a pinned no-group regression (behavior byte-identical to today); enforcement tests cover library intersection, stricter stream limits, download/request denial, and permission masking through the real resolvers. Frontend: 25 tests across the touched suites, tsc, eslint, prettier, and a production build. Pending: the DB-backed group-store integration tests (CRUD, member counts, quality-change revision bump) haven't run yet — the local Postgres VM is wedged; they'll run before merge.

Deferred (groups)

Multiple groups per user, per-user grants above a group, per-group request quotas, and group-scoped custom Rego.

Default group (follow-up commit pair)

A seeded "Default Group" is auto-assigned to newly created users. access_groups.is_default (partial unique index — at most one default, same pattern as profile is_primary) anchors the behavior in schema rather than name-magic; the seeded group ships with house-rule ceilings (5 streams, 5 transcodes, transcoded downloads off, metadata curation masked out; libraries, plain downloads, and requests unrestricted) — existing non-admin users are migrated into it on upgrade (see below). Assignment happens inside the single INSERT INTO users choke point via a scalar subquery, covering setup/signup/invites/OAuth/admin-create by construction; explicit assignment wins, and deleting or unsetting the default cleanly reverts new users to "no group" (pre-feature behavior). The Groups UI shows a Default badge and a "Default for new users" toggle.

User Defaults retired

The legacy "user defaults" (users-table column defaults of 6 streams / 2 transcodes, plus the defaults.* server settings whose only consumer was the Users page's prefill dialog) are removed — the Default Group is now the sole source of default policy. New user rows start unrestricted at the user layer (0 = no restriction), so group ceilings apply cleanly instead of being beaten by stale per-user numbers. Per-user fields remain as the tightening layer for individual users.

Existing users migrate into the Default Group

A follow-up migration moves all existing non-admin users into the seeded Default Group, normalizing per-user limits that still hold the retired 6/2 column defaults to 0 (deliberately customized values are preserved) so the group's ceilings actually govern. Admins stay ungrouped: scope/action decisions are role-blind, so grouping an admin would cap the server owner on upgrade — the planned follow-up is to exempt role = admin from group binding at composition, after which admins can be grouped harmlessly. Net effect: the whole instance is governed by one policy source, and "no group" survives only as the admin/root state.

Quick104 and others added 13 commits July 2, 2026 11:06
Pulls github.com/open-policy-agent/opa v1.18.2 (policy engine core for
the upcoming internal/policy subsystem) and the transitive upgrades go
mod tidy applied (otel 1.44, grpc 1.81.1, prometheus/common 0.67.5).
Full build verified.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
New internal/policy package (dead code — nothing wires into request paths
yet): prepared-query Engine with 25ms eval timeout and fail-closed decode,
typed PDP.ResolveViewerScope, go:embed vendor bundle, capabilities lockdown
for future admin-authored Rego, and vendor scope.rego reproducing
access.Resolver.Resolve (library intersection, disabled-library handling,
quality/rating ceilings) with a narrowing-only silo_custom.scope.override
extension hook.

Parity proven by 1368 dual-execution subtests against the real
access.Resolver, including the nil-vs-empty AllowedLibraryIDs battery and
quality/rating variation; rank tables are test-pinned to internal/access.
Rego unit tests run via opa/v1/tester inside go test. Bench:
~106µs/op per scope decision incl. input marshaling.

Also restores the OPA requirement to go.mod (the earlier deps commit ran
go mod tidy before any import existed, so tidy dropped it).

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed,
corrected (quality.allowed raw-file-rank divergence), and verified here.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
…le-check

policy_foundation migration: policy_documents (one enabled doc per domain
via partial unique index — two enabled docs would define override twice
and conflict at eval), immutable policy_document_versions, single-row
policy_generation counter, and the partitioned policy_decisions log table
(daily range partitions, no FK, denial partial index).

PolicyStore: transactional version numbering (FOR UPDATE), activation
that verifies compiled_ok and bumps the generation in the same tx,
enable/disable with typed ErrDomainAlreadyEnabled, and a delete guard for
documents with an active version. CompileCheck sandboxes admin Rego:
locked capabilities (no http.send/net.*/opa.runtime), enforced
silo_custom.<domain> package path, vendor+stub layering, 2s budget,
structured row/col errors. Engine gains NewEngineWithCustom /
NewEngineFromStore with WARN-and-skip for invalid custom rows.

DB-backed tests verified against a migrated Postgres (concurrent version
numbering, atomic generation bumps, activation guards).

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed and
verified here (domain constants extracted).

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
…ode invalidation

policy.System owns one long-lived Engine and reloads it in place when
policy documents change: EventPolicyChanged on the existing ChannelAdmin
bus (new cache event constant) plus a 60s generation-poll fallback for
Redis-less deployments, with a generation-consistent snapshot read.
Vendor compile failure is startup-fatal; store/custom failures degrade
to vendor-only and the poll loop heals them; runtime reload failures
keep the last known-good engine. NotifyChanged gives the future admin
handlers synchronous local reload + cross-node publish.

Wiring: constructed in integrated/api modes only, PolicySystem field on
api.Dependencies (unused by routes yet), policy.eval_timeout_ms setting
(hot-reloaded via configWatcher.OnChange; default 25ms). Verified by a
full server boot smoke and DB-backed convergence tests (event + poll
paths, degraded boot, last-known-good).

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed and
verified here.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
…d query repo

DecisionLogger batch-inserts each node's policy decisions straight to
the partitioned policy_decisions table via a non-blocking buffered
channel (drop-and-count on overflow — logging never adds latency to or
fails a decision). Scope decisions sample 1-in-N (default 50, setting
policy.decision_log_scope_sample_rate); denials and eval errors always
log; input/result JSON samples only at policy.decision_log_verbosity=
verbose. Cursor-paginated DecisionRepository backs the upcoming admin
log viewer. Retention via partman (daily partitions) and a
PolicyDecisionLogCleanupTask honoring policy.decision_log_retention_days
(default 14). PDP emits entries per evaluation; the System owns the
logger lifecycle and settings hot-reload.

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed and
verified here (removed an unused, unsynchronized PDP setter).

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
/api/v1/policy/capability (authenticated feature detection) plus the
acting-admin /api/v1/admin/policy surface: vendor Rego viewer, document
CRUD with the one-enabled-per-domain conflict mapped to 409, immutable
version creation (compile-checked; failed versions persist as audit
history with structured row/col errors and can never activate),
activate/rollback with synchronous reload + cross-node invalidation via
System.NotifyChanged, stateless validate, throwaway-bundle simulate
(never touches the live engine, never logs decisions), and
cursor-paginated decision-log queries. Routes mount only when the
policy system is wired, keeping proxy/transcode modes untouched.

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed and
verified here (seeded the FK'd test user; replaced an unchecked
fmt.Sscanf with strconv).

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
…d decision log

New Policy admin page (System nav group): documents list with
one-enabled-per-domain conflict handling, CodeMirror 6 Rego editor
(hand-rolled StreamLanguage mode) with server compile issues rendered as
inline lint diagnostics, explicit Save-version vs Activate flow with
confirm, read-only vendor module viewer, simulate panel with seeded
example inputs, version history with rollback, and a cursor-paginated
decision-log browser. Capability-gated via /policy/capability. Adds the
three decision-log settings to Log Retention. First code-editor
dependency in web/ (@uiw/react-codemirror + @codemirror/*), decided in
the design spec.

Implementation drafted by Codex (GPT-5.5) via codex exec; verified here
(lint, format:check, tsc --noEmit, vitest policy suites).

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
policy.ViewerResolver implements the ViewerResolver interface backed by
PDP.ResolveViewerScope and replaces access.Resolver at all five
construction sites: router viewer middleware, notifications scopes, the
reconciler, jellycompat's scope filter, and the ABS resolver (which now
accepts a pre-built resolver, preserving its PIN-at-login semantics).
PIN/profile-token verification and disabled-library loading are
extracted into shared exported helpers used by both implementations, so
the legacy resolver stays compiled as the parity reference with
identical behavior. The adapter lives in internal/policy (which already
depends on internal/access transitively) — direct typed PDP calls, no
new import cycle. Sites without a policy system (proxy modes, bare test
routers) keep the legacy resolver until the cleanup phase.

Verified: full test suite green (jellycompat TestBeginWebOperation* and
one playback GPU test are pre-existing failures, confirmed identical on
main), 1368-case parity suite, dedicated ViewerResolver parity/PIN/
nil-vs-empty/fail-closed tests, and a full server boot smoke.

Implementation drafted by Codex (GPT-5.5) via codex exec; a first-pass
reflection-based adapter was rejected and reworked into the typed
in-policy adapter; reviewed line-by-line and verified here.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
…gates

vendor/permission.rego reproduces the acting-admin rule (admin role +
primary-profile-or-none), HasEffectivePermission semantics for
marker_edit, and the metadata-curation rule including the subtle
admin-past-refused-bypass case that requires the explicitly ASSIGNED
permission. Policy-backed middleware in policy_gates.go keeps all Go-side
lookups (declared-profile primary check, item->library resolution, the
404-on-unknown-item path) and preserves the legacy status/body taxonomy
exactly — proven by dual-execution middleware tests that run every
scenario through both implementations and assert byte-equal responses.
Permission decisions always log (allowed flag populated); simulate and
the capability endpoint gain the permission domain automatically via the
domain registry. Router swaps behind single constructor choice points
with the legacy gates retained for policy-less wiring.

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed and
verified here.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
…ion decisions

vendor/action.rego decides download eligibility (downloads enabled +
user allowed), download-transcode eligibility (transcode enabled + user
allowed + artifacts available), and playback admission (stream/transcode
counts vs limits, zero = unlimited), with a tightening-only
silo_custom.action override that can also clamp a quality ceiling (never
widen — merged via quality.min). Go keeps everything stateful: config
loading, preset-ladder enumeration, and live session counting.

Downloads consult an optional ActionDecider (nil = legacy logic) mapped
back to the existing sentinel errors and capability response. Playback
gains a minimal AdmissionDecider hook at the exact point of the legacy
limit comparison: counts snapshot under the session mutex, PDP evaluated
OUTSIDE the lock, then revalidated under lock before insert (retry on
count drift) — no admission ever decided on stale counts and no eval
under the mutex. Deny reasons map to the legacy ErrTooManyStreams /
ErrTooManyTranscodes sentinels, pinned by tests.

Parity: combination tables driven against the real PresetsFor /
ensureTranscodeAllowed / SessionLimits math; full suite green (known
pre-existing jellycompat flakes only).

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed
(locking design verified line-by-line) and verified here.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
…nizer

The production build (tsc -b) rejects assigning CodeMirror's
string | void next() result to string | undefined; tsc --noEmit did not
catch it. Restructured the string-literal loop.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
…nput

Vendor policies index required input fields directly, so a hand-written
simulate payload missing fields yields an undefined decision. Surface
that as 'decision X is undefined for this input (missing required input
fields?)' instead of 'empty result' — found while exercising the
simulate API against a live server.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 2, 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

This PR adds an embedded OPA policy engine, access-group support, policy-backed authorization wiring, and a new admin policy workspace for editing, validating, simulating, and browsing policy data.

Changes

Policy engine, backend wiring, and access groups

Layer / File(s) Summary
Policy engine core
go.mod, internal/policy/*, internal/policy/vendor/*
Implements the OPA policy engine, typed decision inputs, PDP wrappers, vendor Rego modules, logging, storage, simulation, and parity tests.
Policy runtime and lifecycle
internal/policy/decisionlog.go, internal/policy/decisionlog_cleanup.go, internal/policy/decisionlog_repo.go, internal/policy/system.go, internal/policy/system_test.go, internal/policy/engine_bench_test.go
Adds decision logging, cleanup, repository pagination, the live policy system, and runtime coverage.
Access groups and policy resolution
internal/access/*, internal/auth/repository.go, internal/models/user.go, migrations/sql/20260702172000_access_groups.sql, migrations/sql/20260702173000_default_access_group.sql, internal/requests/service.go
Adds access-group persistence, user assignment, policy merging, repository support, migration data, and request gating.
Policy-backed server wiring
internal/config/*, internal/api/middleware/policy_gates*.go, internal/api/router.go, cmd/silo/main.go, internal/downloads/*, internal/playback/session*.go, internal/audiobooks/access_resolver.go, internal/cache/redis.go, internal/taskmanager/tasks/policy_decision_log_cleanup.go
Wires policy and access-group logic into config, middleware, router, downloads, playback, startup, and cleanup paths.

Admin policy API and UI

Layer / File(s) Summary
Policy admin API
internal/api/handlers/policy.go, internal/api/handlers/policy_test.go, internal/api/handlers/admin.go, internal/api/handlers/access_groups.go, internal/api/handlers/access_groups_test.go, internal/api/handlers/admin_settings_checks_test.go
Adds policy and access-group admin handlers, validation, and DB-backed tests, plus policy-related settings validation.
Admin policy frontend
web/src/api/types.ts, web/src/hooks/queries/admin/*, web/src/lib/*, web/src/pages/admin-policy/*, web/src/pages/AdminAccessGroups*.tsx, web/src/pages/AdminUserDetail*.tsx, web/src/components/AdminSidebar*.tsx, web/src/components/policy/RegoEditor.tsx, web/src/lib/regoLanguage.ts
Adds the /admin/policy workspace, access-group UI, CodeMirror Rego editor, policy/admin hooks and types, and navigation updates.

Estimated code review effort: 5 (Critical) | ~150 minutes

Possibly related issues

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: access groups plus the embedded OPA policy engine and decision audit log.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/wizardly-jepsen-f6f5ea

Comment @coderabbitai help to get the list of available commands.

@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: ed9a832464

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread internal/api/router.go
Comment on lines +366 to +370
metadataCurationAccess = apimw.NewPolicyPermissionMiddleware(
userRepo,
metadataLibraries,
checkPrimaryProfile,
permissionPDP,

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 Wire marker_edit through the PDP

When a custom permission policy denies marker_edit, the write endpoints under /markers still bypass the PDP because the new policy permission middleware is only wired for metadata curation here, while MarkersHandler.requireMarkerEdit continues to grant admins and auth.HasEffectivePermission directly (internal/api/handlers/markers.go:285-300). That leaves admin-authored marker-edit restrictions unenforced for PUT /markers/... and DELETE /markers/...; please route those checks through the policy decider as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 20ecd5e — the marker write routes now go through the PDP-backed policy permission middleware instead of the handler-local admin/HasEffectivePermission check.

Comment thread internal/downloads/policy.go Outdated
user,
cfg,
artifactsAvailable,
"",

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 Preserve device IDs for transcode policy checks

For managed device downloads, Create has the request DeviceID when it calls the download gate, but if the same request needs remux/transcode this path evaluates download_transcode with an empty device id. A custom action policy that restricts transcoded downloads by input.device_id is therefore bypassed for the actual artifact-backed download; thread the request device id through Resolve/ensureTranscodeAvailable instead of hard-coding "".

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in e18aace — the request device ID is now threaded through Resolve/ensureTranscodeAvailable so download_transcode evaluations carry the real device_id (and the quality ceiling from the decision is honored).

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 2, 2026
Quick104 and others added 2 commits July 2, 2026 15:15
…is remote

Remote dev backends sit behind vhost-routing proxies that reject a
localhost Host header; local targets keep the existing pass-through
behavior. Enables pointing the Vite dev server at a hosted backend via
VITE_API_PROXY_TARGET in web/.env.local.

Co-Authored-By: Claude Fable 5 <[email protected]>
…line

The first-pass UI was structurally generic: a five-column document table
squeezed beside the editor, three equal-weight action buttons with
hidden preconditions, raw version IDs, and jargon copy — nothing taught
the model. The page now teaches it:

- A pipeline strip states the mental model up front: Silo decides the
  baseline -> your overrides narrow it -> every decision is logged. Tabs
  renamed to Overrides / Baseline / Decision Log (ids stay stable for
  bookmarked URLs).
- The document table becomes one card per domain (Library visibility /
  Admin & permissions / Downloads & playback) with plain-language
  descriptions, example rules, status pills (Live vN / Draft / Disabled),
  inline creation, and the enable kill-switch in place.
- Selecting an override drills into a full-width editor with a visible
  lifecycle rail (Draft -> Validated -> Saved -> Live) and one contextual
  primary action per step; the unedited live source shows no actions
  until edited. Version comments appear only at the save step.
- Simulate is reframed as 'Test before going live' with a human verdict
  chip (Allowed / Denied — reason / ceiling summary) above the raw JSON;
  internal generation counters no longer surface.
- History uses 'Make live' with plain go-live copy; authors read
  'User N'; the baseline tab explains that upgrades never touch
  overrides.

Hand-written redesign (no Codex); verified via vitest, tsc, eslint,
prettier, and a production build.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>

@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: 14

🧹 Nitpick comments (21)
docs/superpowers/specs/2026-07-02-opa-policy-engine-design.md (1)

130-149: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add language tags to the fenced code blocks.

Markdownlint flags the unlabeled fences at Lines 130-149 and 347-357. Please mark them as text so the spec passes lint.

🛠 Suggested fix
- ```
+ ```text
...
- ```
+ ```text

Also applies to: 347-357

🤖 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/specs/2026-07-02-opa-policy-engine-design.md` around lines
130 - 149, The spec contains unlabeled fenced code blocks that trigger
markdownlint; update the fences in the internal/policy directory layout section
and the later vendor source example to use text as the language tag. Keep the
block contents unchanged and ensure both affected fences are explicitly marked
so the document passes lint.

Source: Linters/SAST tools

internal/api/handlers/policy.go (1)

479-490: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Flatten if/else-after-return to satisfy revive/golangci-lint.

The from/to branches use else after a return, which revive's indent-error-flow flags and is inconsistent with the flat style used just above for user_id/allowed.

♻️ Flatten error flow
-	if from, err := parseTimeQuery(r, "from"); err != nil {
-		writeError(w, http.StatusBadRequest, policyErrorBadRequest, err.Error())
-		return
-	} else {
-		opts.From = from
-	}
-	if to, err := parseTimeQuery(r, "to"); err != nil {
-		writeError(w, http.StatusBadRequest, policyErrorBadRequest, err.Error())
-		return
-	} else {
-		opts.To = to
-	}
+	from, err := parseTimeQuery(r, "from")
+	if err != nil {
+		writeError(w, http.StatusBadRequest, policyErrorBadRequest, err.Error())
+		return
+	}
+	opts.From = from
+	to, err := parseTimeQuery(r, "to")
+	if err != nil {
+		writeError(w, http.StatusBadRequest, policyErrorBadRequest, err.Error())
+		return
+	}
+	opts.To = to

As per coding guidelines: "Go code must stay gofmt/goimports clean and pass golangci-lint".

🤖 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/policy.go` around lines 479 - 490, Flatten the error
flow in the time query parsing logic inside the policy handler by removing the
unnecessary else blocks after the early returns in the from/to handling. Update
the parseTimeQuery checks in the policy handler so that, like the user_id and
allowed branches, each successful parse assigns directly to opts.From and
opts.To without an else, keeping the code gofmt-friendly and compliant with
revive’s indent-error-flow rule.

Source: Coding guidelines

internal/policy/simulate.go (1)

103-127: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Deduplicate the generation-stable snapshot read.

simulationSources replicates the retry loop in System.loadSnapshot (internal/policy/system.go Lines 281-300) exactly, except for the nil-store branch. Extract a shared helper (e.g. loadStableSnapshot(ctx, store)) so the "read generation → sources → re-read generation" invariant lives in one place; keep the permissive nil-store handling here at the call site.

♻️ Sketch
func loadStableSnapshot(ctx context.Context, store *PolicyStore) (map[string]ActiveSource, int64, error) {
	for {
		before, err := store.Generation(ctx)
		if err != nil {
			return nil, 0, err
		}
		sources, err := store.ActiveSources(ctx)
		if err != nil {
			return nil, 0, err
		}
		after, err := store.Generation(ctx)
		if err != nil {
			return nil, 0, err
		}
		if before == after {
			return sources, after, nil
		}
		if err := ctx.Err(); err != nil {
			return nil, 0, err
		}
	}
}

Then simulationSources keeps only the store == nil guard before delegating, and System.loadSnapshot delegates after its own nil check.

🤖 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/policy/simulate.go` around lines 103 - 127, The stable snapshot
retry loop is duplicated between simulationSources and System.loadSnapshot, so
extract the shared “read generation → load ActiveSources → re-read generation
until stable” logic into a helper like loadStableSnapshot(ctx, store). Keep the
permissive nil-store handling in simulationSources itself, then delegate to the
new helper, and update System.loadSnapshot to call the same helper after its own
nil check so the invariant lives in one place.
migrations/sql/20260702153902_policy_foundation.sql (1)

78-90: 🧹 Nitpick | 🔵 Trivial

Operational note: ensure range partitions are provisioned before/at write time.

Only policy_decisions_default is created here; the runtime partition manager creates the range partitions. If provisioning lags or fails, all decision rows accumulate in the default partition, which negates timestamp-based pruning on the ("timestamp" DESC, id DESC) and denied/user indexes and makes retention (DROP PARTITION) ineffective. Worth confirming the partition manager pre-creates upcoming windows and that alerting exists if the default partition grows.

🤖 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/sql/20260702153902_policy_foundation.sql` around lines 78 - 90,
The migration only creates the policy_decisions_default partition and the
related indexes, so writes can spill into the default partition if range
partitions are not ready. Update the partition provisioning flow for
public.policy_decisions to pre-create upcoming time windows at or before write
time, and verify the runtime partition manager does so reliably. Also add
monitoring/alerting around policy_decisions_default growth so fallback
accumulation is detected before it undermines pruning and retention behavior.
internal/policy/decisionlog_repo.go (1)

92-101: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Repeated SELECT column list across List and both Get query variants.

Consider factoring the shared column list into a package-level constant to avoid drift if columns change.

Also applies to: 136-156

🤖 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/policy/decisionlog_repo.go` around lines 92 - 101, The SELECT column
list is duplicated across DecisionLogRepo.List and both Get query variants,
which can drift when columns change. Factor the shared projection in
internal/policy/decisionlog_repo.go into a single package-level constant or
helper used by the query builders, and update the List/Get query construction to
reference that shared symbol instead of repeating the column list.
internal/policy/decisionlog_cleanup.go (1)

79-104: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Tight retry loop without backoff on the fallback path.

deleteExpiredDecisionRowsBefore loops immediately re-issuing 10k-row DELETE batches with no pacing. This path only runs when partition management is already "degraded," so a large backlog could hammer the DB in a tight loop. Consider a small sleep between batches.

🤖 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/policy/decisionlog_cleanup.go` around lines 79 - 104, The fallback
cleanup loop in deleteExpiredDecisionRowsBefore can hammer the database by
reissuing consecutive 10k-row DELETE batches with no pacing. Add a small sleep
or backoff between successful batch deletions inside the loop, keeping the
existing batching and stop condition intact. Make the pause part of the
deleteExpiredDecisionRowsBefore flow so the degraded-path cleanup runs more
gently under large backlogs.
web/src/pages/admin-settings/LogRetentionSettings.tsx (1)

32-44: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate key literals instead of reusing constants.

The three new key strings are hardcoded in GLOBAL_KEYS (Lines 36-38) and then redefined as separate constants immediately after (Lines 41-43). If either copy is edited later, they can silently diverge, breaking the field's load/discard behavior.

♻️ Proposed fix: declare constants first, then reference them
+const POLICY_DECISION_LOG_RETENTION_DAYS_KEY = "policy.decision_log_retention_days";
+const POLICY_DECISION_LOG_VERBOSITY_KEY = "policy.decision_log_verbosity";
+const POLICY_DECISION_LOG_SCOPE_SAMPLE_RATE_KEY = "policy.decision_log_scope_sample_rate";
+
 const GLOBAL_KEYS = [
   OPSLOG_RETENTION_DAYS_KEY,
   OPSLOG_MAX_ROWS_KEY,
   OPSLOG_MAX_SIZE_MB_KEY,
-  "policy.decision_log_retention_days",
-  "policy.decision_log_verbosity",
-  "policy.decision_log_scope_sample_rate",
+  POLICY_DECISION_LOG_RETENTION_DAYS_KEY,
+  POLICY_DECISION_LOG_VERBOSITY_KEY,
+  POLICY_DECISION_LOG_SCOPE_SAMPLE_RATE_KEY,
 ] as const;
-
-const POLICY_DECISION_LOG_RETENTION_DAYS_KEY = "policy.decision_log_retention_days";
-const POLICY_DECISION_LOG_VERBOSITY_KEY = "policy.decision_log_verbosity";
-const POLICY_DECISION_LOG_SCOPE_SAMPLE_RATE_KEY = "policy.decision_log_scope_sample_rate";
🤖 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/admin-settings/LogRetentionSettings.tsx` around lines 32 - 44,
The policy decision log keys are duplicated as string literals in GLOBAL_KEYS
and then redefined as separate constants, which can drift apart over time. Move
POLICY_DECISION_LOG_RETENTION_DAYS_KEY, POLICY_DECISION_LOG_VERBOSITY_KEY, and
POLICY_DECISION_LOG_SCOPE_SAMPLE_RATE_KEY above GLOBAL_KEYS in
LogRetentionSettings and reference those constants inside GLOBAL_KEYS instead of
hardcoding the strings.
web/src/lib/policyDiagnostics.ts (1)

17-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant ternary always evaluates the same way.

line.to === line.from ? from : from + 1 inside the outer Math.max(from + 1, ...) always resolves to from + 1 regardless of the condition, so the ternary can be dropped.

-    const to = clamp(Math.max(from + 1, line.to === line.from ? from : from + 1), from, docLength);
+    const to = clamp(from + 1, from, docLength);
🤖 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/lib/policyDiagnostics.ts` around lines 17 - 30, The
`policyDiagnostics` mapping in `toDiagnostics` contains a redundant ternary in
the `to` calculation that always resolves to the same value. Simplify the `to`
expression by removing the `line.to === line.from ? from : from + 1` branch and
keep the existing clamp logic intact, so the bounds handling remains unchanged
while the code becomes clearer.
web/src/pages/admin-policy/PolicyVersionHistory.tsx (2)

40-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Simplify to a single usePolicyVersion call using effectiveSelectedId.

Two separate usePolicyVersion hooks (selectedVersion, effectiveVersion) are wired with ternaries to pick which one is "live," but effectiveSelectedId (already computed and used for the isSelected row highlight) is exactly the id needed to drive a single call.

♻️ Proposed simplification
-  const selectedVersion = usePolicyVersion(documentId, selectedVersionId);
-
   const effectiveSelectedId = selectedVersionId ?? versions?.[0]?.id;
-  const effectiveVersion = usePolicyVersion(
-    documentId,
-    selectedVersionId === undefined ? versions?.[0]?.id : undefined,
-  );
-  const sourceVersion =
-    selectedVersionId === undefined ? effectiveVersion.data : selectedVersion.data;
+  const sourceVersion = usePolicyVersion(documentId, effectiveSelectedId).data;
🤖 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/admin-policy/PolicyVersionHistory.tsx` around lines 40 - 52,
The version lookup in PolicyVersionHistory should use a single usePolicyVersion
call instead of maintaining both selectedVersion and effectiveVersion with
ternary branching. Reuse the already computed effectiveSelectedId to drive that
one hook, then update sourceVersion to read from that single result so the row
highlight and displayed version stay in sync.

156-175: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Activation confirmation dialog duplicates markup from PolicyEditorPanel.tsx.

This AlertDialog (rollback confirmation) is nearly identical to the one in PolicyEditorPanel.tsx (activation confirmation) — same title, similar description pattern, same action/cancel structure. Consider extracting a shared ActivateVersionDialog component to avoid drift between the two copies.

🤖 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/admin-policy/PolicyVersionHistory.tsx` around lines 156 - 175,
The rollback activation confirmation in PolicyVersionHistory duplicates the
activation dialog markup used in PolicyEditorPanel, so extract a shared
ActivateVersionDialog component and reuse it in both places. Move the common
AlertDialog structure, title/description pattern, and cancel/action footer into
that shared component, then pass in the version text and confirm handler from
PolicyVersionHistory and PolicyEditorPanel to keep the dialogs consistent and
avoid drift.
web/src/components/policy/RegoEditor.tsx (1)

45-56: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Extensions array is rebuilt on every keystroke.

value is part of the useMemo deps, so on every keystroke a brand-new extensions array is produced, forcing CodeMirror to reconfigure gutters/theme/lint/editable facets on every character typed. @uiw/react-codemirror's own docs recommend memoizing to "minimize reference changes which cause costly re-renders," and linter() source functions are meant to read the live document via the view argument rather than closing over a prop snapshot.

♻️ Proposed fix: read live doc via `view` instead of closing over `value`
   const extensions = useMemo(() => {
-    const diagnostics = mapPolicyIssuesToDiagnostics(value, issues);
     return [
       lineNumbers(),
       regoLanguage,
       EditorView.lineWrapping,
       EditorState.readOnly.of(readOnly),
       EditorView.editable.of(!readOnly),
-      linter(() => diagnostics),
+      linter((view) => mapPolicyIssuesToDiagnostics(view.state.doc.toString(), issues)),
       editorTheme,
     ];
-  }, [issues, readOnly, value]);
+  }, [issues, readOnly]);
🤖 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/policy/RegoEditor.tsx` around lines 45 - 56, The
RegoEditor extensions array is being recreated on every keystroke because
useMemo depends on value, which forces CodeMirror to reconfigure on each edit.
Update RegoEditor so the linter callback reads the current document from the
view argument instead of closing over value, then remove value from the useMemo
deps and keep only the truly static inputs like issues and readOnly. This keeps
the extensions stable while still allowing diagnostics to reflect the live
editor content.
web/src/pages/admin-policy/policyPageUtils.ts (1)

1-82: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider relocating generic utilities to web/src/lib.

formatPolicyDate, prettyPolicyJson, compileIssuesFromError, etc. are general-purpose helpers (not admin-policy-page-specific rendering logic) and would fit the project's shared-utility convention better than living under pages/admin-policy/.

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

🤖 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/admin-policy/policyPageUtils.ts` around lines 1 - 82, Move the
shared helpers out of the admin policy page module into the project’s shared
frontend utilities area, since functions like formatPolicyDate,
prettyPolicyJson, compileIssuesFromError, and messageFromError are generic and
not page-specific. Relocate them to web/src/lib or web/src/utils, keep the same
exported APIs, and update any imports that currently reference policyPageUtils
so the admin-policy page still uses the new shared location.

Source: Coding guidelines

web/src/pages/admin-policy/PolicyDocumentList.tsx (1)

125-128: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Async handler passed directly as onClick without void wrapping.

create is an async function passed directly to onClick (line 125), unlike toggleDocument, which is explicitly wrapped with void at line 181. With @typescript-eslint/no-misused-promises's default checksVoidReturn.attributes enabled, this pattern is flagged as a promise-returning function provided where a void return is expected.

🔧 Proposed fix
-          <Button type="button" onClick={create} disabled={createDocument.isPending}>
+          <Button type="button" onClick={() => void create()} disabled={createDocument.isPending}>
🤖 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/admin-policy/PolicyDocumentList.tsx` around lines 125 - 128,
The Button in PolicyDocumentList passes the async create handler directly to
onClick, which triggers the promise-returning callback lint issue. Update the
create usage so the click handler is wrapped to intentionally ignore the
returned promise, matching the existing toggleDocument pattern, and keep the
async logic inside create unchanged.
internal/policy/vendor/custom_stub.rego (1)

1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Filename doesn't follow the custom_<domain>_stub.rego pattern used by siblings.

custom_action_stub.rego and custom_permission_stub.rego are domain-qualified, but this scope stub is just custom_stub.rego. Renaming to custom_scope_stub.rego would keep the three vendor override stubs consistently discoverable.

🤖 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/policy/vendor/custom_stub.rego` at line 1, The vendor scope stub
filename is inconsistent with the sibling override stubs, so rename the
`silo_custom.scope` stub to follow the `custom_<domain>_stub.rego` convention.
Update the scope stub’s filename and keep its package declaration aligned with
the new `custom_scope_stub.rego` name so it stays consistent with
`custom_action_stub.rego` and `custom_permission_stub.rego`.
internal/policy/engine.go (1)

17-17: 🧹 Nitpick | 🔵 Trivial

Confirm 25ms default eval timeout is safe under production load given fail-closed semantics.

Evaluate treats any error — including a timeout — as ErrPolicyEvalFailed, and this engine is becoming the sole authorization path for scope/permission/action decisions. A 25ms default is comfortable for typical Rego evaluation but could be exceeded under GC pauses or CPU contention, causing spurious denials/errors on legitimate requests. Since this is configurable via WithEvalTimeout/SetEvalTimeout, this is a call-out for validation (e.g., load testing) rather than a required code change.

Also applies to: 146-184

🤖 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/policy/engine.go` at line 17, Validate that defaultEvalTimeout
remains safe under production load for the Evaluate path, since any timeout is
converted to ErrPolicyEvalFailed and can cause fail-closed denials. Check the
engine behavior around Evaluate, defaultEvalTimeout, WithEvalTimeout, and
SetEvalTimeout with load testing and production-like CPU/GC contention, and if
needed adjust the default or document a recommended higher timeout for
deployments that cannot guarantee sub-25ms evals.
internal/policy/vendor/lib/ratings.rego (2)

29-44: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

min rule shadows the built-in aggregate min().

Same concern as quality.rego: a rule named min hides the built-in min(collection) within silo.lib.ratings, which will surface as a confusing "undefined function" error if the real built-in is ever called from this package later. Consider renaming (e.g. pick_lower) for clarity, checking for existing callers first.

🤖 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/policy/vendor/lib/ratings.rego` around lines 29 - 44, The `min` rule
in `ratings.rego` is shadowing the built-in aggregate `min()` and can cause
confusing lookup issues later. Rename the rule to a clearer non-conflicting name
such as `pick_lower`, and update any references within `silo.lib.ratings` or
nearby policies that call it so the package can still use the real built-in
`min(collection)` if needed.

Source: Linters/SAST tools


1-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No Rego test file for this module.

Unlike quality.rego/quality_test.rego, there's no companion ratings_test.rego covering allowed()/min() edge cases (unknown rating strings, empty ceiling, boundary comparisons). Given content-rating enforcement is a parental-control/compliance-sensitive path, adding direct unit tests here would be valuable.

🤖 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/policy/vendor/lib/ratings.rego` around lines 1 - 45, Add a companion
ratings_test.rego for internal/policy/vendor/lib/ratings.rego and cover the
exported helpers allowed() and min() with direct unit tests. Include edge cases
for empty ceiling handling, unknown rating strings, and boundary comparisons
across the rank map, using the normalize(), allowed(), and min() behavior as the
reference points.
internal/policy/vendor/lib/quality_test.rego (1)

1-19: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test case for a "4320p"/"8K" ceiling.

None of the current cases set ceiling to "4320p"/"8K". Adding one would have caught the normalize() collapsing issue flagged in quality.rego (Lines 14-30), where such a ceiling can never actually unlock rank-5 content.

🤖 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/policy/vendor/lib/quality_test.rego` around lines 1 - 19, Add a
regression test in quality_test.rego for the allowed() behavior with a
"4320p"/"8K" ceiling, since the current tests in test_allowed_* only cover lower
ceilings. Use the allowed() rule directly to assert the expected outcome for a
4320p input with an 8K ceiling, so the normalize() collapsing issue in
quality.rego is caught if it still prevents rank-5 content from being unlocked.
internal/policy/vendor/permission.rego (1)

87-97: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Bare object.get(...) truthiness checks flagged by static analysis.

user_enabled, acting_as_primary, and user_libraries_restricted all use the returned value as a bare condition rather than comparing it explicitly. These fields are populated from typed Go bools today (lower practical risk), but an explicit == true/== false comparison is more defensive and matches the static analysis guidance.

 user_enabled(i) if {
-	object.get(i, "user_enabled", false)
+	object.get(i, "user_enabled", false) == true
 }

(similarly for acting_as_primary and user_libraries_restricted)

🤖 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/policy/vendor/permission.rego` around lines 87 - 97, The helper
predicates user_enabled, acting_as_primary, and user_libraries_restricted in
permission.rego are using bare object.get(...) results as truthy conditions.
Update each rule to compare the returned value explicitly against true or false,
keeping the same function names so the static analysis warning is addressed
consistently across all three helpers.

Source: Linters/SAST tools

internal/policy/vendor/lib/quality.rego (1)

48-59: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

min rule shadows the built-in aggregate min().

Regal flags this as a bug-category issue, and it's a real landmine: OPA lets a rule silently hide a built-in of the same name within the package, but any later call to the real min(collection) builtin inside silo.lib.quality will fail with an "undefined function" error instead of calling the built-in (confirmed pattern, see open-policy-agent/opa#2567). Renaming avoids the ambiguity for future maintainers of this file.

-min(a, b) := result if {
+pick_lower(a, b) := result if {

Note: check other vendor .rego files (e.g. scope.rego) for existing callers of quality.min before renaming.

🤖 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/policy/vendor/lib/quality.rego` around lines 48 - 59, The min rule
in quality.rego shadows OPA’s built-in min() and can cause future built-in calls
in this package to fail, so rename the rule to a non-conflicting name. Update
the rule definition and any internal references in this package (including other
vendor .rego files such as scope.rego that may call quality.min) to use the new
symbol consistently, while preserving the same logic and behavior.

Source: Linters/SAST tools

internal/policy/vendor_rego_test.go (1)

45-73: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer evaluating the Rego rule over string-matching its source.

These tests assert consistency by searching the raw .rego file text for a literal "key": rank substring. This couples test correctness to exact source formatting rather than actual rule behavior, so a harmless reformat (e.g. opa fmt) could break the test without any functional regression, while a functional bug that preserves the substring pattern could slip through.

Consider evaluating data.silo.lib.quality/data.silo.lib.ratings via rego.New(...).PrepareForEval(...) (already used elsewhere in this package, e.g. internal/policy/engine.go) and comparing computed values instead of grepping source text.

🤖 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/policy/vendor_rego_test.go` around lines 45 - 73, The tests in
TestVendorQualityTableMatchesAccessPackage and
TestVendorRatingTableMatchesAccessPackage are validating raw Rego source text
instead of the rule output. Replace the strings.Contains checks on
readVendorFile with an actual Rego evaluation using
rego.New(...).PrepareForEval(...) as done in internal/policy/engine.go, then
compare the computed values for data.silo.lib.quality and data.silo.lib.ratings
against the access package entries.
🤖 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 1967-1970: The absScopeResolver setup is missing the legacy
fallback, so it can remain nil when policySystem is unavailable. Update the
resolver initialization in main so that the policy.NewViewerResolver branch is
paired with the legacy access.NewResolver(...) branch used elsewhere, and ensure
audiobooks.NewABSAccessResolver always receives a valid scope resolver even when
mode == "" and policySystem is nil.

In `@internal/playback/session.go`:
- Around line 285-287: In `admissionDenyError` handling inside the playback
session flow, the decider failure is being mapped to `ErrTooManyStreams` without
any visibility. Update the `if err != nil` branch in the session admission logic
to log the actual error before returning the deny error, using the existing
logger for this path so policy-evaluation outages and cancellations are
observable while still fail-closed.

In `@internal/policy/compile_test.go`:
- Around line 179-203: The timeout test in TestEvaluateTimeoutFailsClosed is
using an excessively large slow.rego workload, which can waste CPU before the
timeout is hit. Reduce the numbers.range bounds in the slow policy used by
newEngineFromModules to a much smaller range that still forces Evaluate to time
out and return ErrPolicyEvalFailed, keeping the same fail-closed behavior while
making the test safe and fast in CI.

In `@internal/policy/compile.go`:
- Around line 105-129: The timeout in compileModulesWithTimeout only stops
waiting and does not stop ast.Compiler.Compile, so timed-out requests can still
leave compile goroutines running. Add a guard in compileModulesWithTimeout (and
the surrounding compile path) to limit concurrent compiles and/or
validate/reject oversized or overly complex modules before calling
ast.NewCompiler().Compile. Use compileModulesWithTimeout, compileErrorMessage,
and compileErrorFromOPA as the main entry points when threading the new
preflight check or semaphore-based cap.
- Around line 14-36: LockedCapabilities currently starts from all OPA builtins
and only filters a denylist via lockedBuiltin, which means new builtins can slip
in on upgrade and the net. prefix rule blocks too much. Update
LockedCapabilities to build the capabilities from an explicit vetted allowlist
(or builtin metadata) instead of inheriting everything, and remove the broad
prefix-based filtering in lockedBuiltin so only the intended unsafe builtins are
excluded.

In `@internal/policy/decisionlog_cleanup.go`:
- Around line 28-77: CleanupDecisionLogsOnce currently swallows
partition-manager and fallback delete failures by only logging warnings and
returning a count, so the caller cannot detect cleanup outages. Update
CleanupDecisionLogsOnce to surface a failure signal (for example by returning an
error alongside the deleted count or another explicit status) when
EnsureFuturePartitions, DropExpiredPartitions, DeleteExpiredRowsFromDefault, or
deleteExpiredDecisionRowsBefore fail, using the existing decision log cleanup
flow as the reference point. Then adjust PolicyDecisionLogCleanupTask.Execute to
check that failure signal and return the error to the task manager instead of
always reporting success.

In `@internal/policy/vendor/action.rego`:
- Around line 89-107: The input flag predicates in action.rego currently rely on
bare object.get checks, so any non-false value can be treated as enabled.
Tighten downloads_enabled, transcode_enabled, download_allowed,
download_transcode_allowed, and artifacts_available to explicitly verify the
field is a boolean true (matching the override check pattern nearby) so
hand-crafted or malformed simulate input cannot bypass the intended flag
semantics.
- Around line 150-160: The narrowing logic in tightened_allowed and
tightened_reason treats object.get(override, "allowed", true) as a bare truthy
check, so non-boolean values can slip through and fail to tighten correctly.
Update the policy in action.rego to require an explicit boolean comparison for
the override "allowed" field in both tightened_allowed and tightened_reason, and
keep the logic centered on those two helpers so the narrowing-only guarantee
remains enforced.

In `@internal/policy/vendor/lib/quality.rego`:
- Around line 14-30: The normalize() function is collapsing 4320P into the 2160p
bucket, so a ceiling set through allowed() can never reach the rank map’s 4320p
tier. Update normalize() to return a distinct "4320p" value for 4320P/8K inputs
while keeping the existing mappings for lower tiers, and make sure allowed()
continues to derive ceiling_rank from normalize(ceiling) so the 5th tier is
preserved.

In `@web/src/hooks/queries/admin/policy.ts`:
- Around line 146-163: The version cache invalidation in useCreatePolicyVersion
uses the new row id instead of the version identifier that usePolicyVersion
caches under, so the query never matches. Update the onSuccess invalidation to
use the same key shape as adminKeys.policyVersion and usePolicyVersion, passing
the created version’s version_number (or equivalent version field from the
mutation result) rather than data.id. Keep invalidatePolicyDocuments unchanged,
and make sure the invalidated policyVersion key aligns with the
`versions/${version}` route used elsewhere.

In `@web/src/pages/admin-policy/PolicyDecisionLogTable.tsx`:
- Around line 105-113: The goPrevious handler mixes a side effect into the
setCursorStack functional updater by calling setCursor inside the updater, which
can break pagination state under Strict Mode. Refactor goPrevious so the updater
only computes and returns the next cursorStack, then perform setCursor with the
popped value outside the updater using a local variable. Keep
setSelectedID(undefined) as a separate update, and preserve the existing
behavior in PolicyDecisionLogTable’s goPrevious logic.

In `@web/src/pages/admin-policy/PolicyDocumentList.tsx`:
- Around line 167-196: The document selection in PolicyDocumentList is
mouse-only because the TableRow uses onClick without keyboard affordances.
Update the TableRow used for each document to be keyboard-accessible by adding
the appropriate role/tabIndex and an onKeyDown handler that triggers
selectDocument(document.id) for Enter/Space, while preserving the existing
onClick and stopPropagation behavior around the Switch.

In `@web/src/pages/admin-policy/PolicyEditorPanel.tsx`:
- Around line 138-154: The canSave check in PolicyEditorState is reading
validation.result directly even though validation is nullable, which breaks
strict null checking. Update the canSave expression to guard validation the same
way as validationMatchesDraft, using optional chaining or an explicit null check
before accessing compiled_ok. Keep the fix localized to PolicyEditorState and
preserve the existing validationMatchesDraft logic.

In `@web/src/pages/admin-policy/PolicyVersionHistory.tsx`:
- Around line 99-144: The version rows in PolicyVersionHistory are mouse-only
because the TableRow selection relies on onClick without keyboard support.
Update the row interaction so users can focus and activate a row with the
keyboard by adding accessible semantics and a key handler on the TableRow that
calls setSelectedVersionId(version.id) for the same selection behavior as
clicking, while preserving the existing rollback button stopPropagation
behavior.

---

Nitpick comments:
In `@docs/superpowers/specs/2026-07-02-opa-policy-engine-design.md`:
- Around line 130-149: The spec contains unlabeled fenced code blocks that
trigger markdownlint; update the fences in the internal/policy directory layout
section and the later vendor source example to use text as the language tag.
Keep the block contents unchanged and ensure both affected fences are explicitly
marked so the document passes lint.

In `@internal/api/handlers/policy.go`:
- Around line 479-490: Flatten the error flow in the time query parsing logic
inside the policy handler by removing the unnecessary else blocks after the
early returns in the from/to handling. Update the parseTimeQuery checks in the
policy handler so that, like the user_id and allowed branches, each successful
parse assigns directly to opts.From and opts.To without an else, keeping the
code gofmt-friendly and compliant with revive’s indent-error-flow rule.

In `@internal/policy/decisionlog_cleanup.go`:
- Around line 79-104: The fallback cleanup loop in
deleteExpiredDecisionRowsBefore can hammer the database by reissuing consecutive
10k-row DELETE batches with no pacing. Add a small sleep or backoff between
successful batch deletions inside the loop, keeping the existing batching and
stop condition intact. Make the pause part of the
deleteExpiredDecisionRowsBefore flow so the degraded-path cleanup runs more
gently under large backlogs.

In `@internal/policy/decisionlog_repo.go`:
- Around line 92-101: The SELECT column list is duplicated across
DecisionLogRepo.List and both Get query variants, which can drift when columns
change. Factor the shared projection in internal/policy/decisionlog_repo.go into
a single package-level constant or helper used by the query builders, and update
the List/Get query construction to reference that shared symbol instead of
repeating the column list.

In `@internal/policy/engine.go`:
- Line 17: Validate that defaultEvalTimeout remains safe under production load
for the Evaluate path, since any timeout is converted to ErrPolicyEvalFailed and
can cause fail-closed denials. Check the engine behavior around Evaluate,
defaultEvalTimeout, WithEvalTimeout, and SetEvalTimeout with load testing and
production-like CPU/GC contention, and if needed adjust the default or document
a recommended higher timeout for deployments that cannot guarantee sub-25ms
evals.

In `@internal/policy/simulate.go`:
- Around line 103-127: The stable snapshot retry loop is duplicated between
simulationSources and System.loadSnapshot, so extract the shared “read
generation → load ActiveSources → re-read generation until stable” logic into a
helper like loadStableSnapshot(ctx, store). Keep the permissive nil-store
handling in simulationSources itself, then delegate to the new helper, and
update System.loadSnapshot to call the same helper after its own nil check so
the invariant lives in one place.

In `@internal/policy/vendor_rego_test.go`:
- Around line 45-73: The tests in TestVendorQualityTableMatchesAccessPackage and
TestVendorRatingTableMatchesAccessPackage are validating raw Rego source text
instead of the rule output. Replace the strings.Contains checks on
readVendorFile with an actual Rego evaluation using
rego.New(...).PrepareForEval(...) as done in internal/policy/engine.go, then
compare the computed values for data.silo.lib.quality and data.silo.lib.ratings
against the access package entries.

In `@internal/policy/vendor/custom_stub.rego`:
- Line 1: The vendor scope stub filename is inconsistent with the sibling
override stubs, so rename the `silo_custom.scope` stub to follow the
`custom_<domain>_stub.rego` convention. Update the scope stub’s filename and
keep its package declaration aligned with the new `custom_scope_stub.rego` name
so it stays consistent with `custom_action_stub.rego` and
`custom_permission_stub.rego`.

In `@internal/policy/vendor/lib/quality_test.rego`:
- Around line 1-19: Add a regression test in quality_test.rego for the allowed()
behavior with a "4320p"/"8K" ceiling, since the current tests in test_allowed_*
only cover lower ceilings. Use the allowed() rule directly to assert the
expected outcome for a 4320p input with an 8K ceiling, so the normalize()
collapsing issue in quality.rego is caught if it still prevents rank-5 content
from being unlocked.

In `@internal/policy/vendor/lib/quality.rego`:
- Around line 48-59: The min rule in quality.rego shadows OPA’s built-in min()
and can cause future built-in calls in this package to fail, so rename the rule
to a non-conflicting name. Update the rule definition and any internal
references in this package (including other vendor .rego files such as
scope.rego that may call quality.min) to use the new symbol consistently, while
preserving the same logic and behavior.

In `@internal/policy/vendor/lib/ratings.rego`:
- Around line 29-44: The `min` rule in `ratings.rego` is shadowing the built-in
aggregate `min()` and can cause confusing lookup issues later. Rename the rule
to a clearer non-conflicting name such as `pick_lower`, and update any
references within `silo.lib.ratings` or nearby policies that call it so the
package can still use the real built-in `min(collection)` if needed.
- Around line 1-45: Add a companion ratings_test.rego for
internal/policy/vendor/lib/ratings.rego and cover the exported helpers allowed()
and min() with direct unit tests. Include edge cases for empty ceiling handling,
unknown rating strings, and boundary comparisons across the rank map, using the
normalize(), allowed(), and min() behavior as the reference points.

In `@internal/policy/vendor/permission.rego`:
- Around line 87-97: The helper predicates user_enabled, acting_as_primary, and
user_libraries_restricted in permission.rego are using bare object.get(...)
results as truthy conditions. Update each rule to compare the returned value
explicitly against true or false, keeping the same function names so the static
analysis warning is addressed consistently across all three helpers.

In `@migrations/sql/20260702153902_policy_foundation.sql`:
- Around line 78-90: The migration only creates the policy_decisions_default
partition and the related indexes, so writes can spill into the default
partition if range partitions are not ready. Update the partition provisioning
flow for public.policy_decisions to pre-create upcoming time windows at or
before write time, and verify the runtime partition manager does so reliably.
Also add monitoring/alerting around policy_decisions_default growth so fallback
accumulation is detected before it undermines pruning and retention behavior.

In `@web/src/components/policy/RegoEditor.tsx`:
- Around line 45-56: The RegoEditor extensions array is being recreated on every
keystroke because useMemo depends on value, which forces CodeMirror to
reconfigure on each edit. Update RegoEditor so the linter callback reads the
current document from the view argument instead of closing over value, then
remove value from the useMemo deps and keep only the truly static inputs like
issues and readOnly. This keeps the extensions stable while still allowing
diagnostics to reflect the live editor content.

In `@web/src/lib/policyDiagnostics.ts`:
- Around line 17-30: The `policyDiagnostics` mapping in `toDiagnostics` contains
a redundant ternary in the `to` calculation that always resolves to the same
value. Simplify the `to` expression by removing the `line.to === line.from ?
from : from + 1` branch and keep the existing clamp logic intact, so the bounds
handling remains unchanged while the code becomes clearer.

In `@web/src/pages/admin-policy/PolicyDocumentList.tsx`:
- Around line 125-128: The Button in PolicyDocumentList passes the async create
handler directly to onClick, which triggers the promise-returning callback lint
issue. Update the create usage so the click handler is wrapped to intentionally
ignore the returned promise, matching the existing toggleDocument pattern, and
keep the async logic inside create unchanged.

In `@web/src/pages/admin-policy/policyPageUtils.ts`:
- Around line 1-82: Move the shared helpers out of the admin policy page module
into the project’s shared frontend utilities area, since functions like
formatPolicyDate, prettyPolicyJson, compileIssuesFromError, and messageFromError
are generic and not page-specific. Relocate them to web/src/lib or
web/src/utils, keep the same exported APIs, and update any imports that
currently reference policyPageUtils so the admin-policy page still uses the new
shared location.

In `@web/src/pages/admin-policy/PolicyVersionHistory.tsx`:
- Around line 40-52: The version lookup in PolicyVersionHistory should use a
single usePolicyVersion call instead of maintaining both selectedVersion and
effectiveVersion with ternary branching. Reuse the already computed
effectiveSelectedId to drive that one hook, then update sourceVersion to read
from that single result so the row highlight and displayed version stay in sync.
- Around line 156-175: The rollback activation confirmation in
PolicyVersionHistory duplicates the activation dialog markup used in
PolicyEditorPanel, so extract a shared ActivateVersionDialog component and reuse
it in both places. Move the common AlertDialog structure, title/description
pattern, and cancel/action footer into that shared component, then pass in the
version text and confirm handler from PolicyVersionHistory and PolicyEditorPanel
to keep the dialogs consistent and avoid drift.

In `@web/src/pages/admin-settings/LogRetentionSettings.tsx`:
- Around line 32-44: The policy decision log keys are duplicated as string
literals in GLOBAL_KEYS and then redefined as separate constants, which can
drift apart over time. Move POLICY_DECISION_LOG_RETENTION_DAYS_KEY,
POLICY_DECISION_LOG_VERBOSITY_KEY, and POLICY_DECISION_LOG_SCOPE_SAMPLE_RATE_KEY
above GLOBAL_KEYS in LogRetentionSettings and reference those constants inside
GLOBAL_KEYS instead of hardcoding the strings.
🪄 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: 7577720b-d800-4641-89a2-0b42a6169a9c

📥 Commits

Reviewing files that changed from the base of the PR and between 5172155 and ed9a832.

⛔ Files ignored due to path filters (2)
  • go.sum is excluded by !**/*.sum
  • web/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (88)
  • cmd/silo/main.go
  • docs/superpowers/plans/2026-07-02-opa-policy-engine.md
  • docs/superpowers/specs/2026-07-02-opa-policy-engine-design.md
  • go.mod
  • internal/access/resolver.go
  • internal/access/resolver_test.go
  • internal/api/handlers/admin.go
  • internal/api/handlers/policy.go
  • internal/api/handlers/policy_test.go
  • internal/api/middleware/policy_gates.go
  • internal/api/middleware/policy_gates_test.go
  • internal/api/router.go
  • internal/audiobooks/access_resolver.go
  • internal/cache/redis.go
  • internal/config/config.go
  • internal/config/db_loader.go
  • internal/downloads/policy.go
  • internal/downloads/policy_action_test.go
  • internal/downloads/policy_test.go
  • internal/downloads/service.go
  • internal/downloads/subscription_service.go
  • internal/playback/session.go
  • internal/playback/session_test.go
  • internal/policy/action_parity_test.go
  • internal/policy/compile.go
  • internal/policy/compile_test.go
  • internal/policy/decisionlog.go
  • internal/policy/decisionlog_cleanup.go
  • internal/policy/decisionlog_repo.go
  • internal/policy/decisionlog_repo_test.go
  • internal/policy/decisionlog_test.go
  • internal/policy/engine.go
  • internal/policy/engine_bench_test.go
  • internal/policy/errors.go
  • internal/policy/input.go
  • internal/policy/pdp.go
  • internal/policy/permission_parity_test.go
  • internal/policy/playback_adapter.go
  • internal/policy/scope_parity_test.go
  • internal/policy/simulate.go
  • internal/policy/store.go
  • internal/policy/store_test.go
  • internal/policy/system.go
  • internal/policy/system_test.go
  • internal/policy/vendor.go
  • internal/policy/vendor/action.rego
  • internal/policy/vendor/action_test.rego
  • internal/policy/vendor/custom_action_stub.rego
  • internal/policy/vendor/custom_permission_stub.rego
  • internal/policy/vendor/custom_stub.rego
  • internal/policy/vendor/lib/quality.rego
  • internal/policy/vendor/lib/quality_test.rego
  • internal/policy/vendor/lib/ratings.rego
  • internal/policy/vendor/permission.rego
  • internal/policy/vendor/permission_test.rego
  • internal/policy/vendor/scope.rego
  • internal/policy/vendor/scope_test.rego
  • internal/policy/vendor_rego_test.go
  • internal/policy/viewer_resolver.go
  • internal/policy/viewer_resolver_test.go
  • internal/taskmanager/tasks/policy_decision_log_cleanup.go
  • migrations/sql/20260702153902_policy_foundation.sql
  • web/package.json
  • web/src/App.tsx
  • web/src/api/types.ts
  • web/src/components/policy/RegoEditor.tsx
  • web/src/hooks/queries/admin/policy.test.ts
  • web/src/hooks/queries/admin/policy.ts
  • web/src/hooks/queries/keys.ts
  • web/src/lib/adminNavigation.ts
  • web/src/lib/adminSettingsSearch.ts
  • web/src/lib/policyDiagnostics.ts
  • web/src/lib/regoLanguage.ts
  • web/src/pages/admin-policy/AdminPolicyLayout.tsx
  • web/src/pages/admin-policy/PolicyDecisionLogTable.test.tsx
  • web/src/pages/admin-policy/PolicyDecisionLogTable.tsx
  • web/src/pages/admin-policy/PolicyDocumentList.test.tsx
  • web/src/pages/admin-policy/PolicyDocumentList.tsx
  • web/src/pages/admin-policy/PolicyEditorPanel.test.tsx
  • web/src/pages/admin-policy/PolicyEditorPanel.tsx
  • web/src/pages/admin-policy/PolicySimulatePanel.test.tsx
  • web/src/pages/admin-policy/PolicySimulatePanel.tsx
  • web/src/pages/admin-policy/PolicyVendorViewer.tsx
  • web/src/pages/admin-policy/PolicyVersionHistory.tsx
  • web/src/pages/admin-policy/policyExamples.ts
  • web/src/pages/admin-policy/policyPageUtils.ts
  • web/src/pages/admin-policy/policyTestUtils.tsx
  • web/src/pages/admin-settings/LogRetentionSettings.tsx

Comment thread cmd/silo/main.go Resolved
Comment thread internal/playback/session.go Resolved
Comment thread internal/policy/compile_test.go Resolved
Comment thread internal/policy/compile.go Resolved
Comment thread internal/policy/compile.go Resolved
Comment thread web/src/hooks/queries/admin/policy.ts Resolved
… Rego

The Baseline tab dumped five Rego modules into read-only editors. It now
leads with what the rules actually do: one card per domain with
plain-language statements of the shipped behavior and a note on what an
override may change, plus content-rating and playback-quality tier
ladders parsed live from the lib module sources (so the tiers shown are
the ones the server enforces, not a hardcoded copy). The Rego source
stays one click away behind a per-module accordion and remains the
stated source of truth; unrecognized modules fall back to source-only.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai coderabbitai Bot removed the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 2, 2026

@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)
web/src/pages/admin-policy/policyPresentation.tsx (1)

1-123: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Filename should be PascalCase per project convention.

This is a new .tsx file that exports a React component (PolicyStatusPill), but the filename policyPresentation.tsx uses camelCase. As per coding guidelines, "Use PascalCase.tsx for React components and pages." Consider renaming (e.g. PolicyPresentation.tsx) and updating the two importers (PolicyDocumentList.tsx, PolicyVendorViewer.tsx).

🤖 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/admin-policy/policyPresentation.tsx` around lines 1 - 123, The
new React component file uses camelCase naming instead of the project’s
PascalCase convention. Rename the `policyPresentation.tsx` module to
`PolicyPresentation.tsx`, then update the import sites that reference
`policyDomainMeta`, `policyDocumentStatus`, and `PolicyStatusPill` in
`PolicyDocumentList.tsx` and `PolicyVendorViewer.tsx` to use the new filename.

Source: Coding guidelines

🤖 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 `@web/src/pages/admin-policy/policyPresentation.tsx`:
- Around line 1-123: The new React component file uses camelCase naming instead
of the project’s PascalCase convention. Rename the `policyPresentation.tsx`
module to `PolicyPresentation.tsx`, then update the import sites that reference
`policyDomainMeta`, `policyDocumentStatus`, and `PolicyStatusPill` in
`PolicyDocumentList.tsx` and `PolicyVendorViewer.tsx` to use the new filename.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7577720b-d800-4641-89a2-0b42a6169a9c

📥 Commits

Reviewing files that changed from the base of the PR and between ed9a832 and ea75fe6.

📒 Files selected for processing (12)
  • web/src/pages/admin-policy/AdminPolicyLayout.tsx
  • web/src/pages/admin-policy/PolicyDocumentList.tsx
  • web/src/pages/admin-policy/PolicyEditorPanel.test.tsx
  • web/src/pages/admin-policy/PolicyEditorPanel.tsx
  • web/src/pages/admin-policy/PolicySimulatePanel.test.tsx
  • web/src/pages/admin-policy/PolicySimulatePanel.tsx
  • web/src/pages/admin-policy/PolicyVendorViewer.test.tsx
  • web/src/pages/admin-policy/PolicyVendorViewer.tsx
  • web/src/pages/admin-policy/PolicyVersionHistory.tsx
  • web/src/pages/admin-policy/policyPresentation.tsx
  • web/src/pages/admin-policy/vendorBaseline.ts
  • web/vite.config.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • web/src/pages/admin-policy/PolicySimulatePanel.test.tsx
  • web/src/pages/admin-policy/AdminPolicyLayout.tsx
  • web/src/pages/admin-policy/PolicyEditorPanel.test.tsx
  • web/src/pages/admin-policy/PolicyVersionHistory.tsx
  • web/src/pages/admin-policy/PolicyEditorPanel.tsx

Quick104 and others added 3 commits July 2, 2026 15:51
Groups with permission toggles become the everyday admin surface; the
Rego editor is demoted behind policy.editor_enabled (default off).
Restriction-only composition: group grants are an upper bound, per-user
settings tighten further — same rule as the existing account/profile
merge, one layer up.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
…y composition

New access_groups table + users.access_group_id (one group per user, NULL
= today's behavior). Group grants are an upper bound composed with the
user's own settings by strictest-wins rules — library intersection,
MinQuality, AND'd booleans, strictest positive stream/transcode limits,
permission-mask intersection, and a requests toggle gating CreateRequest.
The merge happens in Go (access.ApplyGroupPolicy /
EffectivePolicyForUser) before policy inputs are built, so vendor Rego,
the parity suites, and the decision log are untouched; every enforcement
surface (viewer scope in both resolvers, permission gates, downloads,
playback admission, requests) consumes the effective policy and fails
closed on provider errors. Changing a group's quality ceiling bumps its
members' access_policy_revision, mirroring the per-user rule.

Additive admin API: /admin/access-groups CRUD with member counts;
PUT /admin/users/{id} + user DTOs gain access_group_id.

Also demotes the Rego editor: policy.editor_enabled (default off,
hot-reloaded) drives the capability endpoint's editor_available and
403-gates editor endpoints while the engine and decision logging keep
running.

Design: docs/superpowers/specs/2026-07-02-access-groups-design.md.
Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed
(composition core + fail-closed call-site audit) and verified here.
DB-backed group-store tests pending local Postgres recovery.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
New /admin/access-groups: a card grid summarizing each group (member
count + key restrictions), drilling into an editor that reuses the same
LibraryAccessSelector and quality presets as the user editor, with
toggles for downloads/transcoded-downloads/requests, concurrent-stream
and transcode limits, and a permissions mask (all-assignable by default,
narrowable to specific permissions). Delete warns how many members fall
back to the built-in defaults. Copy states the composition rule up front:
a group grants the most a member can do; their own restrictions still
apply on top.

The user editor gains a Group picker and read-only row; the Policy nav
entry is now hidden unless the capability reports the editor enabled.
Plumbing (types, hooks, user-editor picker, nav gating) drafted by Codex
(GPT-5.5); the Groups page hand-built. Verified: 25 tests across the
touched suites, tsc, eslint, prettier, and a production build.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104 Quick104 changed the title feat(policy): embedded OPA policy engine with admin policy editor and decision audit log feat(policy): access groups + embedded OPA policy engine with decision audit log Jul 2, 2026

@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: 4

🧹 Nitpick comments (3)
web/src/hooks/queries/admin/accessGroups.test.ts (1)

10-10: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shared test utility lives outside lib/utils.

installPolicyStorageMocks/jsonResponse are imported from @/pages/admin-policy/policyTestUtils for an unrelated feature (access groups). Since this utility is now shared across features, consider relocating it to web/src/lib or web/src/utils to match the intended module boundaries.

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

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/hooks/queries/admin/accessGroups.test.ts` at line 10, The access
groups test is importing shared helpers from a feature-specific module, which
breaks the intended frontend module boundaries. Move installPolicyStorageMocks
and jsonResponse out of admin-policy/policyTestUtils into a shared location
under web/src/lib or web/src/utils, then update accessGroups.test.ts and any
other consumers to import them from the new shared module. Keep the shared
utility names the same so the existing test setup remains easy to locate.

Source: Coding guidelines

internal/api/middleware/policy_gates.go (1)

162-166: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Log the effective-policy computation failure before denying.

Failing closed here is correct, but the error from access.EffectivePolicyForUser is dropped entirely. If the group store/DB has an outage, this permission gate will silently deny all metadata curation with no diagnostic trail.

♻️ Proposed fix to log before denying
 		effective, err := access.EffectivePolicyForUser(r.Context(), user, m.groups)
 		if err != nil {
+			slog.Warn("failed to compute effective access policy for metadata curation gate", "user_id", user.ID, "error", err)
 			writeForbidden(w, metadataCurationRequiredMsg)
 			return
 		}
🤖 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/middleware/policy_gates.go` around lines 162 - 166, The
effective-policy lookup in policy gate handling is failing closed without any
diagnostic output, so log the error returned by access.EffectivePolicyForUser
before calling writeForbidden and returning. Update the middleware path in the
policy gate logic to emit a clear error via the existing request/logger context,
including the failure details and the relevant user/groups context if available,
so outages in the group store or DB can be traced while keeping the denial
behavior unchanged.
internal/requests/service.go (1)

780-786: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Don't mask policy-lookup failures as ErrForbidden.

When GetPolicyForUser fails (e.g. transient DB error), returning ErrForbidden presents a permanent authorization denial to the caller and hides the operational fault from logs/metrics. This also diverges from resolver.Resolve and downloads.effectiveDownloadUser, which both propagate the underlying error. Prefer surfacing the real error (fail with a retryable/500 path) so outages aren't misreported as forbidden.

♻️ Propagate the lookup error
 	group, err := s.groupProvider.GetPolicyForUser(ctx, userID)
 	if err != nil {
-		return ErrForbidden
+		return fmt.Errorf("loading access group policy for user %d: %w", userID, 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/requests/service.go` around lines 780 - 786, The policy lookup in
the request flow is masking operational failures by converting every
GetPolicyForUser error into ErrForbidden. Update the logic around
s.groupProvider.GetPolicyForUser in the request service so lookup failures are
returned to the caller as the underlying error (matching resolver.Resolve and
downloads.effectiveDownloadUser), while still returning ErrForbidden only when
the policy explicitly disallows requests.
🤖 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/admin.go`:
- Around line 561-562: The admin access update flow is missing session
revocation when AccessGroupID changes, so active sessions can keep the old
effective scope. Update the handler path around AccessGroupIDSet/AccessGroupID
in admin.go to treat access_group_id as an access policy change: compare the new
value against the stored one, revoke existing sessions when it changes, and bump
access_policy_revision. Make sure the same policy-change logic used for other
access-affecting fields is applied here so session revocation is triggered
consistently.

In `@internal/auth/repository.go`:
- Around line 322-326: Updating access_group_id in the repository update flow
does not bump access_policy_revision, so profile/session tokens can remain valid
after group membership changes. In internal/auth/repository.go, update the
access-group assignment logic in the user update path (the block using
input.AccessGroupIDSet) to also add a revision-bump predicate when
access_group_id changes, using the same style as the existing revision checks
and specifically comparing access_group_id with IS DISTINCT FROM $%d so the
revision is incremented on group changes.

In `@internal/downloads/service.go`:
- Around line 286-303: The nil guard in effectiveDownloadUser is after the
EffectivePolicyForUser call, so a nil user can be passed into policy evaluation
first. Move the user == nil check to the start of effectiveDownloadUser before
calling access.EffectivePolicyForUser, then keep the existing out copy and field
assignments unchanged for the non-nil path.

In `@web/src/pages/AdminAccessGroups.tsx`:
- Around line 238-269: The save logic in AdminAccessGroups should keep the
transcode setting consistent with download access: when downloadAllowed is
false, reset or clamp transcodeAllowed to false before building the
AccessGroupInput in save, and also ensure setPermissionAllowed/group state
updates cannot preserve an enabled transcode flag while downloads are disabled.
Use the existing downloadAllowed, transcodeAllowed, save, and
setPermissionAllowed symbols to locate the fix and apply the same behavior
anywhere this state is synchronized.

---

Nitpick comments:
In `@internal/api/middleware/policy_gates.go`:
- Around line 162-166: The effective-policy lookup in policy gate handling is
failing closed without any diagnostic output, so log the error returned by
access.EffectivePolicyForUser before calling writeForbidden and returning.
Update the middleware path in the policy gate logic to emit a clear error via
the existing request/logger context, including the failure details and the
relevant user/groups context if available, so outages in the group store or DB
can be traced while keeping the denial behavior unchanged.

In `@internal/requests/service.go`:
- Around line 780-786: The policy lookup in the request flow is masking
operational failures by converting every GetPolicyForUser error into
ErrForbidden. Update the logic around s.groupProvider.GetPolicyForUser in the
request service so lookup failures are returned to the caller as the underlying
error (matching resolver.Resolve and downloads.effectiveDownloadUser), while
still returning ErrForbidden only when the policy explicitly disallows requests.

In `@web/src/hooks/queries/admin/accessGroups.test.ts`:
- Line 10: The access groups test is importing shared helpers from a
feature-specific module, which breaks the intended frontend module boundaries.
Move installPolicyStorageMocks and jsonResponse out of
admin-policy/policyTestUtils into a shared location under web/src/lib or
web/src/utils, then update accessGroups.test.ts and any other consumers to
import them from the new shared module. Keep the shared utility names the same
so the existing test setup remains easy to locate.
🪄 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: 9cb29923-f98e-4a92-ba7f-05811d29af4e

📥 Commits

Reviewing files that changed from the base of the PR and between ea75fe6 and f36f50a.

📒 Files selected for processing (47)
  • cmd/silo/main.go
  • docs/superpowers/specs/2026-07-02-access-groups-design.md
  • internal/access/group_store.go
  • internal/access/group_store_test.go
  • internal/access/groups.go
  • internal/access/groups_test.go
  • internal/access/resolver.go
  • internal/access/resolver_test.go
  • internal/api/handlers/access_groups.go
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_settings_checks_test.go
  • internal/api/handlers/policy.go
  • internal/api/handlers/policy_test.go
  • internal/api/middleware/policy_gates.go
  • internal/api/middleware/policy_gates_test.go
  • internal/api/router.go
  • internal/audiobooks/access_resolver.go
  • internal/auth/repository.go
  • internal/auth/repository_access_group_test.go
  • internal/config/config.go
  • internal/config/db_loader.go
  • internal/config/db_loader_test.go
  • internal/config/restart_keys_test.go
  • internal/downloads/policy.go
  • internal/downloads/policy_action_test.go
  • internal/downloads/service.go
  • internal/models/user.go
  • internal/playback/session_test.go
  • internal/policy/viewer_resolver.go
  • internal/policy/viewer_resolver_test.go
  • internal/requests/service.go
  • internal/requests/service_test.go
  • migrations/sql/20260702172000_access_groups.sql
  • web/src/App.tsx
  • web/src/api/types.ts
  • web/src/components/AdminSidebar.test.tsx
  • web/src/components/AdminSidebar.tsx
  • web/src/hooks/queries/admin/accessGroups.test.ts
  • web/src/hooks/queries/admin/accessGroups.ts
  • web/src/hooks/queries/admin/users.ts
  • web/src/hooks/queries/keys.ts
  • web/src/lib/adminNavigation.ts
  • web/src/pages/AdminAccessGroups.test.tsx
  • web/src/pages/AdminAccessGroups.tsx
  • web/src/pages/AdminDashboard.tsx
  • web/src/pages/AdminUserDetail.test.tsx
  • web/src/pages/AdminUserDetail.tsx
✅ Files skipped from review due to trivial changes (2)
  • migrations/sql/20260702172000_access_groups.sql
  • docs/superpowers/specs/2026-07-02-access-groups-design.md
🚧 Files skipped from review as they are similar to previous changes (10)
  • internal/config/db_loader.go
  • internal/config/config.go
  • internal/audiobooks/access_resolver.go
  • internal/policy/viewer_resolver.go
  • internal/downloads/policy_action_test.go
  • internal/playback/session_test.go
  • internal/downloads/policy.go
  • internal/api/handlers/policy_test.go
  • internal/api/handlers/policy.go
  • internal/api/router.go

Comment thread internal/api/handlers/admin.go Resolved
Comment thread internal/auth/repository.go Resolved
Comment thread internal/downloads/service.go Resolved
Comment thread web/src/pages/AdminAccessGroups.tsx Resolved
Quick104 and others added 2 commits July 2, 2026 17:00
Adds access_groups.is_default with a partial unique index (one default
at most — the profiles is_primary pattern) and seeds a permissive
'Default Group' whose ceiling is a no-op, so assignment never changes
anyone's effective access until an admin edits it. The seed is guarded
against pre-existing defaults and name collisions; the Down migration
only removes the row if it is still untouched.

Assignment happens at the single INSERT INTO users choke point
(UserRepository.Create): when no explicit group is given, access_group_id
is filled by a scalar subquery on the default flag — NULL when no default
exists. Every creation path (setup, signup, invites, OAuth, admin create)
is covered by construction. Setting a new default via the API atomically
clears the previous one in the same transaction.

Deleting or unsetting the default is legal: new users then start with no
group, which is pre-feature behavior.

Implementation drafted by Codex (GPT-5.5); migration guards and the
choke-point subquery reviewed line-by-line here.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
Cards show a Default badge; the group editor gains a 'Default for new
users' toggle (with copy noting existing users are never moved); the
delete dialog warns when removing the default that new accounts will
start with no group.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
Quick104 and others added 9 commits July 2, 2026 19:11
…e work

Exclude every nondeterministic builtin from the admin sandbox instead of
denylisting names, so OPA upgrades cannot silently expose impure builtins
while pure helpers like net.cidr_contains stay usable. Apply the same
capabilities to the runtime engine, cap concurrent compile checks, and
reject oversized sources before they reach the uncancelable compiler.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ecks

Bare object.get truthiness treated any non-false value as satisfied, so a
malformed override 'allowed' value could fail to tighten a base grant and
hand-crafted simulate input could flip flag predicates. Compare against
literal true so anything else denies.

Co-Authored-By: Claude Fable 5 <[email protected]>
CleanupDecisionLogsOnce now returns the first error alongside the deleted
count so a broken partition manager or DB outage marks the scheduled task
failed instead of reporting 100% success while policy_decisions grows.

Co-Authored-By: Claude Fable 5 <[email protected]>
A policy-evaluation failure was silently mapped to the too-many-streams
denial, making an engine outage indistinguishable from a real limit hit.

Co-Authored-By: Claude Fable 5 <[email protected]>
…resolver

effectiveDownloadUser dereferenced policy state before its nil-user check,
and the ABS handler lost viewer-scoped filtering entirely when the policy
system was unavailable because no legacy access.NewResolver fallback was
wired like the other resolver paths.

Co-Authored-By: Claude Fable 5 <[email protected]>
- invalidate the version query by version_number, the key usePolicyVersion
  actually caches under
- keep the goPrevious cursor-stack updater pure (Strict Mode double-invoke)
- make version history rows keyboard-selectable like the document list
- clamp download_transcode_allowed when downloads are disabled so groups
  cannot save a contradictory record

Co-Authored-By: Claude Fable 5 <[email protected]>
The policy write endpoints (create document/version, set enabled,
validate, simulate) decoded JSON bodies without a size limit, so an
oversized payload buffered fully in memory before CompileCheck's
256 KiB source cap could reject it. Route all five through a shared
decodePolicyRequest helper that wraps the body in http.MaxBytesReader
and returns 413 with the repo's standard too_large error shape.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UtnZ2Uewzo959hpneLrtRN
Deleting the default group (or unsetting its is_default flag) left the
server with no default: new non-admin users were then created ungrouped
with max_streams/max_transcodes of 0 — unlimited — because the legacy
per-user column defaults were retired in favor of the group's ceilings.

The store now rejects both operations with ErrDefaultGroupRequired
(mapped to 409); promoting another group remains the supported way to
move the default, and atomically clears the previous one. The admin UI
disables the delete button and the default toggle on the default group
and explains the promote-another-group flow.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UtnZ2Uewzo959hpneLrtRN
…lsewhere

The editor state was keyed on the active version's id/sha, so a
background refetch after another admin (or another tab) activated a
version remounted the editor and silently discarded the dirty draft.

PolicyEditorPanel now pins the seed it is editing against and only
adopts an incoming seed when nothing can be lost: the editor is clean,
the draft already equals the incoming source (the same-admin activate
flow), or the selection moved to a different document. Otherwise the
pinned editor stays mounted and an inline notice offers an explicit
"Load live version" action.

Part of #272

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UtnZ2Uewzo959hpneLrtRN
@Quick104

Quick104 commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

Review remediation round 3 — addressed findings 2–4 from the deep review (finding 1, the Default Group capability clamp on upgrade, was reviewed and accepted as intended house-rule behavior):

  • a17d13c0 fix(web): unsaved Rego drafts survive a concurrent activation. The editor pins the seed it's editing against and only adopts a newer one when nothing can be lost; otherwise it keeps the draft and shows an inline "Load live version" notice. Document switches still reset as before.
  • 4d569ee9 fix(access): the default access group can no longer be deleted or demoted (409 ErrDefaultGroupRequired) — promoting another group remains the way to move the default. This closes the path where new non-admin users were created ungrouped and unlimited after the default group was removed. UI disables both actions on the default group with an explanation.
  • b11ca36a fix(api): all five policy write endpoints now decode through a shared 1 MiB MaxBytesReader helper (413 too_large), matching the repo's other upload handlers.

Verification: go build ./..., go test ./internal/{access,api/handlers,policy}/..., golangci-lint (touched files clean), web vitest (admin-policy 12/12, AdminAccessGroups 2/2), tsc -b, ESLint/Prettier clean, make verify-local-paths. DB-gated group-store tests were updated to the new contract but still need a run against a migrated DB (local Postgres remains unavailable).

🤖 Generated with Claude Code

https://claude.ai/code/session_01UtnZ2Uewzo959hpneLrtRN

Quick104 and others added 8 commits July 5, 2026 16:31
…ded/apply state

A stored custom source that stops compiling used to be silently skipped on
reload: the bundle widened to vendor-only for that domain while the generation
reported fully applied. Reload is now strict — a bad enabled source fails the
reload and the last known-good engine keeps serving. Boot keeps its vendor
fallback for availability, but skips are recorded on the engine and exposed
(with store-outage reasons) through System.DegradedState and additive
degraded fields on GET /policy/capability. Activate/SetEnabled re-run
CompileCheck instead of trusting the stored compiled_ok flag.

Mutation endpoints also no longer conflate persistence with live apply:
activation/enable responses carry additive applied/failed_step/
loaded_generation fields and return 202 when the store change persisted but
the local reload failed.

Addresses review findings C1, C2, and the degraded-signal gap (6.1).

Co-Authored-By: Claude Fable 5 <[email protected]>
…e_verified

Deny handling used to branch on exact free-text reason strings in three Go
consumers, and playback reported ANY unrecognized reason — including custom
override free text and engine failures — as a stream-limit error. Decisions
now carry a stable reason_code (custom overrides always get custom_denial);
downloads, the metadata-curation gate, and playback admission switch on codes,
with a new ErrPlaybackNotAllowed -> 403 playback_not_allowed mapping for
non-limit denials. Rego tests pin every vendor code.

The scope contract's tighten-only profile_verified output was also emitted but
never consumed; a policy revocation now surfaces as ErrProfileUnverified (403
profile_unverified) instead of silently proceeding.

Addresses review findings 6.2 and C4.

Co-Authored-By: Claude Fable 5 <[email protected]>
…item authorization

EnsureAccessible, EnsureAccessibleIDs, and FilterAccessibleContentIDs gated
library access with allow/deny predicates over a single joined
media_item_libraries row, so an item linked to BOTH a passing library and a
disabled one satisfied the disabled check via the passing row — a direct-ID
bypass of disabled-library scope on the detail, media-file, playback, and
download paths. All library access predicates now share one helper
(libraryAccessConditions) emitting independent EXISTS / NOT EXISTS subqueries,
the semantics GetByIDsWithAccess already used, including the orphan-item
membership guard for disabled-only scopes. SQL-shape tests pin every builder
and a DB-gated regression test covers the dual-library item end to end.

Addresses review finding C3 (plus the same shape in
buildFilterAccessibleContentIDsSQL, which the review did not flag).

Co-Authored-By: Claude Fable 5 <[email protected]>
…er advisory lock

The concurrent-download quota was check-then-insert with nothing serializing
the pair: parallel creates could all observe free quota before any row
existed, bypassing the cap and stacking artifact encode jobs. All four
check->insert spans (ephemeral original, artifact-backed, series batch,
managed batch) now run inside Repository.WithUserQuotaLock — a
pg_advisory_xact_lock keyed by user, so the serialization holds across nodes.
The artifact path keeps the limiter-before-Ensure ordering (a rejected request
must not leave an encode job behind) by holding the lock across Ensure.
Managed-entry replacement stays quota-exempt and lock-free. A DB-gated
barrier test races 8 creates against a cap of 1.

Addresses review finding C5.

Co-Authored-By: Claude Fable 5 <[email protected]>
… remux downloads

Direct-original and remux downloads serve the source resolution unchanged, but
create-time policy checks left file_quality empty — an over-ceiling source
registered a row serveDownloadBytes could never satisfy. Resolve now runs a
final download action check with FileQuality populated on those two paths
(capped transcodes keep the ceiling-on-artifact behavior), a custom override
ceiling below the served resolution denies, and quality_ceiling_exceeded maps
to ErrQualityUnavailable. The ActionInput contract now documents exactly when
file_quality and the rating facts are supplied so custom policy authors are
not misled.

Addresses review finding C6.

Co-Authored-By: Claude Fable 5 <[email protected]>
…meouts observable

A custom scope override that exceeds the 25ms eval budget compiled fine,
activated fine, and then converted to 500s on every authenticated request —
server-wide lockout authored in the admin editor. Activation and enable now
run GuardEvalCost: the candidate source is evaluated on a throwaway engine
against a canned representative input under the live budget, and a source
that cannot complete is rejected 422 with ErrPolicySlowEval before it goes
live. Runtime timeouts keep failing closed but now carry a distinct
ErrPolicyEvalTimeout sentinel, an Error log, and a per-engine counter exposed
as eval_timeouts on GET /policy/capability so intermittent near-budget
policies are attributable.

Addresses review finding C7.

Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Conflicts resolved:
- internal/config/config.go: keep both new Config fields (Policy from this
  branch, ClientIP from main's trusted-proxy work)
- internal/playback/errors.go: keep both new sentinels (ErrPlaybackNotAllowed
  from this branch, ErrSessionSuperseded/ErrLimitProviderUnavailable from
  main's restart-resilient playback)
- web/src/pages/admin-settings/GeneralSettings.tsx: prettier re-run on the
  auto-merged result

Verified post-merge: go build ./... clean; policy, playback (admission/session),
downloads, catalog, api handlers/middleware, and config test suites green;
web lint 0 errors, format:check and tsc -b clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 merged commit ce17a37 into main Jul 5, 2026
1 check passed
@Quick104
Quick104 deleted the claude/wizardly-jepsen-f6f5ea branch July 5, 2026 21:38
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…n audit log (Silo-Server#282)

* docs(policy): add OPA policy engine design spec and implementation plan

Co-Authored-By: Claude Fable 5 <[email protected]>

* build(deps): add OPA v1.18.2 SDK for the policy engine

Pulls github.com/open-policy-agent/opa v1.18.2 (policy engine core for
the upcoming internal/policy subsystem) and the transitive upgrades go
mod tidy applied (otel 1.44, grpc 1.81.1, prometheus/common 0.67.5).
Full build verified.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(policy): add OPA engine core, vendor scope policy, and parity suite

New internal/policy package (dead code — nothing wires into request paths
yet): prepared-query Engine with 25ms eval timeout and fail-closed decode,
typed PDP.ResolveViewerScope, go:embed vendor bundle, capabilities lockdown
for future admin-authored Rego, and vendor scope.rego reproducing
access.Resolver.Resolve (library intersection, disabled-library handling,
quality/rating ceilings) with a narrowing-only silo_custom.scope.override
extension hook.

Parity proven by 1368 dual-execution subtests against the real
access.Resolver, including the nil-vs-empty AllowedLibraryIDs battery and
quality/rating variation; rank tables are test-pinned to internal/access.
Rego unit tests run via opa/v1/tester inside go test. Bench:
~106µs/op per scope decision incl. input marshaling.

Also restores the OPA requirement to go.mod (the earlier deps commit ran
go mod tidy before any import existed, so tidy dropped it).

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed,
corrected (quality.allowed raw-file-rank divergence), and verified here.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(policy): add policy document store, foundation schema, and compile-check

policy_foundation migration: policy_documents (one enabled doc per domain
via partial unique index — two enabled docs would define override twice
and conflict at eval), immutable policy_document_versions, single-row
policy_generation counter, and the partitioned policy_decisions log table
(daily range partitions, no FK, denial partial index).

PolicyStore: transactional version numbering (FOR UPDATE), activation
that verifies compiled_ok and bumps the generation in the same tx,
enable/disable with typed ErrDomainAlreadyEnabled, and a delete guard for
documents with an active version. CompileCheck sandboxes admin Rego:
locked capabilities (no http.send/net.*/opa.runtime), enforced
silo_custom.<domain> package path, vendor+stub layering, 2s budget,
structured row/col errors. Engine gains NewEngineWithCustom /
NewEngineFromStore with WARN-and-skip for invalid custom rows.

DB-backed tests verified against a migrated Postgres (concurrent version
numbering, atomic generation bumps, activation guards).

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed and
verified here (domain constants extracted).

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(policy): add policy System lifecycle with hot reload and cross-node invalidation

policy.System owns one long-lived Engine and reloads it in place when
policy documents change: EventPolicyChanged on the existing ChannelAdmin
bus (new cache event constant) plus a 60s generation-poll fallback for
Redis-less deployments, with a generation-consistent snapshot read.
Vendor compile failure is startup-fatal; store/custom failures degrade
to vendor-only and the poll loop heals them; runtime reload failures
keep the last known-good engine. NotifyChanged gives the future admin
handlers synchronous local reload + cross-node publish.

Wiring: constructed in integrated/api modes only, PolicySystem field on
api.Dependencies (unused by routes yet), policy.eval_timeout_ms setting
(hot-reloaded via configWatcher.OnChange; default 25ms). Verified by a
full server boot smoke and DB-backed convergence tests (event + poll
paths, degraded boot, last-known-good).

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed and
verified here.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(policy): add async decision logging with sampling, retention, and query repo

DecisionLogger batch-inserts each node's policy decisions straight to
the partitioned policy_decisions table via a non-blocking buffered
channel (drop-and-count on overflow — logging never adds latency to or
fails a decision). Scope decisions sample 1-in-N (default 50, setting
policy.decision_log_scope_sample_rate); denials and eval errors always
log; input/result JSON samples only at policy.decision_log_verbosity=
verbose. Cursor-paginated DecisionRepository backs the upcoming admin
log viewer. Retention via partman (daily partitions) and a
PolicyDecisionLogCleanupTask honoring policy.decision_log_retention_days
(default 14). PDP emits entries per evaluation; the System owns the
logger lifecycle and settings hot-reload.

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed and
verified here (removed an unused, unsynchronized PDP setter).

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(api): add admin policy management API and capability endpoint

/api/v1/policy/capability (authenticated feature detection) plus the
acting-admin /api/v1/admin/policy surface: vendor Rego viewer, document
CRUD with the one-enabled-per-domain conflict mapped to 409, immutable
version creation (compile-checked; failed versions persist as audit
history with structured row/col errors and can never activate),
activate/rollback with synchronous reload + cross-node invalidation via
System.NotifyChanged, stateless validate, throwaway-bundle simulate
(never touches the live engine, never logs decisions), and
cursor-paginated decision-log queries. Routes mount only when the
policy system is wired, keeping proxy/transcode modes untouched.

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed and
verified here (seeded the FK'd test user; replaced an unchecked
fmt.Sscanf with strconv).

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(web): add /admin/policy workspace with Rego editor, simulate, and decision log

New Policy admin page (System nav group): documents list with
one-enabled-per-domain conflict handling, CodeMirror 6 Rego editor
(hand-rolled StreamLanguage mode) with server compile issues rendered as
inline lint diagnostics, explicit Save-version vs Activate flow with
confirm, read-only vendor module viewer, simulate panel with seeded
example inputs, version history with rollback, and a cursor-paginated
decision-log browser. Capability-gated via /policy/capability. Adds the
three decision-log settings to Log Retention. First code-editor
dependency in web/ (@uiw/react-codemirror + @codemirror/*), decided in
the design spec.

Implementation drafted by Codex (GPT-5.5) via codex exec; verified here
(lint, format:check, tsc --noEmit, vitest policy suites).

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(policy): make OPA authoritative for viewer scope resolution

policy.ViewerResolver implements the ViewerResolver interface backed by
PDP.ResolveViewerScope and replaces access.Resolver at all five
construction sites: router viewer middleware, notifications scopes, the
reconciler, jellycompat's scope filter, and the ABS resolver (which now
accepts a pre-built resolver, preserving its PIN-at-login semantics).
PIN/profile-token verification and disabled-library loading are
extracted into shared exported helpers used by both implementations, so
the legacy resolver stays compiled as the parity reference with
identical behavior. The adapter lives in internal/policy (which already
depends on internal/access transitively) — direct typed PDP calls, no
new import cycle. Sites without a policy system (proxy modes, bare test
routers) keep the legacy resolver until the cleanup phase.

Verified: full test suite green (jellycompat TestBeginWebOperation* and
one playback GPU test are pre-existing failures, confirmed identical on
main), 1368-case parity suite, dedicated ViewerResolver parity/PIN/
nil-vs-empty/fail-closed tests, and a full server boot smoke.

Implementation drafted by Codex (GPT-5.5) via codex exec; a first-pass
reflection-based adapter was rejected and reworked into the typed
in-policy adapter; reviewed line-by-line and verified here.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(policy): make OPA authoritative for acting-admin and permission gates

vendor/permission.rego reproduces the acting-admin rule (admin role +
primary-profile-or-none), HasEffectivePermission semantics for
marker_edit, and the metadata-curation rule including the subtle
admin-past-refused-bypass case that requires the explicitly ASSIGNED
permission. Policy-backed middleware in policy_gates.go keeps all Go-side
lookups (declared-profile primary check, item->library resolution, the
404-on-unknown-item path) and preserves the legacy status/body taxonomy
exactly — proven by dual-execution middleware tests that run every
scenario through both implementations and assert byte-equal responses.
Permission decisions always log (allowed flag populated); simulate and
the capability endpoint gain the permission domain automatically via the
domain registry. Router swaps behind single constructor choice points
with the legacy gates retained for policy-less wiring.

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed and
verified here.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(policy): make OPA authoritative for download and playback admission decisions

vendor/action.rego decides download eligibility (downloads enabled +
user allowed), download-transcode eligibility (transcode enabled + user
allowed + artifacts available), and playback admission (stream/transcode
counts vs limits, zero = unlimited), with a tightening-only
silo_custom.action override that can also clamp a quality ceiling (never
widen — merged via quality.min). Go keeps everything stateful: config
loading, preset-ladder enumeration, and live session counting.

Downloads consult an optional ActionDecider (nil = legacy logic) mapped
back to the existing sentinel errors and capability response. Playback
gains a minimal AdmissionDecider hook at the exact point of the legacy
limit comparison: counts snapshot under the session mutex, PDP evaluated
OUTSIDE the lock, then revalidated under lock before insert (retry on
count drift) — no admission ever decided on stale counts and no eval
under the mutex. Deny reasons map to the legacy ErrTooManyStreams /
ErrTooManyTranscodes sentinels, pinned by tests.

Parity: combination tables driven against the real PresetsFor /
ensureTranscodeAllowed / SessionLimits math; full suite green (known
pre-existing jellycompat flakes only).

Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed
(locking design verified line-by-line) and verified here.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(web): satisfy tsc -b strict return typing in the Rego stream tokenizer

The production build (tsc -b) rejects assigning CodeMirror's
string | void next() result to string | undefined; tsc --noEmit did not
catch it. Restructured the string-literal loop.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(policy): clearer error when a decision is undefined for partial input

Vendor policies index required input fields directly, so a hand-written
simulate payload missing fields yields an undefined decision. Surface
that as 'decision X is undefined for this input (missing required input
fields?)' instead of 'empty result' — found while exercising the
simulate API against a live server.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* chore(web): set changeOrigin automatically when the API proxy target is remote

Remote dev backends sit behind vhost-routing proxies that reject a
localhost Host header; local targets keep the existing pass-through
behavior. Enables pointing the Vite dev server at a hosted backend via
VITE_API_PROXY_TARGET in web/.env.local.

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(web): redesign the policy workspace around the decision pipeline

The first-pass UI was structurally generic: a five-column document table
squeezed beside the editor, three equal-weight action buttons with
hidden preconditions, raw version IDs, and jargon copy — nothing taught
the model. The page now teaches it:

- A pipeline strip states the mental model up front: Silo decides the
  baseline -> your overrides narrow it -> every decision is logged. Tabs
  renamed to Overrides / Baseline / Decision Log (ids stay stable for
  bookmarked URLs).
- The document table becomes one card per domain (Library visibility /
  Admin & permissions / Downloads & playback) with plain-language
  descriptions, example rules, status pills (Live vN / Draft / Disabled),
  inline creation, and the enable kill-switch in place.
- Selecting an override drills into a full-width editor with a visible
  lifecycle rail (Draft -> Validated -> Saved -> Live) and one contextual
  primary action per step; the unedited live source shows no actions
  until edited. Version comments appear only at the save step.
- Simulate is reframed as 'Test before going live' with a human verdict
  chip (Allowed / Denied — reason / ceiling summary) above the raw JSON;
  internal generation counters no longer surface.
- History uses 'Make live' with plain go-live copy; authors read
  'User N'; the baseline tab explains that upgrades never touch
  overrides.

Hand-written redesign (no Codex); verified via vitest, tsc, eslint,
prettier, and a production build.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(web): present the policy baseline as readable rules, not raw Rego

The Baseline tab dumped five Rego modules into read-only editors. It now
leads with what the rules actually do: one card per domain with
plain-language statements of the shipped behavior and a note on what an
override may change, plus content-rating and playback-quality tier
ladders parsed live from the lib module sources (so the tiers shown are
the ones the server enforces, not a hardcoded copy). The Rego source
stays one click away behind a per-module accordion and remains the
stated source of truth; unrecognized modules fall back to source-only.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(policy): add access-groups design addendum

Groups with permission toggles become the everyday admin surface; the
Rego editor is demoted behind policy.editor_enabled (default off).
Restriction-only composition: group grants are an upper bound, per-user
settings tighten further — same rule as the existing account/profile
merge, one layer up.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(access): add access groups — group defaults with restriction-only composition

New access_groups table + users.access_group_id (one group per user, NULL
= today's behavior). Group grants are an upper bound composed with the
user's own settings by strictest-wins rules — library intersection,
MinQuality, AND'd booleans, strictest positive stream/transcode limits,
permission-mask intersection, and a requests toggle gating CreateRequest.
The merge happens in Go (access.ApplyGroupPolicy /
EffectivePolicyForUser) before policy inputs are built, so vendor Rego,
the parity suites, and the decision log are untouched; every enforcement
surface (viewer scope in both resolvers, permission gates, downloads,
playback admission, requests) consumes the effective policy and fails
closed on provider errors. Changing a group's quality ceiling bumps its
members' access_policy_revision, mirroring the per-user rule.

Additive admin API: /admin/access-groups CRUD with member counts;
PUT /admin/users/{id} + user DTOs gain access_group_id.

Also demotes the Rego editor: policy.editor_enabled (default off,
hot-reloaded) drives the capability endpoint's editor_available and
403-gates editor endpoints while the engine and decision logging keep
running.

Design: docs/superpowers/specs/2026-07-02-access-groups-design.md.
Implementation drafted by Codex (GPT-5.5) via codex exec; reviewed
(composition core + fail-closed call-site audit) and verified here.
DB-backed group-store tests pending local Postgres recovery.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(web): add Access Groups admin page and gate the policy editor

New /admin/access-groups: a card grid summarizing each group (member
count + key restrictions), drilling into an editor that reuses the same
LibraryAccessSelector and quality presets as the user editor, with
toggles for downloads/transcoded-downloads/requests, concurrent-stream
and transcode limits, and a permissions mask (all-assignable by default,
narrowable to specific permissions). Delete warns how many members fall
back to the built-in defaults. Copy states the composition rule up front:
a group grants the most a member can do; their own restrictions still
apply on top.

The user editor gains a Group picker and read-only row; the Policy nav
entry is now hidden unless the capability reports the editor enabled.
Plumbing (types, hooks, user-editor picker, nav gating) drafted by Codex
(GPT-5.5); the Groups page hand-built. Verified: 25 tests across the
touched suites, tsc, eslint, prettier, and a production build.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(access): seed a Default Group and auto-assign newly created users

Adds access_groups.is_default with a partial unique index (one default
at most — the profiles is_primary pattern) and seeds a permissive
'Default Group' whose ceiling is a no-op, so assignment never changes
anyone's effective access until an admin edits it. The seed is guarded
against pre-existing defaults and name collisions; the Down migration
only removes the row if it is still untouched.

Assignment happens at the single INSERT INTO users choke point
(UserRepository.Create): when no explicit group is given, access_group_id
is filled by a scalar subquery on the default flag — NULL when no default
exists. Every creation path (setup, signup, invites, OAuth, admin create)
is covered by construction. Setting a new default via the API atomically
clears the previous one in the same transaction.

Deleting or unsetting the default is legal: new users then start with no
group, which is pre-feature behavior.

Implementation drafted by Codex (GPT-5.5); migration guards and the
choke-point subquery reviewed line-by-line here.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(web): surface the default access group

Cards show a Default badge; the group editor gains a 'Default for new
users' toggle (with copy noting existing users are never moved); the
delete dialog warns when removing the default that new accounts will
start with no group.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(access): ship the Default Group with house-rule ceilings

Seed values per product decision: 5 concurrent streams, 5 transcodes,
transcoded downloads off, and a permission mask of marker_edit only
(metadata curation excluded). Plain downloads and requests stay on. The
Down guard matches the new values so it still only removes an untouched
seed row. Only newly created users are affected; existing users are
never assigned.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(access): retire per-user defaults — the Default Group is the sole default policy

Removes both legacy 'user defaults' mechanisms now that the seeded
Default Group owns new-user policy:

- users.max_streams / max_transcodes column defaults drop from 6/2 to 0
  (= unrestricted at the user layer), so group ceilings apply to new
  signups/invites/OAuth users instead of fighting stale per-user
  numbers. Existing rows keep their stored values — nobody is silently
  uncapped on upgrade.
- The dead defaults.max_playback_quality / defaults.max_profiles
  settings validation goes away with its only writer (the User Defaults
  dialog, removed on the web side).

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(web): replace the User Defaults dialog with group-governed creation

The Users page's 'User Defaults' dialog (defaults.* server settings)
duplicated what access groups now do properly, and its values were only
ever form prefill — no backend path applied them. The button now links
to Access Groups, and the create-user form seeds unrestricted user-layer
values (0 streams/transcodes, any quality, downloads allowed) so the
member's group governs; per-user fields remain for tightening individual
users.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(access): migrate existing non-admin users into the Default Group

Existing users join the seeded Default Group on upgrade so one policy
source governs the whole instance. Their per-user limits still holding
the retired 6/2 column defaults are normalized to 0 in the same
statement so the group's ceilings actually apply; deliberately
customized values are preserved. Admin accounts stay ungrouped —
scope/action decisions are role-blind, so grouping an admin would cap
the server owner on upgrade.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(access): keep admins out of the Default Group and treat group moves as policy changes

New-user creation now mirrors the migration's admin exclusion: the
default access group is only auto-assigned to non-admin roles, so a
fresh server owner no longer inherits the starter group's transcode
denial and stream caps.

Changing a user's access group now bumps access_policy_revision (the
group carries permissions, quality, and limits, exactly like the
per-user fields that already bump it) and triggers admin session
revocation when the group actually changes.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(policy): enforce marker_edit through the PDP on marker write routes

The Rego permission policy owned marker_edit but no Go caller ever
consulted it: PUT/DELETE /markers went through a handler-local check
that short-circuited admins and read only the user's own permissions,
so group permission masks and custom policy overrides were ignored.

Marker writes are now gated by router middleware like the other
permission surfaces: a PDP-backed RequireMarkerEdit that evaluates the
group-merged effective permissions (plus the legacy variant for
proxy/test wiring without a policy system). The handler-local check and
its user loader are gone.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): assert device/quality policy facts and honor the quality ceiling

The download_transcode action check hard-coded an empty device ID and
never asserted the requested quality, and no caller consumed
ActionDecision.QualityCeiling — custom download policies keyed on those
inputs were silently ineffective.

Resolve now threads the request's device ID and requested quality into
the action input, and a returned quality ceiling downscales the
prepared transcode target (the ceiling applies to what is served,
matching the serve-time rule in serveDownloadBytes). FileQuality and
the content-rating pair stay intentionally empty for downloads —
documented on downloadActionInput: those ceilings are enforced against
the served artifact by the scope-derived access filter, and asserting
the source's quality would wrongly deny capped transcodes.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(access): align the default-group seed assertions with the migration

The DB test still asserted the earlier no-op seed (transcode allowed,
unlimited streams/transcodes, null permissions); the shipped migration
seeds transcode denied, 5/5 limits, and marker_edit-only permissions,
so the test failed on any database with the migration applied.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(policy): lock the Rego sandbox by builtin purity and bound compile work

Exclude every nondeterministic builtin from the admin sandbox instead of
denylisting names, so OPA upgrades cannot silently expose impure builtins
while pure helpers like net.cidr_contains stay usable. Apply the same
capabilities to the runtime engine, cap concurrent compile checks, and
reject oversized sources before they reach the uncancelable compiler.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(policy): require literal booleans in vendor override and input checks

Bare object.get truthiness treated any non-false value as satisfied, so a
malformed override 'allowed' value could fail to tighten a base grant and
hand-crafted simulate input could flip flag predicates. Compare against
literal true so anything else denies.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(policy): surface decision log cleanup failures to the task manager

CleanupDecisionLogsOnce now returns the first error alongside the deleted
count so a broken partition manager or DB outage marks the scheduled task
failed instead of reporting 100% success while policy_decisions grows.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(playback): log admission decider errors before failing closed

A policy-evaluation failure was silently mapped to the too-many-streams
denial, making an engine outage indistinguishable from a real limit hit.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(access): nil-guard the downloads user and restore the ABS legacy resolver

effectiveDownloadUser dereferenced policy state before its nil-user check,
and the ABS handler lost viewer-scoped filtering entirely when the policy
system was unavailable because no legacy access.NewResolver fallback was
wired like the other resolver paths.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(web): address admin policy review feedback

- invalidate the version query by version_number, the key usePolicyVersion
  actually caches under
- keep the goPrevious cursor-stack updater pure (Strict Mode double-invoke)
- make version history rows keyboard-selectable like the document list
- clamp download_transcode_allowed when downloads are disabled so groups
  cannot save a contradictory record

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(api): cap policy endpoint request bodies at 1 MiB

The policy write endpoints (create document/version, set enabled,
validate, simulate) decoded JSON bodies without a size limit, so an
oversized payload buffered fully in memory before CompileCheck's
256 KiB source cap could reject it. Route all five through a shared
decodePolicyRequest helper that wraps the body in http.MaxBytesReader
and returns 413 with the repo's standard too_large error shape.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UtnZ2Uewzo959hpneLrtRN

* fix(access): forbid deleting or demoting the default access group

Deleting the default group (or unsetting its is_default flag) left the
server with no default: new non-admin users were then created ungrouped
with max_streams/max_transcodes of 0 — unlimited — because the legacy
per-user column defaults were retired in favor of the group's ceilings.

The store now rejects both operations with ErrDefaultGroupRequired
(mapped to 409); promoting another group remains the supported way to
move the default, and atomically clears the previous one. The admin UI
disables the delete button and the default toggle on the default group
and explains the promote-another-group flow.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UtnZ2Uewzo959hpneLrtRN

* fix(web): keep unsaved policy drafts when a newer version activates elsewhere

The editor state was keyed on the active version's id/sha, so a
background refetch after another admin (or another tab) activated a
version remounted the editor and silently discarded the dirty draft.

PolicyEditorPanel now pins the seed it is editing against and only
adopts an incoming seed when nothing can be lost: the editor is clean,
the draft already equals the incoming source (the same-admin activate
flow), or the selection moved to a different document. Otherwise the
pinned editor stays mounted and an inline notice offers an explicit
"Load live version" action.

Part of Silo-Server#272

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UtnZ2Uewzo959hpneLrtRN

* fix(policy): fail reloads on invalid custom sources and surface degraded/apply state

A stored custom source that stops compiling used to be silently skipped on
reload: the bundle widened to vendor-only for that domain while the generation
reported fully applied. Reload is now strict — a bad enabled source fails the
reload and the last known-good engine keeps serving. Boot keeps its vendor
fallback for availability, but skips are recorded on the engine and exposed
(with store-outage reasons) through System.DegradedState and additive
degraded fields on GET /policy/capability. Activate/SetEnabled re-run
CompileCheck instead of trusting the stored compiled_ok flag.

Mutation endpoints also no longer conflate persistence with live apply:
activation/enable responses carry additive applied/failed_step/
loaded_generation fields and return 202 when the store change persisted but
the local reload failed.

Addresses review findings C1, C2, and the degraded-signal gap (6.1).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(policy): type deny reasons across the contract and enforce profile_verified

Deny handling used to branch on exact free-text reason strings in three Go
consumers, and playback reported ANY unrecognized reason — including custom
override free text and engine failures — as a stream-limit error. Decisions
now carry a stable reason_code (custom overrides always get custom_denial);
downloads, the metadata-curation gate, and playback admission switch on codes,
with a new ErrPlaybackNotAllowed -> 403 playback_not_allowed mapping for
non-limit denials. Rego tests pin every vendor code.

The scope contract's tighten-only profile_verified output was also emitted but
never consumed; a policy revocation now surfaces as ErrProfileUnverified (403
profile_unverified) instead of silently proceeding.

Addresses review findings 6.2 and C4.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(catalog): close the dual-library disabled-scope bypass in direct item authorization

EnsureAccessible, EnsureAccessibleIDs, and FilterAccessibleContentIDs gated
library access with allow/deny predicates over a single joined
media_item_libraries row, so an item linked to BOTH a passing library and a
disabled one satisfied the disabled check via the passing row — a direct-ID
bypass of disabled-library scope on the detail, media-file, playback, and
download paths. All library access predicates now share one helper
(libraryAccessConditions) emitting independent EXISTS / NOT EXISTS subqueries,
the semantics GetByIDsWithAccess already used, including the orphan-item
membership guard for disabled-only scopes. SQL-shape tests pin every builder
and a DB-gated regression test covers the dual-library item end to end.

Addresses review finding C3 (plus the same shape in
buildFilterAccessibleContentIDsSQL, which the review did not flag).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): serialize quota check and row creation under a per-user advisory lock

The concurrent-download quota was check-then-insert with nothing serializing
the pair: parallel creates could all observe free quota before any row
existed, bypassing the cap and stacking artifact encode jobs. All four
check->insert spans (ephemeral original, artifact-backed, series batch,
managed batch) now run inside Repository.WithUserQuotaLock — a
pg_advisory_xact_lock keyed by user, so the serialization holds across nodes.
The artifact path keeps the limiter-before-Ensure ordering (a rejected request
must not leave an encode job behind) by holding the lock across Ensure.
Managed-entry replacement stays quota-exempt and lock-free. A DB-gated
barrier test races 8 creates against a cap of 1.

Addresses review finding C5.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): assert served quality at create time for original and remux downloads

Direct-original and remux downloads serve the source resolution unchanged, but
create-time policy checks left file_quality empty — an over-ceiling source
registered a row serveDownloadBytes could never satisfy. Resolve now runs a
final download action check with FileQuality populated on those two paths
(capped transcodes keep the ceiling-on-artifact behavior), a custom override
ceiling below the served resolution denies, and quality_ceiling_exceeded maps
to ErrQualityUnavailable. The ActionInput contract now documents exactly when
file_quality and the rating facts are supplied so custom policy authors are
not misled.

Addresses review finding C6.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(policy): guard activation against slow overrides and make eval timeouts observable

A custom scope override that exceeds the 25ms eval budget compiled fine,
activated fine, and then converted to 500s on every authenticated request —
server-wide lockout authored in the admin editor. Activation and enable now
run GuardEvalCost: the candidate source is evaluated on a throwaway engine
against a canned representative input under the live budget, and a source
that cannot complete is rejected 422 with ErrPolicySlowEval before it goes
live. Runtime timeouts keep failing closed but now carry a distinct
ErrPolicyEvalTimeout sentinel, an Error log, and a per-engine counter exposed
as eval_timeouts on GET /policy/capability so intermittent near-budget
policies are attributable.

Addresses review finding C7.

Co-Authored-By: Claude Fable 5 <[email protected]>

* style: gofmt remediation files

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant