Skip to content

NeuroLaunch-AI/insomnia-wiki

Repository files navigation

🌙 Insomnia

Your second brain that doesn't sleep. Your Telegram saved messages, channel subscriptions, and voice notes - compiled overnight into a wiki that grows itself. Obsidian is your dashboard. An LLM agent is your night-shift librarian.

License: MIT Inspired by Karpathy Telegram - NeuroLaunch_AI X - @NeuroLaunch_AI Русская версия

Star this repo · 📢 @NeuroLaunch_AI on Telegram · 𝕏 @NeuroLaunch_AI · 🤖 5-min funnel x-ray

English · Русский


English

This isn't a tool. It's a living loop.

You drop signal. An agent compiles. You review and steer. The agent learns from what you accept and what you reject. Next night it runs smarter. No vendor, no cloud, no pipeline-as-a-service - just you, markdown, and an agent that learns to be useful specifically to you.

The first public artifact from NeuroLaunch-AI - a studio that treats AI as a collaborator, not a feature.

What is this

Insomnia is an open-source knowledge base template for people who:

  • Save 50+ Telegram posts per week to "Saved Messages" and never open them again
  • Read competitor channels and lose every useful thought within two days
  • Record voice memos that die in a transcription queue
  • Want a wiki that grows itself - not another Notion workspace that becomes another graveyard

It's an implementation of Andrej Karpathy's LLM Knowledge Bases method, extended with Telegram ingestion, a four-layer architecture, and a six-phase nightly cycle.

Obsidian is the dashboard. An LLM agent is the night-shift librarian. Plain markdown is the currency.

The wow moment

Friday night: your raw/ folder has 40 Telegram forwards, 12 voice notes, 3 screenshots, a few PDFs. Chaos.

Saturday morning: your wiki/ has five new pages, twelve updated ones, and an Obsidian graph view that shows how they connect. Your competitor analysis lives next to your audience pain points, linked by three wikilinks you didn't write.

The agent did the bookkeeping. You kept the thinking.

Architecture in one diagram

Layer 1 - RAW (immutable) Layer 2 - INBOX (buffer)
raw/dropzone/ ─ classify ─→ inbox/text-thoughts/
raw/voice/ inbox/voice-thoughts/
raw/scrape/tg/ inbox/tg-manual/
 ↓
Layer 4 - WIKI (SSOT) Layer 3 - WORKSPACE (temp, TTL 14d)
wiki/moc/ ←── compile ── workspace/
wiki/strategy/ archive/processed/
wiki/market/
wiki/content/
wiki/products/

Layer 1 (raw): you drop things. TG userbot writes here. No edits, ever. Layer 2 (inbox): a classifier moves raw items into typed folders. Layer 3 (workspace): temporary calculations, TTL 14 days. Layer 4 (wiki): compiled, cross-linked, SSOT. This is version-controlled. Archive: processed originals kept for audit.

The six-phase nightly cycle

An autonomous agent runs while you sleep. By default it's manual (you run claude yourself). Automating via cron or systemd is opt-in and documented in docs/en/six-phases.md.

# Phase What it does Duration
1 OBSERVE Scan git diff, inbox/, stale wiki pages 15 min
2 SYNTHESIZE Compile raw → wiki, route new sources to domains 30 min
3 CONSOLIDATE Find duplicates, propose merges 20 min
4 PROPAGATE Update consumers, optionally sync to LightRAG 15 min
5 PROPOSE Recommendations for you in proposals.md 10 min
6 META-LEARN Analyze what you accepted vs rejected, adjust behavior 10 min

Full protocol: wiki/meta/wiki-maintainer.md.

Security by default

An open-source project that takes your data seriously. Concrete measures below.

  • 🔒 Read-only Telegram by default. READ_ONLY_MODE=true is a hard-wired guard. Send/edit/delete methods are stubs that raise NotImplementedError. To lift, you have to set two environment variables explicitly (READ_ONLY_MODE=false + I_UNDERSTAND_TG_RISKS=yes) and accept the consequences.
  • 🔒 Dry-run by default. Every sync endpoint answers dry_run=true unless you override.
  • 🔒 Empty channel lists by default. You decide what to track. No defaults ship with any channels.
  • 🔒 Nothing leaves your machine. No telemetry, no analytics, no phoning home.
  • 🔒 Local only. Docker container binds 127.0.0.1 only. No public ports.
  • 🔒 Hard .gitignore. .env, sessions/, raw/, inbox/, archive/, *.session all excluded.
  • 🔒 Your API keys, your disk. Insomnia maintainers have zero access to anything you run.

Important: I (or any other LLM agent) do not download, read, or delete your Telegram data. You configure the userbot yourself. You run the sync yourself. You decide which channels to track. The agent only processes what's already on your disk when you explicitly invoke it.

If you want to grant an LLM agent broader permissions (the skip-permission flag in Claude Code), read docs/en/security.md first. The warning there is not decorative.

Full threat model: docs/en/security.md.

Requirements

  • Python 3.10+
  • Docker + Docker Compose (for the Telegram userbot)
  • An LLM CLI agent. Recommended: Claude Code. Works with any CLI that reads CLAUDE.md.
  • Telegram API credentials from my.telegram.org/apps (free, take 3 min)
  • Optional - Obsidian as your graph dashboard

Quick start - 30 to 60 minutes

If you already have Docker, Python 3.10+, and Telegram API keys in hand, this is 15 minutes. If you're setting those up for the first time, plan for an hour. We'd rather tell you the truth than rush you into a broken install.

git clone https://github.com/NeuroLaunch-AI/insomnia-wiki.git
cd insomnia-wiki
./scripts/setup.sh # interactive installer
./scripts/first-run-wizard.py # 5-step identity + config wizard
cd tg-userbot
cp .env.example .env # fill in API_ID / API_HASH / phone
python -m app.auth # one-time Telegram auth (interactive)
cd ..
# open CLAUDE.md in your editor, read the 5-phase focus engine
# then:
claude # opens Claude Code session in this folder

Full deploy walkthrough: docs/en/how-to-deploy.md.

Repository layout

insomnia/
├── README.md you are here
├── CLAUDE.md schema + Focus Engine + rules (the LLM reads this first)
├── AGENTS.md registry of subagents and their roles
├── index.md Karpathy-style master entry point
│
├── .claude/ Claude Code configuration
│ ├── settings.json.example
│ └── agents/ subagent definitions (wiki-maintainer, tg-assistant, pain-extractor)
│
├── wiki/ Layer 4 - SSOT (version-controlled)
│ ├── INDEX.md
│ ├── meta/ protocols, propagation rules, cycle log, proposals
│ └── moc/ 5 LYT-style hub files (🏢 You, 🎯 Strategy, 🔍 Market, 📝 Content, 💰 Products)
│
├── raw/ Layer 1 - immutable sources (gitignored)
├── inbox/ Layer 2 - classified buffer (gitignored)
├── workspace/ Layer 3 - temp, TTL 14d (gitignored)
├── archive/processed/ originals after compile (gitignored by default)
│
├── tg-userbot/ Telegram ingestion module (Telethon, FastAPI)
│ ├── README.md security disclaimer, usage
│ ├── SECURITY.md threat model for this module
│ ├── Dockerfile
│ ├── docker-compose.yml.example
│ └── app/ handlers, config, telegram client
│
├── scripts/ setup, hooks, wizard, lint
├── docs/ full documentation (en/ and ru/)
├── examples/ abstract examples to study, delete when you have your own
├── infra/ docker-compose orchestration
└── .vscode/ optional VS Code recommended extensions

How this relates to Karpathy's original

Karpathy proposed two layers (raw/ + wiki/) and a CLAUDE.md schema, with three operations: ingest, query, lint. That's the core, and it's beautiful in its minimalism.

Insomnia adds:

  • Two more layers (inbox/ for classification, workspace/ for scratch)
  • A six-phase nightly cycle (Karpathy mentions scheduling in passing; we give you a full protocol)
  • Telegram ingestion as a first-class citizen (the original assumes manual drop-in)
  • LYT-style MOC hubs (credit: Nick Milo)
  • A Focus Engine (Observe → Plan → Act → Verify → Compress + money test) baked into CLAUDE.md

Everything else - frontmatter, wikilinks, plain markdown, compile-not-RAG - is Karpathy verbatim. Credit where due.

Full theory: docs/en/karpathy-method.md.

Extending Insomnia

Insomnia is the engine. It's intentionally missing a few things that you can add yourself or acquire as a service:

  • Marketing overlay. Hunt ladder on MOCs, /remix command for donor-post deconstruction, competitor oracles - architectural overlay, not core.
  • Semantic search. LightRAG integration is a documented optional tier.
  • CRM bridge. Notion / Airtable sync for status tables on top of wiki facts.
  • Automation voronki. n8n workflows for downstream publishing.

If you want these integrated into a turnkey setup for your niche, see Insomnia Pro - Architectural Oversight below.

Insomnia Pro

The core engine is free, MIT, forever. Some people prefer a guided setup:

  • Custom MOC hubs for your industry
  • Three domain-specific subagents tuned to your content style
  • Hunt-ladder overlay for your audience segments
  • /remix command adapted to your tone
  • LightRAG + n8n + Notion wired into a cohesive funnel
  • A 1:1 review of your first nightly-cycle output

That's an optional paid service, offered by the maintainer who built this. Details via the Diagnost bot → start a 5-minute funnel x-ray - free, no pitch, just numbers.

Contributing

  • Open issues for bugs, feature requests, or discussion.
  • PRs welcome for: new handlers (Discord, RSS, email), new language docs, new MOC templates for niches not yet covered, better onboarding.
  • Follow the Focus Engine when contributing - tight PRs, money-test every change.

Credits

  • Andrej Karpathy - original LLM Knowledge Bases gist, April 2026.
  • Nick Milo - Linking Your Thinking methodology and the MOC concept.
  • Anthropic - Claude Code, the CLI this project is optimized for.
  • Russian-speaking Claude Code community - for the push to ship this as a lead magnet.

About the author

Built and maintained by the team behind NeuroLaunch-AI - an AI-infrastructure-for-sales studio run by a Russian-speaking engineer who got tired of wiki bookkeeping and decided to hand it to an agent.

If this helped you - a GitHub ⭐ costs you zero, makes the maintainer's day, and improves discoverability for the next person with 200 unread saved messages.

License

MIT. Do whatever you want. Credit the ideas.


Русский

Это не инструмент. Это живая петля.

Ты кидаешь сигнал. Агент компилирует. Ты смотришь и поправляешь. Агент учится на том, что ты принял и что откинул. Следующей ночью бежит умнее. Ни вендора, ни облака, ни pipeline-as-a-service - только ты, markdown и агент, который учится быть полезным именно тебе.

Первый публичный артефакт NeuroLaunch-AI - студии, которая относится к AI как к напарнику, а не к фиче.

Что это

Insomnia - open-source шаблон базы знаний для тех, кто:

  • Сохраняет 50+ постов в неделю в "Избранное" Telegram и больше никогда туда не заходит
  • Читает каналы-конкурентов и забывает любую полезную мысль за два дня
  • Надиктовывает голосовые, которые умирают в очереди на транскрибацию
  • Хочет wiki, которая растёт сама - а не ещё один Notion-воркспейс, который тоже станет кладбищем

Это реализация метода Андрея Карпатого LLM Knowledge Bases, расширенная интеграцией с Telegram, четырьмя слоями архитектуры и шестифазным ночным циклом.

Obsidian - приборная панель. LLM-агент - ночной библиотекарь. Markdown - общий язык.

Момент "вау"

Вечер пятницы: в папке raw/ лежит 40 форвардов из TG, 12 голосовых, 3 скриншота и пара PDF. Хаос.

Утро субботы: в wiki/ пять новых страниц, двенадцать обновлённых, и Obsidian Graph показывает связи между ними. Твой анализ конкурентов соседствует с болями аудитории - связан тремя wikilinks, которые ты не писал.

Агент разложил по полочкам. Думать - твоя часть.

Как это устроено

Та же схема четырёх слоёв и шестифазный цикл - см. английский блок выше или docs/ru/six-phases.md для деталей.

Безопасность по умолчанию

Открытый проект. К твоим данным относится предельно аккуратно - ниже конкретные меры.

  • 🔒 Telegram только на чтение по умолчанию. READ_ONLY_MODE=true - жёстко прошитый предохранитель. Методы send/edit/delete - это заглушки, которые бросают NotImplementedError. Чтобы их разблокировать, нужно явно выставить две переменные (READ_ONLY_MODE=false + I_UNDERSTAND_TG_RISKS=yes) и принять последствия.
  • 🔒 Dry-run по умолчанию. Каждый sync-endpoint отвечает dry_run=true если ты не указал иначе.
  • 🔒 Пустые списки каналов по умолчанию. Ты решаешь что отслеживать. Никаких предустановленных подписок в коде нет.
  • 🔒 Ничего не уходит с твоей машины. Ни телеметрии, ни аналитики, ни звонков домой.
  • 🔒 Только локально. Docker-контейнер слушает только 127.0.0.1. Никаких публичных портов.
  • 🔒 Жёсткий .gitignore. .env, sessions/, raw/, inbox/, archive/, *.session - исключены.
  • 🔒 Твои API-ключи, твой диск. У мейнтейнеров Insomnia нулевой доступ к чему бы то ни было твоему.

Важно: я (или любой другой LLM-агент) не скачиваю, не читаю и не удаляю твои данные Telegram. Ты сам настраиваешь userbot. Ты сам запускаешь sync. Ты сам решаешь какие каналы читать. Агент обрабатывает только то, что уже у тебя на диске, и только когда ты его явно позвал.

Если хочется дать LLM-агенту более широкие права (флаг skip-permission в Claude Code) - сначала прочти docs/ru/security.md. Предупреждение там не декоративное.

Требования

  • Python 3.10+
  • Docker + Docker Compose (для Telegram userbot)
  • LLM CLI агент. Рекомендуется Claude Code. Работает с любым CLI, который читает CLAUDE.md.
  • Telegram API credentials с my.telegram.org/apps (бесплатно, 3 минуты)
  • Опционально - Obsidian как приборная панель графа

Быстрый старт - 30-60 минут

Если у тебя уже есть Docker, Python 3.10+ и ключи Telegram API - уложишься в 15 минут. Если настраиваешь это впервые - час, не торопись. Лучше скажем правду, чем загоним в сломанную установку.

git clone https://github.com/NeuroLaunch-AI/insomnia-wiki.git
cd insomnia-wiki
./scripts/setup.sh # интерактивный инсталлер
./scripts/first-run-wizard.py # мастер настройки (5 шагов)
cd tg-userbot
cp .env.example .env # вписать API_ID / API_HASH / телефон
python -m app.auth # разовая авторизация в Telegram
cd ..
# открой CLAUDE.md в редакторе, прочти 5-фазный Focus Engine
# потом:
claude # открыть Claude Code сессию в этой папке

Полный гайд развёртывания: docs/ru/how-to-deploy.md.

Как это связано с оригиналом Карпатого

Карпаты предложил два слоя (raw/ + wiki/) и CLAUDE.md как схему, с тремя операциями: ingest, query, lint. Это ядро, и оно прекрасно в своём минимализме.

Insomnia добавляет:

  • Ещё два слоя (inbox/ для классификации, workspace/ для черновиков)
  • Шестифазный ночной цикл (Карпаты упоминает scheduling вскользь, у нас - полный протокол)
  • Telegram-интеграцию на уровне ядра (в оригинале её нет)
  • MOC-хабы в стиле LYT (автор методологии - Nick Milo)
  • Focus Engine (Observe → Plan → Act → Verify → Compress + ₽-тест) в CLAUDE.md

Всё остальное - frontmatter, wikilinks, чистый markdown, compile-not-RAG - от Карпатого дословно. Респект автору.

Полная теория: docs/ru/karpathy-method.md.

Расширения

Insomnia - это двигатель. В нём намеренно нет нескольких вещей, которые можно добавить самому или получить как услугу:

  • Маркетинговый слой. Лестница Ханта на MOC-хабах, команда /remix для деконструкции постов-доноров, оракулы конкурентов.
  • Семантический поиск. LightRAG интеграция как документированный опциональный тир.
  • CRM-мост. Синхронизация с Notion / Airtable.
  • Автоматизация воронок. n8n-воркфлоу для публикации.

Если хочется получить это всё настроенным под твою нишу - зайди к Диагносту на 5 минут. Без впаривания, без "запишись на разбор" - просто цифры по твоей воронке. После диагностики сам решишь, нужен ли тебе Architectural Oversight.

Об авторе

Собрано командой NeuroLaunch-AI - студия AI-инфраструктуры для продаж. Делаю build-in-public, показываю как собираю, что ломается, как чиню.

Если пак зашёл - звезда на GitHub помогает найти это следующему, у кого 200 непрочитанных в "Избранном".

Лицензия

MIT. Делай что хочешь. Идеи - указывай в кредитсах.


Questions? Open an issue. Don't like something? Fork it.