---
name: integrate-aletheion-grounding
description: Integrate AletheionAGI's tenant-isolated Grounding API v1 into an existing AI application. Use when implementing canonical memory ingestion, one-call grounded answers through a configured BYOK reader, advanced evidence-only retrieval, namespace authorization, usage accounting, scoped server credentials, or hosted production verification.
---

# Integrate AletheionAGI Grounding

Implement AletheionAGI as the memory, retrieval and grounding boundary. Use
`POST /v1/ground` for the normal question-to-answer flow. Use `POST /v1/queries`
only when the customer's backend must operate reader inference itself. Never claim an
integration is live until hosted calls pass.

## Establish the boundary

Before editing code:

1. Locate the application's server boundary, tenant identity, trusted data sources and
   current answer path.
2. Use `https://api.aletheionagi.com` as the production base URL. Use another host only
   when the user explicitly provides a staging or development environment.
3. Determine the organization, project, environment and namespace mapping. Derive the
   first three from the API key; accept only an authorized namespace selector at runtime.
   The customer does not send `organization_id`, `project_id` or `environment_id` in
   memory or query bodies. Copy a managed `namespace_id` from the dashboard or derive a
   valid delegated `<prefix><uuid>` identifier in the trusted application backend.
4. Choose the namespace policy:
   - `managed`: select a fixed allowlist of namespaces registered in the portal;
   - `delegated`: authorize domain prefixes such as `customer:` or `journey:` and create
     valid `<prefix><uuid>` namespaces idempotently on first use;
   - `environment`: broad reviewed access to existing namespaces; do not use it for
     dynamic provisioning.
5. Store `ALETHEION_API_KEY` only in a server-side secret manager. Never expose it in a
   `NEXT_PUBLIC_*` variable, client bundle, log, exception or screenshot.
6. Configure the organization's reader in **Dashboard → Reader BYOK** before using
   `/v1/ground`. The customer owns the provider account and credential; AletheionAGI stores
   it encrypted and invokes that reader only inside the server-side grounding flow.
7. Issue the least-privilege server key: use `memory:write` for ingestion,
   `memory:read` plus `query:execute` for `/v1/ground` or `/v1/queries`, and add
   `namespace:provision` only for delegated namespaces. Add `memory:delete` and
   `usage:read` only when the application actually performs those operations.

If the base URL, API key, namespace policy or reader configuration is missing, scaffold
the boundary and report the exact gate. Do not invent values.

## Implement the server client

Create a typed server-only client with:

- bearer authentication;
- explicit timeouts and bounded retries;
- structured parsing of `error.code` and `error.correlation_id`;
- unique idempotency keys for each intended memory write;
- no write retry with a newly generated idempotency key;
- redacted logs that exclude API keys, reader credentials and memory content.

Use the project's existing HTTP library. Generate types from the approved OpenAPI v1
snapshot when available.

## Write trusted memory

Call `POST https://api.aletheionagi.com/v1/memories` only for information the customer's
system has admitted as authoritative. Never store an arbitrary user question as a fact.

Send `Authorization: Bearer <ALETHEION_API_KEY>` and an `Idempotency-Key` with 16–255
printable ASCII characters. The JSON body has six required fields:

```json
{
  "memory_id": "policy:refund:v1",
  "namespace_id": "support:550e8400-e29b-41d4-a716-446655440000",
  "occurred_at": "2026-08-13T12:00:00Z",
  "content": "Refunds are available within the approved policy window.",
  "content_type": "text/plain",
  "source_id": "policy-system:refunds"
}
```

The optional fields are:

- `authorization_labels`: an array of stable labels such as `["support", "approved"]`;
  use it when the customer's authorization policy needs an extra boundary;
- `metadata`: a free-form map of string keys to string values, such as
  `{ "version": "1" }`; do not put credentials, unverified user text or sensitive
  profiles in it.

`memory_id`, `namespace_id`, `content_type`, `source_id` and every authorization label
are customer-defined stable identifiers. They may contain letters, numbers, `.`, `_`,
`:`, `/` and `-`; they must not contain spaces. `occurred_at` must be an ISO-8601
timestamp with an explicit timezone. `content` must be a non-empty trusted string. The
contract rejects unknown JSON fields: do not silently invent custom top-level fields.

Treat `202 Accepted` with state `pending` as committed but not retrievable. Poll
`GET /v1/memories/{memory_id}` until `indexed` before depending on the new memory.
Handle `failed`, `deleted` and `revoked` explicitly.

## Return a grounded answer

For each ordinary user question, call
`POST https://api.aletheionagi.com/v1/ground` from the server:

```json
{
  "namespace_id": "customer:3d7c0d83-9642-47b0-84de-4c06408f13ac",
  "input": "What is the approved refund policy?",
  "query_id": "query:6c19d281-bb06-40ad-aaf9-432bcf95e5bf",
  "asked_at": "2026-08-13T12:05:00Z",
  "top_k": 5
}
```

`query_id`, `asked_at` and `top_k` have server defaults and may be omitted. AletheionAGI
retrieves authorized memory, invokes the configured BYOK reader, validates its claims with
the Bridge and returns:

- `grounded_answer`;
- `claims` and cited memory IDs;
- the disclosed evidence package;
- `grounding_action`: `deliver`, `block` or `abstain`;
- `grounding_reasons`.

Enforce the action:

- `deliver`: return `grounded_answer` only when it is non-null;
- `block`: do not deliver the proposed answer or silently call another reader;
- `abstain`: ask a non-factual clarification or state that the answer cannot be confirmed;
- dependency or reader failure: fail closed and expose only a safe product-level error.

Do not let a valid citation cover an unsupported claim. Do not weaken a block because a
reader sounds confident.

## Use evidence-only mode only when required

Call `POST https://api.aletheionagi.com/v1/queries` only when the customer's backend will
operate its own reader call. Send `question` rather than `input`:

```json
{
  "query_id": "query:6c19d281-bb06-40ad-aaf9-432bcf95e5bf",
  "namespace_id": "support:550e8400-e29b-41d4-a716-446655440000",
  "question": "What is the approved refund policy?",
  "asked_at": "2026-08-13T12:05:00Z",
  "top_k": 5
}
```

This endpoint returns authorized evidence, not a generated answer. Pass only the returned
eligible evidence to the customer's reader and implement equivalent claim validation and
fail-closed delivery in the customer backend. Never send a reader credential in an API
request body or expose it to the browser.

## Account for usage

Treat one finalized `accepted`, `reduced`, `rejected` or `abstained` operation as one
grounding query. An `internal_failure` reverses its reservation. The service does not
persist and replay a completed reader response: reusing a completed `query_id` returns
HTTP 409 with `idempotency_replay_unavailable` and must not create another unit. Generate
a new query ID for a new execution. Read allowance and hard-stop state from
`GET /v1/usage` and `GET /v1/usage/credits`; never calculate authoritative balance in the
browser.

## Handle failures

Branch on `error.code`, not `error.message`. Support at least:

`validation_error`, `unauthenticated`, `forbidden`, `not_found`, `conflict`,
`idempotency_conflict`, `idempotency_replay_unavailable`, `rate_limited`,
`request_timeout`, `grounding_rejected`,
`dependency_unavailable`, `internal_error`.

`conflict` from `/v1/ground` commonly means that the environment has no active BYOK reader.
Preserve `error.correlation_id` for support. Never surface stack traces, infrastructure
providers, private endpoints, credentials or memory content.

## Verify before handoff

Run unit, contract and hosted integration tests. Verify:

1. a memory write reaches `indexed`;
2. `/v1/ground` returns `deliver` and the expected grounded answer for known evidence;
3. an empty namespace produces `abstain`, not an invented answer;
4. another tenant or unauthorized namespace cannot retrieve the memory;
5. deleted or revoked evidence is not disclosed;
6. `block`, `abstain` and dependency failures cannot fall through to an ungrounded reader;
7. delegated namespaces remain inside approved prefixes;
8. retries do not double-write or double-charge;
9. browser bundles and logs contain no AletheionAGI or reader secret;
10. accepted, rejected, abstained and internal-failure accounting match the contract.

Report separately what was implemented, verified locally, verified against hosted
infrastructure and blocked by credentials or provisioning.
