Open-source memory engine for AI agentsОткрытый движок памяти для ИИ-агентов

Agent memory that keeps its receipts. Память агента, которая помнит, откуда знает.

Onfim stores what your agents learn together with the evidence behind each fact. Knowledge gets stronger when it is confirmed and used, fades when nobody needs it, and changes only when the change is confirmed. Every automatic step is a written rule with a test.

Onfim хранит то, что узнают ваши агенты, вместе с доказательством для каждого факта. Знание крепнет, когда его подтверждают и используют, угасает, когда оно никому не нужно, и меняется только после подтверждения. Каждый автоматический шаг записан правилом и проверен тестом.

Apache-2.0 Self-hostedСтавится у вас Postgres + pgvector MCP · REST EN · RU searchПоиск RU · EN

Birch-bark drawing: a rider with a red-tipped spear, three people and a robot holding hands, an alphabet and the name Onfim scratched in old letters
gotchans: alice.workstate: currentexampleпример

A Next.js redirect built from request.url points to localhost behind nginx. Build the address from the Host header.

Редирект Next.js через request.url за nginx уводит на localhost. Адрес собирать из заголовка Host.

strength0.68
slotproject:shop#redirects
evidence · 2
claude-code:shop · agent · 2026-09-27 after login the redirect lands on localhost:3002после входа редирект уходит на localhost:3002
owner · 2026-10-02 confirmed, same on stagingподтверждаю, на стенде так же
+0.30 for independent evidence · half-life 180 days+0,30 за независимое доказательство · полураспад 180 дней

One recordОдна запись

A fact, the slot it fills, how strong it is and the quotes that back it. Nothing here was rewritten by a model.

Факт, слот, который он занимает, его сила и цитаты, на которых он держится. Модель здесь ничего не переписывала.

P1–P3principlesпринципы

Most agent memory can't tell you where a fact came from.Обычная память агента не может сказать, откуда она знает факт.

A typical memory layer is a vector store plus a model that rewrites what you save. Facts that look alike get merged, so three different quotes become one. Stale facts stay. Deletes are soft. The nightly job reports success when a stage failed. We built Onfim after running into each of these with our own agents.

Типичный слой памяти — векторная база и модель, которая переписывает сохранённое. Похожие факты сливаются, и три разные сметы становятся одной. Устаревшее остаётся. Удаление мягкое. Ночная задача сообщает об успехе, когда одна из стадий упала. Мы сделали Onfim, наступив на каждую из этих проблем с собственными агентами.

  1. P1

    The service never rewrites what the client sent. There is no model on the write path: text, kind, slot and tags are stored as they came.

    Сервис не переписывает то, что прислал клиент. На пути записи нет модели: текст, вид, слот и теги хранятся как пришли.

  2. P2

    Every automatic action is a formula or a gate, written to the audit log and covered by a test. A model may only propose.

    Каждое автоматическое действие — формула или ворота с записью в журнал и тестом. Модель может только предложить.

  3. P3

    An old fact is replaced only by a confirmed new one. Anything disputed goes to a person, with quotes from both sides.

    Старый факт заменяется только подтверждённым новым. Спорное уходит человеку с цитатами обеих сторон.

evidence

Evidence on every recordДоказательство у каждой записи

Each record carries at least one piece of evidence: source, speaker, date and a short quote. Answers and reports show the quotes, so an agent can say “per Anna, sales chat, Sept 22”.

У каждой записи есть хотя бы одно доказательство: источник, кто сказал, дата и короткая цитата. Ответы и отчёты показывают цитаты, и агент может сказать «со слов Анны, чат продаж, 22.09».

strength

Knowledge strengthСила знания

Strength grows with independent confirmations and real use, and decays at the half-life of the record's kind. A recount never raises it. Decisions and conventions don't decay at all.

Сила растёт от независимых подтверждений и реального использования и затухает по полураспаду вида записи. Пересчёт никогда её не повышает. Решения и конвенции не затухают вовсе.

slot

Replacement with confirmationЗамена с подтверждением

A slot names what a fact is about, like person:anna#role. A new fact in a taken slot waits as a candidate until it is confirmed. History stays, and any replacement can be reverted for 30 days.

Слот называет, о чём факт, например person:anna#role. Новый факт в занятом слоте ждёт претендентом, пока его не подтвердят. История остаётся, любую замену можно откатить в течение 30 дней.

sleep

Sleep cyclesЦиклы сна

Light sleep runs every night and is fully deterministic. Deep sleep runs weekly: a model looks for contradictions and stale facts and drafts summaries, and nothing it proposes applies without passing a gate.

Лёгкий сон идёт каждую ночь и полностью детерминирован. Глубокий — раз в неделю: модель ищет противоречия и устаревшее и готовит сводки, но её предложения применяются только через ворота.

forget

Forgetting that actually forgetsЗабывание всерьёз

Weak records move to an archive you can restore from. Purge physically deletes the text, the vector and the links; the audit log keeps only the fact that it happened.

Слабые записи уходят в архив, откуда их можно вернуть. Purge физически удаляет текст, вектор и связи; в журнале остаётся только факт операции.

explain=true

Ranking you can readРанжирование, которое можно прочитать

Hybrid search over local embeddings and Postgres full-text in English and Russian. The score is one fixed formula, and every term comes back with the result.

Гибридный поиск: локальные эмбеддинги и полнотекстовый поиск Postgres на русском и английском. Оценка — одна формула, и каждое слагаемое возвращается вместе с результатом.

score = 0.50·sem + 0.20·lex + 0.20·strength + 0.10·prior

statelifecycleжизненный цикл

A record's life, from remember to purge.Жизнь записи от remember до purge.

States change only through functions in one module, each writing the audit log in the same transaction. Three gates decide the automatic transitions.

Состояние меняется только функциями одного модуля, и каждая пишет журнал в той же транзакции. Автоматические переходы решают трое ворот.

Record states: current, candidate, superseded, archived, deleted remember slot taken слот занят G1 confirmed G1 подтверждён replaced by new заменена новой strength < 0.08 · G3 сила < 0,08 · G3 unarchive not confirmed in 30 days не подтверждён за 30 дней purge current candidate superseded archived row deletedстроки нет
A superseded record stays in history with its end date. A replacement can be reverted for 30 days.
Заменённая запись остаётся в истории с датой окончания. Замену можно откатить в течение 30 дней.
G1

Promote a candidateПродвинуть претендента

The candidate is newer and confirmed: by the owner, by two independent sources, or by the same person who said the original. Nothing new has come in for the old fact since.

Претендент новее и подтверждён: владельцем, двумя независимыми источниками или тем же человеком, который сказал исходное. С тех пор в пользу старого факта ничего нового не пришло.

G2

Apply a summaryПрименить сводку

Every date, number and name in the summary appears in the sources, so “30.09” can't turn into “by October 1”. Decisions, conventions and facts about people are never folded into summaries.

Каждая дата, число и имя из сводки есть в источниках, и «30.09» не превратится в «до 1 октября». Решения, конвенции и факты о людях в сводки не сворачиваются.

G3

Archive by strengthАрхив по силе

Strength is below 0.08, the record isn't pinned, nobody used it in the last 30 days, and it isn't part of an open dispute.

Сила ниже 0,08, запись не закреплена, её не использовали 30 дней и она не участвует в открытом споре.

Strength over one year by record kind
episode · H 30 note · H 90 insight · H 120 note, used every 30 daysnote, используется раз в 30 дней decision · no decaydecision · не затухает
Strength over a year, starting at 0.55 (importance 2), with no confirmations. An episode reaches the archive threshold in about 83 days, a note in about 250, an insight in about 334. One use a month keeps a note well above it.
Сила за год от 0,55 (важность 2) без подтверждений. Эпизод доходит до порога архива примерно за 83 дня, заметка — за 250, вывод — за 334. Одного использования в месяц хватает, чтобы заметка осталась далеко над порогом.

sleepnightly · weeklyкаждую ночь · раз в неделю

Sleep that reports what it actually did.Сон, который честно отчитывается.

Run status is computed from stage errors: OK, PARTIAL or FAILED, with an alert to your webhook. Running a stage twice on the same data changes nothing, and a dry run returns the same counts without touching anything.

Статус прогона вычисляется из ошибок стадий: OK, PARTIAL или FAILED, с уведомлением на ваш вебхук. Повторный прогон на тех же данных ничего не меняет, а пробный прогон возвращает те же счётчики, ничего не трогая.

Light sleepЛёгкий сонevery night · no modelкаждую ночь · без модели

  1. decayRecords strength after half-life decayФиксирует затухание силы
  2. promoteRuns G1 for every candidateПроверяет претендентов воротами G1
  3. dedup_exactFolds exact duplicates; their evidence reinforces the originalСворачивает точные дубли, их доказательства подкрепляют оригинал
  4. forgetArchives by strength through G3Архивирует по силе через G3
  5. retentionApplies purge rulesПрименяет правила purge
  6. maintenanceChecks data invariantsПроверяет инварианты данных
  7. exportWrites a JSONL backup of each spaceПишет JSONL-копию каждого пространства

Deep sleepГлубокий сонweekly · your modelраз в неделю · ваша модель

  1. contradictionsFinds facts that can't both be true and queues them with quotesИщет факты, которые не могут быть верны одновременно, и ставит их в очередь с цитатами
  2. slot_suggestionsSuggests slots for records about the same attributeПредлагает слоты для записей об одном атрибуте
  3. staleAsks a person whether a weak gotcha still holdsСпрашивает человека, жива ли ослабевшая грабля
  4. summariesFolds old episodes into a summary, applied only through G2Сворачивает старые эпизоды в сводку, применяется только через G2
  5. reportWrites the cleanup reportПишет отчёт уборки

Works with any model behind an OpenAI- or Anthropic-compatible API, including one inside your own network. Without a model, deep sleep skips the model stages.

Подходит любая модель с API, совместимым с OpenAI или Anthropic, в том числе развёрнутая внутри вашей сети. Без модели глубокий сон пропускает её стадии.

# GET /v1/alice.work/sleep/latest
deep sleep · 2026-10-04 · PARTIAL
replaced     2   G1b same speaker
archived    14   episode 11 · note 3
stale?       1   gotcha · strength 0.22
disputes     1   person:anna#role · 2 quotes
summaries    3 applied · 1 rejected (G2a: date not in sources)
stages       contradictions: model timeout → PARTIAL
Example report. Each replacement lists both wordings, the reason and the quotes.
Пример отчёта. По каждой замене — обе формулировки, основание и цитаты.

policy.resolveaccessдоступ

Built for teams, and for agents acting on someone's behalf.Для команд и для агентов, которые действуют от имени человека.

Memory in layersПамять слоями

Personal, team, department and organization layers, each a separate space with its own owner and grants. Search runs across the layers a person may see, nearest first. Sharing a personal fact with the team goes through the team's curator.

Личный слой, команда, отдел и организация, у каждого слоя своё пространство, владелец и гранты. Поиск идёт по слоям, которые человеку можно видеть, ближние выше. Личное попадает в командное только через куратора команды.

Classification levelsУровни конфиденциальности

Each record has a level. Filtering happens in SQL before ranking, so a record above your clearance never shows up in results, counts or explanations.

У каждой записи есть уровень. Фильтр работает в SQL до ранжирования, и запись выше вашего допуска не появляется ни в выдаче, ни в счётчиках, ни в объяснениях.

0 open0 открыто1 internal1 внутреннее2 confidential2 конфиденциально3 restricted3 строго ограничено

Agents act for a personАгент действует за человека

An agent works on behalf of a person and never sees more than that person. In a team chat it acts for the group, so personal layers are out of reach by design.

Агент работает от имени человека и никогда не видит больше, чем он. В командном чате агент действует от имени группы, и личные слои ему недоступны по построению.

Protection from memory poisoningЗащита от отравления памяти

Trust is computed from evidence. Rules from untrusted sources wait for the owner. Hidden text is stripped, keys and tokens are refused, and a forwarded message doesn't count as independent confirmation.

Доверие вычисляется из доказательств. Правила из недоверенных источников ждут владельца. Скрытый текст вырезается, ключи и токены отклоняются, а пересланное сообщение не считается независимым подтверждением.

Texts stay on your serverТексты остаются у вас

Embeddings run in-process on CPU (multilingual-e5-small, ONNX). Record texts leave the server only for deep sleep, only to the model you configure, and owner-only records never do.

Эмбеддинги считаются в процессе на CPU (multilingual-e5-small, ONNX). Тексты уходят с сервера только в глубокий сон, только в модель, которую вы указали, а записи «только для владельца» не уходят никогда.

Open format, your PostgresОткрытый формат, ваш Postgres

Everything lives in one Postgres with pgvector. Export any space to JSONL and import it back. If we disappear, your memory doesn't.

Всё лежит в одном Postgres с pgvector. Любое пространство выгружается в JSONL и загружается обратно. Если нас не станет, ваша память останется.

vshow it differsчем отличается

What changes compared with the usual setups.Что меняется по сравнению с привычными решениями.

Vector storeВекторная база Memory with model extractionПамять с извлечением моделью Onfim
What you saveЧто вы сохранили Stored as isХранится как есть Rewritten by a model on writeПереписывается моделью при записи Stored as isХранится как есть
Where a fact came fromОткуда факт Metadata, if you add itМетаданные, если вы их добавили Often lost in extractionЧасто теряется при извлечении Required evidence with quotes, shown in answersОбязательное доказательство с цитатой, видно в ответах
A fact changesФакт изменился Another vector next to the old oneЕщё один вектор рядом со старым Merged or appended by the modelМодель сливает или дописывает Candidate, confirmation, history, revertПретендент, подтверждение, история, откат
Facts that look alikeПохожие факты Close in vector spaceБлизки в пространстве векторов May be merged into oneМогут слиться в один Never merged; only exact duplicates foldНе сливаются; сворачиваются только точные дубли
ForgettingЗабывание Manual deleteУдаление вручную Rare; deletes are often softРедко; удаление часто мягкое Archive by strength, real purgeАрхив по силе, настоящее удаление
Background jobФоновая задача NoneНет OpaqueНепрозрачна Rules, gates and an honest reportПравила, ворота и честный отчёт

:3120quick startбыстрый старт

From docker compose to the first recall.От docker compose до первого recall.

Onfim runs as one API process with a worker for sleep, next to Postgres 16 with pgvector. Agents connect over MCP (streamable HTTP) or REST with a bearer token.

Onfim — это один процесс API и обработчик сна рядом с Postgres 16 и pgvector. Агенты подключаются по MCP (streamable HTTP) или REST с токеном.

git clone https://github.com/datatim-hq/onfim
cd onfim
cp .env.example .env
sed -i "s/change-me/$(openssl rand -hex 16)/" .env   # database password
docker compose up -d   # API and MCP on 127.0.0.1:3120
docker compose exec api python -m mem.cli init \
  --tenant acme --person alice --name "Alice"
docker compose restart api   # so MCP picks up the new space

init creates the organization, the first person and their personal space alice.work, and prints the agent token once. Save it. The Python package is called mem. Deep sleep needs a model key in .env; without one, Onfim runs everything except the model stages.

init создаёт организацию, первого человека и его личное пространство alice.work и один раз печатает токен агента. Сохраните его. Пакет Python называется mem. Для глубокого сна нужен ключ модели в .env; без него Onfim выполняет всё, кроме стадий модели.

Preview of the 0.1 setup. Commands may change before the release. A record without evidence is refused with 400.

Предварительный вид установки 0.1. До выпуска команды могут измениться. Запись без доказательства сервис отклоняет с ошибкой 400.

0.1statusстатус

Where Onfim is today.Где Onfim сейчас.

  1. Late Oct 2026Конец октября 2026

    Release 0.1Выпуск 0.1

    Public repository, quick start, English docs and a concepts guide, CI on GitHub, a Docker image on GHCR. Design specs ship in docs/design in Russian with English summaries.

    Публичный репозиторий, быстрый старт, документация на английском и описание понятий, CI на GitHub, образ Docker в GHCR. Проектные спецификации лежат в docs/design на русском с кратким английским изложением.

  2. After 0.1После 0.1

    Driven by feedbackПо отзывам

    OAuth sign-in for third-party MCP clients, Python and TypeScript clients, more team memory features. Contributions are welcome under the DCO, with no CLA.

    Вход по OAuth для сторонних MCP-клиентов, клиенты на Python и TypeScript, новые возможности памяти команды. Вклады принимаем по DCO, без CLA.