# Themis Universal Shield Developer Integration Guide

This guide shows how to integrate the Phase 75 Universal Originality Shield into
generation, upload, and publication pipelines. It covers HTTP client usage,
embedded gateway usage, media-specific payloads, configuration, error handling,
and performance tuning.

Use `createShieldApiClient().universalScan()` when a product service calls the
Shield API over HTTP. Use `UniversalShieldGateway` directly only when the scan
adapters run in the same process as the generation or ingestion worker.

---

## Integration Flow

1. Assign a stable `generationId` and request-scoped `scanId`.
2. Build a `UniversalShieldScanRequestBody` with either one `content` item or a
   `components` array for compound media.
3. Set `domain` to the calling domain, such as `calliope`, `isis`, `hathor`,
   `veritas`, `maya`, or `yemaya`.
4. Submit the scan with `client.universalScan()` or `gateway.scan()`.
5. Branch on `actionRequired`.
6. Store the scan response, routed shield ids, component findings, reference
   ids, and the publication decision with the generation record.
7. Route `review`, `remediate`, and `reject` outcomes to the review or
   remediation pipeline before publication.

Default Universal Shield actions are:

| Risk level  | `actionRequired` | Default handling                                  |
| ----------- | ---------------- | ------------------------------------------------- |
| `pass`      | `none`           | Publish and retain the audit record               |
| `advisory`  | `none`           | Publish with monitoring and provenance retention  |
| `flag`      | `review`         | Hold publication for trained reviewer assessment  |
| `high_risk` | `remediate`      | Hold publication and create a remediation package |
| `reject`    | `reject`         | Block publication until legal or policy override  |

---

## Install And Configure

The shield API client is exported from `@themis/shield-api` in this workspace.
Application packages normally depend on the published package or workspace
package:

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

Set the 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 a JWT
issued by the platform identity layer.

```typescript
import { createShieldApiClient } from '@themis/shield-api';

export const shieldClient = createShieldApiClient({
  baseUrl: process.env.THEMIS_SHIELD_API_URL ?? 'http://localhost:8787',
  apiKey: process.env.THEMIS_SHIELD_API_KEY,
  headers: {
    'x-service-name': 'isis-generation-worker',
  },
});
```

---

## Universal Scan Payload

Use `content` for a single artifact:

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

export async function scanImageGeneration(input: {
  readonly generationId: string;
  readonly imageUrl: string;
  readonly prompt: string;
  readonly modelId: string;
}): Promise<void> {
  const response = await shieldClient.universalScan({
    scanId: `image-${input.generationId}`,
    generationId: input.generationId,
    domain: 'isis',
    mediaType: 'image',
    content: {
      kind: 'url',
      data: input.imageUrl,
      contentType: 'image/png',
      filename: `${input.generationId}.png`,
      metadata: {
        prompt: input.prompt,
        modelId: input.modelId,
      },
    },
    metadata: {
      releaseGate: 'pre_publish',
      workflow: 'text_to_image',
    },
  });

  await applyUniversalShieldDecision(input.generationId, response);
}
```

Use `components` for compound content where multiple media types must be
evaluated together:

```typescript
const response = await shieldClient.universalScan({
  scanId: `music-video-${generationId}`,
  generationId,
  domain: 'calliope',
  components: [
    {
      componentId: 'soundtrack',
      role: 'music_track',
      mediaType: 'music',
      content: {
        kind: 'url',
        data: audioUrl,
        contentType: 'audio/wav',
      },
    },
    {
      componentId: 'lyrics',
      role: 'lyric_sheet',
      mediaType: 'text',
      content: {
        kind: 'text',
        data: lyrics,
        contentType: 'text/plain',
      },
    },
    {
      componentId: 'video-render',
      role: 'final_video',
      mediaType: 'video',
      content: {
        kind: 'url',
        data: videoUrl,
        contentType: 'video/mp4',
      },
    },
  ],
  metadata: {
    releaseGate: 'final_publish',
    compoundPolicy: 'music_video',
  },
});
```

The response includes:

- `detectedMediaTypes`: normalized media types scanned.
- `routedShieldIds`: adapters used by the gateway.
- `componentResults`: per-component findings, scores, and reference ids.
- `compoundMatches`: cross-component matches that may raise the overall risk.
- `overallRiskLevel` and `actionRequired`: the publication gate decision.

---

## Media Type Steps

Use the same scan flow for every media type. The difference is how the content
is encoded and which metadata helps reviewers and audit trails.

| Media type    | Content guidance                                 | Required metadata to include              |
| ------------- | ------------------------------------------------ | ----------------------------------------- |
| `audio`       | WAV, FLAC, MP3, or object storage URL            | duration, sample rate, channel count      |
| `music`       | final mix, stems, melody, or MIDI-like object    | prompt, model, genre, tempo, contributors |
| `voice`       | utterance audio or voice embedding reference     | consent id, speaker claim, locale         |
| `image`       | PNG, JPEG, or source image URL                   | prompt, seed, model, dimensions           |
| `text`        | generated text, prompt output, script, or lyrics | prompt, source task, language             |
| `video`       | MP4, MOV, WebM, storyboard bundle, or keyframes  | duration, fps, model, shot list           |
| `model_3d`    | GLB, glTF, OBJ, FBX, or topology object          | asset class, topology stats, source tool  |
| `motion`      | keyframes, BVH-like data, or mocap clip URL      | frame rate, rig type, capture source      |
| `character`   | character sheet, profile, or model bundle        | archetype, silhouette tags, prompt        |
| `fashion`     | garment render, pattern, or tech pack            | garment type, pattern source, collection  |
| `environment` | level layout, scene graph, or environment render | map size, landmarks, asset pack ids       |

### Audio, Music, And Voice

Use `audio` for generic sound effects and recordings, `music` for composition
and track-level scans, and `voice` for voice likeness or consent-sensitive
output. These media types route to `music_shield`.

```typescript
await shieldClient.universalScan({
  generationId,
  domain: 'calliope',
  mediaType: 'voice',
  content: {
    kind: 'url',
    data: voiceClipUrl,
    contentType: 'audio/wav',
    metadata: {
      consentId,
      speakerDisplayName,
      locale: 'en-US',
    },
  },
});
```

### Image And Video

Use `image` for single-frame outputs and `video` for rendered clips,
storyboards, or shot sequences. Include prompts, model versions, source
references, and dimensions so reviewers can reproduce context.

### Text

Use `text` for prose, dialogue, lyrics, prompts, captions, scripts, and
metadata-heavy story exports. Include the generation prompt and any source
constraints. Do not strip paragraph order before scanning; sequence similarity
is part of the signal.

### 3D, Motion, Character, Fashion, And Environment

Use structured object payloads when the artifact is not yet exported:

```typescript
await shieldClient.universalScan({
  generationId,
  domain: 'yemaya',
  mediaType: 'model_3d',
  content: {
    kind: 'object',
    data: {
      mediaType: 'model_3d',
      meshes: meshSummaries,
      vertices: vertexCount,
      materials: materialFingerprints,
    },
    metadata: {
      sourceTool: 'procedural-kitbash-worker',
      assetClass: 'vehicle_prop',
    },
  },
});
```

Use `components` when a character has a visual sheet, 3D model, costume pack,
and animation all tied to one release decision.

---

## Embedded Gateway Integration

Use `UniversalShieldGateway` directly when adapters run in-process:

```typescript
import {
  UniversalShieldGateway,
  type UniversalShieldAdapter,
} from '@themis/shield-api';

const adapters: readonly UniversalShieldAdapter[] = [
  musicAdapter,
  visualAdapter,
  textAdapter,
  videoAdapter,
  model3dAdapter,
  motionAdapter,
  characterAdapter,
  fashionAdapter,
  environmentAdapter,
];

export const universalShield = new UniversalShieldGateway({ adapters });

const response = await universalShield.scan({
  scanId: `embedded-${generationId}`,
  generationId,
  domain: 'hathor',
  mediaType: 'text',
  content: {
    kind: 'text',
    data: sceneText,
    contentType: 'text/plain',
  },
});
```

Adapters must return a `UniversalShieldComponentScanResult` with a stable
`componentId`, `mediaType`, `shieldId`, `status`, `riskLevel`, `score`,
`findings`, and optional `referenceWorkId`.

---

## Decision Handling

Keep publication logic small and auditable:

```typescript
import type { UniversalShieldScanResponse } from '@themis/shield-api';

type PublicationDecision =
  | { readonly action: 'publish'; readonly reason: string }
  | {
      readonly action: 'review';
      readonly queue: string;
      readonly reason: string;
    }
  | { readonly action: 'remediate'; readonly reason: string }
  | { readonly action: 'reject'; readonly reason: string };

export function decisionForUniversalShield(
  response: UniversalShieldScanResponse
): PublicationDecision {
  switch (response.actionRequired) {
    case 'none':
      return {
        action: 'publish',
        reason: 'Universal Shield passed the release gate.',
      };
    case 'review':
      return {
        action: 'review',
        queue: reviewQueueFor(response),
        reason: 'Reviewable similarity requires human assessment.',
      };
    case 'remediate':
      return {
        action: 'remediate',
        reason: 'High-risk similarity requires content remediation.',
      };
    case 'reject':
      return {
        action: 'reject',
        reason: 'Release-blocking similarity detected.',
      };
  }
}
```

Persist the full response with the generated artifact. Do not persist only the
final action; downstream audit, legal review, and quality analysis need the
component-level details.

---

## Error Handling

HTTP callers should handle these classes of failure:

| Condition            | Handling                                                                  |
| -------------------- | ------------------------------------------------------------------------- |
| `400` invalid input  | Treat as integration bug; log request shape and block publication         |
| `401` unauthorized   | Refresh credentials or rotate service key; do not retry indefinitely      |
| `429` rate limited   | Retry with backoff and leave the generation unpublished                   |
| `5xx` server error   | Retry with bounded backoff; escalate if the release gate deadline expires |
| `501` no gateway     | Misconfiguration; enable `universalScan` handler before routing traffic   |
| failed scan response | Block publication and send the scan id to operations for triage           |

When retrying, reuse `generationId` and use a stable or idempotent `scanId`
derived from the generation and release gate. This prevents duplicate audit
records for the same artifact.

---

## Configuration Checklist

Each domain integration should define:

- Which release gates call the shield: preflight, preview, final publish, import
  ingestion, remix export, or marketplace listing.
- Which media types are possible in that domain.
- The adapter set enabled in each environment.
- Request size limits and whether large artifacts must use `url` or object
  storage references.
- Review queues for `flag` results by media type.
- Remediation behavior for `high_risk` results.
- Hard block policy for `reject` results.
- Audit retention policy for the scan response and publication decision.
- Jurisdiction and consent metadata required for voice, biometric, or likeness
  sensitive output.

---

## Performance Tuning

Baseline latency targets are tracked in
`UNIVERSAL_SHIELD_PERFORMANCE_REGRESSION_BASELINE`:

| Scan type             | Target      |
| --------------------- | ----------- |
| image, audio, music   | under 5s    |
| text                  | under 10s   |
| 3D, motion, scene     | under 15s   |
| video                 | under 60s   |
| compound music video  | under 90s   |
| concurrent throughput | 20 scans/s  |
| memory delta          | under 64MiB |

For production callers:

- Prefer object storage URLs for video, 3D, and compound scans.
- Use `quickScan` only for music-specific fast preflight; use `universalScan`
  for cross-media publication gates.
- Batch generation worker submissions by release stage, not by unrelated user
  sessions.
- Cache reference lookups by `referenceWorkId`, but never cache final scan
  decisions across distinct artifacts.
- Record queue wait time separately from scan execution time.
- Run `runUniversalShieldPerformanceBenchmarks()` after adapter changes and
  compare results to the regression baseline before deployment.

---

## Verification

Before merging a new domain integration:

```bash
pnpm nx typecheck @themis/shield-api
pnpm nx test @themis/shield-api
pnpm nx lint @themis/shield-api
pnpm nx build @themis/shield-api
pnpm exec tsx scripts/themis/run-universal-shield-continuous-validation.ts \
  --report-file /tmp/themis-shield-continuous-validation-report.json \
  --trigger manual \
  --fail-on-alerts
```

Add or update tests when an integration changes routing, risk mapping, component
construction, review decisions, remediation, or audit persistence.
