# Memory

Every registered memory instance operation, with source-derived inputs, outputs, access policy, and errors.

Source: https://docs.minds.sh/docs/api/instance/memory



This reference covers **5 HTTP operations** registered by the Akasha daemon. Call these paths on your instance base URL. See [authentication](/docs/api/instance/authentication), [errors](/docs/api/instance/errors), and [coverage](/docs/api/instance/coverage) before integrating.

| Method | Path                          | Operation                                                   |
| ------ | ----------------------------- | ----------------------------------------------------------- |
| `POST` | `/v1/memory/emissions`        | [Memory emissions ingest](#post-v1-memory-emissions)        |
| `GET`  | `/v1/memory/reindex/status`   | [Memory reindex status](#get-v1-memory-reindex-status)      |
| `POST` | `/v1/memory/retrieval/hybrid` | [Memory retrieval hybrid](#post-v1-memory-retrieval-hybrid) |
| `GET`  | `/v1/memory/health`           | [Memory health](#get-v1-memory-health)                      |
| `GET`  | `/v1/memory/stats`            | [Memory stats composite](#get-v1-memory-stats)              |

<a id="post-v1-memory-emissions" />

## POST `/v1/memory/emissions` [#post-v1memoryemissions]

Nous → Akasha MIND emission receiver (FINAL\_SPEC §6.6 GAP 1). Channel authentication is the configured shared-secret bearer (`AKASHA_MIND_EMISSION_TOKEN`), verified by the receiver in constant time; the route fails closed (503) when unconfigured. Payloads are schema-validated against the `nous_mind::EmissionRecord` wire shape and landed via `AkashaDB::mind_emission_ingest`.

| Availability         | Source contract                            |
| -------------------- | ------------------------------------------ |
| Registration         | `config.enable_memory`                     |
| Runtime service      | `memory`                                   |
| Handler dependencies | See handler source and return expressions. |

**Access:** Dedicated MIND channel bearer when configured; otherwise standard daemon auth and receiver fails closed without channel configuration.

### Request [#request]

**Json** — `mind_receiver::EmissionRecordRequest`

| Field           | Rust type      | Required on input | Notes |
| --------------- | -------------- | ----------------- | ----- |
| `perception_id` | `String`       | Yes               |       |
| `ir_id`         | `String`       | Yes               |       |
| `modality`      | `ModalityDto`  | Yes               |       |
| `signer`        | `String`       | Yes               |       |
| `embedding`     | `EmbeddingDto` | Yes               |       |

```rust
struct EmissionRecordRequest {
    pub perception_id: String,
    pub ir_id: String,
    pub modality: ModalityDto,
    pub signer: String,
    pub embedding: EmbeddingDto,
}
```

### Response [#response]

**Declared return:** `Result<impl IntoResponse, DaemonError>`

The following are the exact JSON construction expressions in the handler. Values such as `rows`, `result`, and delegated types are runtime values, not literal example payloads.

```rust
serde_json::json!({
        "status": "accepted",
        "perception_id": validated.perception_hex,
        "deduplicated": outcome.deduplicated,
        "item_id": outcome.item_id.to_string(),
        "vector_id": outcome.vector_id.to_string(),
        "vector_index": outcome.vector_index,
        "episodic_id": outcome.episodic_id.map(|id| id.to_string()),
    })
```

### Errors and validation [#errors-and-validation]

Directly referenced error variants: `Forbidden`, `Internal`, `InvalidRequest`, `ServiceDisabled`, `Unauthorized`. Middleware and delegated services can return additional errors described in the shared error reference.

<Accordions>
  <Accordion title="Inspect implementation">
    This exact source excerpt includes validation, defaults, delegated calls, and response assembly.

    ```rust
    async fn memory_emissions_ingest(
        State(state): State<AppState>,
        headers: axum::http::HeaderMap,
        Extension(db): Extension<Arc<AkashaDB>>,
        Json(req): Json<mind_receiver::EmissionRecordRequest>,
    ) -> Result<impl IntoResponse, DaemonError> {
        state.record_http_request();
        state.ensure_runtime_service_enabled("memory").await?;

        mind_receiver::verify_bearer(&state.mind_receiver, &headers).map_err(|reject| {
            state.metrics.record_mind_emission("rejected_auth");
            match reject {
                mind_receiver::Reject::NotConfigured => DaemonError::ServiceDisabled(
                    "MIND emission receiver is not configured (AKASHA_MIND_EMISSION_TOKEN unset)"
                        .into(),
                ),
                mind_receiver::Reject::Unauthorized => {
                    DaemonError::Unauthorized("invalid MIND channel bearer token".into())
                }
                mind_receiver::Reject::SignerNotAllowed(signer) => {
                    DaemonError::Forbidden(format!("signer DID not allowlisted: {signer}"))
                }
                mind_receiver::Reject::Schema(reason) => DaemonError::InvalidRequest(reason),
            }
        })?;

        let validated = mind_receiver::validate(&req).map_err(|reject| {
            state.metrics.record_mind_emission("rejected_schema");
            match reject {
                mind_receiver::Reject::Schema(reason) => DaemonError::InvalidRequest(reason),
                _ => DaemonError::InvalidRequest("invalid emission record".into()),
            }
        })?;

        mind_receiver::verify_signer_allowed(&state.mind_receiver, &validated.emission.signer)
            .map_err(|reject| {
                state.metrics.record_mind_emission("rejected_auth");
                match reject {
                    mind_receiver::Reject::SignerNotAllowed(signer) => {
                        DaemonError::Forbidden(format!("signer DID not allowlisted: {signer}"))
                    }
                    _ => DaemonError::InvalidRequest("signer rejected".into()),
                }
            })?;

        state.usage_emitter.emit_cognitive_op("memory");
        let outcome = db
            .mind_emission_ingest(validated.emission)
            .await
            .map_err(|e| {
                state.metrics.record_mind_emission("error");
                DaemonError::Internal(format!("emission landing failed: {e}"))
            })?;

        state.metrics.record_mind_emission(if outcome.deduplicated {
            "deduplicated"
        } else {
            "accepted"
        });

        Ok(Json(serde_json::json!({
            "status": "accepted",
            "perception_id": validated.perception_hex,
            "deduplicated": outcome.deduplicated,
            "item_id": outcome.item_id.to_string(),
            "vector_id": outcome.vector_id.to_string(),
            "vector_index": outcome.vector_index,
            "episodic_id": outcome.episodic_id.map(|id| id.to_string()),
        })))
    }
    ```
  </Accordion>
</Accordions>

Source: `akasha-daemon/src/main.rs:7389`. Registration: `akasha-daemon/src/main.rs:4631`.

<a id="get-v1-memory-reindex-status" />

## GET `/v1/memory/reindex/status` [#get-v1memoryreindexstatus]

Memory reindex status

| Availability         | Source contract                            |
| -------------------- | ------------------------------------------ |
| Registration         | `config.enable_memory`                     |
| Runtime service      | `memory`                                   |
| Handler dependencies | See handler source and return expressions. |

**Access:** Daemon authentication and capability namespace authority; memory-domain permissions apply where mapped.

### Request [#request-1]

No typed JSON, query, or path extractor is declared in the handler signature. Headers or request objects may still be consumed; the signature below is authoritative.

### Response [#response-1]

**Declared return:** `Result<impl IntoResponse, DaemonError>`

The following are the exact JSON construction expressions in the handler. Values such as `rows`, `result`, and delegated types are runtime values, not literal example payloads.

```rust
MemoryReindexStatusResponse {
        components: db.memory_reindex_progress(),
    }
```

### Errors and validation [#errors-and-validation-1]

Directly referenced error variants: none in the handler body. Middleware and delegated services can return additional errors described in the shared error reference.

<Accordions>
  <Accordion title="Inspect implementation">
    This exact source excerpt includes validation, defaults, delegated calls, and response assembly.

    ```rust
    async fn memory_reindex_status(
        State(state): State<AppState>,
        Extension(db): Extension<Arc<AkashaDB>>,
    ) -> Result<impl IntoResponse, DaemonError> {
        state.record_http_request();
        Ok(Json(MemoryReindexStatusResponse {
            components: db.memory_reindex_progress(),
        }))
    }
    ```
  </Accordion>
</Accordions>

Source: `akasha-daemon/src/main.rs:3352`. Registration: `akasha-daemon/src/main.rs:4696`.

<a id="post-v1-memory-retrieval-hybrid" />

## POST `/v1/memory/retrieval/hybrid` [#post-v1memoryretrievalhybrid]

Memory retrieval hybrid

| Availability         | Source contract                            |
| -------------------- | ------------------------------------------ |
| Registration         | `config.enable_memory`                     |
| Runtime service      | `memory`                                   |
| Handler dependencies | See handler source and return expressions. |

**Access:** Daemon authentication and capability namespace authority; memory-domain permissions apply where mapped.

### Request [#request-2]

**Json** — `RetrievalReq`

| Field   | Rust type       | Required on input         | Notes            |
| ------- | --------------- | ------------------------- | ---------------- |
| `text`  | `String`        | Yes                       |                  |
| `limit` | `Option<usize>` | No; optional or defaulted |                  |
| `chunk` | `bool`          | No; optional or defaulted | Serde: `default` |

```rust
struct RetrievalReq {
    text: String,
    limit: Option<usize>,
    #[serde(default)]
    chunk: bool,
}
```

### Response [#response-2]

**Declared return:** `Result<impl IntoResponse, DaemonError>`

The following are the exact JSON construction expressions in the handler. Values such as `rows`, `result`, and delegated types are runtime values, not literal example payloads.

```rust
serde_json::json!({
            "rows": all_rows,
            "chunks_queried": chunks.len(),
        })
```

```rust
serde_json::json!({"rows": rows})
```

### Errors and validation [#errors-and-validation-2]

Directly referenced error variants: `InvalidRequest`. Middleware and delegated services can return additional errors described in the shared error reference.

<Accordions>
  <Accordion title="Inspect implementation">
    This exact source excerpt includes validation, defaults, delegated calls, and response assembly.

    ```rust
    async fn memory_retrieval_hybrid(
        Extension(db): Extension<Arc<AkashaDB>>,
        State(state): State<AppState>,
        Json(req): Json<RetrievalReq>,
    ) -> Result<impl IntoResponse, DaemonError> {
        state.usage_emitter.emit_cognitive_op("memory");
        if req.chunk && req.text.len() > state.chunker.config().max_chunk_size {
            let chunks = state.chunker.chunk(&req.text);
            let per_chunk_limit = req.limit.unwrap_or(10);
            let mut all_rows: Vec<serde_json::Value> = Vec::new();
            let mut seen_keys = std::collections::HashSet::new();
            for ch in &chunks {
                let rows = db
                    .memory_retrieve(&ch.text, Some(per_chunk_limit))
                    .await
                    .map_err(|e| DaemonError::InvalidRequest(e.to_string()))?;
                if let Ok(arr) = serde_json::to_value(&rows)
                    && let Some(items) = arr.as_array()
                {
                    for item in items {
                        let key = item.to_string();
                        if seen_keys.insert(key) {
                            all_rows.push(item.clone());
                        }
                    }
                }
            }
            let limit = req.limit.unwrap_or(10);
            all_rows.truncate(limit);
            Ok(Json(serde_json::json!({
                "rows": all_rows,
                "chunks_queried": chunks.len(),
            })))
        } else {
            let rows = db
                .memory_retrieve(&req.text, req.limit)
                .await
                .map_err(|e| DaemonError::InvalidRequest(e.to_string()))?;
            Ok(Json(serde_json::json!({"rows": rows})))
        }
    }
    ```
  </Accordion>
</Accordions>

Source: `akasha-daemon/src/main.rs:7854`. Registration: `akasha-daemon/src/main.rs:4697`.

<a id="get-v1-memory-health" />

## GET `/v1/memory/health` [#get-v1memoryhealth]

Memory health

| Availability         | Source contract                            |
| -------------------- | ------------------------------------------ |
| Registration         | `config.enable_memory`                     |
| Runtime service      | `memory`                                   |
| Handler dependencies | See handler source and return expressions. |

**Access:** Daemon authentication and capability namespace authority; memory-domain permissions apply where mapped.

### Request [#request-3]

No typed JSON, query, or path extractor is declared in the handler signature. Headers or request objects may still be consumed; the signature below is authoritative.

### Response [#response-3]

**Declared return:** `Result<impl IntoResponse, DaemonError>`

Serialization is delegated or the handler returns a raw response. Consult the exact handler below; the OpenAPI response intentionally remains unconstrained.

### Errors and validation [#errors-and-validation-3]

Directly referenced error variants: none in the handler body. Middleware and delegated services can return additional errors described in the shared error reference.

<Accordions>
  <Accordion title="Inspect implementation">
    This exact source excerpt includes validation, defaults, delegated calls, and response assembly.

    ```rust
    async fn memory_health(State(state): State<AppState>) -> Result<impl IntoResponse, DaemonError> {
        service_health_payload(&state, "memory").await
    }
    ```
  </Accordion>
</Accordions>

Source: `akasha-daemon/src/main.rs:10293`. Registration: `akasha-daemon/src/main.rs:4699`.

<a id="get-v1-memory-stats" />

## GET `/v1/memory/stats` [#get-v1memorystats]

Memory stats composite

| Availability         | Source contract                            |
| -------------------- | ------------------------------------------ |
| Registration         | `config.enable_memory`                     |
| Runtime service      | `memory`                                   |
| Handler dependencies | See handler source and return expressions. |

**Access:** Daemon authentication and capability namespace authority; memory-domain permissions apply where mapped.

### Request [#request-4]

No typed JSON, query, or path extractor is declared in the handler signature. Headers or request objects may still be consumed; the signature below is authoritative.

### Response [#response-4]

**Declared return:** `Result<impl IntoResponse, DaemonError>`

The following are the exact JSON construction expressions in the handler. Values such as `rows`, `result`, and delegated types are runtime values, not literal example payloads.

```rust
serde_json::json!({
        "episodicCount": episodic_count,
        "proceduralCount": procedural_count,
        "resourceCount": resource_count,
        "vaultCount": vault_count,
        "totalSizeBytes": 0,
        "oldestMemory": "",
        "newestMemory": "",
        "activeAgents": 0
    })
```

### Errors and validation [#errors-and-validation-4]

Directly referenced error variants: none in the handler body. Middleware and delegated services can return additional errors described in the shared error reference.

<Accordions>
  <Accordion title="Inspect implementation">
    This exact source excerpt includes validation, defaults, delegated calls, and response assembly.

    ```rust
    async fn memory_stats_composite(
        State(state): State<AppState>,
        Extension(db): Extension<Arc<AkashaDB>>,
    ) -> Result<impl IntoResponse, DaemonError> {
        state.record_http_request();

        // Episodic count: search with empty text
        let episodic_count = {
            let q = akasha_memory::Query::new()
                .with_text(String::new())
                .with_limit(0);
            db.episodic_search(q)
                .await
                .map(|rows| rows.len())
                .unwrap_or(0)
        };

        let procedural_count = db
            .procedure_list()
            .await
            .map(|list| list.len())
            .unwrap_or(0);

        let resource_count = db.resource_list().await.map(|list| list.len()).unwrap_or(0);

        let vault_count = db.vault_stats().await.map(|v| v.total_entries).unwrap_or(0);

        Ok(Json(serde_json::json!({
            "episodicCount": episodic_count,
            "proceduralCount": procedural_count,
            "resourceCount": resource_count,
            "vaultCount": vault_count,
            "totalSizeBytes": 0,
            "oldestMemory": "",
            "newestMemory": "",
            "activeAgents": 0
        })))
    }
    ```
  </Accordion>
</Accordions>

Source: `akasha-daemon/src/main.rs:10480`. Registration: `akasha-daemon/src/main.rs:4700`.
