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

# Attach a memory layer to a variation

> Add a memory layer to a variation's cascade at a position you choose.

Wire a [memory layer](/docs/api-reference/memoryservice/list-memory-layers) into one [variation](/docs/api-reference/agentvariationservice/list-variations) so every objective it runs can read the layer's entries through `get_memory`.

<CodeGroup>
  ```typescript TypeScript theme={null}
  const assignment = await client.agents.variations.addMemoryLayer(agentId, variationId, {
    workspaceId,
    memoryLayerId: 'external_id:support-knowledge',
    position: 0,
  });

  console.log(assignment.id);        // 'avml_...' the assignment row, not the layer
  console.log(assignment.position);  // 0
  ```

  ```go Go theme={null}
  assignment, err := client.Agents.Variations.AddMemoryLayer(ctx, agentID, variationID,
  	cadenya.AgentVariationAddMemoryLayerParams{
  		WorkspaceID:   cadenya.String(workspaceID),
  		MemoryLayerID: "external_id:support-knowledge",
  		Position:      cadenya.Int(0),
  	})
  if err != nil {
  	log.Fatal(err)
  }
  log.Println(assignment.ID)       // avml_... the assignment row, not the layer
  log.Println(assignment.Position) // 0
  ```

  ```ruby Ruby theme={null}
  assignment = cadenya.agents.variations.add_memory_layer(
    agent_id,
    variation_id,
    workspace_id: workspace_id,
    memory_layer_id: "external_id:support-knowledge",
    position: 0
  )

  puts assignment.id       # avml_... the assignment row, not the layer
  puts assignment.position # 0
  ```

  ```bash cURL theme={null}
  curl -X POST "https://api.cadenya.com/v1/workspaces/${WORKSPACE_ID}/agents/${AGENT_ID}/variations/${VARIATION_ID}/memory_layer_assignments" \
    -H "Authorization: Bearer ${CADENYA_API_KEY}" \
    -H "Content-Type: application/json" \
    -d '{ "memoryLayerId": "external_id:support-knowledge", "position": 0 }'
  ```
</CodeGroup>

## `position` is cascade order

`position` decides who wins when two layers hold the same key. **Lower is more specific**, and the lowest position that has the key resolves it, the same idea as the [memory cascade](/docs/guides/memory-layers) as a whole. So a variation with a general `company-policy` layer at `position: 10` and a team-specific one at `position: 0` reads the team layer's version of a shared key, and falls through to the general layer for keys only it has.

The numbers are yours to space out; they need not be contiguous. `0` and `10` work as well as `0` and `1`, which leaves room to slot a layer between them later without renumbering.

## One layer, once

A layer can be attached to a variation only once. Attaching the same `memoryLayerId` again is a `409`, even at a different position, so change the [position](/docs/api-reference/agentvariationservice/update-a-variations-memory-layer-assignment) on the existing assignment rather than adding a second.

The response returns the assignment's own `avml_...` id. Hold onto it, or read it back from the variation's `info.memoryLayerAssignments`, since that is the id you pass to [remove](/docs/api-reference/agentvariationservice/remove-a-memory-layer-assignment-from-a-variation) or [reposition](/docs/api-reference/agentvariationservice/update-a-variations-memory-layer-assignment) the layer. The assignment carries no external ID; it is a join record.

## Related

<CardGroup cols={2}>
  <Card title="Memory layers" icon="brain" href="/docs/guides/memory-layers">
    The cascade, and how `position` resolves a key.
  </Card>

  <Card title="Update the assignment" icon="arrows-up-down" href="/docs/api-reference/agentvariationservice/update-a-variations-memory-layer-assignment">
    Move a layer to a new position.
  </Card>

  <Card title="Remove the assignment" icon="xmark" href="/docs/api-reference/agentvariationservice/remove-a-memory-layer-assignment-from-a-variation">
    Unwire the layer from the variation.
  </Card>

  <Card title="Add an assignment" icon="plus" href="/docs/api-reference/agentvariationservice/add-an-assignment-to-a-variation">
    The tool-set and sub-agent equivalent.
  </Card>
</CardGroup>


## OpenAPI

````yaml post /v1/workspaces/{workspaceId}/agents/{agentId}/variations/{variationId}/memory_layer_assignments
openapi: 3.1.0
info:
  title: Cadenya API
  description: API for the Cadenya Agent Runtime platform.
  version: '1.0'
servers:
  - url: https://api.cadenya.com
    description: Production server
security:
  - bearerAuth: []
tags:
  - name: AIProviderKeyService
  - name: APIKeyService
    description: |-
      Issue, rotate, disable, and revoke a workspace's API keys. Every key
       belongs to exactly one workspace; the system-managed global account key is
       managed via GlobalAPIKeyService instead.
  - name: AccountService
    description: >-
      Manage the authenticated account. Accounts are the top-level
      organizational
       unit and contain one or more workspaces.
  - name: AgentScheduleService
    description: >-
      Manage recurring schedules attached to agents. Schedules trigger
      objectives
       on a cadence defined by AgentScheduleSpec.Schedule.
  - name: AgentService
    description: >-
      Manage AI agents within a workspace. Agents define AI behavior and tool
      access.
  - name: AgentVariationService
    description: >-
      Manage variations of an agent and their tool, sub-agent, and memory layer
      assignments.
  - name: GlobalAPIKeyService
    description: |-
      Manage the account's system-provisioned global API key. The global key is
       the only key that spans every workspace; it is created by the system and
       cannot be deleted, so the surface is retrieve, rotate, and the
       disable/enable kill switch.
  - name: MemoryService
    description: >-
      Manage memory layers and their entries. Layers are named containers that
      can
       be composed into an objective's memory cascade; entries are the keyed values
       within a layer. System-managed layers (e.g., episodic layers created by the
       runtime) cannot be mutated through this API.
  - name: ModelService
    description: |-
      Manage LLM models available to a workspace. Models represent provider and
       family pairs (e.g., "anthropic/claude-sonnet-4.6"). Workspaces are seeded
       with the supported models and you can enable or disable each one.
  - name: ObjectiveEventStreamsService
  - name: ObjectiveService
  - name: ProfilesService
    description: |-
      Operations on profiles, the account-level principals (users, API keys,
       system) that authenticate against the API.
  - name: SearchService
  - name: TenantService
    description: >-
      Read and erase tenants and the subjects under them. Tenants and subjects
      are
       created by assertion — on objective creation or widget session mint — never
       directly, so this service has no create or update: it exists to enumerate what
       assertions have produced, and to destroy it on request.
  - name: ToolService
    description: >-
      Manage tool sets and the tools they contain. Tool sets group related
      tools,
       and tools define specific capabilities available to agents.

       When a tool set is managed, only API key actors can modify its tools; human
       (profile) actors cannot.
  - name: UploadService
    description: |-
      Issue short-lived presigned URLs for direct client-to-object-storage
       uploads. Created uploads can be referenced by id when creating or updating
       resources that accept binary content (e.g., MemoryEntry).
  - name: WidgetService
    description: |-
      Manage embeddable chat widgets. A widget binds an agent to a globally
       unique hostname with a per-widget origin allowlist; browsers reach it with
       session tokens minted via WidgetSessionService.
  - name: WidgetSessionService
    description: >-
      Mint and manage widget sessions. Session creation is server-to-server
      only:
       the customer's backend authenticates its visitor, asserts tenant/subject
       context, attaches any per-visitor secrets, and receives a short-lived
       bearer token the browser uses against the widget host.
  - name: WorkspaceAdminService
    description: >-
      Administer workspaces across the account: create and archive workspaces
      and
       manage their membership. These operations are account-scoped and require the
       admin role (a token whose profile holds the WorkOS admin role); they live
       under /v1/account/workspaces rather than the workspace-scoped /v1/workspaces
       tree so an admin can manage any workspace in the account, including ones they
       are not themselves a member of.
  - name: WorkspaceSecretService
  - name: WorkspaceService
    description: |-
      Manage workspaces within an account. Workspaces provide organizational
       grouping and isolation for resources such as agents, tools, and API keys.

       This is the workspace-scoped, end-user surface. Administrative operations
       (create / archive workspaces, manage members) live in WorkspaceAdminService
       under /v1/account/workspaces and require the admin role.
paths:
  /v1/workspaces/{workspaceId}/agents/{agentId}/variations/{variationId}/memory_layer_assignments:
    post:
      tags:
        - AgentVariationService
        - Agent Variations
      summary: Attach a memory layer to a variation
      description: >-
        Attaches a memory layer to a variation at a given position in the
        variation's baseline memory cascade.
      operationId: AgentVariationService_AddAgentVariationMemoryLayer
      parameters:
        - name: workspaceId
          in: path
          description: Workspace ID.
          required: true
          schema:
            type: string
            example: workspace_01HXKD2E5NQM3T9AYWCF133E3Q
        - name: agentId
          in: path
          description: >-
            Agent ID. Accepts the canonical `agent_…` form or the
            `external_id:<value>` form.
          required: true
          schema:
            example: agent_01HXKD2E5NQM3T9AYWCFMGWT9Y
            type: string
        - name: variationId
          in: path
          description: >-
            Variation ID. Accepts the canonical `agentvar_…` form or the
            `external_id:<value>` form.
          required: true
          schema:
            type: string
            example: agentvar_01HXKD2E5NQM3T9AYWCF32BSPP
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AddAgentVariationMemoryLayerRequest'
        required: true
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/VariationMemoryLayerAssignment'
        default:
          description: Default error response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Status'
      x-codeSamples:
        - lang: JavaScript
          source: >-
            import Cadenya from '@cadenya/cadenya';


            const client = new Cadenya({
              apiKey: process.env['CADENYA_API_KEY'], // This is the default and can be omitted
            });


            const variationMemoryLayerAssignment = await
            client.agents.variations.addMemoryLayer(
              'agent_01HXKD2E5NQM3T9AYWCFMGWT9Y',
              'agentvar_01HXKD2E5NQM3T9AYWCF32BSPP',
              {
                workspaceId: 'workspace_01HXKD2E5NQM3T9AYWCF133E3Q',
                memoryLayerId: 'memlyr_01HXKD2E5NQM3T9AYWCFFFBMJH',
              },
            );


            console.log(variationMemoryLayerAssignment.id);
        - lang: Python
          source: >-
            import os

            from cadenya import Cadenya


            client = Cadenya(
                api_key=os.environ.get("CADENYA_API_KEY"),  # This is the default and can be omitted
            )

            variation_memory_layer_assignment =
            client.agents.variations.add_memory_layer(
                agent_id="agent_01HXKD2E5NQM3T9AYWCFMGWT9Y",
                variation_id="agentvar_01HXKD2E5NQM3T9AYWCF32BSPP",
                workspace_id="workspace_01HXKD2E5NQM3T9AYWCF133E3Q",
                memory_layer_id="memlyr_01HXKD2E5NQM3T9AYWCFFFBMJH",
            )

            print(variation_memory_layer_assignment.id)
        - lang: Go
          source: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"go.cadenya.com/cadenya-go\"\n\t\"go.cadenya.com/cadenya-go/option\"\n)\n\nfunc main() {\n\tclient := cadenya.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvariationMemoryLayerAssignment, err := client.Agents.Variations.AddMemoryLayer(\n\t\tcontext.TODO(),\n\t\t\"agent_01HXKD2E5NQM3T9AYWCFMGWT9Y\",\n\t\t\"agentvar_01HXKD2E5NQM3T9AYWCF32BSPP\",\n\t\tcadenya.AgentVariationAddMemoryLayerParams{\n\t\t\tWorkspaceID:   cadenya.String(\"workspace_01HXKD2E5NQM3T9AYWCF133E3Q\"),\n\t\t\tMemoryLayerID: \"memlyr_01HXKD2E5NQM3T9AYWCFFFBMJH\",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", variationMemoryLayerAssignment.ID)\n}\n"
        - lang: Ruby
          source: >-
            require "cadenya"


            cadenya = Cadenya::Client.new(api_key: "My API Key")


            variation_memory_layer_assignment =
            cadenya.agents.variations.add_memory_layer(
              "agent_01HXKD2E5NQM3T9AYWCFMGWT9Y",
              "agentvar_01HXKD2E5NQM3T9AYWCF32BSPP",
              workspace_id: "workspace_01HXKD2E5NQM3T9AYWCF133E3Q",
              memory_layer_id: "memlyr_01HXKD2E5NQM3T9AYWCFFFBMJH"
            )


            puts(variation_memory_layer_assignment)
        - lang: CLI
          source: |-
            cadenya agents:variations add-memory-layer \
              --api-key 'My API Key' \
              --workspace-id workspace_01HXKD2E5NQM3T9AYWCF133E3Q \
              --agent-id agent_01HXKD2E5NQM3T9AYWCFMGWT9Y \
              --variation-id agentvar_01HXKD2E5NQM3T9AYWCF32BSPP \
              --memory-layer-id memlyr_01HXKD2E5NQM3T9AYWCFFFBMJH
components:
  schemas:
    AddAgentVariationMemoryLayerRequest:
      required:
        - memoryLayerId
      type: object
      properties:
        workspaceId:
          readOnly: true
          example: workspace_01HXKD2E5NQM3T9AYWCF133E3Q
          type: string
          description: Workspace ID.
        agentId:
          readOnly: true
          example: agent_01HXKD2E5NQM3T9AYWCFMGWT9Y
          type: string
          description: >-
            Agent ID. Accepts the canonical `agent_…` form or the
            `external_id:<value>` form.
        variationId:
          readOnly: true
          example: agentvar_01HXKD2E5NQM3T9AYWCF32BSPP
          type: string
          description: >-
            Variation ID. Accepts the canonical `agentvar_…` form or the
            `external_id:<value>` form.
        memoryLayerId:
          example: memlyr_01HXKD2E5NQM3T9AYWCFFFBMJH
          type: string
          description: >-
            Layer to attach. Accepts the canonical `memlyr_…` form or the
            `external_id:<value>` form.
        position:
          type: integer
          description: |-
            Position in the baseline cascade (lower = more specific). If
             omitted, the server appends at the most general end (max existing
             position + 1).
          format: int32
      description: |-
        Attach a memory layer to a variation. The request is rejected when:
           - the layer is system-managed (FailedPrecondition)
           - the layer is already assigned to this variation (AlreadyExists)
           - the variation is already at the 10-assignment cap (FailedPrecondition)
           - the position is already in use on this variation (InvalidArgument)
    VariationMemoryLayerAssignment:
      type: object
      properties:
        id:
          readOnly: true
          example: avml_01HXKD2E5NQM3T9AYWCFX8AF59
          type: string
          description: |-
            Assignment row id — handle for removing the assignment. Distinct
             from the referenced memory layer's id.
        memoryLayer:
          allOf:
            - $ref: '#/components/schemas/BareMetadata'
          description: The attached memory layer.
        position:
          type: integer
          description: |-
            Position in the variation's baseline cascade. Position is
             specificity, CSS-style: a LOWER position is more specific and is
             consulted first; the highest-position assignment is the most
             general fallback. Gaps are fine — only relative position matters.
             Positions must be unique within a variation; a request that would
             collide with an existing assignment's position is rejected with
             InvalidArgument.
          format: int32
      description: |-
        VariationMemoryLayerAssignment attaches a single MemoryLayer to a
         variation at a given position in the variation's baseline memory
         cascade. A variation has at most one assignment per memory_layer_id.

         Variations only support whole-layer attachments — entry pinning is an
         objective-level capability.
    Status:
      type: object
      properties:
        code:
          type: integer
          description: >-
            The status code, which should be an enum value of
            [google.rpc.Code][google.rpc.Code].
          format: int32
        message:
          type: string
          description: >-
            A developer-facing error message, which should be in English. Any
            user-facing error message should be localized and sent in the
            [google.rpc.Status.details][google.rpc.Status.details] field, or
            localized by the client.
        details:
          type: array
          items:
            $ref: '#/components/schemas/GoogleProtobufAny'
          description: >-
            A list of messages that carry the error details.  There is a common
            set of message types for APIs to use.
      description: >-
        The `Status` type defines a logical error model that is suitable for
        different programming environments, including REST APIs and RPC APIs. It
        is used by [gRPC](https://github.com/grpc). Each `Status` message
        contains three pieces of data: error code, error message, and error
        details. You can find out more about this error model and how to work
        with it in the [API Design
        Guide](https://cloud.google.com/apis/design/errors).
    BareMetadata:
      type: object
      properties:
        id:
          readOnly: true
          type: string
        name:
          readOnly: true
          type: string
          description: >-
            Human-readable name of the referenced resource, populated by the
            server
             on reads for convenience. Absent on references to resources that do not
             have a name (e.g., objective tasks).
      description: |-
        BareMetadata contains the minimal metadata for a resource: the ID and an
         optional human-readable name. These are used for reference fields where the
         full metadata (account scoping, timestamps, labels, external IDs) is not
         needed — e.g., the tool references inside an agent variation spec or the
         tools assigned to an objective. Both fields are server-populated; clients
         provide IDs through sibling fields rather than by constructing a
         BareMetadata themselves.
    GoogleProtobufAny:
      type: object
      properties:
        '@type':
          type: string
          description: The type of the serialized message.
      additionalProperties: true
      description: >-
        Contains an arbitrary serialized message along with a @type that
        describes the type of the serialized message.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

````