Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat(client): add Memcode memory connector (#1632)

vivekgupta-memcodec663b1139d29
diff --git a/docs/latest/openlit/organisation/connectors.mdx b/docs/latest/openlit/organisation/connectors.mdx
new file mode 100644
index 00000000..479b47c6
--- /dev/null
+++ b/docs/latest/openlit/organisation/connectors.mdx
@@ -0,0 +1,186 @@
+---
+title: 'Connectors'
+sidebarTitle: 'Connectors'
+description: 'Connect OpenLIT to ClickHouse and OpenPlait-backed observability backends — atomic connectors, actions, and the roadmap for a unified connector registry'
+icon: 'plug'
+---
+
+**Connectors** are how OpenLIT attaches to data systems. Each connector is an **atomic** integration: one backend, one credential set, and a clear set of **actions** (test connection, validate AI telemetry, bind signals, manage secrets).
+
+Open the connectors experience from **Organisation → Project → Connectors** (Data sources). Always select the correct [project](/latest/openlit/organisation/projects) and [environment](/latest/openlit/organisation/environments) first — connectors belong to the project, not the organisation root.
+
+<Frame>
+ <img src="/images/organisation/connectors-list.png" alt="OpenLIT Connectors page showing configured connectors and the connector catalog" />
+</Frame>
+
+<Info>
+Connectors are the long-term integration point in OpenLIT: **data-source connectors** for telemetry, **memory connectors** for agent memory providers, with the same registry model expanding to notifications and other action types over time. Several read paths use portable [@openplait](https://github.com/openlit/openplait) adapters so query behavior stays consistent across backends.
+</Info>
+
+## Mental model
+
+```mermaid
+flowchart LR
+ subgraph org [Organisation]
+ proj[Project]
+ end
+ subgraph env [Environment]
+ bindT[traces binding]
+ bindL[logs binding]
+ bindM[metrics binding]
+ end
+ proj --> env
+ bindT --> C1[Connector A]
+ bindL --> C2[Connector B]
+ bindM --> C3[Connector C]
+ C1 --> Tempo[Tempo]
+ C2 --> Loki[Loki]
+ C3 --> Prom[Prometheus]
+```
+
+- **Atomic connectors** — never a multi-backend blob. One Tempo instance, one Loki instance, one Prometheus endpoint.
+- **Signal routing** — each of traces / logs / metrics is bound independently. See [Signal routing](/latest/openlit/organisation/signal-routing).
+- **Database Config** — ClickHouse lives as a Database Config and appears as the built-in connector. See [Database Config](/latest/openlit/organisation/database-config).
+
+## Supported connectors (OpenLIT + OpenPlait)
+
+These are the connectors available in open-source OpenLIT. OpenPlait packages power the portable query adapters for ClickHouse, Tempo, Loki, Prometheus, and Jaeger.
+
+### Built-in app store
+
+| Connector | Package / implementation | Signals | What it’s for |
+| --- | --- | --- | --- |
+| **ClickHouse** | Database Config + `@openplait/adapter-clickhouse` | traces, logs, metrics (+ intelligence) | Default store; full correlation, raw SQL, evals metadata, vault |
+
+### Data-source connectors
+
+| Connector | Package / implementation | Signals | What it’s for |
+| --- | --- | --- | --- |
+| **Grafana Tempo** | `@openplait/adapter-tempo` | traces | TraceQL search, trace tree, span events |
+| **Grafana Loki** | `@openplait/adapter-loki` | logs | LogQL logs; correlate by trace id / service |
+| **Prometheus** | `@openplait/adapter-prometheus` | metrics | PromQL HTTP API (also works with Prometheus-compatible endpoints such as Mimir when you point at their query URL) |
+| **Jaeger** | `@openplait/adapter-jaeger` | traces | Jaeger Query HTTP API; sampled in-process aggregates |
+
+<Tip>
+Prometheus-compatible APIs (for example Grafana Mimir’s PromQL endpoint) use the **Prometheus** connector — there is no separate Mimir connector type in open-source OpenLIT.
+</Tip>
+
+## Capability matrix
+
+| Connector | Signals | Trace tree | Span events | Server aggregation | Raw SQL | Cross-signal correlation |
+| --- | --- | --- | --- | --- | --- | --- |
+| ClickHouse | traces, logs, metrics | Yes | Yes | Yes | Yes | Full |
+| Tempo | traces | Yes | Yes | No* | No | trace / span / service |
+| Loki | logs | — | — | No | No | trace id, service |
+| Prometheus | metrics | — | — | Yes | No | — |
+| Jaeger | traces | Yes | Yes | No* | No | trace / span / service |
+
+\* Aggregate graphs are reconstructed in-process from a bounded sample of full traces when the backend cannot aggregate server-side.
+
+### Memory connectors
+
+Memory connectors store and search long-term agent memory. They use the same catalog, vault, and health-check actions as data-source connectors, but they are not bound to traces, logs, or metrics.
+
+| Connector | What it’s for | Auth |
+| --- | --- | --- |
+| **Mem0** | Hosted or self-hosted Mem0 memories (`add`, `search`, `get`, `list`, `update`, `delete`) | API key (`Authorization: Token …`) |
+| **Zep** | Zep Cloud or self-hosted session memory and graph search | API key (`Authorization: Api-Key …`) |
+
+To add a memory connector: open **Connectors**, choose **Mem0** or **Zep** from the catalog, set the endpoint (or keep the hosted default), paste the API key, and test the connection. Credentials are stored in Vault and never returned to the browser.
+
+## Add a Jaeger connector in OpenLIT
+
+<Frame>
+ <img src="/images/organisation/openlit-jaeger-connector.png" alt="Add source dialog with the connector type menu open, including Jaeger" />
+</Frame>
+
+1. Select a [project](/latest/openlit/organisation/projects) and environment in the header.
+2. Open **Connectors** and choose **Add connector** / **Add source**.
+3. Pick **Jaeger** from the connector type list.
+4. Set the Query URL (local all-in-one: `http://localhost:16686`) and auth if needed.
+5. Bind **traces** to the connector under [signal routing](/latest/openlit/organisation/signal-routing).
+
+<Tip>
+Local demo credentials for seeded installs: email `[email protected]`, password `openlituser`. Jaeger all-in-one + seed script live in the OpenPlait `adapter-jaeger` integration folder.
+</Tip>
+
+## Actions you can take on a connector
+
+The connector registry is designed so **actions** attach to a connector type. Today’s data-source actions:
+
+| Action | When to use it |
+| --- | --- |
+| **Add / edit connector** | Point OpenLIT at a new endpoint or rotate settings |
+| **Store credentials in Vault** | API keys and tokens stay encrypted; decrypted only server-side |
+| **Health check / test connection** | Confirm the endpoint is reachable with current auth |
+| **Validate AI signal** | Confirm recent AI telemetry exists (`gen_ai.*` / OpenLIT markers) |
+| **Bind signal** | Route traces, logs, or metrics to this connector for an environment |
+| **Unbind / rebind** | Move a signal to another connector without deleting history in the backend |
+| **Mark Database Config active** | Choose which ClickHouse app store the UI uses |
+| **Share Database Config** | Grant edit / delete / re-share on a ClickHouse connection |
+
+Enterprise audit logs record connector create/update/delete/test plus bind/unbind (with signal, environment, and previous source when switching). RBAC permissions are `connectors:read|create|update|delete|test|bind` (owner/admin by default).
+
+### Future connector categories
+
+The same registry will grow beyond datasources and memory (for example notification and workflow connectors). Each new category still follows: **atomic connector → credentials → actions → optional bindings**. Data-source connectors remain the foundation for telemetry reads.
+
+## How OpenLIT finds AI telemetry
+
+Backends hold all telemetry — not only AI. OpenLIT applies a layered **AI selector** so reads stay focused:
+
+- Resource `telemetry.sdk.name = openlit`
+- Resource `telemetry.distro.name = openlit-cli`
+- Any `gen_ai.*` attribute
+- `coding_agent.session.id`, or Claude Code session markers
+- Known `coding_agent.*` span names
+
+## Authentication cheat sheet
+
+| Backend | Typical auth |
+| --- | --- |
+| **Grafana Cloud** (Tempo / Loki) | Basic: instance ID + access policy token (`traces:read` / `logs:read`). Use **query** URLs from the Cloud Portal. |
+| **Self-hosted Tempo / Loki / Prometheus / Jaeger** | None, Basic, or Bearer; optional tenant / `X-Scope-OrgID` |
+| **Mem0** | API key as `Authorization: Token <key>` |
+| **Zep** | API key as `Authorization: Api-Key <key>` |
+| **ClickHouse** | Username / password on the Database Config |
+
+## Security and reliability
+
+- Endpoints validated (`http`/`https` only); credentials in URLs rejected; private/metadata SSRF targets blocked where applicable.
+- Secrets live in Vault, redacted from errors, never logged.
+- Per-source concurrency caps, query budgets, short-lived cache + in-flight de-dupe, and backoff on transient `429`/`5xx`.
+
+## OpenPlait packages
+
+OpenLIT wraps these npm packages for portable reads:
+
+| npm package | Used for |
+| --- | --- |
+| `@openplait/core` | Query IR and normalized results |
+| `@openplait/adapter-sdk` | Adapter contracts |
+| `@openplait/adapter-clickhouse` | ClickHouse / OTel |
+| `@openplait/adapter-tempo` | Tempo / TraceQL |
+| `@openplait/adapter-loki` | Loki / LogQL |
+| `@openplait/adapter-prometheus` | Prometheus / PromQL |
+| `@openplait/adapter-jaeger` | Jaeger Query HTTP API |
+| `@openplait/runtime` | Planning and execution helpers |
+
+See the [OpenPlait repository](https://github.com/openlit/openplait) for publishing and adapter docs.
+
+## Related
+
+<CardGroup cols={2}>
+ <Card title="Signal routing" href="/latest/openlit/organisation/signal-routing" icon="route">
+ Bind traces, logs, and metrics independently.
+ </Card>
+ <Card title="Environments" href="/latest/openlit/organisation/environments" icon="layer-group">
+ Partition configs and connectors by environment.
+ </Card>
+ <Card title="Database Config" href="/latest/openlit/organisation/database-config" icon="database">
+ Env vars → ClickHouse Database Config.
+ </Card>
+ <Card title="Projects" href="/latest/openlit/organisation/projects" icon="folder">
+ How connectors are scoped to a project.
+ </Card>
+</CardGroup>
diff --git a/src/client/public/images/connectors/memcode.png b/src/client/public/images/connectors/memcode.png
new file mode 100644
index 00000000..53b64862
Binary files /dev/null and b/src/client/public/images/connectors/memcode.png differ
diff --git a/src/client/src/__tests__/helpers/client/database-config.test.ts b/src/client/src/__tests__/helpers/client/database-config.test.ts
index 81fb8355..68aa47aa 100644
--- a/src/client/src/__tests__/helpers/client/database-config.test.ts
+++ b/src/client/src/__tests__/helpers/client/database-config.test.ts
@@ -103,6 +103,14 @@ describe('fetchDatabaseConfigList', () => {
expect(successCb).toHaveBeenCalledWith([{ id: 'db1' }]);
expect(mockSetList).toHaveBeenCalledWith([{ id: 'db1' }]);
});
+
+ it('coerces non-array payloads to an empty list', async () => {
+ (asaw as jest.Mock).mockResolvedValue([null, '<html>login</html>']);
+ const successCb = jest.fn();
+ await fetchDatabaseConfigList(successCb);
+ expect(successCb).toHaveBeenCalledWith([]);
+ expect(mockSetList).toHaveBeenCalledWith([]);
+ });
});
describe('pingActiveDatabaseConfig', () => {
diff --git a/src/client/src/__tests__/lib/platform/connectors/coverage.test.ts b/src/client/src/__tests__/lib/platform/connectors/coverage.test.ts
index 9212069c..9da63cc4 100644
--- a/src/client/src/__tests__/lib/platform/connectors/coverage.test.ts
+++ b/src/client/src/__tests__/lib/platform/connectors/coverage.test.ts
@@ -1,6 +1,9 @@
import { ensureAdaptersRegistered, __resetBootstrapForTests } from "@/lib/platform/connectors/datasource/bootstrap";
+import { ensureMemoryAdaptersRegistered, __resetMemoryBootstrapForTests } from "@/lib/platform/connectors/memory/bootstrap";
import { __resetRegistryForTests, getAdapterFactory, listSourceTypeDescriptors } from "@/lib/platform/connectors/datasource/registry";
-import { listConnectorTypes } from "@/lib/platform/connectors/registry";
+import { __resetMemoryRegistryForTests, hasMemoryAdapterFactory } from "@/lib/platform/connectors/memory/registry";
+import { __resetConnectorRegistryForTests, listConnectorTypes } from "@/lib/platform/connectors/registry";
+import { connectorIconPath } from "@/lib/platform/connectors/icons";
jest.mock("@/lib/session", () => ({ getCurrentUser: jest.fn() }));
@@ -8,6 +11,9 @@ describe("connector coverage", () => {
afterEach(() => {
__resetBootstrapForTests();
__resetRegistryForTests();
+ __resetMemoryBootstrapForTests();
+ __resetMemoryRegistryForTests();
+ __resetConnectorRegistryForTests();
});
it("exposes every atomic collector through the adapter and connector registries", () => {
@@ -27,4 +33,25 @@ describe("connector coverage", () => {
const registeredTypes = new Set(connectorTypes.map((descriptor) => descriptor.type));
for (const descriptor of descriptors) expect(registeredTypes.has(descriptor.type)).toBe(true);
});
+
+ it("exposes memory connectors through the adapter and connector registries", () => {
+ ensureMemoryAdaptersRegistered();
+ expect(hasMemoryAdapterFactory("claude")).toBe(true);
+ expect(hasMemoryAdapterFactory("mem0")).toBe(true);
+ expect(hasMemoryAdapterFactory("memcode")).toBe(true);
+ expect(hasMemoryAdapterFactory("zep")).toBe(true);
+ expect(listConnectorTypes("memory").map((item) => item.type).sort()).toEqual([
+ "claude",
+ "mem0",
+ "memcode",
+ "zep",
+ ]);
+ });
+
+ it("maps memory vendors to local brand assets", () => {
+ expect(connectorIconPath("claude")).toBe("/images/connectors/claude.svg");
+ expect(connectorIconPath("mem0")).toBe("/images/connectors/mem0.svg");
+ expect(connectorIconPath("memcode")).toBe("/images/connectors/memcode.png");
+ expect(connectorIconPath("zep")).toBe("/images/connectors/zep.svg");
+ });
});
diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-adapters.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-adapters.test.ts
index 3ad1b21e..a1993fcd 100644
--- a/src/client/src/__tests__/lib/platform/connectors/memory-adapters.test.ts
+++ b/src/client/src/__tests__/lib/platform/connectors/memory-adapters.test.ts
@@ -26,19 +26,21 @@ const mockSafeFetch = jest.fn();
import { ClaudeAdapter, claudeAdapterFactory } from "@/lib/platform/connectors/memory/claude/adapter";
import { Mem0Adapter, mem0AdapterFactory } from "@/lib/platform/connectors/memory/mem0/adapter";
+import { MemcodeAdapter, memcodeAdapterFactory } from "@/lib/platform/connectors/memory/memcode/adapter";
import { ZepAdapter, zepAdapterFactory } from "@/lib/platform/connectors/memory/zep/adapter";
import { SourceResponseError } from "@/lib/platform/connectors/datasource/http/safe-fetch";
import { resolveSourceSecret } from "@/lib/platform/connectors/datasource/http/secret";
import type { MemorySourceDescriptor } from "@/lib/platform/connectors/memory/types";
-function defaultUrl(type: "claude" | "mem0" | "zep"): string {
+function defaultUrl(type: "claude" | "mem0" | "memcode" | "zep"): string {
if (type === "claude") return "https://api.anthropic.com";
if (type === "mem0") return "https://api.mem0.ai";
+ if (type === "memcode") return "https://memory.memcode.in";
return "https://api.getzep.com";
}
function descriptor(
- type: "claude" | "mem0" | "zep",
+ type: "claude" | "mem0" | "memcode" | "zep",
settings: Record<string, unknown> = {}
): MemorySourceDescriptor {
return {
@@ -755,6 +757,606 @@ describe("Mem0 adapter", () => {
});
});
+describe("Memcode adapter", () => {
+ it("describes list with no page filters at all", () => {
+ const described = memcodeAdapterFactory.describe();
+ expect(described.type).toBe("memcode");
+ expect(described.capabilities).toEqual({
+ add: true,
+ search: true,
+ get: false,
+ list: true,
+ update: false,
+ delete: false,
+ feedback: false,
+ });
+ expect(described.configFields.map((field) => field.key)).toEqual(
+ expect.arrayContaining(["url", "apiKey"])
+ );
+ // The API key is the tenant: Memory API v2 discards a client-sent user_id
+ // in production, so offering a user control would be a lie.
+ expect(described.filterFields).toEqual([]);
+ // v2 has no get-by-id route, so a listed record is the whole record and
+ // the detail sheet must not warn about a fetch it never needed.
+ expect(described.detailFromList).toBe(true);
+ expect(described.docsUrl).toBe("https://memcode.in/docs");
+ });
+
+ it("probes liveness then GET /v2/test, never the list route", async () => {
+ mockSafeFetch
+ .mockResolvedValueOnce({ status: "ok", data: { status: "ready" } })
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: {
+ authenticated: true,
+ principal_type: "legacy_user",
+ user_id: "user-123",
+ username: "ishaan",
+ },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await expect(adapter.healthCheck()).resolves.toEqual(
+ expect.objectContaining({ ok: true })
+ );
+ const urls = mockSafeFetch.mock.calls.map((call) => String(call[0]));
+ expect(urls).toEqual([
+ "https://memory.memcode.in/health",
+ "https://memory.memcode.in/v2/test",
+ ]);
+ // A limit=1 list still materialises the whole account server-side, so it
+ // must never be the probe.
+ expect(urls.some((url) => url.includes("/v2/memory"))).toBe(false);
+ expect(mockSafeFetch.mock.calls[1][1].headers.Authorization).toBe(
+ "Bearer secret-key"
+ );
+ });
+
+ it("tells the operator when a deployment predates GET /v2/test", async () => {
+ mockSafeFetch
+ .mockResolvedValueOnce({ status: "ok", data: { status: "ready" } })
+ .mockRejectedValueOnce(new SourceResponseError(404, "Not Found"));
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await expect(adapter.healthCheck()).resolves.toEqual(
+ expect.objectContaining({
+ ok: false,
+ message: expect.stringMatching(/\/v2\/test/),
+ })
+ );
+ });
+
+ it("reports a rejected key instead of passing the connection", async () => {
+ mockSafeFetch
+ .mockResolvedValueOnce({ status: "ok", data: { status: "ready" } })
+ .mockRejectedValueOnce(new SourceResponseError(401, "invalid api key"));
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await expect(adapter.healthCheck()).resolves.toEqual(
+ expect.objectContaining({ ok: false, message: expect.stringMatching(/rejected/i) })
+ );
+ });
+
+ it("reports an out-of-credit account separately from a bad key", async () => {
+ mockSafeFetch
+ .mockResolvedValueOnce({ status: "ok", data: { status: "ready" } })
+ .mockRejectedValueOnce(new SourceResponseError(402, "insufficient credits"));
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await expect(adapter.healthCheck()).resolves.toEqual(
+ expect.objectContaining({ ok: false, message: expect.stringMatching(/credit/i) })
+ );
+ });
+
+ it("fails a base URL that is not a Memory API", async () => {
+ // A 404 is the credential probe's success answer, so without a decisive
+ // liveness check a host that 404s everything would pass.
+ mockSafeFetch.mockRejectedValue(new SourceResponseError(404, "not found"));
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await expect(adapter.healthCheck()).resolves.toEqual(
+ expect.objectContaining({
+ ok: false,
+ message: expect.stringMatching(/No MemCode Memory API/i),
+ })
+ );
+ // It never reaches the credential probe.
+ expect(mockSafeFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports a service that is up but still loading", async () => {
+ mockSafeFetch.mockResolvedValueOnce({
+ status: "ok",
+ data: { status: "loading" },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await expect(adapter.healthCheck()).resolves.toEqual(
+ expect.objectContaining({ ok: false, message: expect.stringMatching(/starting up/i) })
+ );
+ expect(mockSafeFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports a 503 from /health as still starting up", async () => {
+ mockSafeFetch.mockRejectedValue(new SourceResponseError(503, "not ready"));
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await expect(adapter.healthCheck()).resolves.toEqual(
+ expect.objectContaining({
+ ok: false,
+ message: expect.stringMatching(/starting up/i),
+ })
+ );
+ });
+
+ it("passes on the live /health envelope shape", async () => {
+ // Exactly what https://memory.memcode.in/health returns today.
+ mockSafeFetch
+ .mockResolvedValueOnce({
+ status: "ok",
+ request_id: null,
+ data: {
+ status: "ready",
+ pipelines_ready: true,
+ version: "1.0.0",
+ uptime_seconds: 1035663.1,
+ error: null,
+ },
+ error: null,
+ })
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: { authenticated: true, principal_type: "legacy_user", user_id: "u1" },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await expect(adapter.healthCheck()).resolves.toEqual(
+ expect.objectContaining({ ok: true })
+ );
+ });
+
+ it("omits user_id when no user filter is pinned", async () => {
+ mockSafeFetch.mockResolvedValue({ status: "ok", data: { memory_results: [] } });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await expect(adapter.search({ query: "berlin" })).resolves.toEqual([]);
+ expect(JSON.parse(mockSafeFetch.mock.calls[0][1].body)).not.toHaveProperty(
+ "user_id"
+ );
+ });
+
+ it("forwards a pinned user id as a narrowing filter", async () => {
+ mockSafeFetch.mockResolvedValue({ status: "ok", data: { memory_results: [] } });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await adapter.search({ query: "berlin", userId: " user_42 " });
+ expect(JSON.parse(mockSafeFetch.mock.calls[0][1].body)).toEqual(
+ expect.objectContaining({ user_id: "user_42" })
+ );
+ });
+
+ it("ingests without a user id when none is pinned", async () => {
+ mockSafeFetch
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: { job_id: "memory_ingest:1", status: "completed" },
+ })
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: { job_id: "memory_ingest:1", status: "completed" },
+ })
+ .mockResolvedValueOnce({ status: "ok", data: { memory_results: [] } });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await adapter.add({ content: "I moved to Berlin." });
+ expect(JSON.parse(mockSafeFetch.mock.calls[0][1].body)).not.toHaveProperty(
+ "user_id"
+ );
+ });
+
+ it("searches v2 memory and maps domains onto records", async () => {
+ mockSafeFetch.mockResolvedValue({
+ status: "ok",
+ data: {
+ memory_results: [
+ {
+ domain: "profile",
+ content: "The user lives in Berlin.",
+ score: 0.94,
+ metadata: { source: "conversation" },
+ },
+ ],
+ original_chunks: [
+ {
+ domain: "original",
+ content: "I moved to Berlin.",
+ score: 0.89,
+ },
+ ],
+ },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ const records = await adapter.search({ query: "where do they live", userId: "user_42" });
+ expect(records).toHaveLength(2);
+ expect(records[0]).toEqual(
+ expect.objectContaining({
+ content: "The user lives in Berlin.",
+ userId: "user_42",
+ categories: ["profile"],
+ score: 0.94,
+ })
+ );
+ expect(records[0].id).toContain("profile:");
+ const [url, options] = mockSafeFetch.mock.calls[0];
+ expect(String(url)).toBe("https://memory.memcode.in/v2/memory/search");
+ expect(JSON.parse(options.body)).toEqual(
+ expect.objectContaining({
+ query: "where do they live",
+ user_id: "user_42",
+ domains: ["profile", "temporal", "summary"],
+ })
+ );
+ });
+
+ it("lists stored memories from GET /v2/memory without user_id", async () => {
+ mockSafeFetch.mockResolvedValue({
+ status: "ok",
+ data: {
+ items: [
+ {
+ id: "mem_01K2",
+ domain: "profile",
+ content: "The user lives in Berlin.",
+ content_complete: true,
+ metadata: {},
+ created_at: "2026-08-17T09:30:04Z",
+ updated_at: "2026-08-17T09:30:04Z",
+ },
+ ],
+ total_memories: 1,
+ limit: 100,
+ offset: 0,
+ has_more: false,
+ },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ const records = await adapter.list({ limit: 10 });
+ expect(records).toEqual([
+ expect.objectContaining({
+ id: "mem_01K2",
+ content: "The user lives in Berlin.",
+ categories: ["profile"],
+ createdAt: "2026-08-17T09:30:04Z",
+ updatedAt: "2026-08-17T09:30:04Z",
+ }),
+ ]);
+ expect(mockSafeFetch).toHaveBeenCalledTimes(1);
+ const [url, options] = mockSafeFetch.mock.calls[0];
+ expect(String(url)).toBe(
+ "https://memory.memcode.in/v2/memory?limit=10&offset=0"
+ );
+ expect(options.method).toBe("GET");
+ expect(options.body).toBeUndefined();
+ });
+
+ it("pages GET /v2/memory while has_more is true", async () => {
+ mockSafeFetch
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: {
+ items: [
+ { id: "mem_1", domain: "profile", content: "Lives in Berlin." },
+ ],
+ total_memories: 2,
+ limit: 1,
+ offset: 0,
+ has_more: true,
+ },
+ })
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: {
+ items: [
+ { id: "mem_2", domain: "temporal", content: "Prefers mornings." },
+ ],
+ total_memories: 2,
+ limit: 1,
+ offset: 1,
+ has_more: false,
+ },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ const records = await adapter.list({ limit: 2 });
+ expect(records.map((record) => record.id)).toEqual(["mem_1", "mem_2"]);
+ expect(String(mockSafeFetch.mock.calls[0][0])).toBe(
+ "https://memory.memcode.in/v2/memory?limit=2&offset=0"
+ );
+ expect(String(mockSafeFetch.mock.calls[1][0])).toBe(
+ "https://memory.memcode.in/v2/memory?limit=1&offset=1"
+ );
+ });
+
+ it("pages GET /v2/memory past the 500-row page cap", async () => {
+ const page = (offset: number, size: number) => ({
+ status: "ok",
+ data: {
+ items: Array.from({ length: size }, (_, index) => ({
+ id: `mem_${offset + index}`,
+ domain: "summary",
+ content: `Memory ${offset + index}`,
+ })),
+ total_memories: 1200,
+ limit: size,
+ offset,
+ has_more: offset + size < 1200,
+ },
+ });
+ mockSafeFetch
+ .mockResolvedValueOnce(page(0, 500))
+ .mockResolvedValueOnce(page(500, 500))
+ .mockResolvedValueOnce(page(1000, 200));
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ const records = await adapter.list({ limit: 1200 });
+ expect(records).toHaveLength(1200);
+ expect(mockSafeFetch.mock.calls.map((call) => String(call[0]))).toEqual([
+ "https://memory.memcode.in/v2/memory?limit=500&offset=0",
+ "https://memory.memcode.in/v2/memory?limit=500&offset=500",
+ "https://memory.memcode.in/v2/memory?limit=200&offset=1000",
+ ]);
+ });
+
+ it("reports total_memories and has_more from one list page", async () => {
+ mockSafeFetch.mockResolvedValue({
+ status: "ok",
+ data: {
+ items: [{ id: "mem_1", domain: "profile", content: "Lives in Berlin." }],
+ total_memories: 42,
+ limit: 1,
+ offset: 10,
+ has_more: true,
+ },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ await expect(adapter.listPage({ limit: 1, offset: 10 })).resolves.toEqual({
+ records: [expect.objectContaining({ id: "mem_1" })],
+ total: 42,
+ hasMore: true,
+ nextOffset: 11,
+ });
+ expect(String(mockSafeFetch.mock.calls[0][0])).toBe(
+ "https://memory.memcode.in/v2/memory?limit=1&offset=10"
+ );
+ });
+
+ it("builds a weighted knowledge graph from GET /v2/memory-graph", async () => {
+ mockSafeFetch.mockResolvedValue({
+ status: "ok",
+ data: {
+ nodes: [
+ {
+ id: "memory_a",
+ type: "profile",
+ label: "Lives in Berlin",
+ metadata: { content: "The user lives in Berlin." },
+ },
+ {
+ id: "memory_b",
+ type: "temporal",
+ label: "Moved in May",
+ metadata: { content: "Moved to Berlin in May." },
+ },
+ ],
+ edges: [
+ {
+ source: "memory_a",
+ target: "memory_b",
+ type: "related_to",
+ domain: "profile",
+ weight: 0.91,
+ strength: 0.91,
+ },
+ // Endpoints outside the node page are dropped rather than drawn
+ // as edges into nothing.
+ { source: "memory_a", target: "memory_z", type: "related_to", weight: 0.4 },
+ ],
+ total_memories: 2,
+ domains: ["profile", "temporal"],
+ limit: 500,
+ offset: 0,
+ has_more: false,
+ has_more_edges: false,
+ },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ const graph = await adapter.graph({});
+ expect(String(mockSafeFetch.mock.calls[0][0])).toBe(
+ "https://memory.memcode.in/v2/memory-graph?limit=5000&offset=0&edge_limit=10000&edge_offset=0"
+ );
+ expect(graph.kind).toBe("knowledge");
+ expect(graph.weighted).toBe(true);
+ expect(graph.totalMemories).toBe(2);
+ expect(graph.domains).toEqual(["profile", "temporal"]);
+ expect(graph.nodes).toEqual([
+ expect.objectContaining({
+ id: "memory_a",
+ type: "memory",
+ memoryId: "memory_a",
+ kind: "profile",
+ }),
+ expect.objectContaining({
+ id: "memory_b",
+ type: "memory",
+ memoryId: "memory_b",
+ kind: "temporal",
+ }),
+ ]);
+ expect(graph.edges).toEqual([
+ {
+ from: "memory_a",
+ to: "memory_b",
+ label: "related_to",
+ domain: "profile",
+ weight: 0.91,
+ },
+ ]);
+ });
+
+ it("drains graph edges before advancing the node cursor", async () => {
+ mockSafeFetch
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: {
+ nodes: [
+ { id: "memory_a", type: "summary", label: "A" },
+ { id: "memory_b", type: "summary", label: "B" },
+ ],
+ edges: [
+ { source: "memory_a", target: "memory_b", type: "related_to", weight: 0.7 },
+ ],
+ total_memories: 4,
+ domains: ["summary"],
+ limit: 500,
+ offset: 0,
+ has_more: true,
+ edge_offset: 0,
+ has_more_edges: true,
+ },
+ })
+ // An edge-continuation page repeats the current node window, so node
+ // dedupe has to hold while only the edge cursor moves.
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: {
+ nodes: [
+ { id: "memory_a", type: "summary", label: "A" },
+ { id: "memory_b", type: "summary", label: "B" },
+ ],
+ edges: [
+ { source: "memory_b", target: "memory_a", type: "related_to", weight: 0.5 },
+ ],
+ total_memories: 4,
+ domains: ["summary"],
+ limit: 500,
+ offset: 0,
+ has_more: true,
+ edge_offset: 1,
+ has_more_edges: false,
+ },
+ })
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: {
+ nodes: [
+ { id: "memory_c", type: "summary", label: "C" },
+ { id: "memory_d", type: "summary", label: "D" },
+ ],
+ edges: [
+ { source: "memory_c", target: "memory_d", type: "related_to", weight: 0.6 },
+ ],
+ total_memories: 4,
+ domains: ["summary"],
+ limit: 500,
+ offset: 2,
+ has_more: false,
+ edge_offset: 0,
+ has_more_edges: false,
+ },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ const graph = await adapter.graph({});
+ expect(mockSafeFetch.mock.calls.map((call) => String(call[0]))).toEqual([
+ "https://memory.memcode.in/v2/memory-graph?limit=5000&offset=0&edge_limit=10000&edge_offset=0",
+ "https://memory.memcode.in/v2/memory-graph?limit=5000&offset=0&edge_limit=10000&edge_offset=1",
+ "https://memory.memcode.in/v2/memory-graph?limit=5000&offset=2&edge_limit=10000&edge_offset=0",
+ ]);
+ expect(graph.nodes.map((node) => node.id)).toEqual([
+ "memory_a",
+ "memory_b",
+ "memory_c",
+ "memory_d",
+ ]);
+ expect(graph.edges).toHaveLength(3);
+ expect(graph.truncated).toBe(false);
+ });
+
+ it("keeps connected memories when the graph is too large to lay out", async () => {
+ // An account with thousands of unconnected memories must not ship every
+ // one of them as an SVG node.
+ mockSafeFetch.mockResolvedValue({
+ status: "ok",
+ data: {
+ nodes: Array.from({ length: 900 }, (_, index) => ({
+ id: `memory_${index}`,
+ type: "summary",
+ label: `Memory ${index}`,
+ })),
+ edges: [
+ { source: "memory_800", target: "memory_801", type: "hebbian", weight: 0.9 },
+ ],
+ total_memories: 900,
+ domains: ["summary"],
+ limit: 5000,
+ offset: 0,
+ has_more: false,
+ has_more_edges: false,
+ },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ const graph = await adapter.graph({});
+ expect(graph.nodes).toHaveLength(600);
+ expect(graph.truncated).toBe(true);
+ // Both endpoints of the only connection survive the cap.
+ expect(graph.nodes.slice(0, 2).map((node) => node.id)).toEqual([
+ "memory_800",
+ "memory_801",
+ ]);
+ expect(graph.edges).toHaveLength(1);
+ });
+
+ it("ingests a turn, polls the job, then searches extracted memories", async () => {
+ mockSafeFetch
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: {
+ job_id: "memory_ingest:8d64",
+ status: "queued",
+ status_url: "/v2/memory/ingest/memory_ingest%3A8d64/status",
+ },
+ })
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: {
+ job_id: "memory_ingest:8d64",
+ status: "completed",
+ result: { classification: ["profile"] },
+ },
+ })
+ .mockResolvedValueOnce({
+ status: "ok",
+ data: {
+ memory_results: [
+ { domain: "profile", content: "The user lives in Berlin.", score: 0.9 },
+ ],
+ },
+ });
+ const adapter = new MemcodeAdapter(descriptor("memcode"));
+ const records = await adapter.add({
+ content: "I moved to Berlin and prefer morning meetings.",
+ userId: "user_42",
+ });
+ expect(records[0]).toEqual(
+ expect.objectContaining({
+ content: "The user lives in Berlin.",
+ userId: "user_42",
+ })
+ );
+ expect(String(mockSafeFetch.mock.calls[0][0])).toBe(
+ "https://memory.memcode.in/v2/memory/ingest"
+ );
+ expect(JSON.parse(mockSafeFetch.mock.calls[0][1].body)).toEqual(
+ expect.objectContaining({
+ user_query: "I moved to Berlin and prefer morning meetings.",
+ user_id: "user_42",
+ })
+ );
+ expect(String(mockSafeFetch.mock.calls[1][0])).toBe(
+ "https://memory.memcode.in/v2/memory/ingest/memory_ingest%3A8d64/status"
+ );
+ expect(mockSafeFetch.mock.calls[0][1].headers["Idempotency-Key"]).toMatch(
+ /^openlit-/
+ );
+ });
+});
+
describe("Zep adapter", () => {
it("describes graph get and session add capabilities", () => {
const described = zepAdapterFactory.describe();
diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-bootstrap.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-bootstrap.test.ts
index e3a23dab..a1a46210 100644
--- a/src/client/src/__tests__/lib/platform/connectors/memory-bootstrap.test.ts
+++ b/src/client/src/__tests__/lib/platform/connectors/memory-bootstrap.test.ts
@@ -24,15 +24,17 @@ beforeEach(() => {
});
describe("memory connector bootstrap", () => {
- it("registers Claude, Mem0, and Zep exactly once", () => {
+ it("registers Claude, Mem0, MemCode, and Zep exactly once", () => {
ensureMemoryAdaptersRegistered();
ensureMemoryAdaptersRegistered();
expect(hasMemoryAdapterFactory("claude")).toBe(true);
expect(hasMemoryAdapterFactory("mem0")).toBe(true);
+ expect(hasMemoryAdapterFactory("memcode")).toBe(true);
expect(hasMemoryAdapterFactory("zep")).toBe(true);
expect(listMemoryTypeDescriptors().map((item) => item.type).sort()).toEqual([
"claude",
"mem0",
+ "memcode",
"zep",
]);
});
@@ -61,6 +63,7 @@ describe("memory connector bootstrap", () => {
expect(listConnectorTypes("memory").map((item) => item.type).sort()).toEqual([
"claude",
"mem0",
+ "memcode",
"zep",
]);
expect(listConnectorTypes("datasource")).toHaveLength(0);
diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-graph.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-graph.test.ts
index a0198d2d..77e5fd3f 100644
--- a/src/client/src/__tests__/lib/platform/connectors/memory-graph.test.ts
+++ b/src/client/src/__tests__/lib/platform/connectors/memory-graph.test.ts
@@ -1,8 +1,13 @@
import {
+ MEMORY_CLUSTER_COLORS,
+ MEMORY_EDGE_TIER_MINIMUM,
buildMemoryGraph,
classifyEntityType,
classifyMemoryKind,
layoutMemoryGraph,
+ memoryClusterColor,
+ memoryEdgeDashPattern,
+ memoryEdgeTier,
radialEdgePoints,
summarizeMemoryStats,
type MemoryGraphModel,
@@ -428,3 +433,88 @@ describe("radialEdgePoints", () => {
);
});
});
+
+describe("memoryEdgeTier", () => {
+ it("buckets a weight into strength tiers", () => {
+ expect(memoryEdgeTier(0.95)).toBe("strong");
+ expect(memoryEdgeTier(0.81)).toBe("strong");
+ // 0.8 itself is medium: strong uses an exclusive bound.
+ expect(memoryEdgeTier(0.8)).toBe("medium");
+ expect(memoryEdgeTier(0.6)).toBe("medium");
+ expect(memoryEdgeTier(0.59)).toBe("weak");
+ expect(memoryEdgeTier(0.51)).toBe("weak");
+ expect(memoryEdgeTier(0.5)).toBe("faint");
+ expect(memoryEdgeTier(0.3)).toBe("faint");
+ });
+
+ it("treats anything below the faint floor as noise", () => {
+ expect(memoryEdgeTier(0.29)).toBeNull();
+ expect(memoryEdgeTier(0)).toBeNull();
+ });
+
+ it("returns null for an unscored edge", () => {
+ expect(memoryEdgeTier(undefined)).toBeNull();
+ expect(memoryEdgeTier(Number.NaN)).toBeNull();
+ expect(memoryEdgeTier(Number.POSITIVE_INFINITY)).toBeNull();
+ });
+
+ it("keeps only edges at or above the selected threshold", () => {
+ const weights = [0.35, 0.55, 0.62, 0.91];
+ expect(
+ weights.filter((weight) => weight >= MEMORY_EDGE_TIER_MINIMUM.strong)
+ ).toEqual([0.91]);
+ expect(
+ weights.filter((weight) => weight >= MEMORY_EDGE_TIER_MINIMUM.medium)
+ ).toEqual([0.62, 0.91]);
+ expect(
+ weights.filter((weight) => weight >= MEMORY_EDGE_TIER_MINIMUM.weak)
+ ).toEqual([0.55, 0.62, 0.91]);
+ expect(
+ weights.filter((weight) => weight >= MEMORY_EDGE_TIER_MINIMUM.faint)
+ ).toEqual(weights);
+ });
+});
+
+describe("weighted graph styling", () => {
+ it("dashes edges by tier", () => {
+ expect(memoryEdgeDashPattern("strong")).toBeUndefined();
+ expect(memoryEdgeDashPattern("medium")).toBe("7 4");
+ expect(memoryEdgeDashPattern("weak")).toBe("4 6");
+ expect(memoryEdgeDashPattern("faint")).toBe("2 6");
+ });
+
+ it("maps a domain onto a stable cluster colour", () => {
+ const profile = memoryClusterColor("profile");
+ expect(MEMORY_CLUSTER_COLORS).toContain(profile);
+ expect(memoryClusterColor("profile")).toBe(profile);
+ expect(memoryClusterColor("temporal")).not.toBe(profile);
+ // An unknown or missing domain still resolves rather than throwing.
+ expect(MEMORY_CLUSTER_COLORS).toContain(memoryClusterColor(undefined));
+ });
+
+ it("lays a weighted graph out as a golden-angle constellation", () => {
+ const model: MemoryGraphModel = {
+ kind: "knowledge",
+ weighted: true,
+ nodes: Array.from({ length: 400 }, (_, index) => ({
+ id: `memory_${index}`,
+ type: "memory" as const,
+ label: `Memory ${index}`,
+ memoryId: `memory_${index}`,
+ })),
+ edges: [],
+ };
+ const laidOut = layoutMemoryGraph(model, 800, 480);
+ expect(laidOut).toHaveLength(400);
+ expect(laidOut.every((node) => Number.isFinite(node.x) && Number.isFinite(node.y))).toBe(
+ true
+ );
+ // Phyllotaxis: distance from centre grows as sqrt(index), so later nodes
+ // sit strictly further out and nothing collapses onto one point.
+ const radius = (index: number) =>
+ Math.hypot(laidOut[index].x - 400, laidOut[index].y - 240);
+ expect(radius(0)).toBeLessThan(radius(50));
+ expect(radius(50)).toBeLessThan(radius(399));
+ expect(new Set(laidOut.map((node) => `${node.x},${node.y}`)).size).toBe(400);
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-read.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-read.test.ts
index f2e8c9a3..dafd55e4 100644
--- a/src/client/src/__tests__/lib/platform/connectors/memory-read.test.ts
+++ b/src/client/src/__tests__/lib/platform/connectors/memory-read.test.ts
@@ -484,7 +484,7 @@ describe("queryProjectMemories", () => {
});
await queryProjectMemories({ limit: 5000 });
- expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 100 }));
+ expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 500 }));
await queryProjectMemories({ limit: -3 });
expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 1 }));
@@ -493,6 +493,249 @@ describe("queryProjectMemories", () => {
expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 12 }));
});
+ it("paginates and reports a backend total when the adapter exposes listPage", async () => {
+ const listPage = jest.fn().mockResolvedValue({
+ records: [{ id: "m1", content: "Lives in Berlin", metadata: {} }],
+ total: 1200,
+ hasMore: true,
+ nextOffset: 101,
+ });
+ const list = jest.fn();
+ mockListMemoryConnectors.mockResolvedValue([connector]);
+ mockGetMemoryRuntime.mockResolvedValue({
+ connector,
+ adapter: {
+ capabilities: () => ({
+ add: true,
+ search: true,
+ get: true,
+ list: true,
+ update: true,
+ delete: true,
+ }),
+ list,
+ listPage,
+ search: jest.fn(),
+ },
+ });
+
+ const result = await queryProjectMemories({ limit: 100, offset: 100 });
+ expect(listPage).toHaveBeenCalledWith(
+ expect.objectContaining({ limit: 100, offset: 100 })
+ );
+ expect(list).not.toHaveBeenCalled();
+ expect(result.offset).toBe(100);
+ expect(result.hasMore).toBe(true);
+ expect(result.total).toBe(1200);
+ // The durable total wins over the length of this page.
+ expect(result.stats.total).toBe(1200);
+ });
+
+ it("prefers the adapter graph over the derived one, and only on the first page", async () => {
+ const graph = jest.fn().mockResolvedValue({
+ nodes: [{ id: "memory_a", type: "memory", label: "A", memoryId: "memory_a" }],
+ edges: [],
+ kind: "knowledge",
+ weighted: true,
+ });
+ mockListMemoryConnectors.mockResolvedValue([connector]);
+ mockGetMemoryRuntime.mockResolvedValue({
+ connector,
+ adapter: {
+ capabilities: () => ({
+ add: true,
+ search: true,
+ get: true,
+ list: true,
+ update: true,
+ delete: true,
+ }),
+ list: jest.fn().mockResolvedValue([]),
+ graph,
+ search: jest.fn(),
+ },
+ });
+
+ const first = await queryProjectMemories({});
+ expect(graph).toHaveBeenCalledTimes(1);
+ expect(first.graph.kind).toBe("knowledge");
+ expect(first.graph.weighted).toBe(true);
+
+ // Paging must not refetch the graph; the page keeps the one it drew.
+ const second = await queryProjectMemories({ offset: 100 });
+ expect(graph).toHaveBeenCalledTimes(1);
+ expect(second.graph).toEqual({ nodes: [], edges: [] });
+ });
+
+ it("counts connections from real graph edges, not user/session pairs", async () => {
+ mockListMemoryConnectors.mockResolvedValue([connector]);
+ mockGetMemoryRuntime.mockResolvedValue({
+ connector,
+ adapter: {
+ capabilities: () => ({
+ add: true,
+ search: true,
+ get: false,
+ list: true,
+ update: false,
+ delete: false,
+ }),
+ // No userId or sessionId on any record: the pairing count would be 0.
+ list: jest.fn().mockResolvedValue([
+ { id: "memory_a", content: "Lives in Berlin", metadata: {} },
+ { id: "memory_b", content: "Moved in May", metadata: {} },
+ ]),
+ graph: jest.fn().mockResolvedValue({
+ nodes: [
+ { id: "memory_a", type: "memory", label: "A", memoryId: "memory_a" },
+ { id: "memory_b", type: "memory", label: "B", memoryId: "memory_b" },
+ ],
+ edges: [
+ { from: "memory_a", to: "memory_b", weight: 0.9 },
+ { from: "memory_b", to: "memory_a", weight: 0.4 },
+ ],
+ kind: "knowledge",
+ weighted: true,
+ }),
+ search: jest.fn(),
+ },
+ });
+
+ const result = await queryProjectMemories({});
+ expect(result.stats.connections).toBe(2);
+ });
+
+ it("leaves the derived graph's connection count as user and session pairing", async () => {
+ mockListMemoryConnectors.mockResolvedValue([connector]);
+ mockGetMemoryRuntime.mockResolvedValue({
+ connector,
+ adapter: {
+ capabilities: () => ({
+ add: true,
+ search: true,
+ get: true,
+ list: true,
+ update: true,
+ delete: true,
+ }),
+ list: jest.fn().mockResolvedValue([
+ { id: "m1", content: "One", userId: "ada", sessionId: "s1", metadata: {} },
+ { id: "m2", content: "Two", userId: "ada", sessionId: "s2", metadata: {} },
+ ]),
+ search: jest.fn(),
+ },
+ });
+
+ const result = await queryProjectMemories({});
+ expect(result.stats.connections).toBe(2);
+ expect(result.graph.kind).toBeUndefined();
+ });
+
+ it("falls back to the derived graph when the adapter graph call fails", async () => {
+ mockListMemoryConnectors.mockResolvedValue([connector]);
+ mockGetMemoryRuntime.mockResolvedValue({
+ connector,
+ adapter: {
+ capabilities: () => ({
+ add: true,
+ search: true,
+ get: true,
+ list: true,
+ update: true,
+ delete: true,
+ }),
+ list: jest.fn().mockResolvedValue([
+ { id: "m1", content: "Lives in Berlin", userId: "ada", metadata: {} },
+ ]),
+ graph: jest.fn().mockRejectedValue(new Error("graph unavailable")),
+ search: jest.fn(),
+ },
+ });
+
+ const result = await queryProjectMemories({});
+ expect(result.memories).toHaveLength(1);
+ expect(result.graph.nodes.length).toBeGreaterThan(0);
+ expect(result.graph.kind).toBeUndefined();
+ });
+
+ it("leaves connectors without the optional ports on the derived graph and single list", async () => {
+ const list = jest.fn().mockResolvedValue([]);
+ mockListMemoryConnectors.mockResolvedValue([connector]);
+ mockGetMemoryRuntime.mockResolvedValue({
+ connector,
+ adapter: {
+ capabilities: () => ({
+ add: true,
+ search: true,
+ get: true,
+ list: true,
+ update: true,
+ delete: true,
+ }),
+ list,
+ search: jest.fn(),
+ },
+ });
+
+ const result = await queryProjectMemories({});
+ expect(list).toHaveBeenCalledTimes(1);
+ expect(result.hasMore).toBe(false);
+ expect(result.total).toBeUndefined();
+ expect(result.graph).toEqual({ nodes: [], edges: [] });
+ });
+
+ it("skips the get_unsupported notice when a listed record is the whole record", async () => {
+ mockListMemoryConnectors.mockResolvedValue([connector]);
+ mockGetMemoryTypeDescriptor.mockReturnValue({
+ type: "full-record-vendor",
+ detailFromList: true,
+ });
+ mockGetMemoryRuntime.mockResolvedValue({
+ connector,
+ adapter: {
+ capabilities: () => ({
+ add: true,
+ search: true,
+ get: false,
+ list: true,
+ update: false,
+ delete: false,
+ }),
+ get: jest.fn(),
+ list: jest.fn(),
+ search: jest.fn(),
+ },
+ });
+
+ const result = await getProjectMemory({ id: "memory_a" });
+ expect(result.memory).toBeNull();
+ expect(result.hint).toBeUndefined();
+ });
+
+ it("still warns for a vendor whose listed record is only a projection", async () => {
+ mockListMemoryConnectors.mockResolvedValue([connector]);
+ mockGetMemoryTypeDescriptor.mockReturnValue({ type: "zep" });
+ mockGetMemoryRuntime.mockResolvedValue({
+ connector,
+ adapter: {
+ capabilities: () => ({
+ add: true,
+ search: true,
+ get: false,
+ list: true,
+ update: false,
+ delete: false,
+ }),
+ get: jest.fn(),
+ list: jest.fn(),
+ search: jest.fn(),
+ },
+ });
+
+ const result = await getProjectMemory({ id: "memory_a" });
+ expect(result.hint).toBe("get_unsupported");
+ });
+
it("dedupes filter choices that appear in more than one source", async () => {
(readRememberedMemoryFilters as jest.Mock).mockResolvedValueOnce({
users: ["ada"],
diff --git a/src/client/src/app/api/memory/route.ts b/src/client/src/app/api/memory/route.ts
index 120f8b99..917573da 100644
--- a/src/client/src/app/api/memory/route.ts
+++ b/src/client/src/app/api/memory/route.ts
@@ -21,6 +21,7 @@ import {
MEMORY_INVALID_JSON,
MEMORY_INVALID_LIMIT,
MEMORY_INVALID_METADATA,
+ MEMORY_INVALID_OFFSET,
MEMORY_LOAD_FAILED,
} from "@/constants/messages/en";
@@ -37,15 +38,27 @@ function optionalFilter(value: string | null, max = FILTER_MAX): string | undefi
return trimmed;
}
+const LIMIT_MAX = 500;
+const OFFSET_MAX = 1_000_000;
+
function parseLimit(value: string | null): number | undefined {
if (value == null || !value.trim()) return undefined;
const parsed = Number(value);
- if (!Number.isFinite(parsed) || parsed < 1 || parsed > 100) {
+ if (!Number.isFinite(parsed) || parsed < 1 || parsed > LIMIT_MAX) {
throw new Error(MEMORY_INVALID_LIMIT);
}
return Math.floor(parsed);
}
+function parseOffset(value: string | null): number | undefined {
+ if (value == null || !value.trim()) return undefined;
+ const parsed = Number(value);
+ if (!Number.isFinite(parsed) || parsed < 0 || parsed > OFFSET_MAX) {
+ throw new Error(MEMORY_INVALID_OFFSET);
+ }
+ return Math.floor(parsed);
+}
+
function parseConnectorId(value: string | null | undefined): string | undefined {
if (value == null) return undefined;
const trimmed = optionalFilter(String(value), 120);
@@ -87,6 +100,7 @@ async function GETHandler(request: NextRequest) {
let sessionId: string | undefined;
let query: string | undefined;
let limit: number | undefined;
+ let offset: number | undefined;
try {
const params = request.nextUrl.searchParams;
connectorId = parseConnectorId(params.get("connectorId"));
@@ -95,6 +109,7 @@ async function GETHandler(request: NextRequest) {
sessionId = optionalFilter(params.get("sessionId"));
query = optionalFilter(params.get("q"), QUERY_MAX);
limit = parseLimit(params.get("limit"));
+ offset = parseOffset(params.get("offset"));
} catch (error) {
return errorResponse(error, MEMORY_INVALID_FILTER, 400);
}
@@ -107,6 +122,7 @@ async function GETHandler(request: NextRequest) {
sessionId,
query,
limit,
+ offset,
})
);
if (err) {
diff --git a/src/client/src/components/(playground)/memory/memory-graph.tsx b/src/client/src/components/(playground)/memory/memory-graph.tsx
index 9160337e..f6cb709e 100644
--- a/src/client/src/components/(playground)/memory/memory-graph.tsx
+++ b/src/client/src/components/(playground)/memory/memory-graph.tsx
@@ -14,13 +14,20 @@ import {
import getMessage from "@/constants/messages";
import type {
LaidOutMemoryNode,
+ MemoryEdgeTier,
MemoryEntityType,
+ MemoryGraphEdge,
MemoryGraphModel,
MemoryKind,
} from "@/lib/platform/connectors/memory/graph";
import {
+ MEMORY_EDGE_TIERS,
+ MEMORY_EDGE_TIER_MINIMUM,
MEMORY_ENTITY_TYPES,
layoutMemoryGraph,
+ memoryClusterColor,
+ memoryEdgeDashPattern,
+ memoryEdgeTier,
radialEdgePoints,
} from "@/lib/platform/connectors/memory/graph";
@@ -40,12 +47,40 @@ const ENTITY_FILL: Record<MemoryEntityType, string> = {
user: "#2dd4bf",
};
+const STRENGTH_FILTERS = ["all", "faint", "weak", "medium", "strong"] as const;
+
+type StrengthFilter = (typeof STRENGTH_FILTERS)[number];
+
+/** Scored connections: colour and dash by tier, thickness and opacity by weight. */
+const EDGE_TIER_CLASS: Record<MemoryEdgeTier, string> = {
+ strong: "stroke-blue-500",
+ medium: "stroke-stone-400 dark:stroke-stone-300",
+ weak: "stroke-rose-500",
+ faint: "stroke-rose-400",
+};
+const SELECTED_STROKE_CLASS = "stroke-stone-900 dark:stroke-stone-100";
+
+function edgeTierStroke(tier: MemoryEdgeTier, weight: number) {
+ if (tier === "strong") {
+ return { opacity: 0.48 + weight * 0.28, width: 1.45 + weight * 0.7 };
+ }
+ if (tier === "medium") {
+ return { opacity: 0.34 + weight * 0.24, width: 1.05 + weight * 0.4 };
+ }
+ // Weak connections stay legible at the fitted overview zoom; selection may
+ // emphasise them but is never required to find them.
+ return { opacity: 0.57 + weight * 0.27, width: 1.35 + weight * 0.5 };
+}
+
+const WEIGHTED_NODE_SIZE = 36;
+const OVERLAY_CLASS = "bg-white/90 dark:bg-stone-950/90";
+
const WIDTH = 840;
const HEIGHT = 520;
const MIN_SPAN = 420;
const PAD = 88;
-const MIN_ZOOM = 0.45;
-const MAX_ZOOM = 2.6;
+const MIN_ZOOM = 0.1;
+const MAX_ZOOM = 16;
type MemoryGraphProps = {
graph: MemoryGraphModel;
@@ -56,6 +91,9 @@ type MemoryGraphProps = {
export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraphProps) {
const messages = getMessage();
const knowledge = graph.kind === "knowledge";
+ // Only graphs whose edges all carry a score can be tiered; everything else
+ // keeps flat edges.
+ const weighted = graph.weighted === true;
const laidOut = useMemo(() => layoutMemoryGraph(graph, WIDTH, HEIGHT), [graph]);
const nodeById = useMemo(() => {
const map = new Map<string, LaidOutMemoryNode>();
@@ -70,6 +108,7 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
const [camera, setCamera] = useState({ x: 0, y: 0, k: 1 });
const [query, setQuery] = useState("");
const [entityFilter, setEntityFilter] = useState("all");
+ const [strengthFilter, setStrengthFilter] = useState<StrengthFilter>("all");
const drag = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null);
const svgRef = useRef<SVGSVGElement | null>(null);
const entityTypes = useMemo(() => {
@@ -84,8 +123,29 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
setCamera({ x: 0, y: 0, k: 1 });
setQuery("");
setEntityFilter("all");
+ setStrengthFilter("all");
}, [graph]);
+ // Large weighted graphs only label connected memories; labels on isolated
+ // nodes are unreadable at the fitted zoom and only cost DOM.
+ const connectedIds = useMemo(() => {
+ if (!weighted) return null;
+ const ids = new Set<string>();
+ for (const edge of graph.edges) {
+ ids.add(edge.from);
+ ids.add(edge.to);
+ }
+ return ids;
+ }, [graph.edges, weighted]);
+
+ const visibleEdges = useMemo(() => {
+ if (!weighted || strengthFilter === "all") return graph.edges;
+ const minimum = MEMORY_EDGE_TIER_MINIMUM[strengthFilter];
+ return graph.edges.filter(
+ (edge) => typeof edge.weight === "number" && edge.weight >= minimum
+ );
+ }, [graph.edges, strengthFilter, weighted]);
+
useEffect(() => {
const node = svgRef.current;
if (!node) return;
@@ -93,7 +153,7 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
event.preventDefault();
setCamera((current) => ({
...current,
- k: clampZoom(current.k * (event.deltaY > 0 ? 0.92 : 1.08)),
+ k: clampZoom(current.k * (event.deltaY > 0 ? 0.88 : 1.14)),
}));
};
node.addEventListener("wheel", onWheel, { passive: false });
@@ -172,7 +232,7 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={messages.MEMORY_GRAPH_SEARCH}
- className="h-7 w-[160px] bg-white/90 pl-7 text-xs dark:bg-stone-950/90"
+ className={`h-7 w-[160px] pl-7 text-xs ${OVERLAY_CLASS}`}
/>
</div>
{entityTypes.length > 1 ? (
@@ -193,6 +253,32 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
</SelectContent>
</Select>
) : null}
+ {weighted ? (
+ <Select
+ value={strengthFilter}
+ onValueChange={(value) => setStrengthFilter(value as StrengthFilter)}
+ >
+ <SelectTrigger
+ className={`h-7 w-[176px] text-xs ${OVERLAY_CLASS}`}
+ aria-label={messages.MEMORY_GRAPH_STRENGTH_FILTER}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {STRENGTH_FILTERS.map((tier) => (
+ <SelectItem key={tier} value={tier}>
+ {strengthLabel(tier, messages)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : null}
+ </div>
+ ) : null}
+ {weighted ? (
+ <div className="pointer-events-none absolute left-2 top-2 z-10 max-w-[55%] truncate rounded border border-stone-200 bg-white/90 px-2 py-1 text-[11px] text-stone-600 dark:border-stone-700 dark:bg-stone-900/90 dark:text-stone-300">
+ {messages.MEMORY_GRAPH_COUNTS(graph.nodes.length, visibleEdges.length)}
+ {graph.truncated ? ` · ${messages.MEMORY_GRAPH_TRUNCATED(graph.nodes.length)}` : ""}
</div>
) : null}
<svg
@@ -216,17 +302,24 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
</filter>
</defs>
<g transform={`translate(${camera.x} ${camera.y}) scale(${camera.k})`}>
- {graph.edges.map((edge, index) => {
+ {visibleEdges.map((edge, index) => {
const from = nodeById.get(edge.from);
const to = nodeById.get(edge.to);
if (!from || !to) return null;
- const selected = !!edge.memoryId && edge.memoryId === selectedId;
+ const selected = edgeTouchesSelection(edge, selectedId);
const dimmed = knowledge && (!nodeVisible(from) || !nodeVisible(to));
const points = knowledge
? `${from.x},${from.y} ${to.x},${to.y}`
: radialEdgePoints(from, to, origin)
.map((point) => `${point.x},${point.y}`)
.join(" ");
+ // A scored edge takes its tier's colour, dash and weight; an
+ // unscored one keeps the flat stroke every other connector draws.
+ const tier = weighted ? memoryEdgeTier(edge.weight) : null;
+ const stroke = tier
+ ? edgeTierStroke(tier, edge.weight ?? 0)
+ : null;
+ const target = edge.memoryId || (weighted ? edge.to : undefined);
return (
<polyline
key={`${edge.from}-${edge.to}-${index}`}
@@ -234,38 +327,58 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
points={points}
className={`cursor-pointer ${
selected
- ? "stroke-stone-900 dark:stroke-stone-100"
- : "stroke-stone-300 dark:stroke-stone-600"
+ ? SELECTED_STROKE_CLASS
+ : tier
+ ? EDGE_TIER_CLASS[tier]
+ : "stroke-stone-300 dark:stroke-stone-600"
}`}
- strokeWidth={selected ? 2.2 : 1.35}
+ strokeDasharray={tier ? memoryEdgeDashPattern(tier) : undefined}
+ strokeWidth={
+ selected ? (stroke?.width ?? 1.35) + 0.8 : stroke?.width ?? 1.35
+ }
strokeLinecap="round"
strokeLinejoin="round"
- opacity={dimmed ? 0.12 : selected ? 1 : 0.85}
+ // The constellation viewBox fits thousands of units into a few
+ // hundred pixels, so a user-unit stroke lands far below one
+ // pixel; scored edges use screen-space strokes instead.
+ vectorEffect={tier ? "non-scaling-stroke" : undefined}
+ opacity={
+ dimmed
+ ? 0.12
+ : selected
+ ? 1
+ : Math.min(1, stroke?.opacity ?? 0.85)
+ }
onPointerDown={(event) => {
- if (!edge.memoryId) return;
+ if (!target) return;
event.stopPropagation();
}}
onClick={(event) => {
event.stopPropagation();
- if (edge.memoryId) onSelect?.(edge.memoryId);
+ if (target) onSelect?.(target);
}}
>
- <title>{edge.label || from.label}</title>
+ <title>{edgeTooltip(edge, from.label, messages)}</title>
</polyline>
);
})}
{laidOut.map((node) => {
const selected =
(node.memoryId && node.memoryId === selectedId) ||
- graph.edges.some(
+ visibleEdges.some(
(edge) =>
edge.memoryId === selectedId &&
(edge.from === node.id || edge.to === node.id)
);
const visible = !knowledge || nodeVisible(node);
const fill = nodeFill(node);
- const radius =
- node.entityType === "user" || node.type === "user"
+ // Weighted-graph memories are rounded squares tinted by their
+ // domain cluster colour.
+ const cluster = weighted ? memoryClusterColor(node.domain) : null;
+ const side = WEIGHTED_NODE_SIZE;
+ const radius = cluster
+ ? side / 2
+ : node.entityType === "user" || node.type === "user"
? 13
: node.type === "memory"
? 9
@@ -296,7 +409,20 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
onSelect?.(node.memoryId);
}}
>
- {selected ? (
+ {selected && cluster ? (
+ <rect
+ x={-(side + 12) / 2}
+ y={-(side + 12) / 2}
+ width={side + 12}
+ height={side + 12}
+ rx={Math.max(3, side * 0.15)}
+ fill="none"
+ className={SELECTED_STROKE_CLASS}
+ strokeWidth={1}
+ vectorEffect="non-scaling-stroke"
+ opacity={0.58}
+ />
+ ) : selected ? (
<circle
r={radius + 7}
fill="none"
@@ -304,7 +430,23 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
strokeWidth={1.5}
/>
) : null}
- {node.type === "memory" && !knowledge ? (
+ {cluster ? (
+ <rect
+ x={-side / 2}
+ y={-side / 2}
+ width={side}
+ height={side}
+ rx={Math.max(2, side * 0.12)}
+ fill={cluster}
+ fillOpacity={0.3}
+ stroke={selected ? undefined : cluster}
+ className={selected ? SELECTED_STROKE_CLASS : undefined}
+ strokeWidth={selected ? 2.5 : 1.5}
+ vectorEffect="non-scaling-stroke"
+ >
+ <title>{node.content || node.label}</title>
+ </rect>
+ ) : node.type === "memory" && !knowledge ? (
<polygon
points={hexPoints(radius + (selected ? 1 : 0))}
fill={fill}
@@ -323,38 +465,56 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
<title>{node.label}</title>
</circle>
)}
- <text
- y={radius + 14}
- textAnchor="middle"
- className="fill-stone-600 dark:fill-stone-300"
- fontSize={9}
- >
- {truncateLabel(node.label)}
- </text>
+ {!connectedIds || connectedIds.has(node.id) || selected ? (
+ <text
+ y={radius + 14}
+ textAnchor="middle"
+ className="fill-stone-600 dark:fill-stone-300"
+ fontSize={cluster ? 10 : 9}
+ >
+ {truncateLabel(node.label)}
+ </text>
+ ) : null}
</g>
);
})}
</g>
</svg>
<div className="absolute bottom-2 left-2 flex max-w-[70%] flex-wrap items-center gap-2 rounded-md border border-stone-200 bg-white/90 px-2 py-1 text-[10px] text-stone-600 dark:border-stone-700 dark:bg-stone-900/90 dark:text-stone-300">
- <span className="uppercase tracking-wide">
- {knowledge ? messages.MEMORY_GRAPH_ENTITY_TYPES : messages.MEMORY_LEGEND}
- </span>
- {knowledge
- ? (entityTypes.length ? entityTypes : MEMORY_ENTITY_TYPES).map((type) => (
- <LegendDot
- key={type}
- color={ENTITY_FILL[type]}
- label={entityTypeLabel(type, messages)}
- />
- ))
- : (
+ {weighted ? null : (
+ <>
+ <span className="uppercase tracking-wide">
+ {entityTypes.length
+ ? messages.MEMORY_GRAPH_ENTITY_TYPES
+ : messages.MEMORY_LEGEND}
+ </span>
+ {entityTypes.length ? (
+ entityTypes.map((type) => (
+ <LegendDot
+ key={type}
+ color={ENTITY_FILL[type]}
+ label={entityTypeLabel(type, messages)}
+ />
+ ))
+ ) : (
<>
<LegendDot color={KIND_FILL.temporal} label={messages.MEMORY_TEMPORAL} />
<LegendDot color={KIND_FILL.profile} label={messages.MEMORY_PROFILE} />
<LegendDot color={KIND_FILL.summary} label={messages.MEMORY_SUMMARY} />
</>
)}
+ </>
+ )}
+ {weighted ? (
+ <>
+ <span className="uppercase tracking-wide">
+ {messages.MEMORY_GRAPH_CONNECTIONS_LEGEND}
+ </span>
+ {MEMORY_EDGE_TIERS.map((tier) => (
+ <LegendLine key={tier} tier={tier} label={tierLabel(tier, messages)} />
+ ))}
+ </>
+ ) : null}
</div>
<div className="absolute bottom-2 right-2 flex flex-col overflow-hidden rounded-md border border-stone-200 bg-white/90 dark:border-stone-700 dark:bg-stone-900/90">
<Button
@@ -362,7 +522,7 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
variant="ghost"
size="sm"
className="h-7 w-7 rounded-none p-0"
- onClick={() => zoomBy(1.15)}
+ onClick={() => zoomBy(1.4)}
title={messages.MEMORY_GRAPH_ZOOM_IN}
>
<Plus className="h-3.5 w-3.5" />
@@ -372,7 +532,7 @@ export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraph
variant="ghost"
size="sm"
className="h-7 w-7 rounded-none p-0"
- onClick={() => zoomBy(0.87)}
+ onClick={() => zoomBy(0.72)}
title={messages.MEMORY_GRAPH_ZOOM_OUT}
>
<Minus className="h-3.5 w-3.5" />
@@ -406,6 +566,51 @@ function entityTypeLabel(
return messages.MEMORY_ENTITY;
}
+function strengthLabel(
+ tier: StrengthFilter,
+ messages: ReturnType<typeof getMessage>
+): string {
+ if (tier === "strong") return messages.MEMORY_GRAPH_STRENGTH_STRONG;
+ if (tier === "medium") return messages.MEMORY_GRAPH_STRENGTH_MEDIUM;
+ if (tier === "weak") return messages.MEMORY_GRAPH_STRENGTH_WEAK;
+ if (tier === "faint") return messages.MEMORY_GRAPH_STRENGTH_FAINT;
+ return messages.MEMORY_GRAPH_STRENGTH_ALL;
+}
+
+function tierLabel(
+ tier: MemoryEdgeTier,
+ messages: ReturnType<typeof getMessage>
+): string {
+ if (tier === "strong") return messages.MEMORY_GRAPH_TIER_STRONG;
+ if (tier === "medium") return messages.MEMORY_GRAPH_TIER_MEDIUM;
+ if (tier === "weak") return messages.MEMORY_GRAPH_TIER_WEAK;
+ return messages.MEMORY_GRAPH_TIER_FAINT;
+}
+
+function edgeTouchesSelection(
+ edge: MemoryGraphEdge,
+ selectedId?: string | null
+): boolean {
+ if (!selectedId) return false;
+ if (edge.memoryId === selectedId) return true;
+ return edge.from === selectedId || edge.to === selectedId;
+}
+
+function edgeTooltip(
+ edge: MemoryGraphEdge,
+ fallback: string,
+ messages: ReturnType<typeof getMessage>
+): string {
+ const label = edge.label || edge.domain || fallback;
+ const tier = memoryEdgeTier(edge.weight);
+ if (typeof edge.weight !== "number" || !tier) return label;
+ return messages.MEMORY_GRAPH_EDGE_TOOLTIP(
+ label,
+ `${Math.round(edge.weight * 100)}%`,
+ tierLabel(tier, messages)
+ );
+}
+
function truncateLabel(label: string): string {
return label.length > 18 ? `${label.slice(0, 16).trimEnd()}…` : label;
}
@@ -417,6 +622,28 @@ function hexPoints(radius: number): string {
}).join(" ");
}
+function LegendLine({ tier, label }: { tier: MemoryEdgeTier; label: string }) {
+ const stroke = edgeTierStroke(tier, 0.6);
+ const dash = memoryEdgeDashPattern(tier);
+ return (
+ <span className="inline-flex items-center gap-1">
+ <svg width="16" height="6" aria-hidden="true" className="shrink-0">
+ <line
+ x1="0"
+ y1="3"
+ x2="16"
+ y2="3"
+ className={EDGE_TIER_CLASS[tier]}
+ strokeWidth={stroke.width}
+ strokeDasharray={dash}
+ opacity={Math.min(1, stroke.opacity)}
+ />
+ </svg>
+ {label}
+ </span>
+ );
+}
+
function LegendDot({ color, label }: { color: string; label: string }) {
return (
<span className="inline-flex items-center gap-1">
diff --git a/src/client/src/components/(playground)/memory/memory-list.tsx b/src/client/src/components/(playground)/memory/memory-list.tsx
index 523140f3..c89e05a1 100644
--- a/src/client/src/components/(playground)/memory/memory-list.tsx
+++ b/src/client/src/components/(playground)/memory/memory-list.tsx
@@ -3,6 +3,7 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { format } from "date-fns";
import { Search } from "lucide-react";
+import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Pagination,
@@ -29,6 +30,12 @@ type MemoryListProps = {
onSearchChange: (value: string) => void;
selectedId?: string | null;
onSelect: (id: string) => void;
+ /** Durable backend total, when the connector reports one. */
+ total?: number;
+ /** True when the backend holds memories past what is loaded. */
+ hasMore?: boolean;
+ loadingMore?: boolean;
+ onLoadMore?: () => void;
};
export default function MemoryList({
@@ -37,6 +44,10 @@ export default function MemoryList({
onSearchChange,
selectedId,
onSelect,
+ total,
+ hasMore,
+ loadingMore,
+ onLoadMore,
}: MemoryListProps) {
const messages = getMessage();
const selectedRef = useRef<HTMLButtonElement | null>(null);
@@ -57,6 +68,10 @@ export default function MemoryList({
(currentPage - 1) * PAGE_SIZE,
currentPage * PAGE_SIZE
);
+ const showLoaded =
+ typeof total === "number" && total > memories.length && memories.length > 0;
+ const showPages = filtered.length > PAGE_SIZE;
+ const showLoadMore = !!hasMore && !!onLoadMore;
useEffect(() => {
jumpedForId.current = null;
@@ -143,9 +158,31 @@ export default function MemoryList({
</ul>
)}
</div>
- {filtered.length > PAGE_SIZE ? (
- <div className="flex shrink-0 items-center justify-end border-t border-stone-200 px-2 py-1.5 dark:border-stone-800">
- <Pagination className="m-0 w-auto">
+ {showPages || showLoaded || showLoadMore ? (
+ <div className="flex shrink-0 items-center justify-between gap-2 border-t border-stone-200 px-2 py-1.5 dark:border-stone-800">
+ <div className="flex min-w-0 items-center gap-2">
+ {showLoaded ? (
+ <span className="truncate text-xs text-stone-500 dark:text-stone-400">
+ {messages.MEMORY_LIST_SHOWING(memories.length, total as number)}
+ </span>
+ ) : null}
+ {showLoadMore ? (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-7 shrink-0 px-2 text-xs"
+ disabled={loadingMore}
+ onClick={onLoadMore}
+ >
+ {loadingMore
+ ? messages.MEMORY_LIST_LOADING_MORE
+ : messages.MEMORY_LIST_LOAD_MORE}
+ </Button>
+ ) : null}
+ </div>
+ {showPages ? (
+ <Pagination className="m-0 w-auto shrink-0">
<PaginationContent className="gap-0.5">
<PaginationItem>
<PaginationPrevious
@@ -178,6 +215,7 @@ export default function MemoryList({
</PaginationItem>
</PaginationContent>
</Pagination>
+ ) : null}
</div>
) : null}
</section>
diff --git a/src/client/src/components/(playground)/memory/memory-page.tsx b/src/client/src/components/(playground)/memory/memory-page.tsx
index 05dc399c..05b82bfa 100644
--- a/src/client/src/components/(playground)/memory/memory-page.tsx
+++ b/src/client/src/components/(playground)/memory/memory-page.tsx
@@ -54,6 +54,12 @@ import MemoryFilterCombobox, {
} from "./memory-filter-combobox";
import AskOtterBar from "./ask-otter";
+/**
+ * One server page. Connectors that report a durable total paginate from here;
+ * the rest return everything they have in the first page, as before.
+ */
+const MEMORY_PAGE_SIZE = 100;
+
export default function MemoryPage() {
const messages = getMessage();
const posthog = usePostHog();
@@ -81,6 +87,7 @@ export default function MemoryPage() {
[]
);
const [saving, setSaving] = useState(false);
+ const [loadingMore, setLoadingMore] = useState(false);
const autoSelecting = useRef(false);
const loadSeq = useRef(0);
const pendingCreated = useRef<MemoryListItem[]>([]);
@@ -117,10 +124,25 @@ export default function MemoryPage() {
const copyTargets = connectors.filter(
(connector) => connector.id !== connectorId && connector.capabilities?.add
);
- const selectedMemory = useMemo(
- () => result?.memories.find((memory) => memory.id === selectedId) || null,
- [result?.memories, selectedId]
- );
+ const selectedMemory = useMemo(() => {
+ if (!selectedId) return null;
+ const listed = result?.memories.find((memory) => memory.id === selectedId);
+ if (listed) return listed;
+ // A connector graph can reach memories outside the loaded list page, so a
+ // node click falls back to the content the graph node carries.
+ const node = result?.graph.nodes.find(
+ (item) => item.memoryId === selectedId && item.content
+ );
+ if (!node?.content) return null;
+ return {
+ id: selectedId,
+ content: node.content,
+ kind: node.kind || "summary",
+ createdAt: node.createdAt,
+ updatedAt: node.updatedAt,
+ metadata: node.domain ? { domain: node.domain } : {},
+ } satisfies MemoryListItem;
+ }, [result?.graph.nodes, result?.memories, selectedId]);
const filters = result?.filters || emptyMemoryFilters();
const filterFields = result?.filterFields || [];
@@ -131,13 +153,14 @@ export default function MemoryPage() {
}
if (!options?.silent) setLoading(true);
setLoadError(null);
+ setLoadingMore(false);
const seq = ++loadSeq.current;
const params = new URLSearchParams();
if (connectorId) params.set("connectorId", connectorId);
if (userId.trim()) params.set("userId", userId.trim());
if (sessionId.trim()) params.set("sessionId", sessionId.trim());
if (agentId.trim()) params.set("agentId", agentId.trim());
- params.set("limit", "100");
+ params.set("limit", String(MEMORY_PAGE_SIZE));
fetch(`/api/memory?${params.toString()}`, {
headers: getRequestHeaders(),
})
@@ -218,6 +241,72 @@ export default function MemoryPage() {
userId,
]);
+ const loadMoreMemories = useCallback(() => {
+ if (loadingMore || !result?.hasMore) return;
+ setLoadingMore(true);
+ const seq = loadSeq.current;
+ const params = new URLSearchParams();
+ if (connectorId) params.set("connectorId", connectorId);
+ if (userId.trim()) params.set("userId", userId.trim());
+ if (sessionId.trim()) params.set("sessionId", sessionId.trim());
+ if (agentId.trim()) params.set("agentId", agentId.trim());
+ params.set("limit", String(MEMORY_PAGE_SIZE));
+ params.set("offset", String(result.offset + result.memories.length));
+ fetch(`/api/memory?${params.toString()}`, {
+ headers: getRequestHeaders(),
+ })
+ .then(async (response) => {
+ const body = await response.json().catch(() => null);
+ if (!response.ok) {
+ throw new Error(apiError(body, messages.MEMORY_LIST_LOAD_MORE_FAILED));
+ }
+ return body as MemoryQueryResult;
+ })
+ .then((payload) => {
+ if (seq !== loadSeq.current) return;
+ setResult((prev) => {
+ if (!prev) return prev;
+ const seen = new Set(prev.memories.map((memory) => memory.id));
+ const appended = payload.memories.filter(
+ (memory) => !seen.has(memory.id)
+ );
+ return {
+ ...prev,
+ memories: [...prev.memories, ...appended],
+ hasMore: payload.hasMore,
+ total: payload.total ?? prev.total,
+ // A later page carries no graph; keep the one already drawn.
+ stats: {
+ ...prev.stats,
+ total: payload.total ?? prev.stats.total,
+ },
+ };
+ });
+ })
+ .catch((caught: unknown) => {
+ if (seq !== loadSeq.current) return;
+ toast.error(
+ caught instanceof Error
+ ? caught.message
+ : messages.MEMORY_LIST_LOAD_MORE_FAILED
+ );
+ })
+ .finally(() => {
+ if (seq !== loadSeq.current) return;
+ setLoadingMore(false);
+ });
+ }, [
+ agentId,
+ connectorId,
+ loadingMore,
+ messages.MEMORY_LIST_LOAD_MORE_FAILED,
+ result?.hasMore,
+ result?.memories,
+ result?.offset,
+ sessionId,
+ userId,
+ ]);
+
useEffect(() => {
posthog?.capture(CLIENT_EVENTS.MEMORY_PAGE_VISITED);
}, [posthog]);
@@ -688,6 +777,10 @@ export default function MemoryPage() {
onSearchChange={setListSearch}
selectedId={selectedId}
onSelect={selectMemory}
+ total={result?.total}
+ hasMore={result?.hasMore}
+ loadingMore={loadingMore}
+ onLoadMore={loadMoreMemories}
/>
</div>
)}
diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.ts
index 4473dbb0..51d02629 100644
--- a/src/client/src/constants/messages/en.ts
+++ b/src/client/src/constants/messages/en.ts
@@ -2735,6 +2735,8 @@ export const MEMORY_CONNECTOR_CLAUDE_DESCRIPTION =
"Browse and edit memories in Anthropic Claude memory stores.";
export const MEMORY_CONNECTOR_MEM0_DESCRIPTION =
"Store and search long-term agent memories with Mem0.";
+export const MEMORY_CONNECTOR_MEMCODE_DESCRIPTION =
+ "Store and search long-term agent memories with MemCode.";
export const MEMORY_CONNECTOR_ZEP_DESCRIPTION =
"Store and search session memory and a knowledge graph with Zep.";
export const MEMORY_CONNECTOR_FIELD_ORG_ID = "Mem0 organization ID";
@@ -2744,12 +2746,26 @@ export const MEMORY_CONNECTOR_AUTH_HELP_CLAUDE =
"Use an Anthropic API key. Memory store calls send x-api-key with the agent-memory beta header.";
export const MEMORY_CONNECTOR_AUTH_HELP_MEM0 =
"Use a Mem0 Platform API key. Self-hosted Mem0 can use a custom endpoint with the same Token authentication.";
+export const MEMORY_CONNECTOR_MEMCODE_NO_TEST_ROUTE =
+ "This MemCode deployment has no GET /v2/test route. Update the Memory API to verify connections.";
+export const MEMORY_CONNECTOR_MEMCODE_NOT_FOUND =
+ "No MemCode Memory API answered at this URL. Check the connector URL.";
+export const MEMORY_CONNECTOR_MEMCODE_NOT_READY =
+ "The MemCode Memory API is reachable but still starting up. Try again shortly.";
+export const MEMORY_CONNECTOR_MEMCODE_KEY_REJECTED =
+ "The MemCode Memory API rejected this key. Check the key and try again.";
+export const MEMORY_CONNECTOR_MEMCODE_PAYMENT_REQUIRED =
+ "This MemCode key is valid but the account is out of credit.";
+export const MEMORY_CONNECTOR_AUTH_HELP_MEMCODE =
+ "Use a MemCode API key from memory.memcode.in. Calls send Authorization: Bearer.";
export const MEMORY_CONNECTOR_AUTH_HELP_ZEP =
"Use a Zep Cloud API key. Self-hosted Zep can use a custom endpoint with the same Api-Key authentication.";
export const MEMORY_CONNECTOR_SETUP_CLAUDE_SUMMARY =
"Claude memory stores keep agent notes across Managed Agents sessions.";
export const MEMORY_CONNECTOR_SETUP_MEM0_SUMMARY =
"Mem0 stores long-term memories scoped by user, run, or agent.";
+export const MEMORY_CONNECTOR_SETUP_MEMCODE_SUMMARY =
+ "MemCode stores long-term memories that agents can search later.";
export const MEMORY_CONNECTOR_SETUP_ZEP_SUMMARY =
"Zep stores session memory and a knowledge graph for agents.";
export const MEMORY_PAGE_DESCRIPTION =
@@ -2788,6 +2804,11 @@ export const MEMORY_PAGE_OF = (current: number, total: number) =>
`${current} of ${total}`;
export const MEMORY_PAGE_PREVIOUS = "Previous page";
export const MEMORY_PAGE_NEXT = "Next page";
+export const MEMORY_LIST_SHOWING = (loaded: number, total: number) =>
+ `${loaded} of ${total} loaded`;
+export const MEMORY_LIST_LOAD_MORE = "Load more";
+export const MEMORY_LIST_LOADING_MORE = "Loading…";
+export const MEMORY_LIST_LOAD_MORE_FAILED = "Failed to load more memories.";
export const MEMORY_CONNECTOR_LABEL = "Memory connector";
export const MEMORY_USER_FILTER = "User";
export const MEMORY_SESSION_FILTER = "Session";
@@ -2825,6 +2846,26 @@ export const MEMORY_GRAPH_TYPE_ALL = "All";
export const MEMORY_GRAPH_ZOOM_IN = "Zoom in";
export const MEMORY_GRAPH_ZOOM_OUT = "Zoom out";
export const MEMORY_GRAPH_TYPE_FILTER = "Entity type";
+export const MEMORY_GRAPH_STRENGTH_FILTER = "Connection strength";
+export const MEMORY_GRAPH_STRENGTH_ALL = "All connections";
+export const MEMORY_GRAPH_STRENGTH_FAINT = "Faint and above";
+export const MEMORY_GRAPH_STRENGTH_WEAK = "Weak and above";
+export const MEMORY_GRAPH_STRENGTH_MEDIUM = "Medium and above";
+export const MEMORY_GRAPH_STRENGTH_STRONG = "Strong only";
+export const MEMORY_GRAPH_TIER_STRONG = "Strong";
+export const MEMORY_GRAPH_TIER_MEDIUM = "Medium";
+export const MEMORY_GRAPH_TIER_WEAK = "Weak";
+export const MEMORY_GRAPH_TIER_FAINT = "Faint";
+export const MEMORY_GRAPH_CONNECTIONS_LEGEND = "Connections";
+export const MEMORY_GRAPH_EDGE_TOOLTIP = (
+ label: string,
+ weight: string,
+ tier: string
+) => `${label} · ${weight} (${tier})`;
+export const MEMORY_GRAPH_TRUNCATED = (shown: number) =>
+ `Showing the first ${shown} memories of this graph.`;
+export const MEMORY_GRAPH_COUNTS = (nodes: number, edges: number) =>
+ `${nodes} memories · ${edges} connections`;
export const MEMORY_ENTITY = "Entity";
export const MEMORY_EVENT = "Event";
export const MEMORY_LOCATION = "Location";
@@ -2833,7 +2874,8 @@ export const MEMORY_PREFERENCE = "Preference";
export const MEMORY_TOPIC = "Topic";
export const MEMORY_USER = "User";
export const MEMORY_INVALID_FILTER = "A memory filter value is invalid.";
-export const MEMORY_INVALID_LIMIT = "Limit must be a number between 1 and 100.";
+export const MEMORY_INVALID_LIMIT = "Limit must be a number between 1 and 500.";
+export const MEMORY_INVALID_OFFSET = "Offset must be a number between 0 and 1000000.";
export const MEMORY_INVALID_JSON = "Request body must be valid JSON.";
export const MEMORY_FEEDBACK_INVALID =
"Feedback must be positive, negative, very negative, or empty to clear.";
@@ -3004,6 +3046,11 @@ export const DATA_SOURCE_SETUP_GUIDES: Record<string, { summary: string; steps:
steps: ["Create a Mem0 Platform API key, or point the endpoint at a self-hosted Mem0 service.", "Paste the API key into the credentials field. It is stored in the OpenLIT vault.", "Optionally set organization and project IDs for a Mem0 Platform workspace, then test the connection."],
docsUrl: "https://docs.mem0.ai/api-reference",
},
+ memcode: {
+ summary: "Connect OpenLIT to MemCode for long-term agent memory.",
+ steps: ["Create a MemCode API key. The key identifies the MemCode account, so no user ID is needed.", "Paste the API key into the credentials field. It is stored in the OpenLIT vault.", "Save the connector, then test the connection before using it from the Memory page."],
+ docsUrl: "https://memcode.in/docs",
+ },
zep: {
summary: "Connect OpenLIT to Zep for session memory and graph search.",
steps: ["Create a Zep Cloud API key, or point the endpoint at a self-hosted Zep service.", "Paste the API key into the credentials field. It is stored in the OpenLIT vault.", "Save the connector, then test the connection before using it from agents."],
diff --git a/src/client/src/helpers/client/connector-analytics.ts b/src/client/src/helpers/client/connector-analytics.ts
index 051f7134..3966d86b 100644
--- a/src/client/src/helpers/client/connector-analytics.ts
+++ b/src/client/src/helpers/client/connector-analytics.ts
@@ -18,6 +18,7 @@ const CONNECTOR_DISPLAY_NAMES: Record<string, string> = {
jaeger: "Jaeger",
claude: "Claude",
mem0: "Mem0",
+ memcode: "MemCode",
zep: "Zep",
};
diff --git a/src/client/src/lib/platform/connectors/descriptions.ts b/src/client/src/lib/platform/connectors/descriptions.ts
index 1d96f187..4393cffb 100644
--- a/src/client/src/lib/platform/connectors/descriptions.ts
+++ b/src/client/src/lib/platform/connectors/descriptions.ts
@@ -6,6 +6,7 @@ const CONNECTOR_DESCRIPTIONS: Record<string, string> = {
jaeger: "Distributed traces from a Jaeger endpoint.",
claude: "Agent memory from Claude memory stores.",
mem0: "Long-term agent memory from Mem0.",
+ memcode: "Long-term agent memory from MemCode.",
zep: "Session and graph memory from Zep.",
trustabl: "Agent SDK and MCP reliability scans from Trustabl.",
};
diff --git a/src/client/src/lib/platform/connectors/icons.ts b/src/client/src/lib/platform/connectors/icons.ts
index d7c14dc8..4c105294 100644
--- a/src/client/src/lib/platform/connectors/icons.ts
+++ b/src/client/src/lib/platform/connectors/icons.ts
@@ -7,6 +7,7 @@ const CONNECTOR_ICONS: Record<string, string> = {
jaeger: "/images/connectors/jaeger.svg",
claude: "/images/connectors/claude.svg",
mem0: "/images/connectors/mem0.svg",
+ memcode: "/images/connectors/memcode.png",
zep: "/images/connectors/zep.svg",
trustabl: "/images/connectors/trustabl.svg",
};
diff --git a/src/client/src/lib/platform/connectors/memory/README.md b/src/client/src/lib/platform/connectors/memory/README.md
index 5a274ef5..66177642 100644
--- a/src/client/src/lib/platform/connectors/memory/README.md
+++ b/src/client/src/lib/platform/connectors/memory/README.md
@@ -1,7 +1,7 @@
# Memory connectors — add-a-vendor checklist
This layer is **vendor-agnostic**: OpenLIT talks to external memory providers
-(Claude, Mem0, and Zep today) through one adapter + a self-describing
+(Claude, Mem0, MemCode, and Zep today) through one adapter + a self-describing
descriptor. The
shared forms, Prisma `ConnectorInstance` rows, and the connector catalog are
driven by that descriptor, so **adding a new memory vendor must not require
@@ -30,6 +30,19 @@ editing shared forms, the schema, or any UI**.
Otter tools call `requireMemoryAccess` /
`recordMemoryMutationAudit` from `@/lib/access/memory-route` so Enterprise
RBAC and audit apply the same way as the HTTP routes.
+ Two ports are **optional** and are used only when the adapter defines them,
+ so a vendor without them keeps today's behaviour unchanged:
+ - `listPage(filter)` — one server page plus the backend's durable total and
+ `hasMore`. Implement it when the vendor reports a total, so the Memory page
+ paginates (`GET /api/memory?offset=`) and the header shows the real count
+ instead of the page length. Without it, `list(filter)` is called once.
+ - `graph(options)` — the vendor's own connection graph, returned as a
+ `MemoryGraphModel`. Implement it only when the vendor has a real graph
+ endpoint. Without it, the graph is
+ derived from list records by `buildMemoryGraph`, as before. Set
+ `edge.weight` (0-1) when the backend scores connections and the Memory page
+ will tier edges and offer a strength filter. Keep the node count within a
+ layout-safe budget: the force layout is O(nodes²).
2. **A `describe(): MemoryTypeDescriptor`** on the factory. This is the single
source of truth for the add/edit form. Set:
- `type`, `displayName`, `capabilities`
diff --git a/src/client/src/lib/platform/connectors/memory/bootstrap.ts b/src/client/src/lib/platform/connectors/memory/bootstrap.ts
index b18261e0..e1038a53 100644
--- a/src/client/src/lib/platform/connectors/memory/bootstrap.ts
+++ b/src/client/src/lib/platform/connectors/memory/bootstrap.ts
@@ -1,5 +1,5 @@
/**
- * Adapter bootstrap for CE memory connectors: Claude, Mem0, and Zep.
+ * Adapter bootstrap for CE memory connectors: Claude, Mem0, MemCode, and Zep.
* Enterprise builds may contribute additional factories through the
* neutral extension hook.
*/
@@ -7,6 +7,7 @@
import { getExternalMemoryAdapters } from "./enterprise";
import { claudeAdapterFactory } from "./claude/adapter";
import { mem0AdapterFactory } from "./mem0/adapter";
+import { memcodeAdapterFactory } from "./memcode/adapter";
import {
hasMemoryAdapterFactory,
registerMemoryAdapterFactory,
@@ -17,6 +18,7 @@ import { registerMemoryConnectorTypes } from "./index";
const VENDOR_FACTORIES = [
claudeAdapterFactory,
mem0AdapterFactory,
+ memcodeAdapterFactory,
zepAdapterFactory,
];
@@ -33,6 +35,7 @@ export function ensureMemoryAdaptersRegistered(): void {
registered &&
hasMemoryAdapterFactory("claude") &&
hasMemoryAdapterFactory("mem0") &&
+ hasMemoryAdapterFactory("memcode") &&
hasMemoryAdapterFactory("zep")
) {
return;
diff --git a/src/client/src/lib/platform/connectors/memory/enterprise.ts b/src/client/src/lib/platform/connectors/memory/enterprise.ts
index 633b9d60..32b7cd98 100644
--- a/src/client/src/lib/platform/connectors/memory/enterprise.ts
+++ b/src/client/src/lib/platform/connectors/memory/enterprise.ts
@@ -1,7 +1,7 @@
/**
* Neutral extension hook for additional memory connector adapters.
*
- * CE memory vendors (Claude, Mem0, Zep) are registered via `bootstrap.ts`. This hook
+ * CE memory vendors (Claude, Mem0, MemCode, Zep) are registered via `bootstrap.ts`. This hook
* stays empty in CE so a private fork can contribute extra factories without
* importing `@/ee/**` from shared code.
*/
diff --git a/src/client/src/lib/platform/connectors/memory/graph.ts b/src/client/src/lib/platform/connectors/memory/graph.ts
index 71c75704..1cf78d92 100644
--- a/src/client/src/lib/platform/connectors/memory/graph.ts
+++ b/src/client/src/lib/platform/connectors/memory/graph.ts
@@ -38,6 +38,16 @@ export interface MemoryGraphNode {
memoryId?: string;
kind?: MemoryKind;
entityType?: MemoryEntityType;
+ /**
+ * Set by backends whose graph reaches past the loaded list page, so a node
+ * click can open the memory even when it was never listed. Only adapters
+ * with their own graph endpoint populate these.
+ */
+ content?: string;
+ createdAt?: string;
+ updatedAt?: string;
+ /** Backend memory domain, used to colour the node by cluster. */
+ domain?: string;
}
export interface MemoryGraphEdge {
@@ -45,12 +55,87 @@ export interface MemoryGraphEdge {
to: string;
memoryId?: string;
label?: string;
+ /** Connection strength in [0,1]. Only set by backends that score edges. */
+ weight?: number;
+ /** Memory domain the connection was drawn in, when the backend reports one. */
+ domain?: string;
}
export interface MemoryGraphModel {
nodes: MemoryGraphNode[];
edges: MemoryGraphEdge[];
kind?: "knowledge" | "tree";
+ /** True when every edge carries a comparable `weight`, so the UI can tier them. */
+ weighted?: boolean;
+ /** Total memories the backend holds, when it reports more than this page. */
+ totalMemories?: number;
+ /** Memory domains present in the full graph, not just this page. */
+ domains?: string[];
+ truncated?: boolean;
+}
+
+/**
+ * Strength buckets for scored edges (`weight` in [0,1]). Anything below the
+ * faint floor is noise and is not drawn at all.
+ */
+export const MEMORY_EDGE_TIERS = ["strong", "medium", "weak", "faint"] as const;
+
+export type MemoryEdgeTier = (typeof MEMORY_EDGE_TIERS)[number];
+
+/** Inclusive floor per tier; `strong` is the one exclusive bound. */
+export const MEMORY_EDGE_TIER_MINIMUM: Record<MemoryEdgeTier, number> = {
+ strong: 0.8,
+ medium: 0.6,
+ weak: 0.51,
+ faint: 0.3,
+};
+
+/**
+ * Cluster palette for memory domains. The hash is deterministic, so a domain
+ * keeps the same colour across loads and connectors.
+ */
+export const MEMORY_CLUSTER_COLORS = [
+ "#58C7E8",
+ "#E7BC52",
+ "#74D680",
+ "#D47B75",
+ "#A789E8",
+ "#62C5A8",
+ "#74ABD8",
+ "#C78AC8",
+ "#D18A58",
+ "#8BCB6F",
+] as const;
+
+function clusterHash(value: string): number {
+ let hash = 0;
+ for (let index = 0; index < value.length; index += 1) {
+ hash = (Math.imul(31, hash) + value.charCodeAt(index)) | 0;
+ }
+ return hash >>> 0;
+}
+
+export function memoryClusterColor(domain?: string): string {
+ return MEMORY_CLUSTER_COLORS[
+ clusterHash(domain || "memory") % MEMORY_CLUSTER_COLORS.length
+ ];
+}
+
+/** Dash pattern per tier; strong edges are solid. */
+export function memoryEdgeDashPattern(tier: MemoryEdgeTier): string | undefined {
+ if (tier === "strong") return undefined;
+ if (tier === "medium") return "7 4";
+ if (tier === "weak") return "4 6";
+ return "2 6";
+}
+
+export function memoryEdgeTier(weight?: number): MemoryEdgeTier | null {
+ if (typeof weight !== "number" || !Number.isFinite(weight)) return null;
+ if (weight < MEMORY_EDGE_TIER_MINIMUM.faint) return null;
+ if (weight > MEMORY_EDGE_TIER_MINIMUM.strong) return "strong";
+ if (weight >= MEMORY_EDGE_TIER_MINIMUM.medium) return "medium";
+ if (weight >= MEMORY_EDGE_TIER_MINIMUM.weak) return "weak";
+ return "faint";
}
export interface LaidOutMemoryNode extends MemoryGraphNode {
@@ -360,6 +445,32 @@ function layoutKnowledgeGraph(
});
}
+const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
+const CONSTELLATION_SPACING = 72;
+
+/**
+ * Phyllotaxis placement for weighted graphs: memories fan out
+ * from the centre on the golden angle, so the graph reads as one constellation
+ * and stays O(nodes) instead of the O(nodes²) force pass.
+ */
+export function layoutMemoryConstellation(
+ model: MemoryGraphModel,
+ width: number,
+ height: number
+): LaidOutMemoryNode[] {
+ const cx = width / 2;
+ const cy = height / 2;
+ return model.nodes.map((node, index) => {
+ const radius = CONSTELLATION_SPACING * Math.sqrt(index + 1);
+ const angle = index * GOLDEN_ANGLE;
+ return {
+ ...node,
+ x: cx + Math.cos(angle) * radius,
+ y: cy + Math.sin(angle) * radius,
+ };
+ });
+}
+
/**
* Superopen-style radial tree: roots near the origin, children on equal
* angular slots, so memories fan out instead of collapsing into a cluster.
@@ -369,6 +480,9 @@ export function layoutMemoryGraph(
width = 800,
height = 480
): LaidOutMemoryNode[] {
+ if (model.weighted) {
+ return layoutMemoryConstellation(model, width, height);
+ }
if (model.kind === "knowledge") {
return layoutKnowledgeGraph(model, width, height);
}
diff --git a/src/client/src/lib/platform/connectors/memory/memcode/adapter.ts b/src/client/src/lib/platform/connectors/memory/memcode/adapter.ts
new file mode 100644
index 00000000..82ed257a
--- /dev/null
+++ b/src/client/src/lib/platform/connectors/memory/memcode/adapter.ts
@@ -0,0 +1,723 @@
+/**
+ * MemCode memory connector.
+ *
+ * Talks to Memory API v2 (`https://memory.memcode.in`): ingest, list, search,
+ * graph, and retrieve. Credentials stay on the connector (`enc:v1:`) and are
+ * sent as `Authorization: Bearer <apiKey>`. The API key identifies the personal
+ * user, so `user_id` is never required on a request: it is forwarded only when
+ * an operator pins one from the Memory page filters.
+ *
+ * MemCode is the only memory connector with a first-class graph endpoint, so it
+ * implements the optional `graph()` port. Every other connector still has its
+ * graph derived from list records by `buildMemoryGraph`.
+ *
+ * @see https://memcode.in/docs
+ */
+
+import getMessage from "@/constants/messages";
+import type { ConnectorHealthResult } from "../../types";
+import type { ResolvedSecret } from "../../datasource/http/secret";
+import { SourceResponseError } from "../../datasource/http/safe-fetch";
+import { BaseMemoryAdapter } from "../base-adapter";
+import { memoryHttpVendorFields, memoryPageFilters } from "../config-fields";
+import { memoryBaseUrl, memoryRequest } from "../http";
+import { classifyMemoryKind } from "../graph";
+import type {
+ MemoryGraphEdge,
+ MemoryGraphModel,
+ MemoryGraphNode,
+} from "../graph";
+import type {
+ MemoryCapabilities,
+ MemoryGraphFilter,
+ MemoryListFilter,
+ MemoryListPage,
+ MemoryMessage,
+ MemoryRecord,
+ MemorySearchQuery,
+ MemorySourceDescriptor,
+ MemoryTypeDescriptor,
+ MemoryWriteInput,
+} from "../types";
+
+const DEFAULT_URL = "https://memory.memcode.in";
+const DOCS_URL = "https://memcode.in/docs";
+const MEMCODE_DOMAINS = ["profile", "temporal", "summary"] as const;
+/** `GET /v2/memory` caps `limit` at 500, so this is the page size, not a total. */
+const LIST_PAGE_MAX = 500;
+/** Upper bound on how many memories one list call will page through. */
+const LIST_RECORD_MAX = 10_000;
+/**
+ * `GET /v2/memory-graph` caps `limit` at 5000 and `edge_limit` at 50000. The
+ * Memory page renders once rather than progressively, so it asks for the whole
+ * budget per request instead of the small pages the MemCode dashboard streams.
+ */
+const GRAPH_NODE_PAGE = 5_000;
+const GRAPH_EDGE_PAGE = 10_000;
+const GRAPH_NODE_MAX = 5_000;
+const GRAPH_EDGE_MAX = 20_000;
+const GRAPH_PAGE_LIMIT = 12;
+/**
+ * How many memories are drawn, near the dashboard's 500-node first page. Past
+ * this the squares fit the panel at roughly a pixel each and the connections
+ * stop being visible, which is the whole point of the view. Edges are still
+ * discovered across the full node budget above; a memory with no connection
+ * tells the graph nothing the list tab does not already show, so connected
+ * memories are kept first and isolated ones fill what is left.
+ */
+const GRAPH_RENDER_MAX = 600;
+const POLL_DEADLINE_MS = 8_000;
+/**
+ * Purpose-built credential check: 200 only when the key maps to an account.
+ * It reports the account's identity too, which this connector does not need.
+ */
+const CREDENTIAL_TEST_PATH = "v2/test";
+
+const MEMCODE_CAPABILITIES: MemoryCapabilities = {
+ add: true,
+ search: true,
+ get: false,
+ list: true,
+ update: false,
+ delete: false,
+ feedback: false,
+};
+
+function asRecord(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+function stringValue(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed || undefined;
+}
+
+function numberValue(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
+}
+
+function objectValue(value: unknown): Record<string, unknown> | undefined {
+ const record = asRecord(value);
+ return Object.keys(record).length ? record : undefined;
+}
+
+function stringList(value: unknown): string[] {
+ if (!Array.isArray(value)) {
+ const one = stringValue(value);
+ return one ? [one] : [];
+ }
+ return value
+ .map((item) => stringValue(item))
+ .filter((item): item is string => !!item);
+}
+
+/**
+ * MemCode resolves the personal user from the API key, so a pinned user id is
+ * an optional narrowing rather than a requirement.
+ */
+function optionalUserId(userId?: string): string | undefined {
+ return userId?.trim() || undefined;
+}
+
+function unwrap(raw: unknown): Record<string, unknown> {
+ const body = asRecord(raw);
+ if (stringValue(body.status) === "error") {
+ throw new Error(
+ stringValue(body.error) || "The MemCode request could not be completed."
+ );
+ }
+ const data = body.data;
+ if (data && typeof data === "object" && !Array.isArray(data)) {
+ return data as Record<string, unknown>;
+ }
+ return body;
+}
+
+function stableId(domain: string, content: string, index: number): string {
+ let hash = 0;
+ const key = `${domain}:${content}`;
+ for (let i = 0; i < key.length; i += 1) {
+ hash = (hash * 31 + key.charCodeAt(i)) | 0;
+ }
+ return `${domain || "memory"}:${Math.abs(hash).toString(16) || String(index)}`;
+}
+
+function normalizeRecord(
+ raw: unknown,
+ ctx: { userId?: string; index?: number } = {}
+): MemoryRecord | null {
+ const row = asRecord(raw);
+ const content =
+ stringValue(row.content) ||
+ stringValue(row.memory) ||
+ stringValue(row.answer) ||
+ stringValue(row.text) ||
+ "";
+ if (!content) return null;
+ const metadata = objectValue(row.metadata) || {};
+ const domain =
+ stringValue(row.domain) ||
+ stringValue(metadata.domain) ||
+ stringValue(metadata.category) ||
+ "summary";
+ const id =
+ stringValue(row.id) ||
+ stringValue(row.ref) ||
+ stringValue(metadata.id) ||
+ stringValue(metadata.memory_id) ||
+ stringValue(metadata.ref) ||
+ stableId(domain, content, ctx.index || 0);
+ const categories = stringList(row.categories);
+ if (domain && !categories.includes(domain)) categories.unshift(domain);
+ if (row.content_complete === false) {
+ metadata.content_complete = false;
+ }
+ return {
+ id,
+ content,
+ userId: stringValue(row.user_id) || ctx.userId,
+ metadata: {
+ ...metadata,
+ domain,
+ category: stringValue(metadata.category) || domain,
+ },
+ categories: categories.length ? categories : undefined,
+ score: numberValue(row.score) ?? numberValue(row.confidence),
+ createdAt: stringValue(row.created_at),
+ updatedAt: stringValue(row.updated_at),
+ };
+}
+
+function normalizeHits(raw: unknown, userId?: string): MemoryRecord[] {
+ const data = unwrap(raw);
+ const rows = [
+ ...(Array.isArray(data.memory_results) ? data.memory_results : []),
+ ...(Array.isArray(data.original_chunks) ? data.original_chunks : []),
+ ...(Array.isArray(data.results) ? data.results : []),
+ ...(Array.isArray(data.sources) ? data.sources : []),
+ ];
+ const records: MemoryRecord[] = [];
+ const seen = new Set<string>();
+ rows.forEach((item, index) => {
+ const record = normalizeRecord(item, { userId, index });
+ if (!record || seen.has(record.id)) return;
+ seen.add(record.id);
+ records.push(record);
+ });
+ return records;
+}
+
+function listPageItems(data: Record<string, unknown>): unknown[] {
+ if (Array.isArray(data.items)) return data.items;
+ if (Array.isArray(data.memories)) return data.memories;
+ return [];
+}
+
+function normalizeListPage(
+ raw: unknown,
+ ctx: { userId?: string; offset: number }
+): MemoryListPage {
+ const data = unwrap(raw);
+ const items = listPageItems(data);
+ const records = items
+ .map((item, index) => normalizeRecord(item, { userId: ctx.userId, index }))
+ .filter((record): record is MemoryRecord => !!record);
+ const offset = numberValue(data.offset) ?? ctx.offset;
+ const total = numberValue(data.total_memories);
+ const hasMore =
+ data.has_more === true ||
+ (total !== undefined && offset + items.length < total);
+ return { records, total, hasMore, nextOffset: offset + items.length };
+}
+
+function ingestPayload(input: MemoryWriteInput, userId?: string) {
+ const messages = input.messages || [];
+ const lastUser = [...messages]
+ .reverse()
+ .find((message) => message.role === "user" && message.content.trim());
+ const lastAssistant = [...messages]
+ .reverse()
+ .find((message) => message.role === "assistant" && message.content.trim());
+ const userQuery =
+ lastUser?.content.trim() || input.content?.trim() || messagesForWrite(messages);
+ if (!userQuery) {
+ throw new Error(getMessage().MEMORY_CONNECTOR_CONTENT_REQUIRED);
+ }
+ return {
+ user_query: userQuery.slice(0, 10_000),
+ ...(userId ? { user_id: userId } : {}),
+ ...(lastAssistant
+ ? { agent_response: lastAssistant.content.trim().slice(0, 10_000) }
+ : {}),
+ session_datetime: new Date().toISOString(),
+ };
+}
+
+function messagesForWrite(messages: MemoryMessage[]): string {
+ return messages
+ .map((message) => message.content.trim())
+ .filter(Boolean)
+ .join("\n")
+ .slice(0, 10_000);
+}
+
+/**
+ * `GET /v2/memory-graph` returns memory nodes keyed by the same public memory id
+ * the list route uses, so a node click can open the memory detail sheet. The
+ * node `type` is the memory domain; edges carry a 0-1 connection `weight`.
+ */
+function normalizeGraphNode(raw: unknown): MemoryGraphNode | null {
+ const row = asRecord(raw);
+ const id = stringValue(row.id);
+ if (!id) return null;
+ const domain = stringValue(row.type) || "summary";
+ const metadata = objectValue(row.metadata) || {};
+ const content = stringValue(metadata.content) || "";
+ const label = stringValue(row.label) || content || id;
+ return {
+ id,
+ type: "memory",
+ label: label.length > 64 ? `${label.slice(0, 61).trimEnd()}…` : label,
+ memoryId: id,
+ kind: classifyMemoryKind({
+ id,
+ content,
+ categories: [domain],
+ metadata: { domain },
+ }),
+ // MemCode has no get-by-id route and the graph spans far more memories
+ // than one list page, so the node carries what the detail sheet needs.
+ domain,
+ content: content || undefined,
+ createdAt: stringValue(metadata.created_at),
+ updatedAt: stringValue(metadata.updated_at),
+ };
+}
+
+function normalizeGraphEdge(raw: unknown): MemoryGraphEdge | null {
+ const row = asRecord(raw);
+ const from = stringValue(row.source);
+ const to = stringValue(row.target);
+ if (!from || !to || from === to) return null;
+ const weight = numberValue(row.weight) ?? numberValue(row.strength);
+ const domain = stringValue(row.domain);
+ return {
+ from,
+ to,
+ label: stringValue(row.type),
+ domain,
+ weight:
+ weight === undefined ? undefined : Math.min(1, Math.max(0, weight)),
+ };
+}
+
+function edgeKey(edge: MemoryGraphEdge): string {
+ return JSON.stringify([edge.domain || "", edge.from, edge.to, edge.label || ""]);
+}
+
+function renderableNodes(
+ nodes: Map<string, MemoryGraphNode>,
+ edges: MemoryGraphEdge[]
+): MemoryGraphNode[] {
+ if (nodes.size <= GRAPH_RENDER_MAX) return Array.from(nodes.values());
+ const connected = new Set<string>();
+ for (const edge of edges) {
+ connected.add(edge.from);
+ connected.add(edge.to);
+ }
+ const kept: MemoryGraphNode[] = [];
+ const isolated: MemoryGraphNode[] = [];
+ for (const node of Array.from(nodes.values())) {
+ if (connected.has(node.id)) kept.push(node);
+ else isolated.push(node);
+ }
+ if (kept.length >= GRAPH_RENDER_MAX) return kept.slice(0, GRAPH_RENDER_MAX);
+ return kept.concat(isolated.slice(0, GRAPH_RENDER_MAX - kept.length));
+}
+
+function clampCount(value: number | undefined, fallback: number, max: number): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
+ return Math.min(max, Math.max(1, Math.floor(value)));
+}
+
+function statusPath(jobId: string, statusUrl?: string): string {
+ const relative = stringValue(statusUrl)?.replace(/^\//, "");
+ if (relative && !/^https?:/i.test(relative)) return relative;
+ return `v2/memory/ingest/${encodeURIComponent(jobId)}/status`;
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+export class MemcodeAdapter extends BaseMemoryAdapter {
+ readonly type = "memcode";
+
+ private get baseUrl(): string {
+ return memoryBaseUrl(this.descriptor, DEFAULT_URL);
+ }
+
+ private request<T>(
+ path: string,
+ opts: {
+ method?: string;
+ body?: unknown;
+ headers?: Record<string, string>;
+ timeoutMs?: number;
+ } = {}
+ ) {
+ return memoryRequest<T>(this.descriptor, this.baseUrl, path, {
+ ...opts,
+ authHeaders: (secret: ResolvedSecret): Record<string, string> => {
+ const apiKey = secret.credentials.apiKey || secret.raw;
+ return apiKey ? { Authorization: `Bearer ${apiKey}` } : {};
+ },
+ });
+ }
+
+ capabilities(): MemoryCapabilities {
+ return { ...MEMCODE_CAPABILITIES };
+ }
+
+ /**
+ * Test connection in two cheap steps.
+ *
+ * `GET /health` proves the URL really is a Memory API and that its pipelines
+ * are up. It is unauthenticated, so it can never stand alone: with a bad key
+ * it still answers 200.
+ * `GET /v2/test` then checks the credential itself: it answers 200 only when
+ * the key maps to a live account, and 401/403 otherwise. Listing is not used
+ * as a probe — a `limit=1` list still materialises every memory in the
+ * account server-side before it slices the page.
+ */
+ async healthCheck(): Promise<ConnectorHealthResult> {
+ const started = Date.now();
+ const latencyMs = () => Date.now() - started;
+ const messages = getMessage();
+
+ // Decisive: /health ships with every deployment of the Memory API, so a
+ // URL that cannot answer it is not a Memory API. Without this the
+ // credential probe below would read any host's blanket 404 as success.
+ try {
+ const health = unwrap(await this.request("health", { timeoutMs: 10_000 }));
+ const state = stringValue(health.status);
+ if (health.pipelines_ready !== true && state !== "ready") {
+ return {
+ ok: false,
+ latencyMs: latencyMs(),
+ message: state
+ ? messages.MEMORY_CONNECTOR_MEMCODE_NOT_READY
+ : messages.MEMORY_CONNECTOR_MEMCODE_NOT_FOUND,
+ };
+ }
+ } catch (error) {
+ const status = error instanceof SourceResponseError ? error.status : undefined;
+ return {
+ ok: false,
+ latencyMs: latencyMs(),
+ message:
+ status === 503
+ ? messages.MEMORY_CONNECTOR_MEMCODE_NOT_READY
+ : status === 404
+ ? messages.MEMORY_CONNECTOR_MEMCODE_NOT_FOUND
+ : String((error as Error)?.message || error),
+ };
+ }
+
+ try {
+ await this.request(CREDENTIAL_TEST_PATH, { timeoutMs: 10_000 });
+ return { ok: true, latencyMs: latencyMs() };
+ } catch (error) {
+ const status = error instanceof SourceResponseError ? error.status : undefined;
+ // 429 means the credential was accepted and then throttled.
+ if (status === 429) {
+ return { ok: true, latencyMs: latencyMs() };
+ }
+ // /health already proved this is a Memory API, so a 404 here means the
+ // deployment predates the credential-test route rather than a bad URL.
+ if (status === 404) {
+ return {
+ ok: false,
+ latencyMs: latencyMs(),
+ message: messages.MEMORY_CONNECTOR_MEMCODE_NO_TEST_ROUTE,
+ };
+ }
+ if (status === 401 || status === 403) {
+ return {
+ ok: false,
+ latencyMs: latencyMs(),
+ message: messages.MEMORY_CONNECTOR_MEMCODE_KEY_REJECTED,
+ };
+ }
+ if (status === 402) {
+ return {
+ ok: false,
+ latencyMs: latencyMs(),
+ message: messages.MEMORY_CONNECTOR_MEMCODE_PAYMENT_REQUIRED,
+ };
+ }
+ return {
+ ok: false,
+ latencyMs: latencyMs(),
+ message: String((error as Error)?.message || error),
+ };
+ }
+ }
+
+ async add(input: MemoryWriteInput): Promise<MemoryRecord[]> {
+ const userId = optionalUserId(input.userId);
+ const payload = ingestPayload(input, userId);
+ const ingested = unwrap(
+ await this.request("v2/memory/ingest", {
+ method: "POST",
+ body: payload,
+ headers: {
+ "Idempotency-Key": `openlit-${this.descriptor.id}-${Date.now()}`,
+ },
+ })
+ );
+ const jobId =
+ stringValue(ingested.job_id) ||
+ stringValue(ingested.request_id) ||
+ `memory_ingest:${Date.now()}`;
+ const job = await this.pollIngest(jobId, stringValue(ingested.status_url));
+ const jobStatus = stringValue(job.status) || stringValue(ingested.status) || "queued";
+ if (jobStatus === "failed" || jobStatus === "cancelled") {
+ throw new Error(
+ stringValue(job.error) || `MemCode ingest ${jobStatus}.`
+ );
+ }
+ if (jobStatus === "completed") {
+ try {
+ const hits = await this.search({
+ query: payload.user_query.slice(0, 5_000),
+ userId,
+ limit: 8,
+ });
+ if (hits.length) return hits;
+ } catch {
+ // Fall through to the ingest receipt when search is not ready yet.
+ }
+ }
+ const result = asRecord(job.result);
+ const categories = stringList(result.classification);
+ return [
+ {
+ id: jobId,
+ content: payload.user_query,
+ userId,
+ input: input.messages,
+ categories: categories.length ? categories : undefined,
+ metadata: {
+ ...(input.metadata || {}),
+ category: categories[0] || "summary",
+ domain: categories[0],
+ jobId,
+ jobStatus,
+ },
+ lifecycleState: jobStatus,
+ createdAt: stringValue(job.created_at) || stringValue(job.completed_at),
+ },
+ ];
+ }
+
+ async search(query: MemorySearchQuery): Promise<MemoryRecord[]> {
+ const q = query.query.trim();
+ if (!q) throw new Error(getMessage().MEMORY_CONNECTOR_QUERY_REQUIRED);
+ return this.searchMemories({
+ query: q,
+ userId: optionalUserId(query.userId),
+ limit: query.limit || 10,
+ domains: [...MEMCODE_DOMAINS],
+ });
+ }
+
+ /**
+ * One server page, so callers can paginate with a durable `total_memories`
+ * instead of re-reading from offset 0.
+ */
+ async listPage(filter: MemoryListFilter): Promise<MemoryListPage> {
+ const offset = Math.max(0, Math.floor(filter.offset || 0));
+ const params = new URLSearchParams({
+ limit: String(clampCount(filter.limit, 100, LIST_PAGE_MAX)),
+ offset: String(offset),
+ });
+ return normalizeListPage(
+ await this.request(`v2/memory?${params.toString()}`),
+ { userId: optionalUserId(filter.userId), offset }
+ );
+ }
+
+ async list(filter: MemoryListFilter): Promise<MemoryRecord[]> {
+ const wanted = clampCount(filter.limit, 100, LIST_RECORD_MAX);
+ const records: MemoryRecord[] = [];
+ let offset = Math.max(0, Math.floor(filter.offset || 0));
+ while (records.length < wanted) {
+ const page = await this.listPage({
+ ...filter,
+ limit: Math.min(wanted - records.length, LIST_PAGE_MAX),
+ offset,
+ });
+ records.push(...page.records);
+ if (!page.hasMore || page.records.length === 0) break;
+ if (page.nextOffset <= offset) break;
+ offset = page.nextOffset;
+ }
+ return records.slice(0, wanted);
+ }
+
+ /**
+ * Page `GET /v2/memory-graph` into the shared graph model. The API exhausts
+ * the edges incident to the current node page before advancing the node
+ * cursor, so both cursors are followed the way the MemCode dashboard does.
+ */
+ async graph(options: MemoryGraphFilter = {}): Promise<MemoryGraphModel> {
+ const maxNodes = clampCount(options.maxNodes, GRAPH_NODE_MAX, GRAPH_NODE_MAX);
+ const maxEdges = clampCount(options.maxEdges, GRAPH_EDGE_MAX, GRAPH_EDGE_MAX);
+ const nodes = new Map<string, MemoryGraphNode>();
+ const edges = new Map<string, MemoryGraphEdge>();
+ const domains = new Set<string>();
+ let totalMemories = 0;
+ let offset = 0;
+ let edgeOffset = 0;
+ let truncated = false;
+ // Page sizes stay fixed: the node window must not change while its edge
+ // cursor is being drained, or the next page describes a different window.
+ const nodePage = Math.min(GRAPH_NODE_PAGE, maxNodes);
+ const edgePage = Math.min(GRAPH_EDGE_PAGE, maxEdges);
+
+ for (let page = 0; page < GRAPH_PAGE_LIMIT; page += 1) {
+ const params = new URLSearchParams({
+ limit: String(nodePage),
+ offset: String(offset),
+ edge_limit: String(edgePage),
+ edge_offset: String(edgeOffset),
+ });
+ const data = unwrap(await this.request(`v2/memory-graph?${params.toString()}`));
+ const pageNodes = Array.isArray(data.nodes) ? data.nodes : [];
+ const pageEdges = Array.isArray(data.edges) ? data.edges : [];
+ for (const raw of pageNodes) {
+ const node = normalizeGraphNode(raw);
+ if (node && !nodes.has(node.id)) nodes.set(node.id, node);
+ }
+ for (const raw of pageEdges) {
+ const edge = normalizeGraphEdge(raw);
+ if (edge) edges.set(edgeKey(edge), edge);
+ }
+ for (const domain of stringList(data.domains)) domains.add(domain);
+ totalMemories = Math.max(
+ totalMemories,
+ numberValue(data.total_memories) ?? 0,
+ nodes.size
+ );
+
+ if (nodes.size >= maxNodes || edges.size >= maxEdges) {
+ truncated = data.has_more === true || data.has_more_edges === true;
+ break;
+ }
+ // Edges first: the node cursor only advances once this page's edges
+ // are drained, matching the API's pagination contract.
+ if (data.has_more_edges === true && pageEdges.length > 0) {
+ edgeOffset = (numberValue(data.edge_offset) ?? edgeOffset) + pageEdges.length;
+ continue;
+ }
+ if (data.has_more === true && pageNodes.length > 0) {
+ offset = (numberValue(data.offset) ?? offset) + pageNodes.length;
+ edgeOffset = 0;
+ continue;
+ }
+ truncated = data.has_more === true || data.has_more_edges === true;
+ break;
+ }
+
+ // An edge may name an endpoint delivered on a page we never asked for;
+ // drop it rather than draw a connection into nothing.
+ const edgeList = Array.from(edges.values()).filter(
+ (edge) => nodes.has(edge.from) && nodes.has(edge.to)
+ );
+ const rendered = renderableNodes(nodes, edgeList);
+ const renderedIds = new Set(rendered.map((node) => node.id));
+ const renderedEdges =
+ rendered.length === nodes.size
+ ? edgeList
+ : edgeList.filter(
+ (edge) => renderedIds.has(edge.from) && renderedIds.has(edge.to)
+ );
+ return {
+ nodes: rendered,
+ edges: renderedEdges,
+ kind: "knowledge",
+ weighted:
+ renderedEdges.length > 0 &&
+ renderedEdges.every((edge) => edge.weight !== undefined),
+ totalMemories,
+ domains: Array.from(domains).sort(),
+ truncated: truncated || rendered.length < nodes.size,
+ };
+ }
+
+ private async searchMemories(input: {
+ query: string;
+ userId?: string;
+ limit: number;
+ domains?: string[];
+ }): Promise<MemoryRecord[]> {
+ const body = await this.request("v2/memory/search", {
+ method: "POST",
+ body: {
+ query: input.query.slice(0, 5_000),
+ ...(input.userId ? { user_id: input.userId } : {}),
+ domains: input.domains?.length ? input.domains : [...MEMCODE_DOMAINS],
+ memory_top_k: input.limit,
+ original_top_k: Math.min(input.limit, 8),
+ include_original_chunks: true,
+ },
+ });
+ return normalizeHits(body, input.userId);
+ }
+
+ private async pollIngest(
+ jobId: string,
+ statusUrl?: string
+ ): Promise<Record<string, unknown>> {
+ const deadline = Date.now() + POLL_DEADLINE_MS;
+ let delay = 200;
+ let last: Record<string, unknown> = { job_id: jobId, status: "queued" };
+ while (Date.now() < deadline) {
+ last = unwrap(await this.request(statusPath(jobId, statusUrl)));
+ const status = stringValue(last.status);
+ if (status === "completed" || status === "failed" || status === "cancelled") {
+ return last;
+ }
+ await sleep(delay);
+ delay = Math.min(delay * 2, 1_200);
+ }
+ return last;
+ }
+}
+
+export const memcodeAdapterFactory = {
+ type: "memcode",
+ create: (descriptor: MemorySourceDescriptor) => new MemcodeAdapter(descriptor),
+ describe: (): MemoryTypeDescriptor => ({
+ type: "memcode",
+ displayName: "MemCode",
+ description: getMessage().MEMORY_CONNECTOR_MEMCODE_DESCRIPTION,
+ capabilities: { ...MEMCODE_CAPABILITIES },
+ configFields: memoryHttpVendorFields({ placeholder: DEFAULT_URL }),
+ // No page filters: the API key is the tenant. Memory API v2 resolves the
+ // personal user from the credential and discards any `user_id` a client
+ // sends (it is honoured only for a local static dev key), so a user
+ // control here could neither narrow a read nor redirect a write.
+ filterFields: memoryPageFilters([]),
+ // v2 has no get-by-id route; a list or graph record is already everything
+ // the API can return for a memory, so the detail sheet needs no caveat.
+ detailFromList: true,
+ authStyle: "api-key",
+ authHelp: getMessage().MEMORY_CONNECTOR_AUTH_HELP_MEMCODE,
+ docsUrl: DOCS_URL,
+ }),
+};
diff --git a/src/client/src/lib/platform/connectors/memory/read.ts b/src/client/src/lib/platform/connectors/memory/read.ts
index 4ec3499c..8c8d5e1b 100644
--- a/src/client/src/lib/platform/connectors/memory/read.ts
+++ b/src/client/src/lib/platform/connectors/memory/read.ts
@@ -61,6 +61,7 @@ export interface MemoryQueryInput {
sessionId?: string;
query?: string;
limit?: number;
+ offset?: number;
}
export interface MemoryListItem extends MemoryRecord {
@@ -84,6 +85,12 @@ export interface MemoryQueryResult {
filters: MemoryFilterOptions;
filterFields: MemoryFilterField[];
hint?: MemoryQueryHint;
+ /** Offset this page started at. */
+ offset: number;
+ /** True when the backend holds more memories past this page. */
+ hasMore: boolean;
+ /** Durable total reported by the backend, when it reports one. */
+ total?: number;
}
export interface MemoryDetailResult {
@@ -101,7 +108,8 @@ export interface MemoryFeedbackResult {
}
const DEFAULT_LIMIT = 50;
-const MAX_LIMIT = 100;
+const MAX_LIMIT = 500;
+const MAX_OFFSET = 1_000_000;
const FEEDBACK_REASON_MAX = 1000;
function trim(value?: string): string | undefined {
@@ -114,6 +122,11 @@ function clampLimit(value?: number): number {
return Math.min(MAX_LIMIT, Math.max(1, Math.floor(value)));
}
+function clampOffset(value?: number): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) return 0;
+ return Math.min(MAX_OFFSET, Math.max(0, Math.floor(value)));
+}
+
function fallbackFilterFields(): MemoryFilterField[] {
const messages = getMessage();
return [
@@ -303,6 +316,8 @@ function emptyResult(partial: {
filters: partial.filters || emptyMemoryFilters(),
filterFields: partial.filterFields || [],
hint: partial.hint,
+ offset: 0,
+ hasMore: false,
};
}
@@ -330,11 +345,13 @@ export async function queryProjectMemories(
const capabilities = adapter.capabilities();
const filterFields = resolveFilterFields(String(connector.type || ""));
const limit = clampLimit(input.limit);
+ const offset = clampOffset(input.offset);
const filter = {
userId: trim(input.userId),
agentId: trim(input.agentId),
sessionId: trim(input.sessionId),
limit,
+ offset,
};
const query = trim(input.query);
const filters = await safeListFilters(adapter);
@@ -343,6 +360,8 @@ export async function queryProjectMemories(
);
let records: MemoryRecord[] = [];
+ let total: number | undefined;
+ let hasMore = false;
if (query) {
if (!capabilities.search) {
throw new Error(MEMORY_CONNECTOR_QUERY_REQUIRED);
@@ -361,7 +380,16 @@ export async function queryProjectMemories(
}
} else {
try {
- records = await adapter.list(filter);
+ // Adapters whose backend reports a durable total paginate; the rest
+ // keep the single-shot list they have always used.
+ if (typeof adapter.listPage === "function") {
+ const page = await adapter.listPage(filter);
+ records = page.records;
+ total = page.total;
+ hasMore = page.hasMore;
+ } else {
+ records = await adapter.list(filter);
+ }
} catch (error) {
return emptyResult({
connectors,
@@ -399,6 +427,17 @@ export async function queryProjectMemories(
};
});
+ const stats = summarizeMemoryStats(memories);
+ // A backend total outranks the page length so the header does not shrink to
+ // "50" when the operator is looking at the first page of thousands.
+ if (typeof total === "number" && total > stats.total) stats.total = total;
+
+ const resolved = await resolveGraph(adapter, records, { filter, offset, query });
+ // With a real graph, "connections" means scored edges between memories. The
+ // derived graph only has user/session parent links, which are not
+ // connections in that sense, so it keeps the user+session pairing count.
+ if (resolved.fromAdapter) stats.connections = resolved.graph.edges.length;
+
return {
connectors: connectorsWithCopyMeta,
connector: {
@@ -408,13 +447,42 @@ export async function queryProjectMemories(
},
capabilities,
memories,
- stats: summarizeMemoryStats(memories),
- graph: buildMemoryGraph(records),
+ stats,
+ graph: resolved.graph,
filters: knownFilters(filters, remembered, filter, records),
filterFields,
+ offset,
+ hasMore,
+ total,
};
}
+/**
+ * Prefer a connector's own graph endpoint; fall back to the graph derived from
+ * list records for connectors that do not expose one. Paging the list must not
+ * refetch the graph, and a graph failure must not fail the page.
+ */
+async function resolveGraph(
+ adapter: MemoryAdapter,
+ records: MemoryRecord[],
+ ctx: { filter: { userId?: string }; offset: number; query?: string }
+): Promise<{ graph: MemoryGraphModel; fromAdapter: boolean }> {
+ if (typeof adapter.graph !== "function") {
+ return { graph: buildMemoryGraph(records), fromAdapter: false };
+ }
+ if (ctx.offset > 0 || ctx.query) {
+ return { graph: { nodes: [], edges: [] }, fromAdapter: false };
+ }
+ try {
+ return {
+ graph: await adapter.graph({ userId: ctx.filter.userId }),
+ fromAdapter: true,
+ };
+ } catch {
+ return { graph: buildMemoryGraph(records), fromAdapter: false };
+ }
+}
+
export async function resolveProjectMemoryAdapter(connectorId?: string) {
const connectors = await listMemoryConnectors();
if (!connectors.length) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);
@@ -453,7 +521,15 @@ export async function getProjectMemory(input: {
input.connectorId
);
if (!capabilities.get) {
- return { connector, capabilities, memory: null, hint: "get_unsupported" };
+ const described = getMemoryTypeDescriptor(String(connector.type || ""));
+ return {
+ connector,
+ capabilities,
+ memory: null,
+ // Vendors whose listed record is the full record have nothing to warn
+ // about; the page already shows everything the API can return.
+ hint: described?.detailFromList ? undefined : "get_unsupported",
+ };
}
let record: MemoryRecord | null;
diff --git a/src/client/src/lib/platform/connectors/memory/registry.ts b/src/client/src/lib/platform/connectors/memory/registry.ts
index 03aaf108..f3145a9d 100644
--- a/src/client/src/lib/platform/connectors/memory/registry.ts
+++ b/src/client/src/lib/platform/connectors/memory/registry.ts
@@ -2,7 +2,7 @@
* Memory connector adapter registry (CE).
*
* Holds adapter factories keyed by connector type. `bootstrap.ts` registers
- * Claude, Mem0, and Zep. Extra private factories can still be contributed
+ * Claude, Mem0, MemCode, and Zep. Extra private factories can still be contributed
* through the neutral `getExternalMemoryAdapters()` hook without an
* `@/ee/**` import.
*/
diff --git a/src/client/src/lib/platform/connectors/memory/types.ts b/src/client/src/lib/platform/connectors/memory/types.ts
index e76d2b28..fd9f1aa5 100644
--- a/src/client/src/lib/platform/connectors/memory/types.ts
+++ b/src/client/src/lib/platform/connectors/memory/types.ts
@@ -9,6 +9,7 @@
import type { ConnectorHealthResult, ConnectorRuntime } from "../types";
import type { AuthStyle, FieldDef } from "../datasource/types";
+import type { MemoryGraphModel } from "./graph";
export interface MemoryCapabilities {
add: boolean;
@@ -136,6 +137,29 @@ export interface MemoryListFilter {
agentId?: string;
sessionId?: string;
limit?: number;
+ offset?: number;
+}
+
+/**
+ * One server-side page of memories. Adapters whose backend reports a durable
+ * total implement `listPage` so the Memory page can paginate instead of
+ * guessing from the records it happens to hold.
+ */
+export interface MemoryListPage {
+ records: MemoryRecord[];
+ total?: number;
+ hasMore: boolean;
+ nextOffset: number;
+}
+
+/**
+ * Bounds for a server-side graph read. `maxNodes`/`maxEdges` cap how far an
+ * adapter pages so one connector cannot stall the Memory page.
+ */
+export interface MemoryGraphFilter {
+ userId?: string;
+ maxNodes?: number;
+ maxEdges?: number;
}
export interface MemoryFilterChoice {
@@ -192,6 +216,13 @@ export interface MemoryTypeDescriptor {
configFields: FieldDef[];
/** Memory page filters for this vendor. Empty means no user/session/agent bar. */
filterFields?: MemoryFilterField[];
+ /**
+ * True when a listed record is already the whole record, so there is nothing
+ * richer to fetch by id. Lets a vendor without `get` skip the
+ * "showing the listed record" notice, which would otherwise warn about a
+ * limitation the operator can never observe.
+ */
+ detailFromList?: boolean;
authStyle: AuthStyle;
authHelp?: string;
docsUrl?: string;
@@ -205,6 +236,16 @@ export interface MemoryAdapter extends ConnectorRuntime {
search(query: MemorySearchQuery): Promise<MemoryRecord[]>;
get(id: string): Promise<MemoryRecord | null>;
list(filter: MemoryListFilter): Promise<MemoryRecord[]>;
+ /**
+ * Optional paginated list. Implemented only by adapters whose backend
+ * returns a total and a `has_more` cursor; callers fall back to `list`.
+ */
+ listPage?(filter: MemoryListFilter): Promise<MemoryListPage>;
+ /**
+ * Optional server-side graph. Implemented only by adapters with a real
+ * graph endpoint; callers fall back to deriving one from list records.
+ */
+ graph?(options: MemoryGraphFilter): Promise<MemoryGraphModel>;
listFilters(): Promise<MemoryFilterOptions>;
update(id: string, input: MemoryUpdateInput): Promise<MemoryRecord>;
delete(id: string): Promise<void>;
diff --git a/src/client/src/lib/platform/connectors/visible-types.ts b/src/client/src/lib/platform/connectors/visible-types.ts
index f6e7fcc2..cda43c91 100644
--- a/src/client/src/lib/platform/connectors/visible-types.ts
+++ b/src/client/src/lib/platform/connectors/visible-types.ts
@@ -7,6 +7,7 @@ export const VISIBLE_CONNECTOR_TYPES = [
"jaeger",
"claude",
"mem0",
+ "memcode",
"zep",
"trustabl",
] as const;