# Themis Music Shield Developer Guide

This guide shows how to integrate the Phase 74 Music Shield into a music
generation or publishing pipeline with the `@themis/shield-client` TypeScript
SDK.

Use the SDK when the generation service calls the Shield API over HTTP. Use
`@themis/music-shield` directly only when embedding the scan pipeline in the
same process as the generation worker.

---

## Integration Flow

1. Generate or receive the candidate audio.
2. Call `client.quickScan()` for low-latency preflight, or `client.scan()` for a
   full release gate.
3. Branch on `result.overallRisk`.
4. Store `result.provenance` and any publication decision with the generation
   record.
5. For `flag`, `high_risk`, or `reject`, route to review, remediation, or block
   publication according to the policy below.

Default risk levels are:

| Risk level  | Default meaning                         | Typical action                                   |
| ----------- | --------------------------------------- | ------------------------------------------------ |
| `pass`      | No material similarity detected         | Publish and retain provenance                    |
| `advisory`  | Low similarity or weak signal           | Publish with monitoring and audit logging        |
| `flag`      | Reviewable similarity                   | Hold publication for human review                |
| `high_risk` | Strong similarity needing legal review  | Hold publication and prepare remediation package |
| `reject`    | Release-blocking similarity or compound | Block publication and remediate or abandon       |

---

## Install

From a workspace package:

```bash
pnpm add @themis/shield-client
```

For typed result handling in a package that also imports Music Shield types:

```bash
pnpm add @themis/shield-client @themis/music-shield
```

Set the Shield API base URL and one authentication mechanism:

```bash
THEMIS_SHIELD_API_URL=https://shield.internal.example.com
THEMIS_SHIELD_API_KEY=replace-with-service-key
```

Use `bearerToken` instead of `apiKey` when the caller authenticates with an
issuer-managed JWT.

---

## Create a Client

```typescript
import { createShieldClient } from '@themis/shield-client';

export const shield = createShieldClient({
  baseUrl: process.env.THEMIS_SHIELD_API_URL ?? 'http://localhost:8787',
  apiKey: process.env.THEMIS_SHIELD_API_KEY,
  retryPolicy: {
    maxAttempts: 3,
    baseDelayMs: 100,
    maxDelayMs: 1_000,
  },
  idempotencyKeyFactory: (operation) => {
    return `${operation}-${crypto.randomUUID()}`;
  },
});
```

The SDK sends JSON, attaches `x-api-key` or `Authorization: Bearer ...`, and
adds `x-idempotency-key` to POST requests. Transient statuses are retried by
default: `408`, `409`, `425`, `429`, `500`, `502`, `503`, and `504`.

---

## Scan a Generated Track

Use `base64` for small artifacts already in memory. Use `url` or
`object_storage` for larger files that the Shield API can fetch.

```typescript
import { readFile } from 'node:fs/promises';

import { shield } from './shield-client.js';

export async function scanGeneratedTrack(input: {
  readonly generationId: string;
  readonly audioPath: string;
  readonly lyrics?: string;
  readonly prompt: string;
  readonly modelId: string;
  readonly modelVersion: string;
}): Promise<void> {
  const audioBase64 = await readFile(input.audioPath, 'base64');

  const response = await shield.scan({
    generationId: input.generationId,
    audio: {
      kind: 'base64',
      data: audioBase64,
      contentType: 'audio/wav',
      filename: `${input.generationId}.wav`,
    },
    lyrics: input.lyrics,
    metadata: {
      generationPrompt: input.prompt,
      modelId: input.modelId,
      modelVersion: input.modelVersion,
      genre: 'pop',
      durationMs: 180_000,
      sampleRateHz: 44_100,
      channelCount: 2,
    },
    scanConfig: {
      mode: 'full',
      jurisdictions: ['US'],
      maxLatencyMs: 30_000,
      bypassCache: false,
    },
  });

  if (response.status !== 'completed' || response.result === undefined) {
    await enqueueShieldPolling(response.scanId);
    return;
  }

  await applyShieldDecision(
    input.generationId,
    response.scanId,
    response.result
  );
}
```

If the API returns `queued` or `running`, poll the result endpoint:

```typescript
export async function waitForShieldResult(scanId: string): Promise<void> {
  const response = await shield.getResult(scanId);

  if (response.status === 'failed') {
    throw new Error(response.error ?? `Shield scan ${scanId} failed.`);
  }

  if (response.status !== 'completed' || response.result === undefined) {
    await enqueueShieldPolling(scanId);
    return;
  }

  await applyShieldDecision(response.result.scanId, scanId, response.result);
}
```

---

## Branch on Scan Results

Keep the automated decision small and auditable. The detailed explanation stays
in the Shield result: `overallScore`, `confidence`, `matches`,
`recommendations`, `elementScores`, and `provenance`.

```typescript
import type { MusicShieldScanResult } from '@themis/music-shield';

type ReleaseDecision =
  | { readonly action: 'publish'; readonly reason: string }
  | { readonly action: 'monitor'; readonly reason: string }
  | {
      readonly action: 'review';
      readonly reason: string;
      readonly reviewQueue: string;
    }
  | {
      readonly action: 'remediate';
      readonly reason: string;
      readonly remediationRequired: true;
    }
  | { readonly action: 'reject'; readonly reason: string };

export function decisionForShieldResult(
  result: MusicShieldScanResult
): ReleaseDecision {
  switch (result.overallRisk) {
    case 'pass':
      return {
        action: 'publish',
        reason: 'Music Shield passed the release gate.',
      };
    case 'advisory':
      return {
        action: 'monitor',
        reason: 'Low-risk similarity detected; retain audit trail.',
      };
    case 'flag':
      return {
        action: 'review',
        reason: 'Reviewable similarity detected.',
        reviewQueue: 'musicology',
      };
    case 'high_risk':
      return {
        action: 'remediate',
        reason: 'High-risk similarity requires remediation and legal review.',
        remediationRequired: true,
      };
    case 'reject':
      return {
        action: 'reject',
        reason: 'Release-blocking similarity detected.',
      };
  }
}

async function applyShieldDecision(
  generationId: string,
  scanId: string,
  result: MusicShieldScanResult
): Promise<void> {
  const decision = decisionForShieldResult(result);

  await saveShieldAuditRecord({
    generationId,
    scanId,
    risk: result.overallRisk,
    score: result.overallScore,
    recommendations: result.recommendations,
    provenance: result.provenance,
    decision,
  });

  if (decision.action === 'publish' || decision.action === 'monitor') {
    await publishGeneration(generationId);
    return;
  }

  if (decision.action === 'review') {
    await routeToHumanReview(
      generationId,
      scanId,
      result.matches,
      decision.reviewQueue
    );
    return;
  }

  if (decision.action === 'remediate') {
    await requestRemediation(generationId, scanId, result);
    return;
  }

  await blockPublication(generationId, decision.reason);
}
```

---

## Quick Scan, Full Scan, and Batch Scan

Use quick scans during interactive generation loops. Quick scans are partial and
optimized for early feedback.

```typescript
const quick = await shield.quickScan({
  generationId: 'generation-123',
  audio: {
    kind: 'url',
    data: 'https://object-store.example.com/generation-123-preview.wav',
  },
  scanConfig: {
    mode: 'quick',
    maxLatencyMs: 5_000,
  },
});
```

Use full scans before release:

```typescript
const full = await shield.scan({
  generationId: 'generation-123',
  audio: {
    kind: 'object_storage',
    data: 's3://generated-music/generation-123/final.wav',
    contentType: 'audio/wav',
  },
  scanConfig: {
    mode: 'full',
    jurisdictions: ['US', 'UK', 'EU'],
    riskThreshold: 'flag',
    maxLatencyMs: 30_000,
  },
});
```

Use batch scans for nightly corpus gates or bulk backfills:

```typescript
const batch = await shield.batchScan({
  batchId: 'release-batch-2026-06-26',
  streamResults: false,
  items: generatedTracks.map((track) => ({
    itemId: track.generationId,
    request: {
      generationId: track.generationId,
      audio: {
        kind: 'object_storage',
        data: track.objectStorageUri,
        contentType: 'audio/wav',
      },
      metadata: track.metadata,
      scanConfig: {
        mode: 'batch',
        jurisdictions: ['US'],
      },
    },
  })),
});
```

---

## Remediation and Human Review

When a result is `flag`, `high_risk`, or `reject`, keep the Shield result
attached to the review or remediation record. Reviewers need:

- `matches[]` with reference work ids, matched elements, compound scores, time
  segments, and jurisdiction risk.
- `elementScores` for melody, lyrics, vocal, harmony, spectral, structure, and
  rhythm engines.
- `recommendations` from the decision engine.
- `provenance` for request hash, normalized audio hash, engines completed, cache
  status, and audit level.

Submit reviewer decisions through the SDK when a reviewer approves, rejects,
requests modifications, or escalates:

```typescript
await shield.submitReview('review-123', {
  decision: {
    reviewId: 'review-123',
    decision: 'modify',
    rationale:
      'Melodic overlap is below protected-expression threshold after A/B review.',
    conditions: [
      'Retain audit bundle',
      'Run post-publication monitoring for 30 days',
    ],
    reviewerExpertise: 'musicologist',
    reviewerId: 'reviewer-42',
  },
});
```

For remediation, send the remediation request shape defined by
`@themis/remediation`. In this example, `shieldResult` is the
`MusicShieldScanResult` returned by the release gate:

```typescript
await shield.remediate({
  remediation: {
    requestId: 'remediation-123',
    scanResult: shieldResult,
    flaggedElements: [
      {
        elementType: 'melody',
        matchedWorkId: 'reference-work-123',
        timeSegments: [{ startMs: 32_000, endMs: 36_000, confidence: 0.92 }],
        preferredStrategy: 'melody_variation',
      },
    ],
    preserveIntent: {
      mood: 'uplifting',
      energy: 0.78,
      genre: 'synth-pop',
      tempo: 124,
      key: 'A minor',
    },
    originalLyrics: 'Original lyric draft',
  },
});
```

---

## Provenance

Store the scan result provenance with the generation record. It provides the
minimum audit package needed to reconstruct the release gate:

- `requestHash`
- `normalizedAudioHash`
- `startedAtIso` and `completedAtIso`
- `enginesRequested` and `enginesCompleted`
- `engineErrors`
- `cacheHit`
- `partial`
- `auditLevel`

Fetch the full provenance chain for a generation when preparing legal, reviewer,
or customer-facing evidence packages:

```typescript
const provenance = await shield.getProvenance('generation-123');
```

---

## API Surface

The SDK maps directly to the Shield API:

| SDK method               | HTTP endpoint                    | Use                                         |
| ------------------------ | -------------------------------- | ------------------------------------------- |
| `scan(request)`          | `POST /scan`                     | Full scan or configured scan                |
| `quickScan(request)`     | `POST /scan/quick`               | Low-latency partial scan                    |
| `batchScan(request)`     | `POST /scan/batch`               | Bulk scans                                  |
| `getResult(scanId)`      | `GET /scan/{id}`                 | Poll queued/running scans                   |
| `remediate(request)`     | `POST /remediate`                | Start remediation workflow                  |
| `lookupReference(id)`    | `GET /reference/{id}`            | Inspect a matched reference work            |
| `submitReview(id, body)` | `POST /review/{id}/decide`       | Record a review decision                    |
| `getProvenance(id)`      | `GET /provenance/{generationId}` | Retrieve generation provenance chain        |
| `getHealth()`            | `GET /health`                    | Service and dependency health               |
| `getStats()`             | `GET /stats`                     | Scan volume, queue, active scan, risk stats |

`submitReviewDecision(id, body)` is also available as an alias for
`submitReview(id, body)`.

---

## Configuration Reference

### `ShieldClientConfig`

| Option                  | Required | Description                                                  |
| ----------------------- | -------- | ------------------------------------------------------------ |
| `baseUrl`               | Yes      | Shield API origin, with or without a trailing slash.         |
| `apiKey`                | No       | Sent as `x-api-key`.                                         |
| `bearerToken`           | No       | Sent as `Authorization: Bearer <token>`.                     |
| `headers`               | No       | Extra headers merged into each request.                      |
| `fetch`                 | No       | Custom fetch implementation for tests, workers, or runtimes. |
| `retryPolicy`           | No       | Partial retry override. See below.                           |
| `connectionPool`        | No       | Supplies an `agent` or `dispatcher` per URL.                 |
| `sleep`                 | No       | Custom delay function used by retry backoff.                 |
| `idempotencyKeyFactory` | No       | Factory for POST idempotency keys.                           |
| `signal`                | No       | Abort signal attached to SDK requests.                       |

### `ShieldClientRetryPolicy`

| Option             | Default                           | Description                         |
| ------------------ | --------------------------------- | ----------------------------------- |
| `maxAttempts`      | `3`                               | Total attempts per operation.       |
| `baseDelayMs`      | `100`                             | First retry delay.                  |
| `maxDelayMs`       | `1000`                            | Upper bound for exponential delay.  |
| `retryStatusCodes` | `408,409,425,429,500,502,503,504` | HTTP statuses treated as transient. |

### `ShieldAudioInput`

| Option         | Required | Description                                       |
| -------------- | -------- | ------------------------------------------------- |
| `kind`         | Yes      | `base64`, `url`, or `object_storage`.             |
| `data`         | Yes      | Base64 payload, fetchable URL, or storage URI.    |
| `contentType`  | No       | Example: `audio/wav`, `audio/flac`, `audio/mpeg`. |
| `filename`     | No       | Original or generated file name.                  |
| `sampleRateHz` | No       | Source sample rate, if known.                     |
| `channelCount` | No       | Source channel count, if known.                   |

### `ShieldScanRequestBody`

| Option         | Required | Description                                      |
| -------------- | -------- | ------------------------------------------------ |
| `scanId`       | No       | Caller-supplied id for idempotent scan tracking. |
| `generationId` | No       | Generation or artifact id to link provenance.    |
| `audio`        | Yes      | Audio input.                                     |
| `lyrics`       | No       | Lyrics to include in lyric similarity scanning.  |
| `metadata`     | No       | Generation metadata.                             |
| `scanConfig`   | No       | Scan behavior and thresholds.                    |
| `callbackUrl`  | No       | URL for async scan completion callbacks.         |

### `MusicShieldScanMetadata`

| Option             | Description                                     |
| ------------------ | ----------------------------------------------- |
| `genre`            | Genre label used for threshold overrides.       |
| `tempo`            | Beats per minute, if known.                     |
| `key`              | Musical key, if known.                          |
| `generationPrompt` | Prompt or compact prompt hash/source reference. |
| `modelId`          | Generation model identifier.                    |
| `modelVersion`     | Generation model version.                       |
| `artistId`         | Internal artist/persona/profile id.             |
| `durationMs`       | Audio duration in milliseconds.                 |
| `sampleRateHz`     | Source sample rate.                             |
| `channelCount`     | Source channel count.                           |

### `MusicShieldScanConfig`

| Option          | Description                                                      |
| --------------- | ---------------------------------------------------------------- |
| `engines`       | Restrict scan to named engines. Omit for configured default set. |
| `jurisdictions` | Apply jurisdiction threshold overrides, for example `US`, `UK`.  |
| `riskThreshold` | Caller policy threshold as a risk level or numeric score.        |
| `maxLatencyMs`  | Caller latency budget for the scan.                              |
| `bypassCache`   | Force a fresh scan even when normalized audio is cached.         |
| `mode`          | `full`, `quick`, or `batch`.                                     |

### `ShieldBatchScanRequestBody`

| Option          | Required | Description                                      |
| --------------- | -------- | ------------------------------------------------ |
| `batchId`       | No       | Caller-supplied batch id.                        |
| `items`         | Yes      | Scan items with `itemId` and `request`.          |
| `callbackUrl`   | No       | Completion callback URL for the batch.           |
| `streamResults` | No       | Request streaming response support when enabled. |

---

## Troubleshooting

### `401 unauthorized`

Confirm the caller sends exactly one accepted credential path: `apiKey` for
`x-api-key`, or `bearerToken` for the `Authorization` header. Health checks may
be public depending on server configuration, so do not use `getHealth()` alone
to verify protected route access.

### `429 rate_limited`

The server-side limiter is per authenticated client id. Reduce concurrency,
batch scans, or tune the caller retry policy. The SDK retries `429` by default.

### `400 bad_request`

Check `audio.kind`, `audio.data`, and `callbackUrl`. The server validates audio
input and requires callback URLs to be valid URLs. For base64 input, send the
raw base64 string without a data URL prefix.

### Scan stays `queued` or `running`

Poll `getResult(scanId)` and inspect `getHealth()` plus `getStats()`. If
`queuedScans` is rising, scale workers or lower scan concurrency in the
generation service.

### Unexpected `flag` or `reject`

Inspect `matches`, `matchedElements`, `timeSegments`, and `jurisdictionRisk`. If
a reviewer clears the item, submit a review decision and keep the override
rationale with the provenance bundle. Repeated false positives should be fed to
the analytics false-positive tracker.

### Missed infringement report after publication

Fetch the provenance chain and scan result, then create a false-negative record
with the missed reference work id, engine coverage, and whether the work was in
the reference database at scan time. Re-run with `bypassCache: true` after the
reference database is updated.

### SDK throws `ShieldClientError`

Inspect:

- `error.status`
- `error.operation`
- `error.responseBody`
- `error.attempts`

Network failures use status `0`. Non-transient API errors are not retried.

---

## Verification Checklist

Before enabling Music Shield as a release gate for a new generation pipeline:

- Full scan is called before publication.
- Quick scan results are treated as advisory only.
- `flag`, `high_risk`, and `reject` cannot publish without review or remediation
  policy.
- `generationId`, prompt/model metadata, and provenance are persisted.
- `scanId` is idempotent or the SDK idempotency key factory is stable enough for
  retries.
- Reference work lookup is available to reviewers.
- Health and stats are monitored.
- False-positive and false-negative outcomes feed the analytics package.
