# Implement the Vieunite Hosted Picker backend integration

You are working inside an existing application repository. Implement the backend half of a Vieunite Hosted Picker integration while preserving the application's current architecture, behaviour, conventions, and user-owned work.

## Outcome

Add the smallest production-shaped backend integration that lets an authenticated editor create a Vieunite Picker session, redeem a completed selection through the application backend, and hand the result to the application's existing content or media workflow.

Do not implement or modify frontend UI in this task.

## Authoritative documentation gate

Before editing any file, read the complete current Vieunite developer documentation. Do not rely only on this prompt, previous knowledge, or isolated code examples.

1. Open `https://collection.vieunite.com/docs`.
2. Fetch `https://collection.vieunite.com/docs/search-index.json`.
3. From `data[].href`, remove URL fragments, deduplicate the page paths, resolve them against `https://collection.vieunite.com`, and read every unique documentation page returned by the index. Follow same-origin redirects.
4. Read `https://collection.vieunite.com/docs/openapi.json` as the exact tenant API contract.
5. Read linked Hosted Picker, authentication, reference lifecycle, asset delivery, error handling, go-live, and official implementation case-study material in full.
6. Keep compact implementation notes rather than copying the documentation into the repository or conversation.

Treat the live documentation and OpenAPI schema as the source of truth. If this prompt conflicts with them, follow the live documentation. Do not invent endpoints, fields, scopes, headers, limits, error codes, or Picker behaviour.

If network access is unavailable, the documentation index is incomplete, or any required page or schema cannot be read, stop before editing and report exactly what could not be accessed. Ask the user for an accessible documentation snapshot instead of guessing.

## Repository safety contract

- Begin with read-only inspection.
- Read every applicable repository instruction file, including `AGENTS.md`, `CLAUDE.md`, `README`, contribution guidance, and directory-scoped instructions, before editing.
- Detect the actual backend framework, architecture, package manager, configuration system, authentication and authorisation model, persistence layer, HTTP client, error format, logging conventions, and test runner. Do not assume a language or framework.
- If the repository uses Git, inspect its status first. Treat all existing modified, staged, and untracked files as user-owned.
- Never reset, clean, stash, revert, checkout over, delete, overwrite, or reformat user-owned work.
- If a required edit overlaps an existing uncommitted change and cannot be preserved with confidence, stop and report the exact file and conflict.
- Make the smallest compatible change. Reuse existing routes, services, repositories, models, configuration, HTTP clients, error helpers, observability, and tests.
- Do not introduce a parallel architecture, duplicate an existing abstraction, or replace working code merely because another design is preferable.
- Do not perform unrelated refactors, dependency upgrades, repository-wide formatting, schema redesigns, public API breakage, or speculative cleanup.
- Avoid new production dependencies. If the integration genuinely requires one, stop and explain why the existing stack cannot satisfy the requirement.
- Do not modify generated files directly when the repository has a documented source or generator.
- Do not weaken authentication, authorisation, CSRF, origin checks, TLS validation, tests, type checks, lint rules, or error handling to make the change pass.
- Keep the coding agent's normal approval, permission, and sandbox controls enabled. Do not bypass them or widen filesystem or network access to finish the task.
- Do not commit, push, open a pull request, deploy, change cloud resources, access production data, or perform any external write unless the user explicitly requests it.
- Do not use real tenant credentials in tests or ask the user to paste secrets into source code, chat, logs, fixtures, or commands.

## Read-only discovery

Locate and understand:

- the backend application entrypoint and route registration;
- authenticated editor identity, organisation or tenant ownership, and permission checks;
- CSRF protection and trusted-origin configuration;
- existing server-side secret and environment configuration;
- existing outbound HTTP client, timeout, retry, tracing, and error-mapping patterns;
- current media, asset, content-entry, external-provider, or reference models;
- existing idempotency, job, transaction, and deduplication utilities;
- the nearest analogous integration and its tests;
- repository-supported build, lint, type-check, and test commands.

After discovery, write a brief implementation plan naming the minimal files and existing patterns you will reuse. Continue without waiting only when the change is clear, local, and compatible with this safety contract. Stop for a concise user decision when authentication ownership is ambiguous, a destructive migration would be required, production access would be needed, or more than one materially different persistence model is equally valid.

## Backend scope

Implement only the server-side boundary required by the documented Hosted Picker flow.

### CMS-local bridge

- Add the session-creation and selection-redemption endpoints on the application's own origin, using its existing route naming and response conventions.
- Require the application's normal authenticated editor session and authorisation on both endpoints.
- Apply the application's normal CSRF protection when browser credentials are cookie-based.
- Keep the Vieunite tenant token entirely server-side in the existing secret/configuration system. Never return, serialize, log, or expose it to browser code.
- Use the documented environment base URL and keep Test and Production configuration separate.
- Use the existing outbound HTTP abstraction with explicit connect/read timeouts and normal TLS verification.
- Allowlist and normalise browser-controlled Picker options. Never proxy an arbitrary browser request body to Vieunite.
- Derive the exact `callback_origin` from trusted server configuration, never from untrusted request input.
- Apply the documented immutable host capabilities on the trusted backend.
- Bind each created Picker session to the authenticated editor, organisation or tenant, and relevant content context using the smallest existing persistence or session mechanism.
- Reject redemption unless the same authorised context owns the Picker session.
- Redeem the one-time selection with a stable documented `Idempotency-Key`, preserving the same key across an uncertain retry.
- Preserve Vieunite problem details, HTTP status semantics, and request IDs through the application's established error boundary without leaking secrets or temporary capabilities.

### Existing content or media model

First inspect the application's current model; do not create a new media subsystem.

- If the application already supports external-provider references, persist the documented canonical identity using its existing extension points: provider, resource type, resource ID, and artwork rendition.
- If the application only accepts native media and already has a secure server-side import pipeline, adapt the documented import pattern to that pipeline and retain canonical Vieunite provenance for deduplication and audit.
- Treat rendition or version keys as opaque documented values.
- Do not persist Picker launch capabilities, selection codes, signed delivery URLs, thumbnails, physical asset variants, or metadata snapshots as authoritative source data.
- Resolve current metadata, rights, availability, and the saved rendition at the documented lifecycle points.
- Request signed delivery URLs close to use. If importing an asset, download it only on the backend through the application's constrained asset client, enforce the documented origin, type, redirect, timeout, and size rules, then discard the temporary URL.
- Preserve partial-success semantics when the documented operation is item-based.
- Do not add a database migration if an existing JSON, metadata, provider, integration, or provenance field can represent the contract cleanly.
- If durable ownership cannot be implemented without a schema migration or public contract change, stop after discovery and propose the smallest reversible change. Do not apply it silently.

### Scope discipline

- Do not edit frontend components, styles, routes, browser SDK code, or UI tests.
- Do not build a custom artwork browser when the Hosted Picker satisfies the requirement.
- Do not copy framework-specific examples literally. Translate the documented behaviour into the repository's established patterns.
- Do not make live Vieunite calls unless the repository already has an explicitly authorised integration-test environment and the user has asked for live verification.

## Verification

Add behaviour-level tests using the repository's existing test style and mocked upstream HTTP boundary. Cover at least:

- authorised session creation;
- unauthenticated or unauthorised rejection;
- CSRF rejection where applicable;
- browser options are allowlisted rather than transparently proxied;
- callback origin comes from trusted configuration;
- tenant credentials and temporary capabilities never appear in the public response or logs;
- session ownership is enforced during redemption;
- redemption retries reuse the same idempotency key;
- documented upstream 4xx, 5xx, timeout, malformed response, and request-ID handling;
- the chosen canonical-reference or native-media persistence path;
- partial success and replay behaviour where applicable.

Run the smallest relevant tests first, then the repository's normal lint, type-check, and broader test commands when proportionate. Use only temporary or test databases. Do not alter unrelated tests to hide a failure.

Inspect the final diff and repository status. Confirm that only intended backend and test files changed, no secret was introduced, and existing user-owned files remain untouched.

## Final response

Report:

1. the backend architecture and existing patterns reused;
2. every file changed;
3. the CMS-local frontend contract: paths, methods, authentication, CSRF requirements, request bodies, responses, and error shape;
4. whether the integration stores canonical references or imports native media, and why that matches the existing application;
5. documentation pages and OpenAPI successfully reviewed;
6. commands run and exact results;
7. any pre-existing failures, unverified assumptions, or work deliberately left out of scope.

Do not claim completion without executable verification evidence.
