> ## Documentation Index
> Fetch the complete documentation index at: https://docs.go.aiinsurance.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Repair Policies

> Company-scoped Policy integrity repair. Choose `segmentHashes` to recompute stored segment hashes, `joinHistory` to rebuild relationship history from immutable segments, or `fieldValues` to rewrite a reviewed field-value manifest across a single Policy's history.

Segment hashes and join history default to `dryRun: true`, have a bounded `limit`, and return an exclusive `nextCursor`; repeat the same scope with that cursor until it is null. Join history refuses link loss unless `allowLinkLoss: true`; inspect the dry-run loss samples before applying. A dry run rolls back the rebuilt relationships.

For `fieldValues`, supply `repair.policyId` and an explicit `repair.dryRun`. Preview returns current/projected SHA-256 fingerprints and occurrences. Apply requires both reviewed fingerprints, writes atomically, and returns `unchanged` on replay. A stale preimage or unexpected postimage returns 409 without changes. Apply records one transactional audit entry. Repairs do not create Policy versions.

**Required permission:** none — staff level `staff` (a staff user's own Bearer token or a verified platform service identity); API keys are rejected.



## OpenAPI

````yaml /openapi/generated-external-api.yaml post /api/v1/companies/{companyId}/policies/repair
openapi: 3.0.3
info:
  title: AI Insurance External API
  description: External API for AI Insurance platform
  version: 1.0.0
  contact:
    email: support@aiinsurance.io
servers:
  - url: https://go.aiinsurance.io
    description: Production
security:
  - ApiKeyAuth: []
paths:
  /api/v1/companies/{companyId}/policies/repair:
    post:
      tags:
        - Field Model Policy Transactions
      summary: Repair Policies
      description: >-
        Company-scoped Policy integrity repair. Choose `segmentHashes` to
        recompute stored segment hashes, `joinHistory` to rebuild relationship
        history from immutable segments, or `fieldValues` to rewrite a reviewed
        field-value manifest across a single Policy's history.


        Segment hashes and join history default to `dryRun: true`, have a
        bounded `limit`, and return an exclusive `nextCursor`; repeat the same
        scope with that cursor until it is null. Join history refuses link loss
        unless `allowLinkLoss: true`; inspect the dry-run loss samples before
        applying. A dry run rolls back the rebuilt relationships.


        For `fieldValues`, supply `repair.policyId` and an explicit
        `repair.dryRun`. Preview returns current/projected SHA-256 fingerprints
        and occurrences. Apply requires both reviewed fingerprints, writes
        atomically, and returns `unchanged` on replay. A stale preimage or
        unexpected postimage returns 409 without changes. Apply records one
        transactional audit entry. Repairs do not create Policy versions.


        **Required permission:** none — staff level `staff` (a staff user's own
        Bearer token or a verified platform service identity); API keys are
        rejected.
      operationId: repairPolicies
      parameters:
        - $ref: '#/components/parameters/companyId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - type: object
                  additionalProperties: false
                  required:
                    - kind
                  properties:
                    kind:
                      type: string
                      enum:
                        - segmentHashes
                    dryRun:
                      type: boolean
                      default: true
                    limit:
                      type: integer
                      minimum: 1
                      maximum: 1000
                      default: 100
                    cursor:
                      type: object
                      additionalProperties: false
                      required:
                        - policyId
                        - policyVersion
                        - startDate
                      properties:
                        policyId:
                          type: string
                          format: uuid
                        policyVersion:
                          type: integer
                          minimum: 1
                        startDate:
                          type: string
                          format: date
                - type: object
                  additionalProperties: false
                  required:
                    - kind
                  properties:
                    kind:
                      type: string
                      enum:
                        - joinHistory
                    dryRun:
                      type: boolean
                      default: true
                    limit:
                      type: integer
                      minimum: 1
                      maximum: 1000
                      default: 100
                    cursor:
                      type: object
                      additionalProperties: false
                      required:
                        - companyId
                        - policyId
                      properties:
                        companyId:
                          type: string
                          format: uuid
                        policyId:
                          type: string
                          format: uuid
                    allowLinkLoss:
                      type: boolean
                      default: false
                - type: object
                  additionalProperties: false
                  required:
                    - kind
                    - repair
                  properties:
                    kind:
                      type: string
                      enum:
                        - fieldValues
                    repair:
                      oneOf:
                        - type: object
                          additionalProperties: false
                          required:
                            - dryRun
                            - rewrites
                            - policyId
                          properties:
                            dryRun:
                              type: boolean
                              enum:
                                - true
                            rewrites:
                              type: array
                              minItems: 1
                              items:
                                $ref: '#/components/schemas/PolicyFieldValueRewrite'
                            policyId:
                              type: string
                              format: uuid
                        - type: object
                          additionalProperties: false
                          required:
                            - dryRun
                            - expectedPreFingerprint
                            - expectedPostFingerprint
                            - rewrites
                            - policyId
                          properties:
                            dryRun:
                              type: boolean
                              enum:
                                - false
                            expectedPreFingerprint:
                              type: string
                              pattern: ^[0-9a-f]{64}$
                              description: >-
                                Reviewed SHA-256 fingerprint of the exact
                                preimage occurrences.
                            expectedPostFingerprint:
                              type: string
                              pattern: ^[0-9a-f]{64}$
                              description: >-
                                Reviewed SHA-256 fingerprint of the exact
                                postimage occurrences.
                            rewrites:
                              type: array
                              minItems: 1
                              items:
                                $ref: '#/components/schemas/PolicyFieldValueRewrite'
                            policyId:
                              type: string
                              format: uuid
            examples:
              previewHashes:
                summary: Preview segment hash repairs
                value:
                  kind: segmentHashes
                  dryRun: true
              previewJoinHistory:
                summary: Preview relationship history repairs
                value:
                  kind: joinHistory
                  dryRun: true
                  limit: 100
              previewFields:
                summary: Preview a field-value rewrite
                value:
                  kind: fieldValues
                  repair:
                    policyId: 550e8400-e29b-41d4-a716-446655440001
                    dryRun: true
                    rewrites:
                      - path: policy.commissionPercentage
                        expectedValue: 25
                        replacementValue: 0.25
      responses:
        '200':
          description: >-
            Kind-specific repair report. Continue bounded scans until nextCursor
            is null.
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    additionalProperties: false
                    required:
                      - kind
                      - scanned
                      - mismatched
                      - repaired
                      - remaining
                      - nextCursor
                      - byCompany
                    properties:
                      kind:
                        type: string
                        enum:
                          - segmentHashes
                      scanned:
                        type: integer
                        minimum: 0
                      mismatched:
                        type: integer
                        minimum: 0
                      repaired:
                        type: integer
                        minimum: 0
                      remaining:
                        type: integer
                        minimum: 0
                      nextCursor:
                        type: object
                        additionalProperties: false
                        required:
                          - policyId
                          - policyVersion
                          - startDate
                        properties:
                          policyId:
                            type: string
                            format: uuid
                          policyVersion:
                            type: integer
                            minimum: 1
                          startDate:
                            type: string
                            format: date
                        nullable: true
                      byCompany:
                        type: array
                        items:
                          type: object
                          additionalProperties: false
                          required:
                            - companyId
                            - scanned
                            - mismatched
                            - repaired
                          properties:
                            companyId:
                              type: string
                              format: uuid
                            scanned:
                              type: integer
                              minimum: 0
                            mismatched:
                              type: integer
                              minimum: 0
                            repaired:
                              type: integer
                              minimum: 0
                  - type: object
                    required:
                      - kind
                      - scanned
                      - mismatched
                      - repaired
                      - unversionedCleared
                      - linksGained
                      - linksLost
                      - skippedLinkLoss
                      - lostSamples
                      - remaining
                      - nextCursor
                      - byCompany
                    properties:
                      kind:
                        type: string
                        enum:
                          - joinHistory
                      scanned:
                        type: integer
                        minimum: 0
                      remaining:
                        type: integer
                        minimum: 0
                      nextCursor:
                        type: object
                        additionalProperties: false
                        required:
                          - companyId
                          - policyId
                        properties:
                          companyId:
                            type: string
                            format: uuid
                          policyId:
                            type: string
                            format: uuid
                        nullable: true
                      mismatched:
                        type: integer
                        minimum: 0
                      repaired:
                        type: integer
                        minimum: 0
                      unversionedCleared:
                        type: integer
                        minimum: 0
                      linksGained:
                        type: integer
                        minimum: 0
                      linksLost:
                        type: integer
                        minimum: 0
                      skippedLinkLoss:
                        type: integer
                        minimum: 0
                      lostSamples:
                        type: array
                        items:
                          type: string
                      byCompany:
                        type: array
                        items:
                          type: object
                          required:
                            - companyId
                            - scanned
                            - mismatched
                            - repaired
                            - unversionedCleared
                            - linksGained
                            - linksLost
                            - skippedLinkLoss
                          properties:
                            companyId:
                              type: string
                              format: uuid
                            scanned:
                              type: integer
                              minimum: 0
                            mismatched:
                              type: integer
                              minimum: 0
                            repaired:
                              type: integer
                              minimum: 0
                            unversionedCleared:
                              type: integer
                              minimum: 0
                            linksGained:
                              type: integer
                              minimum: 0
                            linksLost:
                              type: integer
                              minimum: 0
                            skippedLinkLoss:
                              type: integer
                              minimum: 0
                  - type: object
                    required:
                      - status
                      - currentFingerprint
                      - projectedFingerprint
                      - occurrences
                      - kind
                    properties:
                      status:
                        type: string
                        enum:
                          - dryRun
                      currentFingerprint:
                        type: string
                        pattern: ^[0-9a-f]{64}$
                      projectedFingerprint:
                        type: string
                        pattern: ^[0-9a-f]{64}$
                      occurrences:
                        type: array
                        items:
                          oneOf:
                            - $ref: >-
                                #/components/schemas/PolicySegmentFieldValueOccurrence
                            - $ref: >-
                                #/components/schemas/PolicyTransactionDeltaFieldValueOccurrence
                      kind:
                        type: string
                        enum:
                          - fieldValues
                  - type: object
                    required:
                      - status
                      - fingerprint
                      - occurrences
                      - kind
                    properties:
                      status:
                        type: string
                        enum:
                          - changed
                          - unchanged
                      fingerprint:
                        type: string
                        pattern: ^[0-9a-f]{64}$
                      occurrences:
                        type: array
                        items:
                          oneOf:
                            - $ref: >-
                                #/components/schemas/PolicySegmentFieldValueOccurrence
                            - $ref: >-
                                #/components/schemas/PolicyTransactionDeltaFieldValueOccurrence
                      kind:
                        type: string
                        enum:
                          - fieldValues
              examples:
                cleanHashes:
                  summary: Completed segment hash preview
                  value:
                    kind: segmentHashes
                    scanned: 0
                    mismatched: 0
                    repaired: 0
                    remaining: 0
                    nextCursor: null
                    byCompany: []
        '400':
          description: The strict rewrite manifest is invalid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: The live Policy does not exist in the company named by the URL.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '409':
          description: >-
            The current preimage or projected postimage differs from the
            reviewed manifest; nothing was written.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PolicyFieldValueRewriteConflict'
        '500':
          $ref: '#/components/responses/InternalServerError'
      security:
        - BearerAuth: []
components:
  parameters:
    companyId:
      name: companyId
      in: path
      required: true
      schema:
        type: string
        format: uuid
      description: Company identifier
  schemas:
    PolicyFieldValueRewrite:
      type: object
      description: >-
        One exact value mapping. The same path may appear more than once when
        Policy history contains different raw values, but each
        path/expectedValue pair must be unique so one physical occurrence can
        match at most one mapping.
      additionalProperties: false
      required:
        - path
        - expectedValue
        - replacementValue
      properties:
        path:
          type: string
          pattern: ^policy(?:\.[A-Za-z0-9_-]+)+$
          example: policy.commissionPercentage
        expectedValue:
          description: The exact value to replace wherever this logical path occurs.
        replacementValue:
          description: The canonical replacement value.
    PolicySegmentFieldValueOccurrence:
      type: object
      additionalProperties: false
      required:
        - surface
        - policyVersion
        - startDate
        - path
        - valuePath
        - value
      properties:
        surface:
          type: string
          enum:
            - policySegment
        policyVersion:
          type: integer
        startDate:
          type: string
          format: date
        path:
          type: string
        valuePath:
          type: string
          description: JSON Pointer within the bare policy segment blob.
        value: {}
    PolicyTransactionDeltaFieldValueOccurrence:
      type: object
      additionalProperties: false
      required:
        - surface
        - transactionId
        - deltaId
        - deltaPath
        - path
        - valuePath
        - value
      properties:
        surface:
          type: string
          enum:
            - policyTransactionDelta
        transactionId:
          type: string
          format: uuid
        deltaId:
          type: string
          format: uuid
        deltaPath:
          type: string
        path:
          type: string
        valuePath:
          type: string
          description: JSON Pointer within the delta value; empty for a direct delta.
        value: {}
    ErrorResponse:
      type: object
      description: Standard error response for all external API endpoints
      required:
        - error
      properties:
        error:
          type: object
          required:
            - code
            - message
          properties:
            code:
              type: string
              description: Machine-readable error code
              example: VALIDATION_ERROR
            message:
              type: string
              description: Human-readable error message
              example: 'submissionId: Required field is missing'
            userMessages:
              type: array
              description: >-
                Clean, verbatim-displayable messages — one entry per failure,
                free of error-code tags, field paths, and internal noise.
                Suitable for showing to end users as-is.
              items:
                type: string
              example:
                - Exposures of type 'company' require an address
            details:
              type: array
              description: Additional details for validation errors (field-level errors)
              items:
                type: object
                properties:
                  field:
                    type: string
                    description: The field that caused the error
                    example: submissionId
                  code:
                    type: string
                    description: Stable problem code for this individual validation failure
                    example: BLANK_LIST_ELEMENT
                  reason:
                    type: string
                    description: Stable reason the value violates its canonical contract
                    example: blank-list-element
                  expected:
                    type: string
                    description: The expected canonical value contract
                    example: nonblank trimmed string
                  message:
                    type: string
                    description: Description of the field error
                    example: Required field is missing
    PolicyFieldValueRewriteConflict:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          required:
            - code
            - message
            - expectedPostFingerprint
            - occurrences
          properties:
            code:
              type: string
              enum:
                - policy-field-value-rewrite-preimage-mismatch
                - policy-field-value-rewrite-postimage-mismatch
            message:
              type: string
            userMessages:
              type: array
              items:
                type: string
            expectedPreFingerprint:
              type: string
              pattern: ^[0-9a-f]{64}$
            expectedPostFingerprint:
              type: string
              pattern: ^[0-9a-f]{64}$
            currentFingerprint:
              type: string
              pattern: ^[0-9a-f]{64}$
            actualPostFingerprint:
              type: string
              pattern: ^[0-9a-f]{64}$
            occurrences:
              type: array
              items:
                oneOf:
                  - $ref: '#/components/schemas/PolicySegmentFieldValueOccurrence'
                  - $ref: >-
                      #/components/schemas/PolicyTransactionDeltaFieldValueOccurrence
  responses:
    Unauthorized:
      description: Unauthorized - Invalid or missing API key
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            missingApiKey:
              summary: Missing API key
              value:
                error:
                  code: AuthenticationError
                  message: API key authentication required
                  userMessages:
                    - API key authentication required
            invalidApiKey:
              summary: >-
                Invalid API key (e.g. unknown key, or a Bearer token used
                instead of an API key)
              value:
                error:
                  code: AuthenticationError
                  message: Invalid API key
                  userMessages:
                    - Invalid API key
    Forbidden:
      description: Forbidden - Insufficient permissions
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            insufficientPermissions:
              summary: Insufficient permissions
              value:
                error:
                  code: AuthorizationError
                  message: User is not authorized to perform the requested action
                  userMessages:
                    - User is not authorized to perform the requested action
            companyMismatch:
              summary: A valid API key naming another company in the URL
              value:
                error:
                  code: AuthorizationError
                  message: API key is not scoped to the requested company
                  userMessages:
                    - API key is not scoped to the requested company
    InternalServerError:
      description: Internal Server Error - Unexpected error occurred
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            internalError:
              summary: Unexpected server error
              value:
                error:
                  code: UncaughtActionError
                  message: Uncaught error occurred in <actionName>
                  userMessages:
                    - An unexpected error occurred. Please try again later.
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: Authorization
      description: >-
        API key authentication. Send your raw API key as the `Authorization`
        header value with NO scheme prefix — `Authorization: YOUR-API-KEY`. Do
        NOT prefix it with `Bearer ` or `ApiKey `, and do not use an `X-API-Key`
        header; those are not accepted.
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >-
        User-principal OAuth 2.0 Bearer authentication. Send a user-scoped Auth0
        access token (audience = the app API audience) as `Authorization: Bearer
        <jwt>`. The request resolves to the user's identity and is authorized by
        their Role on the `{companyId}` in the path — the same role-based
        permissions the web app enforces. This is the path the MCP connector
        uses to act on a user's behalf; endpoints that accept it list both
        `BearerAuth` and `ApiKeyAuth`.

````