Initial commit: agent-second-brain (vault storage, session management)

This commit is contained in:
xiaowei
2026-05-24 16:58:31 +08:00
commit feca79da75
114 changed files with 17916 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
{
"permissions": {
"allow": [
"Bash(git push origin main)",
"Bash(mcp-cli :*)"
]
}
}
+14
View File
@@ -0,0 +1,14 @@
# Telegram Bot API token from @BotFather
TELEGRAM_BOT_TOKEN=
# Deepgram API key for voice transcription
DEEPGRAM_API_KEY=
# Todoist API key for task management
TODOIST_API_KEY=
# Path to Obsidian vault directory
VAULT_PATH=./vault
# JSON array of Telegram user IDs allowed to use the bot (empty = allow all)
ALLOWED_USER_IDS=[123456789]
+70
View File
@@ -0,0 +1,70 @@
# This workflow will upload a Python Package to PyPI when a release is created
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
name: Upload Python Package
on:
release:
types: [published]
permissions:
contents: read
jobs:
release-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.x"
- name: Build release distributions
run: |
# NOTE: put your own distribution build steps here.
python -m pip install build
python -m build
- name: Upload distributions
uses: actions/upload-artifact@v4
with:
name: release-dists
path: dist/
pypi-publish:
runs-on: ubuntu-latest
needs:
- release-build
permissions:
# IMPORTANT: this permission is mandatory for trusted publishing
id-token: write
# Dedicated environments with protections for publishing are strongly recommended.
# For more information, see: https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment#deployment-protection-rules
environment:
name: pypi
# OPTIONAL: uncomment and update to include your PyPI project URL in the deployment status:
# url: https://pypi.org/p/YOURPROJECT
#
# ALTERNATIVE: if your GitHub Release name is the PyPI project version string
# ALTERNATIVE: exactly, uncomment the following line instead:
# url: https://pypi.org/project/YOURPROJECT/${{ github.event.release.name }}
steps:
- name: Retrieve release distributions
uses: actions/download-artifact@v4
with:
name: release-dists
path: dist/
- name: Publish release distributions to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
packages-dir: dist/
+37
View File
@@ -0,0 +1,37 @@
# Environment files (ВАЖНО: секреты!)
.env
.env.local
.env.*.local
# Python
__pycache__/
*.py[cod]
*$py.class
.venv/
venv/
.Python
# Node
node_modules/
# IDE
.idea/
.vscode/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Vault personal data (never commit these)
vault/daily/
vault/contacts/
vault/finances/
vault/attachments/
vault/.session/
vault/.graph/
vault/business/
vault/projects/
vault/thoughts/
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Serge Shima
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+223
View File
@@ -0,0 +1,223 @@
# Agent Second Brain
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Stars](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fapi.github.com%2Frepos%2Fsmixs%2Fagent-second-brain&query=%24.stargazers_count&label=stars&logo=github&color=blue)](https://github.com/smixs/agent-second-brain/stargazers)
[![Forks](https://img.shields.io/github/forks/smixs/agent-second-brain?style=flat&logo=github)](https://github.com/smixs/agent-second-brain/forks)
<p align="center">
<img alt="Agent Second Brain" src="https://github.com/user-attachments/assets/5b3611d9-11ba-40a1-92fc-8dc78d78d75b" />
</p>
**Send a voice note to Telegram. Get an organized knowledge base, completed tasks, and a daily report back.** That's it. That's the whole idea.
[🇷🇺 Читать на русском](README.ru.md)
---
## The problem
Every productivity system dies the same way. You set it up on a Sunday, use it for two weeks, then slowly stop because the overhead of maintaining it is more work than the work itself.
You have notes everywhere. Voice memos you never re-listen to. Ideas that disappear into chat history. Tasks you forget to write down. And even when you do capture something, it sits in a folder you'll never open again.
The real issue: organizing takes more effort than thinking. So the thinking never gets organized.
## What this actually does
You talk to a Telegram bot. Voice, text, photos, forwarded messages - whatever is natural. You don't think about categories, tags, or where things go.
The agent handles everything else:
- **Transcribes** your voice notes (Deepgram, takes seconds)
- **Classifies** each entry - task, idea, client note, goal update, random thought
- **Creates tasks** in Todoist with the right priority and due date
- **Saves everything** to an Obsidian vault with proper links and tags
- **Sends you a daily report** at 9pm - what happened, what got done, what's still hanging
- **Remembers what matters, forgets what doesn't** - memory fades over time like a real brain
The bot runs 24/7 on a $5 VPS. You don't maintain it. You just talk to it.
## Talk to it like a person
This isn't a button-pressing bot. You have a conversation.
> **You:** what did I write about the marketing project last week?
>
> **Bot:** *finds and shows relevant entries*
>
> **You:** turn the second idea into a task for Monday
>
> **Bot:** *creates the task in Todoist*
>
> **You:** actually make it high priority and add a subtask for the presentation
>
> **Bot:** *updates the task*
It has access to your entire vault, all your goals, and your Todoist. Ask it anything about your own notes, and it'll find the answer.
## Memory that works like memory
Most AI systems either remember everything forever (drowning you in noise) or forget everything between sessions.
Agent Second Brain uses the Ebbinghaus forgetting curve - the same model that describes how human memory works. Every piece of information starts strong and gradually fades unless you access it again.
Five tiers, from always-on to nearly forgotten:
| Tier | What happens |
|------|-------------|
| **Core** | Always in context. Your current projects, active clients, key goals. |
| **Active** | Checked regularly. Recent ideas, ongoing conversations. |
| **Warm** | Found when you search. Last month's notes, past decisions. |
| **Cold** | Only surfaces in deep searches. Old projects, archived plans. |
| **Archive** | Almost gone - but sometimes randomly recalled for creative connections. |
The archive tier is the interesting one. Occasionally, the agent pulls a random old memory and connects it to something current. Sometimes it's noise. Sometimes it's the best idea you forgot you had.
## Vault health - your notes maintain themselves
Over time, note systems rot. Links break. Files become orphans. Tags diverge. You end up with a graveyard of markdown files that nobody, including you, can navigate.
The vault-health system runs automatically:
- Scores your vault on a 100-point scale
- Finds orphan notes (no links in or out) and suggests connections
- Repairs broken wiki-links
- Generates Maps of Content (MOCs) for each domain
- Flags files missing descriptions
You don't run maintenance. The agent does.
## What you send, what happens
| You send | Agent does |
|----------|-----------|
| Voice note about a client call | Transcribes, creates CRM card, adds follow-up task |
| Quick text: "idea for the Q2 campaign" | Saves to ideas folder, links to related notes |
| Forwarded article from a chat | Saves with source, extracts key points |
| Photo of a whiteboard | Saves with AI-generated description |
| "Process" button | Runs the full pipeline right now |
| "What are my priorities this week?" | Reads your goals and Todoist, gives you a straight answer |
## How it works (for the curious)
The daily processing runs in three phases:
1. **Capture** - reads today's entries, classifies each one (task? idea? CRM update? goal progress?)
2. **Execute** - creates Todoist tasks, writes vault files, updates cards
3. **Reflect** - generates a summary report, updates long-term memory, sends it to Telegram
Each phase produces a clean JSON that the next phase picks up. If something breaks, you can see exactly where and why.
```
Telegram → Deepgram → Claude Code → Todoist + Obsidian vault → Telegram report
```
## What it costs
| Service | Cost |
|---------|------|
| Claude Pro | $20/mo |
| VPS (any cheap one works) | ~$5/mo |
| Deepgram | Free tier ($200 credit) |
| Todoist | Free plan works |
| **Total** | **~$25/mo** |
$25/month for a personal assistant that organizes your life, never sleeps, and gets better the more you use it.
## Quick start
### 1. Fork this repo
Click **Fork** at the top of this page. Make it **private** - it will contain your personal data.
### 2. Clone it
```bash
git clone https://github.com/YOUR_USERNAME/agent-second-brain.git
cd agent-second-brain
```
### 3. Fill in your info
Open these files and replace the placeholders:
- `vault/goals/` - your vision, yearly goals, monthly priorities, weekly focus
- `vault/.claude/skills/dbrain-processor/references/about.md` - tell the agent about yourself
- `vault/.claude/skills/dbrain-processor/references/classification.md` - how you want entries sorted
### 4. Get four API keys
| What | Where | Time |
|------|-------|------|
| Telegram Bot Token | [@BotFather](https://t.me/BotFather) | 2 min |
| Your Telegram ID | [@userinfobot](https://t.me/userinfobot) | 30 sec |
| Deepgram API Key | [console.deepgram.com](https://console.deepgram.com/) | 3 min |
| Todoist API Token | Todoist → Settings → Integrations → Developer | 1 min |
### 5. Deploy
Follow the [VPS setup guide](docs/vps-setup.md), or run:
```bash
ssh root@YOUR_SERVER_IP
curl -fsSL https://raw.githubusercontent.com/YOUR_USERNAME/agent-second-brain/main/bootstrap.sh | bash
```
That's it. The bot starts, you send it a message, and the system is alive.
---
## Vault structure
```
vault/
├── daily/ # Your daily entries (voice, text, photos)
├── goals/ # Vision → yearly → monthly → weekly
├── business/
│ ├── crm/ # Client cards
│ └── network/ # Professional contacts
├── projects/ # Client work, leads, pipeline
├── thoughts/
│ ├── ideas/ # Ideas and brainstorms
│ ├── learnings/ # Lessons learned
│ └── reflections/ # Personal reflections
├── MOC/ # Maps of Content (auto-generated)
└── MEMORY.md # Agent's long-term memory
```
## Skills
The agent has five built-in skills:
| Skill | What it does |
|-------|-------------|
| **dbrain-processor** | Classifies entries, creates tasks, saves notes |
| **agent-memory** | Ebbinghaus decay engine - remembers, forgets, recalls |
| **vault-health** | Scores vault health, fixes links, generates MOCs |
| **graph-builder** | Maps relationships between notes, finds clusters |
| **todoist-ai** | Manages tasks, projects, priorities |
Want just the memory engine? See [agent-memory-skill](https://github.com/smixs/agent-memory-skill) - works standalone, no dependencies.
## Configuration
| File | What it controls |
|------|-----------------|
| `.env` | API tokens (copy from `.env.example`) |
| `.memory-config.json` | How fast memories decay, tier boundaries |
| `mcp-config.json` | External tool connections |
| `vault/.claude/CLAUDE.md` | Agent personality and rules |
All secrets stay in `.env`, which is gitignored. Don't commit tokens.
---
## Built by
[Serge Shima](https://shima.me) - 20 years in marketing (BBDO, Publicis), now running an AI creative agency in Central Asia and teaching businesses how to work with AI at [aimasters.me](https://aimasters.me).
This system runs my actual life. 1,100+ vault cards, 5 AI agents, daily reports. It started as a weekend project and became infrastructure.
## License
[MIT](LICENSE) - do whatever you want with it.
+221
View File
@@ -0,0 +1,221 @@
# Agent Second Brain
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Stars](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fapi.github.com%2Frepos%2Fsmixs%2Fagent-second-brain&query=%24.stargazers_count&label=stars&logo=github&color=blue)](https://github.com/smixs/agent-second-brain/stargazers)
[![Forks](https://img.shields.io/github/forks/smixs/agent-second-brain?style=flat&logo=github)](https://github.com/smixs/agent-second-brain/forks)
<p align="center">
<img alt="Agent Second Brain" src="https://github.com/user-attachments/assets/5b3611d9-11ba-40a1-92fc-8dc78d78d75b" />
</p>
**Отправь голосовое в Telegram - получи организованную базу знаний, выполненные задачи и дневной отчёт.** Всё. Вся идея в одном предложении.
[🇬🇧 Read in English](README.md)
---
## Проблема
Любая система продуктивности умирает одинаково. Настраиваешь в воскресенье, пользуешься две недели, потом бросаешь - потому что поддержка системы отнимает больше сил, чем сама работа.
Заметки раскиданы везде. Голосовые, которые никогда не переслушаешь. Идеи, утонувшие в истории чатов. Задачи, которые забыл записать. А если записал - они лежат в папке, которую ты больше не откроешь.
Корень проблемы: организовывать сложнее, чем думать. Поэтому мысли остаются неорганизованными.
## Что делает эта штука
Ты пишешь боту в Telegram. Голосовые, текст, фото, пересланные сообщения - как удобно. Не думаешь про категории, теги или куда что положить.
Агент разбирается сам:
- **Расшифровывает** голосовые (Deepgram, пара секунд)
- **Классифицирует** каждую запись - задача, идея, заметка о клиенте, прогресс по цели, случайная мысль
- **Создаёт задачи** в Todoist с нужным приоритетом и датой
- **Сохраняет всё** в Obsidian-хранилище с правильными ссылками и тегами
- **Присылает дневной отчёт** в 21:00 - что произошло, что сделано, что висит
- **Помнит важное, забывает ненужное** - память угасает со временем, как у живого человека
Бот работает 24/7 на сервере за $5. Ты его не обслуживаешь. Ты просто с ним разговариваешь.
## Разговаривай как с человеком
Это не бот с кнопками. Это разговор.
> **Ты:** что я писал про маркетинговый проект на прошлой неделе?
>
> **Бот:** *находит и показывает записи*
>
> **Ты:** вторую идею превращай в задачу на понедельник
>
> **Бот:** *создаёт задачу в Todoist*
>
> **Ты:** сделай высокий приоритет и добавь подзадачу на презентацию
>
> **Бот:** *обновляет задачу*
У агента доступ ко всему хранилищу, всем целям и Todoist. Спроси что угодно про свои записи - найдёт.
## Память, которая работает как память
Большинство AI-систем либо помнят всё навсегда (утопая в шуме), либо забывают всё между сессиями.
Agent Second Brain использует кривую забывания Эббингауза - ту же модель, что описывает работу человеческой памяти. Каждая запись начинает с максимальной «яркости» и постепенно тускнеет, если к ней не возвращаются.
Пять уровней - от «всегда под рукой» до «почти забыто»:
| Уровень | Что происходит |
|---------|---------------|
| **Ядро** | Всегда в контексте. Текущие проекты, активные клиенты, ключевые цели. |
| **Активные** | Проверяются регулярно. Свежие идеи, текущие разговоры. |
| **Тёплые** | Находятся при поиске. Заметки за прошлый месяц, принятые решения. |
| **Холодные** | Всплывают только при глубоком поиске. Старые проекты, архивные планы. |
| **Архив** | Почти забытые - но иногда случайно вспоминаются для неожиданных связей. |
Архив - самое интересное. Иногда агент достаёт случайную старую запись и связывает с чем-то текущим. Бывает - мимо. А бывает - это лучшая идея, которую ты забыл.
## Здоровье хранилища - заметки сами себя чинят
Со временем любая система заметок гниёт. Ссылки ломаются. Файлы становятся сиротами. Теги расползаются. В итоге - кладбище маркдаун-файлов, по которому не может пройти никто.
Система здоровья работает автоматически:
- Оценивает хранилище по 100-балльной шкале
- Находит сироты (файлы без связей) и предлагает ссылки
- Чинит сломанные вики-линки
- Генерирует карты содержимого (MOC) для каждой области
- Отмечает файлы без описаний
Ты не занимаешься обслуживанием. Агент занимается.
## Что отправляешь - что получаешь
| Ты отправляешь | Агент делает |
|----------------|-------------|
| Голосовое о звонке с клиентом | Расшифровывает, создаёт CRM-карточку, добавляет follow-up задачу |
| Текст: «идея для Q2 кампании» | Сохраняет в папку идей, связывает с похожими заметками |
| Пересланная статья из чата | Сохраняет с источником, вытаскивает ключевые мысли |
| Фото доски | Сохраняет с AI-описанием |
| Кнопка «Process» | Запускает полный цикл обработки прямо сейчас |
| «Какие приоритеты на эту неделю?» | Читает цели и Todoist, даёт прямой ответ |
## Как это работает (для любопытных)
Ежедневная обработка идёт в три фазы:
1. **Захват** - читает записи за день, классифицирует каждую (задача? идея? обновление CRM? прогресс по цели?)
2. **Исполнение** - создаёт задачи в Todoist, пишет файлы в хранилище, обновляет карточки
3. **Рефлексия** - генерирует сводный отчёт, обновляет долговременную память, отправляет в Telegram
Каждая фаза создаёт чистый JSON, который подхватывает следующая. Если что-то ломается - видно где именно и почему.
```
Telegram → Deepgram → Claude Code → Todoist + Obsidian → Telegram отчёт
```
## Сколько стоит
| Сервис | Цена |
|--------|------|
| Claude Pro | $20/мес |
| VPS (любой дешёвый) | ~$5/мес |
| Deepgram | Бесплатно ($200 кредит) |
| Todoist | Бесплатный план работает |
| **Итого** | **~$25/мес** |
$25 в месяц за личного ассистента, который организует твою жизнь, никогда не спит и становится лучше с каждым днём использования.
## Быстрый старт
### 1. Форкни репо
Нажми **Fork** вверху страницы. Сделай форк **приватным** - в нём будут твои личные данные.
### 2. Склонируй
```bash
git clone https://github.com/YOUR_USERNAME/agent-second-brain.git
cd agent-second-brain
```
### 3. Заполни свою информацию
Открой эти файлы и замени шаблоны на свои данные:
- `vault/goals/` - видение, годовые цели, месячные приоритеты, фокус недели
- `vault/.claude/skills/dbrain-processor/references/about.md` - расскажи агенту о себе
- `vault/.claude/skills/dbrain-processor/references/classification.md` - как сортировать записи
### 4. Получи четыре API-ключа
| Что | Где взять | Время |
|-----|----------|-------|
| Telegram Bot Token | [@BotFather](https://t.me/BotFather) | 2 мин |
| Твой Telegram ID | [@userinfobot](https://t.me/userinfobot) | 30 сек |
| Deepgram API Key | [console.deepgram.com](https://console.deepgram.com/) | 3 мин |
| Todoist API Token | Todoist → Settings → Integrations → Developer | 1 мин |
### 5. Разверни
Следуй [инструкции по настройке VPS](docs/vps-setup.md), или:
```bash
ssh root@YOUR_SERVER_IP
curl -fsSL https://raw.githubusercontent.com/YOUR_USERNAME/agent-second-brain/main/bootstrap.sh | bash
```
Бот запускается, ты отправляешь ему сообщение - система живёт.
---
## Структура хранилища
```
vault/
├── daily/ # Дневные записи (голосовые, текст, фото)
├── goals/ # Видение → год → месяц → неделя
├── business/
│ ├── crm/ # Карточки клиентов
│ └── network/ # Профессиональные контакты
├── projects/ # Клиентские проекты, лиды, пайплайн
├── thoughts/
│ ├── ideas/ # Идеи и мозговые штурмы
│ ├── learnings/ # Уроки
│ └── reflections/ # Рефлексии
├── MOC/ # Карты содержимого (генерируются автоматически)
└── MEMORY.md # Долговременная память агента
```
## Навыки агента
| Навык | Что делает |
|-------|-----------|
| **dbrain-processor** | Классифицирует записи, создаёт задачи, сохраняет заметки |
| **agent-memory** | Движок памяти Эббингауза - помнит, забывает, вспоминает |
| **vault-health** | Оценка здоровья, починка ссылок, генерация MOC |
| **graph-builder** | Карта связей между заметками, поиск кластеров |
| **todoist-ai** | Управление задачами, проектами, приоритетами |
Нужен только движок памяти? Смотри [agent-memory-skill](https://github.com/smixs/agent-memory-skill) - работает отдельно, без зависимостей.
## Конфигурация
| Файл | За что отвечает |
|------|----------------|
| `.env` | API-токены (скопируй из `.env.example`) |
| `.memory-config.json` | Скорость угасания памяти, границы уровней |
| `mcp-config.json` | Подключения к внешним инструментам |
| `vault/.claude/CLAUDE.md` | Личность и правила агента |
Все секреты в `.env`, который в gitignore. Не коммить токены.
---
## Кто сделал
[Сергей Шима](https://shima.me) - 20 лет в маркетинге (BBDO, Publicis), сейчас руководит AI-креативным агентством в Центральной Азии и учит бизнес работать с AI на [aimasters.me](https://aimasters.me).
Эта система работает в моей реальной жизни. 1,100+ карточек в хранилище, 5 AI-агентов, ежедневные отчёты. Начиналось как проект на выходных - стало инфраструктурой.
## Лицензия
[MIT](LICENSE) - делай с этим что хочешь.
Executable
+62
View File
@@ -0,0 +1,62 @@
#!/bin/bash
# =============================================================================
# Agent Second Brain - Bootstrap Script
# =============================================================================
# Downloads setup.sh and runs it properly (not via pipe)
#
# Usage:
# curl -fsSL https://raw.githubusercontent.com/smixs/agent-second-brain/main/bootstrap.sh | bash
# =============================================================================
set -e
RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m'
echo ""
echo -e "${CYAN}Agent Second Brain - Bootstrap${NC}"
echo ""
# Check if running as root
if [ "$EUID" -eq 0 ]; then
echo -e "${RED}[X] Do not run as root!${NC}"
echo " Create a user first: adduser myuser && usermod -aG sudo myuser"
echo " Then: su - myuser"
exit 1
fi
# Always download from original repo
SETUP_URL="https://raw.githubusercontent.com/smixs/agent-second-brain/main/setup.sh"
echo "Downloading setup script..."
# Create temp file
TEMP_SCRIPT=$(mktemp /tmp/setup-XXXXXX.sh)
# Download setup script
if command -v curl &> /dev/null; then
curl -fsSL "$SETUP_URL" -o "$TEMP_SCRIPT"
elif command -v wget &> /dev/null; then
wget -q "$SETUP_URL" -O "$TEMP_SCRIPT"
else
echo -e "${RED}[X] Neither curl nor wget found${NC}"
echo " Install: sudo apt install curl"
exit 1
fi
if [ ! -s "$TEMP_SCRIPT" ]; then
echo -e "${RED}[X] Failed to download setup script${NC}"
rm -f "$TEMP_SCRIPT"
exit 1
fi
echo -e "${GREEN}[OK] Downloaded${NC}"
echo ""
# Make executable and run PROPERLY (not via pipe!)
# exec replaces current process, so stdin works normally
chmod +x "$TEMP_SCRIPT"
exec bash "$TEMP_SCRIPT"
+15
View File
@@ -0,0 +1,15 @@
[Unit]
Description=d-brain Telegram Bot
After=network.target
[Service]
Type=simple
User=shima
WorkingDirectory=/home/shima/projects/dbrain
ExecStart=/home/shima/.local/bin/uv run python -m d_brain
Restart=always
RestartSec=10
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
+9
View File
@@ -0,0 +1,9 @@
[Unit]
Description=d-brain Daily Processing
[Service]
Type=oneshot
User=shima
WorkingDirectory=/home/shima/projects/agent-second-brain
ExecStart=/home/shima/projects/agent-second-brain/scripts/process.sh
Environment=PYTHONUNBUFFERED=1
+9
View File
@@ -0,0 +1,9 @@
[Unit]
Description=Run d-brain processing daily at 21:00
[Timer]
OnCalendar=*-*-* 21:00:00
Persistent=true
[Install]
WantedBy=timers.target
+12
View File
@@ -0,0 +1,12 @@
[Unit]
Description=d-brain Weekly Digest
After=network.target
[Service]
Type=oneshot
User=shima
WorkingDirectory=/home/shima/projects/agent-second-brain
ExecStart=/home/shima/.local/bin/uv run python scripts/weekly.py
EnvironmentFile=/home/shima/projects/agent-second-brain/.env
StandardOutput=journal
StandardError=journal
+9
View File
@@ -0,0 +1,9 @@
[Unit]
Description=Run d-brain weekly digest Friday morning
[Timer]
OnCalendar=Fri 06:00
Persistent=true
[Install]
WantedBy=timers.target
File diff suppressed because it is too large Load Diff
+194
View File
@@ -0,0 +1,194 @@
# MCP через mcp-cli
Стабильное подключение к MCP серверам через mcp-cli вместо прямого протокола.
## Зачем это нужно
MCP протокол напрямую иногда отваливается. mcp-cli решает эту проблему:
- **Connection pooling** - daemon держит соединения
- **Auto-retry** - автоматические повторы при сетевых ошибках
- **Стабильность** - работа через bash надёжнее чем MCP протокол напрямую
## Как это работает
```
До:
Claude → MCP Protocol → Todoist MCP Server → Todoist API
(отваливается)
После:
Claude → Bash → mcp-cli → Todoist MCP Server → Todoist API
(daemon, retry, pooling)
```
---
## Установка
### 1. Установите mcp-cli
```bash
curl -fsSL https://raw.githubusercontent.com/philschmid/mcp-cli/main/install.sh | bash
```
Проверка:
```bash
~/.local/bin/mcp-cli --version
# mcp-cli v0.3.0
```
### 2. Создайте конфиг
```bash
mkdir -p ~/.config/mcp
cat > ~/.config/mcp/mcp_servers.json << 'EOF'
{
"mcpServers": {
"todoist": {
"command": "npx",
"args": ["-y", "@doist/todoist-ai"],
"env": {
"TODOIST_API_KEY": "${TODOIST_API_KEY}"
}
}
}
}
EOF
```
### 3. Добавьте токены в shell
```bash
# Добавить в ~/.bashrc
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
echo 'export TODOIST_API_KEY="ваш_токен"' >> ~/.bashrc
source ~/.bashrc
```
### 4. Уберите прямое MCP подключение из Claude
```bash
# Удалить прямое MCP подключение
claude mcp remove todoist
```
Проверить что удалено:
```bash
claude mcp list
# todoist НЕ должен быть в списке
```
Теперь Claude работает через mcp-cli (bash), а не через MCP протокол напрямую.
---
## Проверка
```bash
# Список инструментов (24 шт)
mcp-cli info todoist
# Тест - задачи на сегодня
mcp-cli call todoist find-tasks-by-date '{"startDate": "today"}'
# Обзор всех проектов
mcp-cli call todoist get-overview '{}'
```
---
## Todoist Tools (24)
### Задачи
| Tool | Описание |
|------|----------|
| `add-tasks` | Создать задачи |
| `update-tasks` | Обновить задачи |
| `complete-tasks` | Завершить задачи |
| `find-tasks` | Поиск по тексту/проекту/label |
| `find-tasks-by-date` | Задачи по дате |
| `find-completed-tasks` | Завершённые задачи |
### Проекты и секции
| Tool | Описание |
|------|----------|
| `add-projects` | Создать проекты |
| `update-projects` | Обновить проекты |
| `find-projects` | Поиск проектов |
| `add-sections` | Создать секции |
| `update-sections` | Обновить секции |
| `find-sections` | Секции проекта |
### Комментарии и коллаборация
| Tool | Описание |
|------|----------|
| `add-comments` | Добавить комментарии |
| `update-comments` | Обновить комментарии |
| `find-comments` | Найти комментарии |
| `find-project-collaborators` | Участники проекта |
| `manage-assignments` | Bulk назначение |
### Общее
| Tool | Описание |
|------|----------|
| `get-overview` | Обзор (markdown) |
| `find-activity` | Лог активности |
| `delete-object` | Удалить объект |
| `fetch-object` | Получить объект |
| `user-info` | Инфо о пользователе |
| `search` | Универсальный поиск |
| `fetch` | Получить по ID |
---
## Примеры команд
### Задачи на сегодня
```bash
mcp-cli call todoist find-tasks-by-date '{"startDate": "today"}'
```
### Создать задачу
```bash
mcp-cli call todoist add-tasks '{"tasks": [{"content": "Тест задача", "dueString": "tomorrow", "priority": 2}]}'
```
### Завершить задачу
```bash
mcp-cli call todoist complete-tasks '{"ids": ["task_id_here"]}'
```
### Поиск задач
```bash
mcp-cli call todoist find-tasks '{"searchText": "проект"}'
```
### Обзор проекта
```bash
mcp-cli call todoist get-overview '{"projectId": "project_id"}'
```
### Найти проекты
```bash
mcp-cli call todoist find-projects '{"search": "Work"}'
```
---
## Отладка
```bash
MCP_DEBUG=1 mcp-cli call todoist find-tasks-by-date '{"startDate": "today"}'
```
---
## Требования
- Node.js 18+ (для npx)
- Todoist API Token (Settings → Integrations → Developer)
+515
View File
@@ -0,0 +1,515 @@
# VPS Setup Guide
Run Agent Second Brain 24/7 on a virtual private server.
## Requirements
- VPS with Ubuntu 22.04+ (minimum 1GB RAM, recommended 2GB)
- Root or sudo access
- SSH client
## Recommended VPS Providers
| Provider | Price | Region |
|----------|-------|--------|
| Contabo | from $5/mo | Europe |
| Hetzner | from $4/mo | Europe |
| DigitalOcean | from $6/mo | Global |
| Vultr | from $5/mo | Global |
---
## Step 1: Connect to Server
After purchasing VPS, you'll get:
- IP address (e.g., `162.55.123.45`)
- Root password
Connect via SSH:
```bash
ssh root@162.55.123.45
```
Enter password (characters won't display — that's normal).
---
## Step 2: Create User
Never work as root. Create a regular user:
```bash
# Create user (replace "myuser" with your name)
adduser myuser
# Follow prompts:
# - Enter password (twice)
# - Other fields can be skipped (Enter)
# Grant sudo rights
usermod -aG sudo myuser
# Switch to new user
su - myuser
```
---
## Step 3: Update System
```bash
sudo apt update && sudo apt upgrade -y
```
---
## Step 4: Install Base Tools
```bash
# Git
sudo apt install -y git
# Curl and wget
sudo apt install -y curl wget
# Build tools
sudo apt install -y build-essential
# Verify
git --version
```
---
## Step 5: Install Python 3.12
```bash
sudo apt install -y software-properties-common
sudo add-apt-repository -y ppa:deadsnakes/ppa
sudo apt update
sudo apt install -y python3.12 python3.12-venv python3.12-dev
# Verify
python3.12 --version
```
---
## Step 6: Install uv
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
source ~/.bashrc
# Verify
uv --version
```
---
## Step 7: Install Node.js
Required for MCP servers (Todoist integration):
```bash
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
# Verify
node --version
npm --version
```
---
## Step 8: Install Claude CLI
```bash
npm install -g @anthropic-ai/claude-code
# Verify
which claude
claude --version
# Authenticate
claude auth login
```
After `claude auth login`:
1. A URL appears
2. Copy and open it in browser on your computer
3. Log in to Anthropic account
4. Authorize access
5. Return to terminal — it will confirm
---
## Step 9: Clone Project
```bash
cd ~
mkdir -p projects
cd projects
git clone https://github.com/smixs/agent-second-brain.git
cd agent-second-brain
ls -la
```
---
## Step 10: Install Dependencies
```bash
uv sync
# Verify
uv run python -c "import aiogram; print('aiogram OK')"
```
---
## Step 11: Get Tokens
### Telegram Bot Token
1. Open Telegram
2. Find `@BotFather`
3. Send `/newbot`
4. Enter bot name and username
5. Copy the token
### Your Telegram User ID
1. Find `@userinfobot` in Telegram
2. Send any message
3. Copy the ID number
### Deepgram API Key
1. Go to https://console.deepgram.com/
2. Sign up (free $200 credit)
3. Settings → API Keys
4. Create key and copy
### Todoist API Token (optional)
1. Go to https://todoist.com/
2. Settings → Integrations → Developer
3. Copy API token
---
## Step 12: Configure Environment
```bash
nano ~/projects/agent-second-brain/.env
```
Paste (replace with your values):
```bash
TELEGRAM_BOT_TOKEN=7123456789:AAHdN8J2K4m5N6o7P8q9R0s1T2u3V4w5X6y
DEEPGRAM_API_KEY=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0
TODOIST_API_KEY=
VAULT_PATH=./vault
ALLOWED_USER_IDS=[123456789]
```
Save: `Ctrl+O`, `Enter`, `Ctrl+X`
---
## Step 13: Clean Vault Examples
```bash
cd ~/projects/agent-second-brain
rm -rf vault/daily/*
rm -rf vault/thoughts/ideas/*
rm -rf vault/thoughts/projects/*
rm -rf vault/thoughts/learnings/*
rm -rf vault/thoughts/reflections/*
rm -rf vault/summaries/*
rm -rf vault/attachments/*
```
---
## Step 14: Customize Goals
Edit goals to match yours:
```bash
nano vault/goals/0-vision-3y.md # 3-year vision
nano vault/goals/1-yearly-2026.md # Yearly goals
nano vault/goals/2-monthly.md # Monthly priorities
nano vault/goals/3-weekly.md # Weekly focus
```
---
## Step 15: Test Run
```bash
cd ~/projects/agent-second-brain
uv run python -m d_brain
```
Should show:
```
INFO:aiogram.dispatcher:Start polling
INFO:aiogram.dispatcher:Run polling for bot @your_bot_name
```
Test in Telegram:
- Find your bot
- Send `/start`
- Send a voice message
Stop with `Ctrl+C`.
---
## Step 16: Setup Autostart (systemd)
### Bot Service
```bash
sudo nano /etc/systemd/system/d-brain-bot.service
```
Paste (replace `myuser`):
```ini
[Unit]
Description=d-brain Telegram Bot
After=network.target
[Service]
Type=simple
User=myuser
WorkingDirectory=/home/myuser/projects/agent-second-brain
ExecStart=/home/myuser/.local/bin/uv run python -m d_brain
Restart=always
RestartSec=10
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
```
Enable and start:
```bash
sudo systemctl daemon-reload
sudo systemctl start d-brain-bot
sudo systemctl enable d-brain-bot
# Check status
sudo systemctl status d-brain-bot
```
---
## Step 17: Daily Processing Timer (optional)
Automatically process entries at 21:00 daily.
### Edit process script
```bash
nano ~/projects/agent-second-brain/scripts/process.sh
```
Update paths at the top:
```bash
export HOME="/home/myuser"
PROJECT_DIR="/home/myuser/projects/agent-second-brain"
```
Make executable:
```bash
chmod +x ~/projects/agent-second-brain/scripts/process.sh
```
### Create timer
```bash
sudo nano /etc/systemd/system/d-brain-process.timer
```
```ini
[Unit]
Description=Run d-brain processing daily at 21:00
[Timer]
OnCalendar=*-*-* 21:00:00
Persistent=true
[Install]
WantedBy=timers.target
```
### Create service
```bash
sudo nano /etc/systemd/system/d-brain-process.service
```
```ini
[Unit]
Description=d-brain Daily Processing
[Service]
Type=oneshot
User=myuser
WorkingDirectory=/home/myuser/projects/agent-second-brain
ExecStart=/home/myuser/projects/agent-second-brain/scripts/process.sh
Environment=PYTHONUNBUFFERED=1
```
### Enable
```bash
sudo systemctl daemon-reload
sudo systemctl enable d-brain-process.timer
sudo systemctl start d-brain-process.timer
# Check timer
sudo systemctl list-timers | grep d-brain
```
---
## Step 18: Git Configuration
```bash
cd ~/projects/agent-second-brain
git config user.email "your@email.com"
git config user.name "Your Name"
```
### Create your own repository
1. GitHub → "+" → "New repository"
2. Name: `my-second-brain`
3. Leave empty (no README)
4. Create
### Change remote
```bash
git remote set-url origin https://github.com/YOUR_USERNAME/my-second-brain.git
git remote -v
git push -u origin main
```
If prompted for password, use Personal Access Token:
- GitHub → Settings → Developer settings → Personal access tokens
---
## Useful Commands
```bash
# Bot status
sudo systemctl status d-brain-bot
# Restart bot
sudo systemctl restart d-brain-bot
# Stop bot
sudo systemctl stop d-brain-bot
# Real-time logs
sudo journalctl -u d-brain-bot -f
# Last 100 log lines
sudo journalctl -u d-brain-bot -n 100
# All d-brain services
sudo systemctl status 'd-brain-*'
# List timers
sudo systemctl list-timers
# Manual processing
cd ~/projects/agent-second-brain
./scripts/process.sh
# Update code
cd ~/projects/agent-second-brain
git pull
uv sync
sudo systemctl restart d-brain-bot
```
---
## Troubleshooting
### Bot doesn't respond
```bash
sudo systemctl status d-brain-bot
sudo journalctl -u d-brain-bot -n 100
cat ~/projects/agent-second-brain/.env | grep TELEGRAM_BOT_TOKEN
sudo systemctl restart d-brain-bot
```
### Voice not transcribing
```bash
cat ~/projects/agent-second-brain/.env | grep DEEPGRAM
sudo journalctl -u d-brain-bot | grep -i error
```
### Processing errors
```bash
claude --version
claude auth status
claude auth login # if needed
```
### Todoist not working
```bash
cat ~/projects/agent-second-brain/.env | grep TODOIST
mcp-cli call todoist find-tasks-by-date '{"startDate": "today"}'
```
### Permission errors
```bash
sudo chown -R myuser:myuser ~/projects/agent-second-brain
chmod -R 755 ~/projects/agent-second-brain
```
### Git push fails
```bash
git remote -v
git status
git config --global credential.helper store
git push
```
---
## Sync with Local Computer
See main [README](../README.md) for Obsidian sync options.
---
## Security Tips
- Use SSH keys instead of passwords
- Keep system updated: `sudo apt update && sudo apt upgrade`
- `.env` is in `.gitignore` — never commit tokens
- Consider setting up firewall: `sudo ufw enable`
Executable
+525
View File
@@ -0,0 +1,525 @@
#!/bin/bash
# Agent Second Brain — One-command installer
# Works on Mac and Windows WSL
# https://github.com/smixs/agent-second-brain
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Config
REPO_URL="https://github.com/smixs/agent-second-brain.git"
INSTALL_DIR="$HOME/agent-second-brain"
#######################################
# Print colored message
#######################################
info() { echo -e "${BLUE}ℹ${NC} $1"; }
success() { echo -e "${GREEN}✓${NC} $1"; }
warn() { echo -e "${YELLOW}⚠${NC} $1"; }
error() { echo -e "${RED}✗${NC} $1"; exit 1; }
#######################################
# Detect OS
#######################################
detect_os() {
if [[ "$OSTYPE" == "darwin"* ]]; then
OS="mac"
info "Detected: macOS"
elif grep -q Microsoft /proc/version 2>/dev/null; then
OS="wsl"
info "Detected: Windows WSL"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
OS="linux"
info "Detected: Linux"
else
error "Unsupported OS. This script works on Mac and Windows WSL only."
fi
}
#######################################
# Check if command exists
#######################################
has_command() {
command -v "$1" &> /dev/null
}
#######################################
# Install Homebrew (Mac only)
#######################################
install_homebrew() {
if [[ "$OS" != "mac" ]]; then return; fi
if has_command brew; then
success "Homebrew already installed"
else
info "Installing Homebrew..."
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Add to PATH for current session
if [[ -f /opt/homebrew/bin/brew ]]; then
eval "$(/opt/homebrew/bin/brew shellenv)"
elif [[ -f /usr/local/bin/brew ]]; then
eval "$(/usr/local/bin/brew shellenv)"
fi
success "Homebrew installed"
fi
}
#######################################
# Install dependencies
#######################################
install_dependencies() {
info "Installing dependencies..."
if [[ "$OS" == "mac" ]]; then
# Node.js
if ! has_command node; then
info "Installing Node.js..."
brew install node
fi
success "Node.js $(node --version)"
# Python 3.12
if ! has_command python3.12; then
info "Installing Python 3.12..."
brew install python@3.12
fi
success "Python $(python3.12 --version)"
# Git
if ! has_command git; then
info "Installing Git..."
brew install git
fi
success "Git $(git --version | head -1)"
elif [[ "$OS" == "wsl" ]] || [[ "$OS" == "linux" ]]; then
info "Updating apt packages..."
sudo apt update && sudo apt upgrade -y
# Node.js 20
if ! has_command node; then
info "Installing Node.js..."
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
fi
success "Node.js $(node --version)"
# Python 3.12
if ! has_command python3.12; then
info "Installing Python 3.12..."
sudo apt install -y software-properties-common
sudo add-apt-repository -y ppa:deadsnakes/ppa
sudo apt update
sudo apt install -y python3.12 python3.12-venv python3.12-dev
fi
success "Python $(python3.12 --version)"
# Git
if ! has_command git; then
info "Installing Git..."
sudo apt install -y git curl wget
fi
success "Git $(git --version | head -1)"
fi
}
#######################################
# Install uv (Python package manager)
#######################################
install_uv() {
if has_command uv; then
success "uv already installed: $(uv --version)"
else
info "Installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | sh
# Add to PATH for current session
export PATH="$HOME/.local/bin:$PATH"
success "uv installed: $(uv --version)"
fi
}
#######################################
# Install Claude Code CLI
#######################################
install_claude() {
if has_command claude; then
success "Claude Code already installed: $(claude --version)"
else
info "Installing Claude Code CLI..."
npm install -g @anthropic-ai/claude-code
success "Claude Code installed"
fi
}
#######################################
# Clone repository
#######################################
clone_repo() {
if [[ -d "$INSTALL_DIR" ]]; then
warn "Directory $INSTALL_DIR already exists"
read -p "Overwrite? (y/n): " -n 1 -r < /dev/tty
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
rm -rf "$INSTALL_DIR"
else
error "Installation cancelled"
fi
fi
info "Cloning repository..."
git clone "$REPO_URL" "$INSTALL_DIR"
success "Repository cloned to $INSTALL_DIR"
}
#######################################
# Prompt for token
#######################################
prompt_token() {
local name="$1"
local desc="$2"
local url="$3"
local var_name="$4"
local optional="${5:-false}"
echo
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}$name${NC}"
echo "$desc"
echo -e "Get it here: ${GREEN}$url${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
if [[ "$optional" == "true" ]]; then
read -p "Enter token (or press Enter to skip): " token < /dev/tty
else
while true; do
read -p "Enter token: " token < /dev/tty
if [[ -n "$token" ]]; then
break
fi
warn "This token is required"
done
fi
eval "$var_name=\"$token\""
}
#######################################
# Collect tokens interactively
#######################################
collect_tokens() {
echo
echo -e "${GREEN}╔════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ TOKEN CONFIGURATION ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════╝${NC}"
echo
echo "You'll need to provide 4 tokens. Instructions for each below."
# Telegram Bot Token
prompt_token \
"1/4: Telegram Bot Token" \
"Create a bot via @BotFather in Telegram:
1. Open Telegram and search for @BotFather
2. Send /newbot
3. Follow instructions to create your bot
4. Copy the token (looks like: 7123456789:AAHd...)" \
"https://t.me/BotFather" \
"TELEGRAM_BOT_TOKEN"
# Telegram User ID
prompt_token \
"2/4: Your Telegram User ID" \
"Get your ID via @userinfobot:
1. Search for @userinfobot in Telegram
2. Send any message
3. Copy your ID (just the number)" \
"https://t.me/userinfobot" \
"TELEGRAM_USER_ID"
# Deepgram API Key
prompt_token \
"3/4: Deepgram API Key" \
"For voice transcription (free \$200 credit):
1. Sign up at console.deepgram.com
2. Go to Settings → API Keys
3. Create new key and copy it" \
"https://console.deepgram.com/" \
"DEEPGRAM_API_KEY"
# Todoist API Token (optional)
prompt_token \
"4/4: Todoist API Token (optional)" \
"For task management:
1. Log in to todoist.com
2. Settings → Integrations → Developer
3. Copy the API token" \
"https://todoist.com/app/settings/integrations/developer" \
"TODOIST_API_KEY" \
"true"
}
#######################################
# Create .env file
#######################################
create_env() {
info "Creating .env file..."
cat > "$INSTALL_DIR/.env" << EOF
# Telegram Bot Token (from @BotFather)
TELEGRAM_BOT_TOKEN=$TELEGRAM_BOT_TOKEN
# Deepgram API Key (from console.deepgram.com)
DEEPGRAM_API_KEY=$DEEPGRAM_API_KEY
# Todoist API Token (optional)
TODOIST_API_KEY=$TODOIST_API_KEY
# Path to vault (don't change)
VAULT_PATH=./vault
# Your Telegram ID (bot responds only to you)
ALLOWED_USER_IDS=[$TELEGRAM_USER_ID]
EOF
success ".env file created"
}
#######################################
# Install Python dependencies
#######################################
install_python_deps() {
info "Installing Python dependencies..."
cd "$INSTALL_DIR"
uv sync
success "Python dependencies installed"
}
#######################################
# Install mcp-cli
#######################################
install_mcp_cli() {
if has_command mcp-cli; then
success "mcp-cli already installed"
else
info "Installing mcp-cli..."
curl -fsSL https://raw.githubusercontent.com/philschmid/mcp-cli/main/install.sh | bash
export PATH="$HOME/.local/bin:$PATH"
success "mcp-cli installed"
fi
# Configure mcp-cli for Todoist if token provided
if [[ -n "$TODOIST_API_KEY" ]]; then
info "Configuring mcp-cli for Todoist..."
mkdir -p ~/.config/mcp
cat > ~/.config/mcp/mcp_servers.json << EOF
{
"mcpServers": {
"todoist": {
"command": "npx",
"args": ["-y", "@doist/todoist-ai"],
"env": {
"TODOIST_API_KEY": "$TODOIST_API_KEY"
}
}
}
}
EOF
success "mcp-cli configured"
fi
}
#######################################
# Authenticate Claude
#######################################
auth_claude() {
echo
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}Claude Authentication${NC}"
echo "You need Claude Pro subscription (\$20/month) for this to work."
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo
if claude auth status &>/dev/null; then
success "Claude already authenticated"
else
info "Starting Claude authentication..."
echo "A browser window will open. Log in with your Anthropic account."
echo
claude auth login
success "Claude authenticated"
fi
}
#######################################
# Setup autostart (optional)
#######################################
setup_autostart() {
echo
read -p "Configure autostart (bot runs when computer starts)? (y/n): " -n 1 -r < /dev/tty
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
info "Skipping autostart configuration"
return
fi
if [[ "$OS" == "mac" ]]; then
setup_launchd
else
setup_systemd
fi
}
#######################################
# Setup launchd (Mac)
#######################################
setup_launchd() {
info "Configuring launchd..."
mkdir -p ~/Library/LaunchAgents
cat > ~/Library/LaunchAgents/com.agent-second-brain.plist << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.agent-second-brain</string>
<key>ProgramArguments</key>
<array>
<string>$HOME/.local/bin/uv</string>
<string>run</string>
<string>python</string>
<string>-m</string>
<string>d_brain</string>
</array>
<key>WorkingDirectory</key>
<string>$INSTALL_DIR</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>$INSTALL_DIR/logs/bot.log</string>
<key>StandardErrorPath</key>
<string>$INSTALL_DIR/logs/bot-error.log</string>
</dict>
</plist>
EOF
mkdir -p "$INSTALL_DIR/logs"
launchctl load ~/Library/LaunchAgents/com.agent-second-brain.plist
success "Autostart configured (launchd)"
info "Bot will start automatically on login"
}
#######################################
# Setup systemd (Linux/WSL)
#######################################
setup_systemd() {
info "Configuring systemd..."
mkdir -p ~/.config/systemd/user
cat > ~/.config/systemd/user/agent-second-brain.service << EOF
[Unit]
Description=Agent Second Brain Telegram Bot
After=network.target
[Service]
Type=simple
WorkingDirectory=$INSTALL_DIR
ExecStart=$HOME/.local/bin/uv run python -m d_brain
Restart=always
RestartSec=10
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=default.target
EOF
systemctl --user daemon-reload
systemctl --user enable agent-second-brain
systemctl --user start agent-second-brain
success "Autostart configured (systemd)"
info "Bot is running now and will start on boot"
}
#######################################
# Start bot manually
#######################################
start_bot() {
echo
echo -e "${GREEN}╔════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ INSTALLATION COMPLETE! ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════╝${NC}"
echo
if [[ "$OS" == "mac" ]] && [[ -f ~/Library/LaunchAgents/com.agent-second-brain.plist ]]; then
echo "Bot is running in background."
echo
echo "Commands:"
echo " Stop: launchctl unload ~/Library/LaunchAgents/com.agent-second-brain.plist"
echo " Start: launchctl load ~/Library/LaunchAgents/com.agent-second-brain.plist"
echo " Logs: tail -f $INSTALL_DIR/logs/bot.log"
elif systemctl --user is-active --quiet agent-second-brain 2>/dev/null; then
echo "Bot is running in background."
echo
echo "Commands:"
echo " Stop: systemctl --user stop agent-second-brain"
echo " Start: systemctl --user start agent-second-brain"
echo " Logs: journalctl --user -u agent-second-brain -f"
else
echo "To start the bot manually:"
echo
echo -e " ${GREEN}cd $INSTALL_DIR && uv run python -m d_brain${NC}"
echo
read -p "Start bot now? (y/n): " -n 1 -r < /dev/tty
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
cd "$INSTALL_DIR"
info "Starting bot... (Ctrl+C to stop)"
uv run python -m d_brain
fi
fi
}
#######################################
# Main
#######################################
main() {
echo
echo -e "${GREEN}╔════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ AGENT SECOND BRAIN INSTALLER ║${NC}"
echo -e "${GREEN}║ ║${NC}"
echo -e "${GREEN}║ Voice-first AI assistant with memory ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════╝${NC}"
echo
detect_os
install_homebrew
install_dependencies
install_uv
install_claude
clone_repo
collect_tokens
create_env
install_python_deps
install_mcp_cli
auth_claude
setup_autostart
start_bot
}
main "$@"
+9
View File
@@ -0,0 +1,9 @@
{
"mcpServers": {
"todoist": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@doist/todoist-ai"]
}
}
}
+52
View File
@@ -0,0 +1,52 @@
[project]
name = "agent-second-brain"
version = "1.0.0"
description = "Voice-first personal assistant for Telegram with Obsidian and Todoist integration"
readme = "README.md"
authors = [
{ name = "smixs", email = "mixshima@gmail.com" }
]
requires-python = ">=3.12"
dependencies = [
"aiogram>=3.0",
"deepgram-sdk",
"httpx",
"pydantic>=2.0",
"pydantic-settings",
"todoist-api-python>=3.1.0",
]
[project.optional-dependencies]
dev = [
"pytest",
"pytest-asyncio",
"ruff",
"mypy",
]
[build-system]
requires = ["uv_build>=0.9.7,<0.10.0"]
build-backend = "uv_build"
[tool.uv.build-backend]
module-name = "d_brain"
[tool.ruff]
line-length = 88
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]
[tool.mypy]
python_version = "3.12"
strict = true
[tool.pytest.ini_options]
asyncio_mode = "auto"
[dependency-groups]
dev = [
"pytest>=9.0.2",
"pytest-asyncio>=1.3.0",
]
+213
View File
@@ -0,0 +1,213 @@
#!/bin/bash
set -e
# PATH for systemd (claude, uv, npx, node)
export PATH="$HOME/.local/bin:$HOME/.nvm/versions/node/$(ls "$HOME/.nvm/versions/node/" 2>/dev/null | tail -1)/bin:/usr/local/bin:/usr/bin:/bin:$PATH"
# Paths — auto-detect from script location
PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
VAULT_DIR="$PROJECT_DIR/vault"
ENV_FILE="$PROJECT_DIR/.env"
# Load environment variables
if [ -f "$ENV_FILE" ]; then
export $(grep -v '^#' "$ENV_FILE" | xargs)
fi
# Check token
if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
echo "ERROR: TELEGRAM_BOT_TOKEN not set"
exit 1
fi
# Timezone (configure in .env: TZ=Your/Timezone)
export TZ="${TZ:-UTC}"
# Date and chat_id
TODAY=$(date +%Y-%m-%d)
CHAT_ID="${ALLOWED_USER_IDS//[\[\]]/}" # remove brackets from [123456]
echo "=== d-brain processing for $TODAY ==="
# ── ORIENT PHASE: pre-flight checks ──
DAILY_FILE="$VAULT_DIR/daily/$TODAY.md"
HANDOFF_FILE="$VAULT_DIR/.session/handoff.md"
GRAPH_FILE="$VAULT_DIR/.graph/vault-graph.json"
# Check daily file exists and has content
if [ ! -f "$DAILY_FILE" ]; then
echo "ORIENT: daily/$TODAY.md not found — creating empty file"
echo "# $TODAY" > "$DAILY_FILE"
fi
DAILY_SIZE=$(wc -c < "$DAILY_FILE" 2>/dev/null || echo "0")
if [ "$DAILY_SIZE" -lt 50 ]; then
echo "ORIENT: daily/$TODAY.md is empty ($DAILY_SIZE bytes) — skipping Claude processing"
echo "ORIENT: Running graph rebuild only"
# Still rebuild graph and commit
cd "$VAULT_DIR"
uv run .claude/skills/graph-builder/scripts/analyze.py || echo "Graph rebuild failed (non-critical)"
cd "$PROJECT_DIR"
git add -A
git commit -m "chore: process daily $TODAY" || true
git push || true
echo "=== Done (empty daily, graph-only) ==="
exit 0
fi
# Check handoff exists
if [ ! -f "$HANDOFF_FILE" ]; then
echo "ORIENT: handoff.md not found — creating stub"
mkdir -p "$VAULT_DIR/.session"
echo -e "---\nupdated: $(date -Iseconds)\n---\n\n## Last Session\n(none)\n\n## Observations" > "$HANDOFF_FILE"
fi
# Check graph freshness (warn if >7 days old)
if [ -f "$GRAPH_FILE" ]; then
GRAPH_AGE=$(( ($(date +%s) - $(stat -c %Y "$GRAPH_FILE" 2>/dev/null || stat -f %m "$GRAPH_FILE" 2>/dev/null || echo 0)) / 86400 ))
if [ "$GRAPH_AGE" -gt 7 ]; then
echo "ORIENT: vault-graph.json is $GRAPH_AGE days old (>7)"
fi
fi
echo "ORIENT: daily=$DAILY_SIZE bytes, handoff=OK, graph=OK"
# ── END ORIENT PHASE ──
# MCP timeout for stdio server (default 5 sec is too short)
export MCP_TIMEOUT=30000
export MAX_MCP_OUTPUT_TOKENS=50000
# ── 3-PHASE PIPELINE ──
# Phase 1: CAPTURE (classify entries → JSON)
# Phase 2: EXECUTE (create tasks, save thoughts → JSON)
# Phase 3: REFLECT (generate HTML report, update MEMORY)
# Each phase = fresh Claude context for better quality.
SESSION_DIR="$VAULT_DIR/.session"
mkdir -p "$SESSION_DIR"
CAPTURE_FILE="$SESSION_DIR/capture.json"
EXECUTE_FILE="$SESSION_DIR/execute.json"
# Find yearly goals file (auto-detect year)
YEARLY_GOALS=$(ls "$VAULT_DIR/goals/1-yearly-"*.md 2>/dev/null | tail -1)
YEARLY_GOALS_NAME=$(basename "$YEARLY_GOALS" 2>/dev/null || echo "1-yearly.md")
# MCP config (needed for Phase 2)
MCP_PROMPT="CRITICAL: MCP loads in 10-30 seconds. You are NOT in subprocess.
Algorithm: 1) Call. 2) Error? Wait 10 sec. 3) Call again. 4) Wait 20 sec. 5) Call — GUARANTEED to work.
DO NOT say MCP unavailable. It is available. Just wait and call."
cd "$VAULT_DIR"
# ── Phase 1: CAPTURE ──
echo "=== Phase 1: CAPTURE ==="
CAPTURE=$(claude --print --dangerously-skip-permissions \
-p "Today is $TODAY. Read .claude/skills/dbrain-processor/phases/capture.md and execute Phase 1.
Read daily/$TODAY.md, goals/3-weekly.md, goals/2-monthly.md, goals/$YEARLY_GOALS_NAME.
Classify each entry. Return ONLY JSON." \
2>&1) || true
# Extract JSON from output (Claude may add text around it)
echo "$CAPTURE" | grep -o '{.*}' | python3 -c "
import sys, json
for line in sys.stdin:
try:
data = json.loads(line.strip())
json.dump(data, sys.stdout, ensure_ascii=False, indent=2)
sys.exit(0)
except: pass
# Fallback: save raw output
sys.stdout.write('{\"error\": \"failed to parse capture output\", \"raw\": \"see capture.log\"}')
" > "$CAPTURE_FILE" 2>/dev/null || echo '{"error": "capture failed"}' > "$CAPTURE_FILE"
echo "Capture saved: $(wc -c < "$CAPTURE_FILE") bytes"
# Check if capture produced valid entries
if grep -q '"error"' "$CAPTURE_FILE"; then
echo "WARN: Capture phase had issues, falling back to monolith mode"
# Fallback to monolith processing
REPORT=$(claude --print --dangerously-skip-permissions \
--mcp-config "$PROJECT_DIR/mcp-config.json" \
-p "Today is $TODAY. Execute daily processing according to dbrain-processor skill.
$MCP_PROMPT" \
2>&1) || true
else
# ── Phase 2: EXECUTE ──
echo "=== Phase 2: EXECUTE ==="
EXECUTE=$(claude --print --dangerously-skip-permissions \
--mcp-config "$PROJECT_DIR/mcp-config.json" \
-p "Today is $TODAY. Read .claude/skills/dbrain-processor/phases/execute.md and execute Phase 2.
Read .session/capture.json for input data.
Read business/_index.md and projects/_index.md for context.
Create tasks in Todoist, save thoughts, update CRM. Return ONLY JSON.
$MCP_PROMPT" \
2>&1) || true
echo "$EXECUTE" | grep -o '{.*}' | python3 -c "
import sys, json
for line in sys.stdin:
try:
data = json.loads(line.strip())
json.dump(data, sys.stdout, ensure_ascii=False, indent=2)
sys.exit(0)
except: pass
sys.stdout.write('{\"error\": \"failed to parse execute output\"}')
" > "$EXECUTE_FILE" 2>/dev/null || echo '{"error": "execute failed"}' > "$EXECUTE_FILE"
echo "Execute saved: $(wc -c < "$EXECUTE_FILE") bytes"
# ── Phase 3: REFLECT ──
echo "=== Phase 3: REFLECT ==="
REPORT=$(claude --print --dangerously-skip-permissions \
-p "Today is $TODAY. Read .claude/skills/dbrain-processor/phases/reflect.md and execute Phase 3.
Read .session/capture.json and .session/execute.json for input data.
Read MEMORY.md, .session/handoff.md, .graph/health-history.json.
Generate HTML report, update MEMORY, record observations.
Return ONLY RAW HTML (for Telegram)." \
2>&1) || true
fi
cd "$PROJECT_DIR"
echo "=== Claude output ==="
echo "$REPORT"
echo "===================="
# Remove HTML comments (break Telegram HTML parser)
REPORT_CLEAN=$(echo "$REPORT" | sed '/<!--/,/-->/d')
# Rebuild vault graph (keeps structure up to date)
echo "=== Rebuilding vault graph ==="
cd "$VAULT_DIR"
uv run .claude/skills/graph-builder/scripts/analyze.py || echo "Graph rebuild failed (non-critical)"
# Memory decay (update relevance scores and tiers)
echo "=== Memory decay ==="
uv run .claude/skills/agent-memory/scripts/memory-engine.py decay . || echo "Memory decay failed (non-critical)"
cd "$PROJECT_DIR"
# Git commit
git add -A
git commit -m "chore: process daily $TODAY" || true
git push || true
# Send to Telegram
if [ -n "$REPORT_CLEAN" ] && [ -n "$CHAT_ID" ]; then
echo "=== Sending to Telegram ==="
RESULT=$(curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
-d "chat_id=$CHAT_ID" \
-d "text=$REPORT_CLEAN" \
-d "parse_mode=HTML")
# If HTML failed, send without formatting
if echo "$RESULT" | grep -q '"ok":false'; then
echo "HTML failed: $RESULT"
curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
-d "chat_id=$CHAT_ID" \
-d "text=$REPORT_CLEAN"
fi
fi
echo "=== Done ==="
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python
"""Weekly digest script - generates and sends to Telegram."""
import asyncio
import logging
import sys
from pathlib import Path
# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from aiogram import Bot
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from d_brain.config import get_settings
from d_brain.services.git import VaultGit
from d_brain.services.processor import ClaudeProcessor
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
async def main() -> None:
"""Generate weekly digest and send to Telegram."""
settings = get_settings()
processor = ClaudeProcessor(settings.vault_path, settings.todoist_api_key)
git = VaultGit(settings.vault_path)
logger.info("Starting weekly digest generation...")
result = processor.generate_weekly()
if "error" in result:
report = f"Error: {result['error']}"
logger.error("Weekly digest failed: %s", result["error"])
else:
report = result.get("report", "No output")
logger.info("Weekly digest generated successfully")
# Commit any changes
git.commit_and_push("chore: weekly digest")
# Send to Telegram
bot = Bot(
token=settings.telegram_bot_token,
default=DefaultBotProperties(parse_mode=ParseMode.HTML),
)
try:
user_id = settings.allowed_user_ids[0] if settings.allowed_user_ids else None
if not user_id:
logger.error("No allowed user IDs configured")
return
try:
await bot.send_message(chat_id=user_id, text=report)
except Exception:
# Fallback: send without HTML parsing
await bot.send_message(chat_id=user_id, text=report, parse_mode=None)
logger.info("Weekly digest sent to user %s", user_id)
finally:
await bot.session.close()
if __name__ == "__main__":
asyncio.run(main())
Executable
+641
View File
@@ -0,0 +1,641 @@
#!/bin/bash
# =============================================================================
# Agent Second Brain - VPS Setup Script
# =============================================================================
# One-command setup for your personal AI assistant
# Usage: curl -fsSL https://raw.githubusercontent.com/YOUR_USER/agent-second-brain/main/setup.sh | bash
# Or: bash setup.sh
# =============================================================================
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
BOLD='\033[1m'
# Emojis (safe for most terminals)
CHECK="[OK]"
CROSS="[X]"
WARN="[!]"
ARROW="-->"
GEAR="[*]"
# =============================================================================
# Helper functions
# =============================================================================
print_banner() {
echo ""
echo -e "${PURPLE}${BOLD}"
echo " ╔═══════════════════════════════════════════════════════════╗"
echo " ║ ║"
echo " ║ AGENT SECOND BRAIN - VPS SETUP ║"
echo " ║ ║"
echo " ║ Personal AI Assistant with Long-term Memory ║"
echo " ║ ║"
echo " ╚═══════════════════════════════════════════════════════════╝"
echo -e "${NC}"
echo ""
}
info() {
echo -e "${BLUE}${GEAR}${NC} $1"
}
success() {
echo -e "${GREEN}${CHECK}${NC} $1"
}
warn() {
echo -e "${YELLOW}${WARN}${NC} $1"
}
error() {
echo -e "${RED}${CROSS}${NC} $1"
}
step() {
echo ""
echo -e "${CYAN}${BOLD}${ARROW} $1${NC}"
echo -e "${CYAN}$(printf '%.0s─' {1..60})${NC}"
}
ask() {
echo -e "${YELLOW}?${NC} $1"
}
# =============================================================================
# Validation functions
# =============================================================================
validate_telegram_token() {
local token="$1"
# Telegram bot token format: 123456789:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
if [[ $token =~ ^[0-9]+:[A-Za-z0-9_-]+$ ]]; then
return 0
fi
return 1
}
validate_telegram_id() {
local id="$1"
# Telegram ID is a positive integer
if [[ $id =~ ^[0-9]+$ ]] && [ "$id" -gt 0 ]; then
return 0
fi
return 1
}
validate_deepgram_key() {
local key="$1"
# Deepgram key is alphanumeric, typically 40+ chars
if [[ $key =~ ^[A-Za-z0-9]+$ ]] && [ ${#key} -ge 20 ]; then
return 0
fi
return 1
}
validate_todoist_key() {
local key="$1"
# Todoist API token is alphanumeric, 40 chars
if [[ $key =~ ^[A-Za-z0-9]+$ ]] && [ ${#key} -ge 30 ]; then
return 0
fi
return 1
}
# =============================================================================
# Check functions
# =============================================================================
check_root() {
if [ "$EUID" -eq 0 ]; then
error "Do not run this script as root!"
echo " Create a regular user first: adduser myuser && usermod -aG sudo myuser"
echo " Then run: su - myuser && bash setup.sh"
exit 1
fi
}
check_os() {
if [ -f /etc/os-release ]; then
. /etc/os-release
if [[ "$ID" != "ubuntu" && "$ID" != "debian" ]]; then
warn "This script is tested on Ubuntu/Debian. You're running: $ID"
read -p "Continue anyway? (y/N): " -r REPLY
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
exit 1
fi
fi
fi
}
check_command() {
command -v "$1" &> /dev/null
}
# =============================================================================
# Installation functions
# =============================================================================
install_system_deps() {
step "Installing system dependencies"
info "Updating package list..."
sudo apt-get update -qq
info "Installing git, curl, wget, build-essential..."
sudo apt-get install -y -qq git curl wget build-essential software-properties-common
success "System dependencies installed"
}
install_python() {
step "Installing Python 3.12"
if check_command python3.12; then
success "Python 3.12 already installed"
return
fi
info "Adding deadsnakes PPA..."
sudo add-apt-repository -y ppa:deadsnakes/ppa
sudo apt-get update -qq
info "Installing Python 3.12..."
sudo apt-get install -y -qq python3.12 python3.12-venv python3.12-dev
success "Python 3.12 installed"
}
install_uv() {
step "Installing uv (Python package manager)"
if check_command uv; then
success "uv already installed"
return
fi
info "Downloading and installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | sh
# Add to current session
export PATH="$HOME/.local/bin:$PATH"
# Add to .bashrc if not already there
if ! grep -q 'export PATH="$HOME/.local/bin:$PATH"' ~/.bashrc 2>/dev/null; then
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
fi
success "uv installed"
}
install_nodejs() {
step "Installing Node.js 20"
if check_command node; then
NODE_VERSION=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -ge 18 ]; then
success "Node.js $(node --version) already installed"
return
fi
fi
info "Adding NodeSource repository..."
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
info "Installing Node.js..."
sudo apt-get install -y -qq nodejs
success "Node.js $(node --version) installed"
}
install_claude_cli() {
step "Installing Claude CLI"
if check_command claude; then
success "Claude CLI already installed: $(claude --version 2>/dev/null || echo 'version unknown')"
return
fi
info "Installing @anthropic-ai/claude-code globally..."
sudo npm install -g @anthropic-ai/claude-code
success "Claude CLI installed"
}
# =============================================================================
# Configuration functions
# =============================================================================
clone_repository() {
step "Setting up project"
PROJECTS_DIR="$HOME/projects"
PROJECT_DIR="$PROJECTS_DIR/agent-second-brain"
mkdir -p "$PROJECTS_DIR"
if [ -d "$PROJECT_DIR" ]; then
warn "Project directory already exists: $PROJECT_DIR"
read -p "Remove and re-clone? (y/N): " -r REPLY
if [[ $REPLY =~ ^[Yy]$ ]]; then
rm -rf "$PROJECT_DIR"
else
cd "$PROJECT_DIR"
success "Using existing directory"
return
fi
fi
ask "Enter your GitHub username (the one where you forked the repo):"
read -r GITHUB_USER
if [ -z "$GITHUB_USER" ]; then
error "GitHub username cannot be empty"
exit 1
fi
REPO_URL="https://github.com/$GITHUB_USER/agent-second-brain.git"
info "Cloning from $REPO_URL..."
if ! git clone "$REPO_URL" "$PROJECT_DIR" 2>/dev/null; then
error "Failed to clone repository!"
echo " Make sure you've forked the repo and the username is correct"
exit 1
fi
cd "$PROJECT_DIR"
success "Repository cloned to $PROJECT_DIR"
# Save GitHub user for later
echo "$GITHUB_USER" > .github_user
}
collect_tokens() {
step "Collecting API tokens"
echo ""
echo "You'll need these tokens (get them from the services):"
echo " - Telegram Bot Token (from @BotFather)"
echo " - Your Telegram ID (from @userinfobot)"
echo " - Deepgram API Key (from console.deepgram.com)"
echo " - Todoist API Token (from Todoist Settings > Integrations > Developer)"
echo ""
# Telegram Bot Token
while true; do
ask "Telegram Bot Token (from @BotFather):"
read -r TELEGRAM_BOT_TOKEN
if validate_telegram_token "$TELEGRAM_BOT_TOKEN"; then
success "Token format valid"
break
else
error "Invalid token format. Should be like: 123456789:ABC-DEF1234ghIkl-zyx57W2v"
fi
done
# Telegram User ID
while true; do
ask "Your Telegram User ID (from @userinfobot):"
read -r TELEGRAM_USER_ID
if validate_telegram_id "$TELEGRAM_USER_ID"; then
success "User ID valid"
break
else
error "Invalid User ID. Should be a number like: 123456789"
fi
done
# Deepgram API Key
while true; do
ask "Deepgram API Key (from console.deepgram.com):"
read -r DEEPGRAM_API_KEY
if validate_deepgram_key "$DEEPGRAM_API_KEY"; then
success "API Key format valid"
break
else
error "Invalid API key format. Should be alphanumeric, 20+ characters"
fi
done
# Todoist API Token
while true; do
ask "Todoist API Token (from Settings > Integrations > Developer):"
read -r TODOIST_API_KEY
if validate_todoist_key "$TODOIST_API_KEY"; then
success "API Token format valid"
break
else
error "Invalid API token format. Should be alphanumeric, 30+ characters"
fi
done
}
create_env_file() {
step "Creating .env file"
ENV_FILE="$PROJECT_DIR/.env"
if [ -f "$ENV_FILE" ]; then
warn ".env file already exists"
read -p "Overwrite? (y/N): " -r REPLY
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
success "Keeping existing .env"
return
fi
fi
cat > "$ENV_FILE" << EOF
# Telegram Bot API token from @BotFather
TELEGRAM_BOT_TOKEN=$TELEGRAM_BOT_TOKEN
# Deepgram API key for voice transcription
DEEPGRAM_API_KEY=$DEEPGRAM_API_KEY
# Todoist API key for task management
TODOIST_API_KEY=$TODOIST_API_KEY
# Path to Obsidian vault directory
VAULT_PATH=./vault
# JSON array of Telegram user IDs allowed to use the bot
ALLOWED_USER_IDS=[$TELEGRAM_USER_ID]
EOF
chmod 600 "$ENV_FILE"
success ".env file created (permissions: 600)"
}
install_dependencies() {
step "Installing Python dependencies"
cd "$PROJECT_DIR"
info "Running uv sync..."
"$HOME/.local/bin/uv" sync
success "Dependencies installed"
}
configure_systemd() {
step "Configuring systemd service"
SERVICE_FILE="/etc/systemd/system/d-brain-bot.service"
SERVICE_NAME="d-brain-bot"
# Generate service file content
SERVICE_CONTENT="[Unit]
Description=d-brain Telegram Bot
After=network.target
[Service]
Type=simple
User=$USER
WorkingDirectory=$PROJECT_DIR
ExecStart=$HOME/.local/bin/uv run python -m d_brain
Restart=always
RestartSec=10
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target"
info "Creating systemd service..."
echo "$SERVICE_CONTENT" | sudo tee "$SERVICE_FILE" > /dev/null
info "Reloading systemd daemon..."
sudo systemctl daemon-reload
info "Enabling service to start on boot..."
sudo systemctl enable "$SERVICE_NAME"
info "Starting service..."
sudo systemctl start "$SERVICE_NAME"
# Wait a moment for service to start
sleep 2
success "Systemd service configured"
}
configure_git_remote() {
step "Configuring Git for push access"
cd "$PROJECT_DIR"
# Set git config
git config user.name "Agent Second Brain Bot"
git config user.email "bot@localhost"
ask "Do you want to configure GitHub push access? (for auto-sync)"
read -p "(y/N): " -r REPLY
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
warn "Skipping GitHub push configuration"
return
fi
echo ""
echo "Create a Personal Access Token on GitHub:"
echo " 1. Go to: github.com > Settings > Developer settings > Personal access tokens > Tokens (classic)"
echo " 2. Generate new token with 'repo' scope"
echo " 3. Copy the token"
echo ""
ask "Enter your GitHub Personal Access Token:"
read -rs GITHUB_TOKEN
echo ""
if [ -z "$GITHUB_TOKEN" ]; then
warn "No token provided, skipping"
return
fi
GITHUB_USER=$(cat .github_user 2>/dev/null || echo "")
if [ -z "$GITHUB_USER" ]; then
ask "Enter your GitHub username:"
read -r GITHUB_USER
fi
git remote set-url origin "https://$GITHUB_TOKEN@github.com/$GITHUB_USER/agent-second-brain.git"
success "Git remote configured for push"
}
# =============================================================================
# Status and verification
# =============================================================================
check_status() {
step "Final status check"
ERRORS=()
WARNINGS=()
echo ""
# Check Python
if check_command python3.12; then
success "Python 3.12: $(python3.12 --version)"
else
ERRORS+=("Python 3.12 not found")
fi
# Check uv
if check_command uv || [ -f "$HOME/.local/bin/uv" ]; then
success "uv: $($HOME/.local/bin/uv --version 2>/dev/null || uv --version)"
else
ERRORS+=("uv not found")
fi
# Check Node.js
if check_command node; then
success "Node.js: $(node --version)"
else
ERRORS+=("Node.js not found")
fi
# Check Claude CLI
if check_command claude; then
success "Claude CLI: installed"
else
WARNINGS+=("Claude CLI not found (needed for AI processing)")
fi
# Check .env
if [ -f "$PROJECT_DIR/.env" ]; then
success ".env file: exists"
else
ERRORS+=(".env file not found")
fi
# Check systemd service
if systemctl is-active --quiet d-brain-bot; then
success "Bot service: running"
else
STATUS=$(systemctl is-active d-brain-bot 2>/dev/null || echo "unknown")
ERRORS+=("Bot service not running (status: $STATUS)")
fi
echo ""
# Summary
if [ ${#ERRORS[@]} -eq 0 ] && [ ${#WARNINGS[@]} -eq 0 ]; then
echo -e "${GREEN}${BOLD}"
echo " ╔═══════════════════════════════════════════════════════════╗"
echo " ║ ║"
echo " ║ SETUP COMPLETE! ║"
echo " ║ ║"
echo " ╚═══════════════════════════════════════════════════════════╝"
echo -e "${NC}"
echo ""
echo " Next steps:"
echo " 1. Open Telegram and find your bot"
echo " 2. Send /start to test"
echo " 3. Send a voice message!"
echo ""
echo " Useful commands:"
echo " - View logs: sudo journalctl -u d-brain-bot -f"
echo " - Restart bot: sudo systemctl restart d-brain-bot"
echo " - Stop bot: sudo systemctl stop d-brain-bot"
echo ""
else
if [ ${#ERRORS[@]} -gt 0 ]; then
echo -e "${RED}${BOLD}ERRORS:${NC}"
for err in "${ERRORS[@]}"; do
error "$err"
done
echo ""
fi
if [ ${#WARNINGS[@]} -gt 0 ]; then
echo -e "${YELLOW}${BOLD}WARNINGS:${NC}"
for wrn in "${WARNINGS[@]}"; do
warn "$wrn"
done
echo ""
fi
echo "Troubleshooting:"
echo " - Check logs: sudo journalctl -u d-brain-bot -n 50"
echo " - Check .env: cat $PROJECT_DIR/.env"
echo " - Manual start: cd $PROJECT_DIR && uv run python -m d_brain"
echo ""
fi
}
authorize_claude() {
step "Claude CLI Authorization"
if claude auth status 2>/dev/null | grep -q "Logged in"; then
success "Claude CLI already authorized"
return
fi
warn "Claude CLI needs authorization"
echo ""
echo "Run this command manually:"
echo -e " ${CYAN}claude auth login${NC}"
echo ""
echo "This will open a browser for authentication."
echo "After authorizing, the bot will be able to use Claude for AI processing."
echo ""
}
# =============================================================================
# Main script
# =============================================================================
main() {
print_banner
check_root
check_os
echo "This script will:"
echo " 1. Install required software (Python, Node.js, uv, Claude CLI)"
echo " 2. Clone your fork of the repository"
echo " 3. Ask for your API tokens"
echo " 4. Create configuration files"
echo " 5. Set up auto-start service"
echo ""
read -p "Ready to start? (Y/n): " -r REPLY
if [[ $REPLY =~ ^[Nn]$ ]]; then
echo "Setup cancelled."
exit 0
fi
# Installation
install_system_deps
install_python
install_uv
install_nodejs
install_claude_cli
# Configuration
clone_repository
collect_tokens
create_env_file
install_dependencies
configure_systemd
configure_git_remote
authorize_claude
# Final check
check_status
}
# Run main if script is executed (not sourced)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
+3
View File
@@ -0,0 +1,3 @@
"""d-brain: Voice-first system for capturing thoughts and tasks."""
__version__ = "0.1.0"
+28
View File
@@ -0,0 +1,28 @@
"""Entry point for running d-brain as a module."""
import asyncio
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
async def main() -> None:
"""Main entry point."""
from d_brain.bot.main import run_bot
from d_brain.config import get_settings
settings = get_settings()
logger.info("d-brain starting...")
logger.info("Vault path: %s", settings.vault_path)
logger.info("Allowed users: %s", settings.allowed_user_ids or "all")
await run_bot(settings)
if __name__ == "__main__":
asyncio.run(main())
+1
View File
@@ -0,0 +1 @@
"""Telegram bot module."""
+202
View File
@@ -0,0 +1,202 @@
"""Report formatters for Telegram messages."""
import html
import re
from typing import Any
# Allowed HTML tags in Telegram
ALLOWED_TAGS = {"b", "i", "code", "pre", "a", "s", "u"}
def sanitize_telegram_html(text: str) -> str:
"""Sanitize HTML for Telegram, keeping only allowed tags.
Telegram supports: <b>, <i>, <code>, <pre>, <a>, <s>, <u>
Args:
text: Raw HTML text from Claude
Returns:
Sanitized HTML safe for Telegram
"""
if not text:
return ""
# First, escape any raw < > that are not part of tags
# This regex matches < or > not followed/preceded by tag patterns
result = []
i = 0
while i < len(text):
if text[i] == "<":
# Check if this looks like a valid tag
tag_match = re.match(r"</?([a-zA-Z]+)(?:\s[^>]*)?>", text[i:])
if tag_match:
tag_name = tag_match.group(1).lower()
if tag_name in ALLOWED_TAGS:
# Keep the allowed tag
result.append(tag_match.group(0))
i += len(tag_match.group(0))
continue
else:
# Escape disallowed tag
result.append("&lt;")
i += 1
continue
else:
# Not a valid tag pattern, escape
result.append("&lt;")
i += 1
continue
elif text[i] == ">":
# Standalone > should be escaped
result.append("&gt;")
i += 1
elif text[i] == "&":
# Check if already escaped
entity_match = re.match(r"&(amp|lt|gt|quot|#\d+|#x[0-9a-fA-F]+);", text[i:])
if entity_match:
result.append(entity_match.group(0))
i += len(entity_match.group(0))
else:
result.append("&amp;")
i += 1
else:
result.append(text[i])
i += 1
return "".join(result)
def validate_telegram_html(text: str) -> bool:
"""Validate that HTML tags are properly closed.
Args:
text: HTML text to validate
Returns:
True if valid, False otherwise
"""
tag_stack = []
tag_pattern = re.compile(r"<(/?)([a-zA-Z]+)(?:\s[^>]*)?>")
for match in tag_pattern.finditer(text):
is_closing = match.group(1) == "/"
tag_name = match.group(2).lower()
if tag_name not in ALLOWED_TAGS:
continue
if is_closing:
if not tag_stack or tag_stack[-1] != tag_name:
return False
tag_stack.pop()
else:
tag_stack.append(tag_name)
return len(tag_stack) == 0
def truncate_html(text: str, max_length: int = 4096) -> str:
"""Truncate HTML text while keeping tags balanced.
Args:
text: HTML text
max_length: Maximum length (Telegram limit is 4096)
Returns:
Truncated text with balanced tags
"""
if len(text) <= max_length:
return text
# Find a safe cut point
cut_point = max_length - 50 # Leave room for closing tags and ellipsis
# Don't cut in the middle of a tag
last_open = text.rfind("<", 0, cut_point)
last_close = text.rfind(">", 0, cut_point)
if last_open > last_close:
# We're in the middle of a tag, cut before it
cut_point = last_open
truncated = text[:cut_point]
# Close any open tags
tag_pattern = re.compile(r"<(/?)([a-zA-Z]+)(?:\s[^>]*)?>")
open_tags = []
for match in tag_pattern.finditer(truncated):
is_closing = match.group(1) == "/"
tag_name = match.group(2).lower()
if tag_name not in ALLOWED_TAGS:
continue
if is_closing and open_tags and open_tags[-1] == tag_name:
open_tags.pop()
elif not is_closing:
open_tags.append(tag_name)
# Add closing tags in reverse order
closing_tags = "".join(f"</{tag}>" for tag in reversed(open_tags))
return truncated + "..." + closing_tags
def format_process_report(report: dict[str, Any]) -> str:
"""Format processing report for Telegram HTML.
The report from Claude is expected to be in HTML format.
We sanitize it to ensure only Telegram-safe tags are used.
Args:
report: Processing report from ClaudeProcessor
Returns:
Formatted HTML message for Telegram
"""
if "error" in report:
error_msg = html.escape(str(report["error"]))
return f"❌ <b>Ошибка:</b> {error_msg}"
if "report" in report:
raw_report = report["report"]
# Sanitize HTML, keeping allowed tags
sanitized = sanitize_telegram_html(raw_report)
# Validate tag balance
if not validate_telegram_html(sanitized):
# Fall back to plain text if tags are broken
return html.escape(raw_report)
# Truncate if too long
return truncate_html(sanitized, max_length=4096)
return "✅ <b>Обработка завершена</b>"
def format_error(error: str) -> str:
"""Format error message for Telegram.
Args:
error: Error message
Returns:
Formatted HTML error message
"""
return f"❌ <b>Ошибка:</b> {html.escape(error)}"
def format_empty_daily() -> str:
"""Format message for empty daily file.
Returns:
Formatted HTML message
"""
return (
"📭 <b>Нет записей для обработки</b>\n\n"
"<i>Добавьте голосовые сообщения или текст в течение дня</i>"
)
+25
View File
@@ -0,0 +1,25 @@
"""Bot message handlers."""
from d_brain.bot.handlers import (
buttons,
commands,
do,
forward,
photo,
process,
text,
voice,
weekly,
)
__all__ = [
"buttons",
"commands",
"do",
"forward",
"photo",
"process",
"text",
"voice",
"weekly",
]
+51
View File
@@ -0,0 +1,51 @@
"""Button handlers for reply keyboard."""
from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import Message
from d_brain.bot.states import DoCommandState
router = Router(name="buttons")
@router.message(F.text == "📊 Статус")
async def btn_status(message: Message) -> None:
"""Handle Status button."""
from d_brain.bot.handlers.commands import cmd_status
await cmd_status(message)
@router.message(F.text == "⚙️ Обработать")
async def btn_process(message: Message) -> None:
"""Handle Process button."""
from d_brain.bot.handlers.process import cmd_process
await cmd_process(message)
@router.message(F.text == "📅 Неделя")
async def btn_weekly(message: Message) -> None:
"""Handle Weekly button."""
from d_brain.bot.handlers.weekly import cmd_weekly
await cmd_weekly(message)
@router.message(F.text == "✨ Запрос")
async def btn_do(message: Message, state: FSMContext) -> None:
"""Handle Do button - set state and wait for input."""
await state.set_state(DoCommandState.waiting_for_input)
await message.answer(
"🎯 <b>Что сделать?</b>\n\n"
"Отправь голосовое или текстовое сообщение с запросом."
)
@router.message(F.text == "❓ Помощь")
async def btn_help(message: Message) -> None:
"""Handle Help button."""
from d_brain.bot.handlers.commands import cmd_help
await cmd_help(message)
+102
View File
@@ -0,0 +1,102 @@
"""Command handlers for /start, /help, /status."""
from datetime import date
from aiogram import Router
from aiogram.filters import Command
from aiogram.types import Message
from d_brain.bot.keyboards import get_main_keyboard
from d_brain.config import get_settings
from d_brain.services.session import SessionStore
from d_brain.services.storage import VaultStorage
router = Router(name="commands")
@router.message(Command("start"))
async def cmd_start(message: Message) -> None:
"""Handle /start command."""
await message.answer(
"<b>d-brain</b> - твой голосовой дневник\n\n"
"Отправляй мне:\n"
"🎤 Голосовые сообщения\n"
"💬 Текст\n"
"📷 Фото\n"
"↩️ Пересланные сообщения\n\n"
"Всё будет сохранено и обработано.\n\n"
"<b>Команды:</b>\n"
"/status - статус сегодняшнего дня\n"
"/process - обработать записи\n"
"/do - выполнить произвольный запрос\n"
"/weekly - недельный дайджест\n"
"/help - справка",
reply_markup=get_main_keyboard(),
)
@router.message(Command("help"))
async def cmd_help(message: Message) -> None:
"""Handle /help command."""
await message.answer(
"<b>Как использовать d-brain:</b>\n\n"
"1. Отправь голосовое — я транскрибирую и сохраню\n"
"2. Отправь текст — сохраню как есть\n"
"3. Отправь фото — сохраню в attachments\n"
"4. Перешли сообщение — сохраню с источником\n\n"
"Вечером используй /process для обработки:\n"
"Мысли → Obsidian, Задачи → Todoist\n\n"
"<b>Команды:</b>\n"
"/status - сколько записей сегодня\n"
"/process - обработать записи\n"
"/do - выполнить произвольный запрос\n"
"/weekly - недельный дайджест\n\n"
"<i>Пример: /do перенеси просроченные задачи на понедельник</i>"
)
@router.message(Command("status"))
async def cmd_status(message: Message) -> None:
"""Handle /status command."""
user_id = message.from_user.id if message.from_user else 0
settings = get_settings()
storage = VaultStorage(settings.vault_path)
# Log command
session = SessionStore(settings.vault_path)
session.append(user_id, "command", cmd="/status")
today = date.today()
content = storage.read_daily(today)
if not content:
await message.answer(f"📅 <b>{today}</b>\n\nЗаписей пока нет.")
return
lines = content.strip().split("\n")
entries = [line for line in lines if line.startswith("## ")]
voice_count = sum(1 for e in entries if "[voice]" in e)
text_count = sum(1 for e in entries if "[text]" in e)
photo_count = sum(1 for e in entries if "[photo]" in e)
forward_count = sum(1 for e in entries if "[forward from:" in e)
total = len(entries)
# Get weekly stats from session
week_stats = ""
stats = session.get_stats(user_id, days=7)
if stats:
week_stats = "\n\n<b>За 7 дней:</b>"
for entry_type, count in sorted(stats.items()):
week_stats += f"\n• {entry_type}: {count}"
await message.answer(
f"📅 <b>{today}</b>\n\n"
f"Всего записей: <b>{total}</b>\n"
f"- 🎤 Голосовых: {voice_count}\n"
f"- 💬 Текстовых: {text_count}\n"
f"- 📷 Фото: {photo_count}\n"
f"- ↩️ Пересланных: {forward_count}"
f"{week_stats}"
)
+122
View File
@@ -0,0 +1,122 @@
"""Handler for /do command - arbitrary Claude requests."""
import asyncio
import logging
from aiogram import Bot, Router
from aiogram.filters import Command, CommandObject
from aiogram.fsm.context import FSMContext
from aiogram.types import Message
from d_brain.bot.formatters import format_process_report
from d_brain.bot.states import DoCommandState
from d_brain.config import get_settings
from d_brain.services.processor import ClaudeProcessor
from d_brain.services.transcription import DeepgramTranscriber
router = Router(name="do")
logger = logging.getLogger(__name__)
@router.message(Command("do"))
async def cmd_do(message: Message, command: CommandObject, state: FSMContext) -> None:
"""Handle /do command."""
user_id = message.from_user.id if message.from_user else 0
# Check for inline text: /do move overdue tasks
if command.args:
await process_request(message, command.args, user_id)
return
# Otherwise, wait for next message
await state.set_state(DoCommandState.waiting_for_input)
await message.answer(
"🎯 <b>Что сделать?</b>\n\n"
"Отправь голосовое или текстовое сообщение с запросом."
)
@router.message(DoCommandState.waiting_for_input)
async def handle_do_input(message: Message, bot: Bot, state: FSMContext) -> None:
"""Handle voice/text input after /do command."""
await state.clear() # Clear state immediately
prompt = None
# Handle voice input
if message.voice:
await message.chat.do(action="typing")
settings = get_settings()
transcriber = DeepgramTranscriber(settings.deepgram_api_key)
try:
file = await bot.get_file(message.voice.file_id)
if not file.file_path:
await message.answer("❌ Не удалось скачать голосовое")
return
file_bytes = await bot.download_file(file.file_path)
if not file_bytes:
await message.answer("❌ Не удалось скачать голосовое")
return
audio_bytes = file_bytes.read()
prompt = await transcriber.transcribe(audio_bytes)
except Exception as e:
logger.exception("Failed to transcribe voice for /do")
await message.answer(f"❌ Не удалось транскрибировать: {e}")
return
if not prompt:
await message.answer("❌ Не удалось распознать речь")
return
# Echo transcription to user
await message.answer(f"🎤 <i>{prompt}</i>")
# Handle text input
elif message.text:
prompt = message.text
else:
await message.answer("❌ Отправь текст или голосовое сообщение")
return
user_id = message.from_user.id if message.from_user else 0
await process_request(message, prompt, user_id)
async def process_request(message: Message, prompt: str, user_id: int = 0) -> None:
"""Process the user's request with Claude."""
status_msg = await message.answer("⏳ Выполняю...")
settings = get_settings()
processor = ClaudeProcessor(settings.vault_path, settings.todoist_api_key)
async def run_with_progress() -> dict:
task = asyncio.create_task(
asyncio.to_thread(processor.execute_prompt, prompt, user_id)
)
elapsed = 0
while not task.done():
await asyncio.sleep(30)
elapsed += 30
if not task.done():
try:
await status_msg.edit_text(
f"⏳ Выполняю... ({elapsed // 60}m {elapsed % 60}s)"
)
except Exception:
pass
return await task
report = await run_with_progress()
formatted = format_process_report(report)
try:
await status_msg.edit_text(formatted)
except Exception:
# Fallback: send without HTML parsing
await status_msg.edit_text(formatted, parse_mode=None)
+58
View File
@@ -0,0 +1,58 @@
"""Forwarded message handler."""
import logging
from datetime import datetime
from aiogram import Router
from aiogram.types import Message
from d_brain.config import get_settings
from d_brain.services.session import SessionStore
from d_brain.services.storage import VaultStorage
router = Router(name="forward")
logger = logging.getLogger(__name__)
@router.message(lambda m: m.forward_origin is not None)
async def handle_forward(message: Message) -> None:
"""Handle forwarded messages."""
if not message.from_user:
return
settings = get_settings()
storage = VaultStorage(settings.vault_path)
# Determine source name
source_name = "Unknown"
origin = message.forward_origin
if hasattr(origin, "sender_user") and origin.sender_user:
user = origin.sender_user
source_name = user.full_name
elif hasattr(origin, "sender_user_name") and origin.sender_user_name:
source_name = origin.sender_user_name
elif hasattr(origin, "chat") and origin.chat:
chat = origin.chat
source_name = f"@{chat.username}" if chat.username else chat.title or "Channel"
elif hasattr(origin, "sender_name") and origin.sender_name:
source_name = origin.sender_name
content = message.text or message.caption or "[media]"
msg_type = f"[forward from: {source_name}]"
timestamp = datetime.fromtimestamp(message.date.timestamp())
storage.append_to_daily(content, timestamp, msg_type)
# Log to session
session = SessionStore(settings.vault_path)
session.append(
message.from_user.id,
"forward",
text=content,
source=source_name,
msg_id=message.message_id,
)
await message.answer(f"✓ Сохранено (от {source_name})")
logger.info("Forwarded message saved from: %s", source_name)
+78
View File
@@ -0,0 +1,78 @@
"""Photo message handler."""
import logging
from datetime import datetime
from aiogram import Bot, Router
from aiogram.types import Message
from d_brain.config import get_settings
from d_brain.services.session import SessionStore
from d_brain.services.storage import VaultStorage
router = Router(name="photo")
logger = logging.getLogger(__name__)
@router.message(lambda m: m.photo is not None)
async def handle_photo(message: Message, bot: Bot) -> None:
"""Handle photo messages."""
if not message.photo or not message.from_user:
return
settings = get_settings()
storage = VaultStorage(settings.vault_path)
# Get largest photo
photo = message.photo[-1]
try:
file = await bot.get_file(photo.file_id)
if not file.file_path:
await message.answer("Failed to download photo")
return
file_bytes = await bot.download_file(file.file_path)
if not file_bytes:
await message.answer("Failed to download photo")
return
timestamp = datetime.fromtimestamp(message.date.timestamp())
photo_bytes = file_bytes.read()
# Determine extension from file path
extension = "jpg"
if file.file_path and "." in file.file_path:
extension = file.file_path.rsplit(".", 1)[-1]
# Save photo and get relative path
relative_path = storage.save_attachment(
photo_bytes,
timestamp.date(),
timestamp,
extension,
)
# Create content with Obsidian embed
content = f"![[{relative_path}]]"
if message.caption:
content += f"\n\n{message.caption}"
storage.append_to_daily(content, timestamp, "[photo]")
# Log to session
session = SessionStore(settings.vault_path)
session.append(
message.from_user.id,
"photo",
path=relative_path,
caption=message.caption,
msg_id=message.message_id,
)
await message.answer("📷 ✓ Сохранено")
logger.info("Photo saved: %s", relative_path)
except Exception as e:
logger.exception("Error processing photo")
await message.answer(f"Error: {e}")
+65
View File
@@ -0,0 +1,65 @@
"""Process command handler."""
import asyncio
import logging
from datetime import date
from aiogram import Router
from aiogram.filters import Command
from aiogram.types import Message
from d_brain.bot.formatters import format_process_report
from d_brain.config import get_settings
from d_brain.services.git import VaultGit
from d_brain.services.processor import ClaudeProcessor
router = Router(name="process")
logger = logging.getLogger(__name__)
@router.message(Command("process"))
async def cmd_process(message: Message) -> None:
"""Handle /process command - trigger Claude processing."""
user_id = message.from_user.id if message.from_user else "unknown"
logger.info("Process command triggered by user %s", user_id)
status_msg = await message.answer("⏳ Processing... (may take up to 10 min)")
settings = get_settings()
processor = ClaudeProcessor(settings.vault_path, settings.todoist_api_key)
git = VaultGit(settings.vault_path)
# Run subprocess in thread to avoid blocking event loop
async def process_with_progress() -> dict:
task = asyncio.create_task(
asyncio.to_thread(processor.process_daily, date.today())
)
elapsed = 0
while not task.done():
await asyncio.sleep(30)
elapsed += 30
if not task.done():
try:
await status_msg.edit_text(
f"⏳ Processing... ({elapsed // 60}m {elapsed % 60}s)"
)
except Exception:
pass # Ignore edit errors
return await task
report = await process_with_progress()
# Commit and push changes
if "error" not in report:
today = date.today().isoformat()
await asyncio.to_thread(git.commit_and_push, f"chore: process daily {today}")
# Format and send report
formatted = format_process_report(report)
try:
await status_msg.edit_text(formatted)
except Exception:
# Fallback: send without HTML parsing
await status_msg.edit_text(formatted, parse_mode=None)
+39
View File
@@ -0,0 +1,39 @@
"""Text message handler."""
import logging
from datetime import datetime
from aiogram import Router
from aiogram.types import Message
from d_brain.config import get_settings
from d_brain.services.session import SessionStore
from d_brain.services.storage import VaultStorage
router = Router(name="text")
logger = logging.getLogger(__name__)
@router.message(lambda m: m.text is not None and not m.text.startswith("/"))
async def handle_text(message: Message) -> None:
"""Handle text messages (excluding commands)."""
if not message.text or not message.from_user:
return
settings = get_settings()
storage = VaultStorage(settings.vault_path)
timestamp = datetime.fromtimestamp(message.date.timestamp())
storage.append_to_daily(message.text, timestamp, "[text]")
# Log to session
session = SessionStore(settings.vault_path)
session.append(
message.from_user.id,
"text",
text=message.text,
msg_id=message.message_id,
)
await message.answer("✓ Сохранено")
logger.info("Text message saved: %d chars", len(message.text))
+66
View File
@@ -0,0 +1,66 @@
"""Voice message handler."""
import logging
from datetime import datetime
from aiogram import Bot, Router
from aiogram.types import Message
from d_brain.config import get_settings
from d_brain.services.session import SessionStore
from d_brain.services.storage import VaultStorage
from d_brain.services.transcription import DeepgramTranscriber
router = Router(name="voice")
logger = logging.getLogger(__name__)
@router.message(lambda m: m.voice is not None)
async def handle_voice(message: Message, bot: Bot) -> None:
"""Handle voice messages."""
if not message.voice or not message.from_user:
return
await message.chat.do(action="typing")
settings = get_settings()
storage = VaultStorage(settings.vault_path)
transcriber = DeepgramTranscriber(settings.deepgram_api_key)
try:
file = await bot.get_file(message.voice.file_id)
if not file.file_path:
await message.answer("Failed to download voice message")
return
file_bytes = await bot.download_file(file.file_path)
if not file_bytes:
await message.answer("Failed to download voice message")
return
audio_bytes = file_bytes.read()
transcript = await transcriber.transcribe(audio_bytes)
if not transcript:
await message.answer("Could not transcribe audio")
return
timestamp = datetime.fromtimestamp(message.date.timestamp())
storage.append_to_daily(transcript, timestamp, "[voice]")
# Log to session
session = SessionStore(settings.vault_path)
session.append(
message.from_user.id,
"voice",
text=transcript,
duration=message.voice.duration,
msg_id=message.message_id,
)
await message.answer(f"🎤 {transcript}\n\n✓ Сохранено")
logger.info("Voice message saved: %d chars", len(transcript))
except Exception as e:
logger.exception("Error processing voice message")
await message.answer(f"Error: {e}")
+60
View File
@@ -0,0 +1,60 @@
"""Weekly digest command handler."""
import asyncio
import logging
from aiogram import Router
from aiogram.filters import Command
from aiogram.types import Message
from d_brain.bot.formatters import format_process_report
from d_brain.config import get_settings
from d_brain.services.git import VaultGit
from d_brain.services.processor import ClaudeProcessor
router = Router(name="weekly")
logger = logging.getLogger(__name__)
@router.message(Command("weekly"))
async def cmd_weekly(message: Message) -> None:
"""Handle /weekly command - generate weekly digest."""
user_id = message.from_user.id if message.from_user else "unknown"
logger.info("Weekly digest triggered by user %s", user_id)
status_msg = await message.answer("⏳ Генерирую недельный дайджест...")
settings = get_settings()
processor = ClaudeProcessor(settings.vault_path, settings.todoist_api_key)
git = VaultGit(settings.vault_path)
async def run_with_progress() -> dict:
task = asyncio.create_task(
asyncio.to_thread(processor.generate_weekly)
)
elapsed = 0
while not task.done():
await asyncio.sleep(30)
elapsed += 30
if not task.done():
try:
await status_msg.edit_text(
f"⏳ Генерирую дайджест... ({elapsed // 60}m {elapsed % 60}s)"
)
except Exception:
pass
return await task
report = await run_with_progress()
# Commit any changes (weekly goal updates, etc)
if "error" not in report:
await asyncio.to_thread(git.commit_and_push, "chore: weekly digest")
formatted = format_process_report(report)
try:
await status_msg.edit_text(formatted)
except Exception:
await status_msg.edit_text(formatted, parse_mode=None)
+18
View File
@@ -0,0 +1,18 @@
"""Reply keyboards for Telegram bot."""
from aiogram.types import ReplyKeyboardMarkup
from aiogram.utils.keyboard import ReplyKeyboardBuilder
def get_main_keyboard() -> ReplyKeyboardMarkup:
"""Main reply keyboard with common commands."""
builder = ReplyKeyboardBuilder()
# First row: main commands
builder.button(text="📊 Статус")
builder.button(text="⚙️ Обработать")
builder.button(text="📅 Неделя")
# Second row: additional
builder.button(text="✨ Запрос")
builder.button(text="❓ Помощь")
builder.adjust(3, 2) # 3 in first row, 2 in second
return builder.as_markup(resize_keyboard=True, is_persistent=True)
+95
View File
@@ -0,0 +1,95 @@
"""Telegram bot initialization and polling."""
import logging
from collections.abc import Awaitable, Callable
from typing import Any
from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.types import Update
from d_brain.config import Settings
logger = logging.getLogger(__name__)
def create_bot(settings: Settings) -> Bot:
"""Create and configure the Telegram bot."""
return Bot(
token=settings.telegram_bot_token,
default=DefaultBotProperties(parse_mode=ParseMode.HTML),
)
def create_dispatcher() -> Dispatcher:
"""Create and configure the dispatcher with routers."""
from d_brain.bot.handlers import buttons, commands, do, forward, photo, process, text, voice, weekly
# Use memory storage for FSM (required for /do command state)
dp = Dispatcher(storage=MemoryStorage())
# Register routers - ORDER MATTERS
dp.include_router(commands.router)
dp.include_router(process.router)
dp.include_router(weekly.router)
dp.include_router(do.router) # Before voice/text to catch FSM state
dp.include_router(buttons.router) # Reply keyboard buttons
dp.include_router(voice.router)
dp.include_router(photo.router)
dp.include_router(forward.router)
dp.include_router(text.router) # Must be last (catch-all for text)
return dp
MiddlewareHandler = Callable[[Update, dict[str, Any]], Awaitable[Any]]
MiddlewareType = Callable[[MiddlewareHandler, Update, dict[str, Any]], Awaitable[Any]]
def create_auth_middleware(settings: Settings) -> MiddlewareType:
"""Create middleware to check user authorization."""
async def auth_middleware(
handler: Callable[[Update, dict[str, Any]], Awaitable[Any]],
event: Update,
data: dict[str, Any],
) -> Any:
# If explicitly allowed all users, just bypass check
if settings.allow_all_users:
return await handler(event, data)
user = None
if event.message:
user = event.message.from_user
elif event.callback_query:
user = event.callback_query.from_user
# If no users allowed and not allow_all_users -> deny everyone
if not settings.allowed_user_ids:
logger.warning("Access denied: no allowed_user_ids configured and allow_all_users is False")
return None
# Check if user is in allowed list
if user and user.id not in settings.allowed_user_ids:
logger.warning("Unauthorized access attempt from user %s", user.id)
return None
return await handler(event, data)
return auth_middleware
async def run_bot(settings: Settings) -> None:
"""Run the bot with polling."""
bot = create_bot(settings)
dp = create_dispatcher()
# Always add auth middleware for security (it handles allow_all_users internally)
dp.update.middleware(create_auth_middleware(settings))
logger.info("Starting bot polling...")
try:
await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types())
finally:
await bot.session.close()
+9
View File
@@ -0,0 +1,9 @@
"""Bot FSM states."""
from aiogram.fsm.state import State, StatesGroup
class DoCommandState(StatesGroup):
"""States for /do command flow."""
waiting_for_input = State() # Waiting for voice or text after /do
+52
View File
@@ -0,0 +1,52 @@
"""Application configuration using Pydantic Settings."""
from pathlib import Path
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Application settings loaded from environment variables."""
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)
telegram_bot_token: str = Field(description="Telegram Bot API token")
deepgram_api_key: str = Field(description="Deepgram API key for transcription")
todoist_api_key: str = Field(default="", description="Todoist API key for tasks")
vault_path: Path = Field(
default=Path("./vault"),
description="Path to Obsidian vault directory",
)
allowed_user_ids: list[int] = Field(
default_factory=list,
description="List of Telegram user IDs allowed to use the bot",
)
allow_all_users: bool = Field(
default=False,
description="Whether to allow access to all users (security risk!)",
)
@property
def daily_path(self) -> Path:
"""Path to daily notes directory."""
return self.vault_path / "daily"
@property
def attachments_path(self) -> Path:
"""Path to attachments directory."""
return self.vault_path / "attachments"
@property
def thoughts_path(self) -> Path:
"""Path to thoughts directory."""
return self.vault_path / "thoughts"
def get_settings() -> Settings:
"""Get application settings instance."""
return Settings()
+1
View File
@@ -0,0 +1 @@
"""Business logic services."""
+88
View File
@@ -0,0 +1,88 @@
"""Git automation service for vault."""
import logging
import subprocess
from pathlib import Path
logger = logging.getLogger(__name__)
class VaultGit:
"""Service for git operations on vault."""
def __init__(self, vault_path: Path) -> None:
self.vault_path = Path(vault_path)
def _run_git(self, *args: str) -> subprocess.CompletedProcess[str]:
"""Run git command in vault directory."""
return subprocess.run(
["git", *args],
cwd=self.vault_path,
capture_output=True,
text=True,
check=False,
)
def get_status(self) -> str:
"""Get git status."""
result = self._run_git("status", "--porcelain")
return result.stdout
def has_changes(self) -> bool:
"""Check if there are uncommitted changes."""
return bool(self.get_status().strip())
def commit_changes(self, message: str) -> bool:
"""Stage all changes and commit.
Args:
message: Commit message
Returns:
True if commit was made, False otherwise
"""
if not self.has_changes():
logger.info("No changes to commit")
return False
# Stage all changes
add_result = self._run_git("add", "-A")
if add_result.returncode != 0:
logger.error("Git add failed: %s", add_result.stderr)
return False
# Commit
commit_result = self._run_git("commit", "-m", message)
if commit_result.returncode != 0:
logger.error("Git commit failed: %s", commit_result.stderr)
return False
logger.info("Committed: %s", message)
return True
def push(self) -> bool:
"""Push to remote.
Returns:
True if push was successful
"""
result = self._run_git("push")
if result.returncode != 0:
logger.error("Git push failed: %s", result.stderr)
return False
logger.info("Pushed to remote")
return True
def commit_and_push(self, message: str) -> bool:
"""Commit all changes and push.
Args:
message: Commit message
Returns:
True if successful
"""
if self.commit_changes(message):
return self.push()
return True # No changes is not an error
+405
View File
@@ -0,0 +1,405 @@
"""Claude processing service."""
import logging
import os
import subprocess
from datetime import date
from pathlib import Path
from typing import Any
from d_brain.services.session import SessionStore
logger = logging.getLogger(__name__)
DEFAULT_TIMEOUT = 1200 # 20 minutes
class ClaudeProcessor:
"""Service for triggering Claude Code processing."""
def __init__(self, vault_path: Path, todoist_api_key: str = "") -> None:
self.vault_path = Path(vault_path)
self.todoist_api_key = todoist_api_key
self._mcp_config_path = (self.vault_path.parent / "mcp-config.json").resolve()
def _load_skill_content(self) -> str:
"""Load dbrain-processor skill content for inclusion in prompt.
NOTE: @vault/ references don't work in --print mode,
so we must include skill content directly in the prompt.
"""
skill_path = self.vault_path / ".claude/skills/dbrain-processor/SKILL.md"
if skill_path.exists():
return skill_path.read_text()
return ""
def _load_todoist_reference(self) -> str:
"""Load Todoist reference for inclusion in prompt."""
ref_path = self.vault_path / ".claude/skills/dbrain-processor/references/todoist.md"
if ref_path.exists():
return ref_path.read_text()
return ""
def _get_session_context(self, user_id: int) -> str:
"""Get today's session context for Claude.
Args:
user_id: Telegram user ID
Returns:
Recent session entries formatted for inclusion in prompt.
"""
if user_id == 0:
return ""
session = SessionStore(self.vault_path)
today_entries = session.get_today(user_id)
if not today_entries:
return ""
lines = ["=== TODAY'S SESSION ==="]
for entry in today_entries[-10:]:
ts = entry.get("ts", "")[11:16] # HH:MM from ISO
entry_type = entry.get("type", "unknown")
text = entry.get("text", "")[:80]
if text:
lines.append(f"{ts} [{entry_type}] {text}")
lines.append("=== END SESSION ===\n")
return "\n".join(lines)
def _html_to_markdown(self, html: str) -> str:
"""Convert Telegram HTML to Obsidian Markdown."""
import re
text = html
# <b>text</b> → **text**
text = re.sub(r"<b>(.*?)</b>", r"**\1**", text)
# <i>text</i> → *text*
text = re.sub(r"<i>(.*?)</i>", r"*\1*", text)
# <code>text</code> → `text`
text = re.sub(r"<code>(.*?)</code>", r"`\1`", text)
# <s>text</s> → ~~text~~
text = re.sub(r"<s>(.*?)</s>", r"~~\1~~", text)
# Remove <u> (no Markdown equivalent, just keep text)
text = re.sub(r"</?u>", "", text)
# <a href="url">text</a> → [text](url)
text = re.sub(r'<a href="([^"]+)">([^<]+)</a>', r"[\2](\1)", text)
return text
def _save_weekly_summary(self, report_html: str, week_date: date) -> Path:
"""Save weekly summary to vault/summaries/YYYY-WXX-summary.md."""
# Calculate ISO week number
year, week, _ = week_date.isocalendar()
filename = f"{year}-W{week:02d}-summary.md"
summary_path = self.vault_path / "summaries" / filename
# Convert HTML to Markdown for Obsidian
content = self._html_to_markdown(report_html)
# Add frontmatter
frontmatter = f"""---
date: {week_date.isoformat()}
type: weekly-summary
week: {year}-W{week:02d}
---
"""
summary_path.write_text(frontmatter + content)
logger.info("Weekly summary saved to %s", summary_path)
return summary_path
def _update_weekly_moc(self, summary_path: Path) -> None:
"""Add link to new summary in MOC-weekly.md."""
moc_path = self.vault_path / "MOC" / "MOC-weekly.md"
if moc_path.exists():
content = moc_path.read_text()
link = f"- [[summaries/{summary_path.name}|{summary_path.stem}]]"
# Insert after "## Previous Weeks" if not already there
if summary_path.stem not in content:
content = content.replace(
"## Previous Weeks\n",
f"## Previous Weeks\n\n{link}\n",
)
moc_path.write_text(content)
logger.info("Updated MOC-weekly.md with link to %s", summary_path.stem)
def process_daily(self, day: date | None = None) -> dict[str, Any]:
"""Process daily file with Claude.
Args:
day: Date to process (default: today)
Returns:
Processing report as dict
"""
if day is None:
day = date.today()
daily_file = self.vault_path / "daily" / f"{day.isoformat()}.md"
if not daily_file.exists():
logger.warning("No daily file for %s", day)
return {
"error": f"No daily file for {day}",
"processed_entries": 0,
}
# Load skill content directly (@ references don't work in --print mode)
skill_content = self._load_skill_content()
prompt = f"""Сегодня {day}. Выполни ежедневную обработку.
=== SKILL INSTRUCTIONS ===
{skill_content}
=== END SKILL ===
ПЕРВЫМ ДЕЛОМ: вызови mcp__todoist__user-info чтобы убедиться что MCP работает.
CRITICAL MCP RULE:
- ТЫ ИМЕЕШЬ ДОСТУП к mcp__todoist__* tools — ВЫЗЫВАЙ ИХ НАПРЯМУЮ
- НИКОГДА не пиши "MCP недоступен" или "добавь вручную"
- Для задач: вызови mcp__todoist__add-tasks tool
- Если tool вернул ошибку — покажи ТОЧНУЮ ошибку в отчёте
CRITICAL OUTPUT FORMAT:
- Return ONLY raw HTML for Telegram (parse_mode=HTML)
- NO markdown: no **, no ## , no ```, no tables
- Start directly with 📊 <b>Обработка за {day}</b>
- Allowed tags: <b>, <i>, <code>, <s>, <u>
- If entries already processed, return status report in same HTML format"""
try:
# Pass TODOIST_API_KEY to Claude subprocess
env = os.environ.copy()
if self.todoist_api_key:
env["TODOIST_API_KEY"] = self.todoist_api_key
result = subprocess.run(
[
"claude",
"--print",
"--dangerously-skip-permissions",
"--mcp-config",
str(self._mcp_config_path),
"-p",
prompt,
],
cwd=self.vault_path.parent,
capture_output=True,
text=True,
timeout=DEFAULT_TIMEOUT,
check=False,
env=env,
)
if result.returncode != 0:
logger.error("Claude processing failed: %s", result.stderr)
return {
"error": result.stderr or "Claude processing failed",
"processed_entries": 0,
}
# Return human-readable output
output = result.stdout.strip()
return {
"report": output,
"processed_entries": 1, # успешно обработано
}
except subprocess.TimeoutExpired:
logger.error("Claude processing timed out")
return {
"error": "Processing timed out",
"processed_entries": 0,
}
except FileNotFoundError:
logger.error("Claude CLI not found")
return {
"error": "Claude CLI not installed",
"processed_entries": 0,
}
except Exception as e:
logger.exception("Unexpected error during processing")
return {
"error": str(e),
"processed_entries": 0,
}
def execute_prompt(self, user_prompt: str, user_id: int = 0) -> dict[str, Any]:
"""Execute arbitrary prompt with Claude.
Args:
user_prompt: User's natural language request
user_id: Telegram user ID for session context
Returns:
Execution report as dict
"""
today = date.today()
# Load context
todoist_ref = self._load_todoist_reference()
session_context = self._get_session_context(user_id)
prompt = f"""Ты - персональный ассистент d-brain.
CONTEXT:
- Текущая дата: {today}
- Vault path: {self.vault_path}
{session_context}=== TODOIST REFERENCE ===
{todoist_ref}
=== END REFERENCE ===
ПЕРВЫМ ДЕЛОМ: вызови mcp__todoist__user-info чтобы убедиться что MCP работает.
CRITICAL MCP RULE:
- ТЫ ИМЕЕШЬ ДОСТУП к mcp__todoist__* tools — ВЫЗЫВАЙ ИХ НАПРЯМУЮ
- НИКОГДА не пиши "MCP недоступен" или "добавь вручную"
- Если tool вернул ошибку — покажи ТОЧНУЮ ошибку в отчёте
USER REQUEST:
{user_prompt}
CRITICAL OUTPUT FORMAT:
- Return ONLY raw HTML for Telegram (parse_mode=HTML)
- NO markdown: no **, no ##, no ```, no tables, no -
- Start with emoji and <b>header</b>
- Allowed tags: <b>, <i>, <code>, <s>, <u>
- Be concise - Telegram has 4096 char limit
EXECUTION:
1. Analyze the request
2. Call MCP tools directly (mcp__todoist__*, read/write files)
3. Return HTML status report with results"""
try:
env = os.environ.copy()
if self.todoist_api_key:
env["TODOIST_API_KEY"] = self.todoist_api_key
result = subprocess.run(
[
"claude",
"--print",
"--dangerously-skip-permissions",
"--mcp-config",
str(self._mcp_config_path),
"-p",
prompt,
],
cwd=self.vault_path.parent,
capture_output=True,
text=True,
timeout=DEFAULT_TIMEOUT,
check=False,
env=env,
)
if result.returncode != 0:
logger.error("Claude execution failed: %s", result.stderr)
return {
"error": result.stderr or "Claude execution failed",
"processed_entries": 0,
}
return {
"report": result.stdout.strip(),
"processed_entries": 1,
}
except subprocess.TimeoutExpired:
logger.error("Claude execution timed out")
return {"error": "Execution timed out", "processed_entries": 0}
except FileNotFoundError:
logger.error("Claude CLI not found")
return {"error": "Claude CLI not installed", "processed_entries": 0}
except Exception as e:
logger.exception("Unexpected error during execution")
return {"error": str(e), "processed_entries": 0}
def generate_weekly(self) -> dict[str, Any]:
"""Generate weekly digest with Claude.
Returns:
Weekly digest report as dict
"""
today = date.today()
prompt = f"""Сегодня {today}. Сгенерируй недельный дайджест.
ПЕРВЫМ ДЕЛОМ: вызови mcp__todoist__user-info чтобы убедиться что MCP работает.
CRITICAL MCP RULE:
- ТЫ ИМЕЕШЬ ДОСТУП к mcp__todoist__* tools — ВЫЗЫВАЙ ИХ НАПРЯМУЮ
- НИКОГДА не пиши "MCP недоступен" или "добавь вручную"
- Для выполненных задач: вызови mcp__todoist__find-completed-tasks tool
- Если tool вернул ошибку — покажи ТОЧНУЮ ошибку в отчёте
WORKFLOW:
1. Собери данные за неделю (daily файлы в vault/daily/, completed tasks через MCP)
2. Проанализируй прогресс по целям (goals/3-weekly.md)
3. Определи победы и вызовы
4. Сгенерируй HTML отчёт
CRITICAL OUTPUT FORMAT:
- Return ONLY raw HTML for Telegram (parse_mode=HTML)
- NO markdown: no **, no ##, no ```, no tables
- Start with 📅 <b>Недельный дайджест</b>
- Allowed tags: <b>, <i>, <code>, <s>, <u>
- Be concise - Telegram has 4096 char limit"""
try:
env = os.environ.copy()
if self.todoist_api_key:
env["TODOIST_API_KEY"] = self.todoist_api_key
result = subprocess.run(
[
"claude",
"--print",
"--dangerously-skip-permissions",
"--mcp-config",
str(self._mcp_config_path),
"-p",
prompt,
],
cwd=self.vault_path.parent,
capture_output=True,
text=True,
timeout=DEFAULT_TIMEOUT,
check=False,
env=env,
)
if result.returncode != 0:
logger.error("Weekly digest failed: %s", result.stderr)
return {
"error": result.stderr or "Weekly digest failed",
"processed_entries": 0,
}
output = result.stdout.strip()
# Save to summaries/ and update MOC
try:
summary_path = self._save_weekly_summary(output, today)
self._update_weekly_moc(summary_path)
except Exception as e:
logger.warning("Failed to save weekly summary: %s", e)
return {
"report": output,
"processed_entries": 1,
}
except subprocess.TimeoutExpired:
logger.error("Weekly digest timed out")
return {"error": "Weekly digest timed out", "processed_entries": 0}
except FileNotFoundError:
logger.error("Claude CLI not found")
return {"error": "Claude CLI not installed", "processed_entries": 0}
except Exception as e:
logger.exception("Unexpected error during weekly digest")
return {"error": str(e), "processed_entries": 0}
+106
View File
@@ -0,0 +1,106 @@
"""Session persistence service.
Stores all bot interactions in JSONL format for history and analytics.
Inspired by Clawdbot's session persistence pattern.
"""
import json
from datetime import datetime
from pathlib import Path
from typing import Any
class SessionStore:
"""Persistent session storage in JSONL format.
Each user gets their own session file at vault/.sessions/{user_id}.jsonl.
Entries are append-only for reliability and simplicity.
"""
def __init__(self, vault_path: Path | str) -> None:
self.sessions_dir = Path(vault_path) / ".sessions"
self.sessions_dir.mkdir(exist_ok=True)
def _get_session_file(self, user_id: int) -> Path:
return self.sessions_dir / f"{user_id}.jsonl"
def append(self, user_id: int, entry_type: str, **data: Any) -> None:
"""Append entry to user's session file.
Args:
user_id: Telegram user ID
entry_type: Type of entry (voice, text, photo, forward, command, etc.)
**data: Additional data to store (text, duration, msg_id, etc.)
"""
entry = {
"ts": datetime.now().astimezone().isoformat(),
"type": entry_type,
**data,
}
path = self._get_session_file(user_id)
with path.open("a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
def get_recent(self, user_id: int, limit: int = 50) -> list[dict]:
"""Get recent session entries.
Args:
user_id: Telegram user ID
limit: Maximum number of entries to return
Returns:
List of session entries, most recent last
"""
path = self._get_session_file(user_id)
if not path.exists():
return []
entries = []
with path.open("r", encoding="utf-8") as f:
for line in f:
if line.strip():
try:
entries.append(json.loads(line))
except json.JSONDecodeError:
continue # Skip malformed lines
return entries[-limit:]
def get_today(self, user_id: int) -> list[dict]:
"""Get today's session entries.
Args:
user_id: Telegram user ID
Returns:
List of today's entries
"""
today = datetime.now().date().isoformat()
return [
e
for e in self.get_recent(user_id, limit=200)
if e.get("ts", "").startswith(today)
]
def get_stats(self, user_id: int, days: int = 7) -> dict[str, int]:
"""Get usage statistics for the last N days.
Args:
user_id: Telegram user ID
days: Number of days to analyze
Returns:
Dict with counts by entry type
"""
from datetime import timedelta
cutoff = (datetime.now() - timedelta(days=days)).isoformat()
entries = self.get_recent(user_id, limit=1000)
stats: dict[str, int] = {}
for entry in entries:
if entry.get("ts", "") >= cutoff:
entry_type = entry.get("type", "unknown")
stats[entry_type] = stats.get(entry_type, 0) + 1
return stats
+85
View File
@@ -0,0 +1,85 @@
"""Vault storage service for saving entries."""
from datetime import date, datetime
from pathlib import Path
class VaultStorage:
"""Service for storing entries in Obsidian vault."""
def __init__(self, vault_path: Path) -> None:
self.vault_path = Path(vault_path)
self.daily_path = self.vault_path / "daily"
self.attachments_path = self.vault_path / "attachments"
def _ensure_dirs(self) -> None:
"""Ensure required directories exist."""
self.daily_path.mkdir(parents=True, exist_ok=True)
self.attachments_path.mkdir(parents=True, exist_ok=True)
def get_daily_file(self, day: date) -> Path:
"""Get path to daily file for given date."""
self._ensure_dirs()
return self.daily_path / f"{day.isoformat()}.md"
def read_daily(self, day: date) -> str:
"""Read content of daily file."""
file_path = self.get_daily_file(day)
if not file_path.exists():
return ""
return file_path.read_text(encoding="utf-8")
def append_to_daily(
self,
text: str,
timestamp: datetime,
msg_type: str,
) -> None:
"""Append entry to daily file.
Args:
text: Content to append
timestamp: Entry timestamp
msg_type: Type marker like [voice], [text], [photo], [forward from: Name]
"""
self._ensure_dirs()
file_path = self.get_daily_file(timestamp.date())
time_str = timestamp.strftime("%H:%M")
entry = f"\n## {time_str} {msg_type}\n{text}\n"
with file_path.open("a", encoding="utf-8") as f:
f.write(entry)
def get_attachments_dir(self, day: date) -> Path:
"""Get attachments directory for given date."""
dir_path = self.attachments_path / day.isoformat()
dir_path.mkdir(parents=True, exist_ok=True)
return dir_path
def save_attachment(
self,
data: bytes,
day: date,
timestamp: datetime,
extension: str = "jpg",
) -> str:
"""Save attachment and return relative path for Obsidian embed.
Args:
data: File bytes
day: Date for organizing
timestamp: Timestamp for filename
extension: File extension
Returns:
Relative path for Obsidian embed: attachments/YYYY-MM-DD/img-HHMMSS.ext
"""
dir_path = self.get_attachments_dir(day)
time_str = timestamp.strftime("%H%M%S")
filename = f"img-{time_str}.{extension}"
file_path = dir_path / filename
file_path.write_bytes(data)
return f"attachments/{day.isoformat()}/{filename}"
+47
View File
@@ -0,0 +1,47 @@
"""Deepgram transcription service."""
import logging
from deepgram import AsyncDeepgramClient
logger = logging.getLogger(__name__)
class DeepgramTranscriber:
"""Service for transcribing audio using Deepgram Nova-3."""
def __init__(self, api_key: str) -> None:
self.client = AsyncDeepgramClient(api_key=api_key)
async def transcribe(self, audio_bytes: bytes) -> str:
"""Transcribe audio bytes to text.
Args:
audio_bytes: Audio file content
Returns:
Transcribed text
Raises:
Exception: If transcription fails
"""
logger.info("Starting transcription, audio size: %d bytes", len(audio_bytes))
response = await self.client.listen.v1.media.transcribe_file(
request=audio_bytes,
model="nova-3",
language="ru",
punctuate=True,
smart_format=True,
)
transcript = (
response.results.channels[0].alternatives[0].transcript
if response.results
and response.results.channels
and response.results.channels[0].alternatives
else ""
)
logger.info("Transcription complete: %d chars", len(transcript))
return transcript
Generated
+1146
View File
File diff suppressed because it is too large Load Diff
+31
View File
@@ -0,0 +1,31 @@
{
"name": "d-brain",
"version": "2.0.0",
"description": "Voice-first personal assistant for capturing thoughts and tasks via Telegram, with goal tracking and Obsidian integration",
"author": {
"name": "[Your Name]",
"url": "https://github.com/[yourusername]"
},
"license": "MIT",
"capabilities": {
"agents": true,
"skills": true,
"rules": true
},
"integrations": {
"telegram": "Voice/text/photo capture",
"todoist": "Task management via MCP",
"obsidian": "PKM vault storage",
"deepgram": "Voice transcription"
},
"keywords": [
"voice-capture",
"telegram-bot",
"todoist",
"obsidian",
"pkm",
"goals",
"productivity",
"personal-assistant"
]
}
+249
View File
@@ -0,0 +1,249 @@
# Agent Second Brain
Voice-first personal assistant for capturing thoughts and managing tasks via Telegram.
## EVERY SESSION BOOTSTRAP
**Before doing anything else, read these files in order:**
1. `vault/MEMORY.md` — curated long-term memory (preferences, decisions, context)
2. `vault/.memory-config.json` — memory decay configuration
3. `vault/daily/YYYY-MM-DD.md` — today's entries
4. `vault/daily/YYYY-MM-DD.md` — yesterday's entries (for continuity)
5. `vault/goals/3-weekly.md` — this week's ONE Big Thing
6. `vault/.session/handoff.md` — previous session context (if exists)
**Don't ask permission, just do it.** This ensures context continuity across sessions.
---
## SESSION END PROTOCOL
**Before ending a significant session, write to today's daily:**
```markdown
## HH:MM [text]
Session summary: [what was discussed/decided/created]
- Key decision: [if any]
- Created: [[link]] [if any files created]
- Next action: [if any]
```
**Also update `vault/MEMORY.md` if:**
- New key decision was made
- User preference discovered
- Important fact learned
- Active context changed significantly
**Update `vault/.session/handoff.md`:**
- Last Session: what was done
- Key Decisions: if any
- In Progress: unfinished work
- Next Steps: what to do next
- Observations: friction signals, patterns, ideas (type: `[friction]`, `[pattern]`, `[idea]`)
---
## Mission
Help user stay aligned with goals, capture valuable insights, and maintain clarity.
## Directory Structure
| Folder | Purpose |
|--------|---------|
| `daily/` | Raw daily entries (YYYY-MM-DD.md) |
| `goals/` | Goal cascade (3y → yearly → monthly → weekly) |
| `thoughts/` | Processed notes by category |
| `MOC/` | Maps of Content indexes |
| `attachments/` | Photos by date |
| `business/` | Business data (CRM, network, events) |
| `projects/` | Side projects (clients, leads) |
## Business Context
**Entry point:** `business/_index.md`
```
business/
├── _index.md ← Start here (stats, overview)
├── crm/ ← Client records (companies + deals in one file)
├── network/ ← Company structure, partners
└── events/ ← Events, conferences
```
Search: `business/crm/{kebab-case}.md` (e.g. `acme-corp.md`, `client-b.md`)
## Projects Context
**Entry point:** `projects/_index.md`
```
projects/
├── _index.md ← Start here
├── clients/ ← Project clients
├── leads/ ← Leads
└── projects/ ← Active projects
```
## Current Focus
See [[goals/3-weekly]] for this week's ONE Big Thing.
See [[goals/2-monthly]] for monthly priorities.
## Goals Hierarchy
```
goals/0-vision-3y.md → 3-year vision by life areas
goals/1-yearly-YYYY.md → Annual goals + quarterly breakdown
goals/2-monthly.md → Current month's top 3 priorities
goals/3-weekly.md → This week's focus + ONE Big Thing
```
## Entry Format
```markdown
## HH:MM [type]
Content
```
Types: `[voice]`, `[text]`, `[forward from: Name]`, `[photo]`
## Processing Workflow
Run daily processing via `/process` command or automatically at 21:00.
### 3-Phase Pipeline:
1. **CAPTURE** — Read daily entries → classify → JSON
2. **EXECUTE** — Create Todoist tasks, save thoughts, update CRM → JSON
3. **REFLECT** — Generate HTML report, update MEMORY, record observations
Each phase = fresh Claude context for better quality.
## Card Template (agent-memory)
**Skill:** `.claude/skills/agent-memory/SKILL.md`
All new vault cards follow the agent-memory template:
```yaml
---
type: crm|lead|contact|project|personal|note
description: >-
One line — what a searcher will see in results
tags: [tag1, tag2] # 2-5 tags, lowercase
status: active|draft|pending|done|inactive
industry: FMCG # for CRM/leads
region: US # ISO codes
created: YYYY-MM-DD
updated: YYYY-MM-DD
# Auto fields (don't edit manually):
last_accessed: YYYY-MM-DD
relevance: 0.85
tier: active
---
```
**Rules:**
- `description` — REQUIRED. Write as a search snippet, NOT "contact" or "crm"
- `tags` — REQUIRED. 2-5 tags, lowercase, hyphen-separated
- `status` ≠ `tier`: status = business status, tier = memory (automatic)
- One fact = one place (DRY). References via [[wikilinks]]
- Decay engine: `uv run .claude/skills/agent-memory/scripts/memory-engine.py decay .`
## Skills & References
| Skill | Purpose |
|-------|---------|
| `dbrain-processor` | Main daily processing (3-phase pipeline) |
| `graph-builder` | Vault link analysis and building |
| `vault-health` | Health scoring, MOC generation, link repair |
| `agent-memory` | Card template, decay engine, tiered search |
| `todoist-ai` | Todoist task management via MCP |
- **Processing:** `.claude/skills/dbrain-processor/SKILL.md`
- **Graph Builder:** `.claude/skills/graph-builder/SKILL.md`
- **Vault Health:** `.claude/skills/vault-health/SKILL.md`
- **Agent Memory:** `.claude/skills/agent-memory/SKILL.md`
- **Todoist:** `.claude/skills/todoist-ai/SKILL.md`
- **Rules:** `.claude/rules/` (daily, thoughts, goals, obsidian-markdown, weekly-reflection)
- **Docs:** `.claude/docs/`
## Graph Builder
**Purpose:** Analysis and maintenance of vault link structure.
**Architecture:**
1. `scripts/analyze.py` — deterministic vault traversal
2. `scripts/add_links.py` — batch link addition
3. Agent — semantic links for orphan files
**Usage:**
```bash
# Analyze vault
uv run vault/.claude/skills/graph-builder/scripts/analyze.py
# Result
vault/.graph/vault-graph.json # JSON graph with stats
vault/.graph/report.md # Human-readable report
```
**Domains:**
| Domain | Path | Hub |
|--------|------|-----|
| Personal | thoughts/, goals/, daily/ | MEMORY.md |
| Business | business/crm/, business/network/ | business/_index.md |
| Projects | projects/clients/, projects/leads/ | projects/_index.md |
## Available Agents
| Agent | Purpose |
|-------|---------|
| `weekly-digest` | Weekly review with goal progress |
| `goal-aligner` | Check task-goal alignment |
| `note-organizer` | Organize vault, fix links |
| `inbox-processor` | GTD-style inbox processing |
## Path-Specific Rules
See `.claude/rules/` for format requirements:
- `daily-format.md` — daily files format
- `thoughts-format.md` — thought notes format
- `goals-format.md` — goals format
- `telegram-report.md` — HTML report format
- `obsidian-markdown.md` — Obsidian syntax rules
- `weekly-reflection.md` — weekly reflection template
## Report Format
Reports use Telegram HTML:
- `<b>bold</b>` for headers
- `<i>italic</i>` for metadata
- Only allowed tags: b, i, code, pre, a
## Quick Commands
| Command | Action |
|---------|--------|
| `/process` | Run daily processing |
| `/do` | Execute arbitrary request |
| `/weekly` | Generate weekly digest |
| `/align` | Check goal alignment |
| `/organize` | Organize vault |
| `/graph` | Analyze vault links |
## Customization
For personal overrides: create `CLAUDE.local.md`
## Learnings (from experience)
1. **Don't rewrite working code** without reason (KISS, DRY, YAGNI)
2. **Don't add checks** that weren't there — let the agent decide
3. **Don't propose solutions** without studying git log/diff first
4. **Don't break architecture** (process.sh → Claude → skill is correct)
5. **Problems are usually simple** (e.g., sed one-liner for HTML fix)
---
*System Version: 3.0*
+141
View File
@@ -0,0 +1,141 @@
---
name: goal-aligner
description: Check alignment between tasks in Todoist and goals in vault. Find orphan tasks and stale goals.
---
# Goal Aligner Agent
Ensures tasks and goals stay in sync.
## When to Run
- Weekly during digest
- On demand via `/align` command
- When too many unaligned tasks detected
## Workflow
### Step 1: Load All Goals
```
Read goals/0-vision-3y.md → Life areas
Read goals/1-yearly-2025.md → Yearly goals
Read goals/2-monthly.md → Monthly priorities
Read goals/3-weekly.md → ONE Big Thing
```
Extract goal keywords for matching.
### Step 2: Get All Active Tasks
```
mcp__todoist__find-tasks
responsibleUserFiltering: "all"
limit: 100
```
### Step 3: Analyze Alignment
For each task:
1. **Check description** for goal references
2. **Match keywords** against goals
3. **Classify:**
- ✅ Aligned — has goal reference
- 🔶 Possibly aligned — keyword match
- ❌ Orphan — no connection
### Step 4: Find Stale Goals
For each yearly goal:
1. **Count recent activity:**
- Tasks completed in last 7 days
- Notes saved with goal tag
- Progress updates
2. **Classify:**
- ✅ Active — activity in 7 days
- 🟡 Quiet — no activity 7-14 days
- 🔴 Stale — no activity 14+ days
### Step 5: Generate Report
Format: Telegram HTML
```html
🎯 <b>Alignment Check</b>
<b>📋 Задачи без связи с целями:</b>
{if orphan tasks:}
• {task_name} — <i>Предложение: {goal}</i>
{else:}
✅ Все задачи связаны с целями
<b>🎯 Цели без активности:</b>
{if stale goals:}
• 🔴 {goal} — {days} дней без активности
• 🟡 {goal} — {days} дней без активности
{else:}
✅ Все цели активны
<b>📊 Распределение по целям:</b>
• {goal}: {N} активных задач
• {goal}: {M} активных задач
• Без цели: {K} задач
<b>💡 Рекомендации:</b>
{recommendations based on analysis}
<b>Действия:</b>
• <b>Начать:</b> {goal to focus on}
• <b>Остановить:</b> {tasks not aligned}
• <b>Продолжить:</b> {aligned work}
```
### Step 6: Suggest Fixes
For orphan tasks, suggest:
1. Which goal it might relate to
2. Or mark as "operational"
For stale goals:
1. Suggest next action
2. Or reconsider goal relevance
## Alignment Scoring
| Score | Meaning |
|-------|---------|
| 90-100% | Excellent alignment |
| 70-89% | Good, minor gaps |
| 50-69% | Needs attention |
| <50% | Serious misalignment |
```
Score = (Aligned Tasks / Total Tasks) × 100
```
## Auto-Fix Options
If enabled, agent can:
1. **Add goal references** to task descriptions
2. **Create follow-up tasks** for stale goals
3. **Archive** completed goals
## Start/Stop/Continue Framework
Based on analysis, recommend:
**Start:**
- Goals with low activity that matter
- New initiatives from stale areas
**Stop:**
- Tasks not aligned with any goal
- Goals that no longer resonate
**Continue:**
- Well-aligned, progressing work
- High-impact activities
+171
View File
@@ -0,0 +1,171 @@
---
name: inbox-processor
description: GTD-style processing of incoming entries. Decide action for each item - do now, schedule, delegate, save, or delete.
---
# Inbox Processor Agent
Applies GTD methodology to process unhandled items.
## When to Run
- When daily file has many unprocessed entries
- During weekly review
- On demand via `/inbox` command
## GTD Decision Tree
For each entry, ask:
```
Is it actionable?
├─ NO → Is it useful?
│ ├─ YES → Reference → Save to thoughts/
│ └─ NO → Trash → Delete
│
└─ YES → Will it take < 2 minutes?
├─ YES → Do it now
└─ NO → Is it a single action?
├─ YES → Schedule in Todoist
└─ NO → Create project
```
## Workflow
### Step 1: Load Unprocessed Items
```
Read daily/{today}.md
Find entries without "processed" marker
```
### Step 2: Classify Each Item
Apply GTD decision tree:
| Decision | Action |
|----------|--------|
| Do Now | Execute immediately, report done |
| Schedule | Create task in Todoist |
| Project | Create task + note in thoughts/projects/ |
| Reference | Save to thoughts/{category}/ |
| Waiting | Create task with "waiting" label |
| Trash | Mark for deletion |
### Step 3: Execute Actions
**Do Now (<2 min):**
- Simple lookups, quick replies
- Report completion immediately
**Schedule (single task):**
```
mcp__todoist__add-tasks
content: {task}
dueString: {date}
priority: {p1-p4}
```
**Project (multi-step):**
1. Create parent task in Todoist
2. Add subtasks for first steps
3. Create note in thoughts/projects/
4. Link task and note
**Reference:**
1. Classify: idea/learning/reflection
2. Save to thoughts/{category}/
3. Build links
4. Update MOC
**Waiting:**
```
mcp__todoist__add-tasks
content: "Waiting: {description}"
labels: ["waiting"]
dueString: "in 3 days" # follow-up
```
**Trash:**
- Mark entry with ~~strikethrough~~
- Or move to archive section
### Step 4: Mark as Processed
Add marker to each entry:
```markdown
## 14:30 [voice] ✓
Content...
```
Or add footer:
```markdown
---
processed: 2024-12-20T21:00:00
```
### Step 5: Generate Report
Format: Telegram HTML
```html
📥 <b>Inbox Processing Complete</b>
<b>📊 Обработано записей:</b> {N}
<b>⚡ Сделано сразу:</b> {quick_actions}
• {action 1}
• {action 2}
<b>📅 Запланировано:</b> {scheduled}
• {task} <i>({date})</i>
<b>🎯 Создано проектов:</b> {projects}
• {project_name}
<b>📓 Сохранено:</b> {saved}
• {note} → {category}/
<b>⏳ Ожидание:</b> {waiting}
• {item}
<b>🗑️ Удалено:</b> {deleted}
<b>📭 Inbox теперь:</b> {remaining} items
{if remaining == 0: ✨ Inbox Zero!}
```
## Quick Actions
Things that can be "Done Now":
- Simple web searches
- Quick calculations
- Short answers to questions
- File organization
- Quick message replies
## Project Indicators
Entry needs project if:
- Multiple steps mentioned
- "Need to research"
- "Then... after that..."
- Timeline spans days/weeks
- Multiple people involved
## Reference Categories
| Keywords | Category |
|----------|----------|
| "интересная идея", "что если" | idea |
| "узнал", "оказывается", "TIL" | learning |
| "понял", "осознал", "урок" | reflection |
| "проект", "задумка", "план" | project |
## Inbox Zero Philosophy
Goal is not just empty inbox, but:
- Every item has a home
- Decisions are made, not deferred
- Nothing falls through cracks
- Mind is clear for focus work
+158
View File
@@ -0,0 +1,158 @@
---
name: note-organizer
description: Organize vault, find orphan notes, suggest connections, update MOC indexes, consolidate duplicates.
---
# Note Organizer Agent
Keeps the vault organized and connected.
## When to Run
- Weekly maintenance
- When vault grows cluttered
- On demand via `/organize` command
## Workflow
### Step 1: Scan Vault
```
Glob thoughts/**/*.md
Glob daily/**/*.md
Glob goals/**/*.md
```
Build index of all notes with:
- File path
- Title
- Tags
- Links (outgoing)
- Frontmatter
### Step 2: Find Orphan Notes
A note is orphan if:
- No incoming links from other notes
- Not listed in any MOC
- Has no related notes in frontmatter
```
For each note in thoughts/:
Check if any other note links to it
Check if listed in MOC/
If neither → mark as orphan
```
### Step 3: Suggest Connections
For each orphan note:
1. **Extract keywords** from title and content
2. **Search for related notes** using keywords
3. **Check goals** for topic overlap
4. **Suggest links** ranked by relevance
### Step 4: Find Duplicates
Look for similar notes:
1. **Title similarity** — fuzzy match
2. **Content overlap** — key phrases
3. **Same topic** — tag match
Flag potential duplicates for review.
### Step 5: Update MOC Indexes
For each MOC file:
1. **List all notes** in corresponding category
2. **Group by topic** or date
3. **Add missing entries**
4. **Remove dead links**
MOC structure:
```markdown
# MOC: Ideas
## Recent
- [[2024-12-20-new-idea]] — Brief description
## By Topic
### AI & Voice
- [[voice-agents-architecture]]
- [[chatterbox-tts]]
### Productivity
- [[daily-routine-optimization]]
```
### Step 6: Generate Report
Format: Telegram HTML
```html
🗂️ <b>Vault Organization Report</b>
<b>📊 Статистика:</b>
• Всего заметок: {N}
• В thoughts/: {M}
• В daily/: {K}
<b>🔗 Связность:</b>
• Связанных: {connected}%
• Изолированных: {orphans}
<b>📭 Orphan Notes:</b>
{for each orphan:}
• {note_title}
→ Предложение: [[{suggested_link}]]
<b>🔄 Возможные дубликаты:</b>
{for each duplicate pair:}
• {note1} ≈ {note2}
<b>📑 MOC Updates:</b>
• {moc_name}: +{added} / -{removed}
<b>💡 Рекомендации:</b>
{actionable suggestions}
```
### Step 7: Optional Auto-Fix
If enabled:
1. **Add backlinks** to orphan notes
2. **Update MOC** with new entries
3. **Merge duplicates** (with confirmation)
## Connection Quality Score
```
Score = (Notes with 2+ links / Total Notes) × 100
```
| Score | Quality |
|-------|---------|
| 80%+ | Excellent |
| 60-79% | Good |
| 40-59% | Needs work |
| <40% | Fragmented |
## MOC Categories
| MOC | Covers |
|-----|--------|
| MOC-ideas.md | thoughts/ideas/ |
| MOC-learnings.md | thoughts/learnings/ |
| MOC-projects.md | thoughts/projects/ |
| MOC-reflections.md | thoughts/reflections/ |
## Link Discovery Strategies
1. **Topic match** — same tags or keywords
2. **Temporal proximity** — notes from same period
3. **Goal alignment** — notes under same goal
4. **Reference chain** — A links to B, B links to C → suggest A↔C
+138
View File
@@ -0,0 +1,138 @@
---
name: weekly-digest
description: Generate weekly digest with goal progress, wins, challenges, and next week planning. Run on Sundays.
---
# Weekly Digest Agent
Analyzes the past week and generates comprehensive digest report.
## When to Run
- Every Sunday evening
- On demand via `/weekly` command
## Workflow
### Step 1: Collect Week Data
1. **Read all daily files for the week:**
```
daily/YYYY-MM-DD.md (7 files)
```
2. **Get completed tasks from Todoist:**
```
mcp__todoist__find-completed-tasks
since: {monday}
until: {sunday}
```
3. **Get current goals:**
```
Read goals/1-yearly-2025.md
Read goals/2-monthly.md
Read goals/3-weekly.md
```
### Step 2: Analyze Progress
Calculate for each yearly goal:
- Tasks completed related to goal
- Notes saved related to goal
- Progress delta (this week vs last week)
### Step 3: Identify Wins & Challenges
**Wins:**
- Completed tasks marked as important
- Goals with progress increase
- Streak maintained (habits)
**Challenges:**
- Overdue tasks
- Goals without activity
- Incomplete ONE Big Thing
### Step 4: Plan Next Week
1. **Update weekly focus:**
- Suggest new ONE Big Thing
- Based on goal alignment
2. **Recommend priorities:**
- Top 3 tasks for next week
- Based on goals + overdue
### Step 5: Generate Report
Format: Telegram HTML
```html
📅 <b>Недельный дайджест: {WEEK}</b>
<b>🎯 ONE Big Thing на прошлой неделе:</b>
{status: ✅ Выполнено | ❌ Не выполнено | 🟡 Частично}
{description}
<b>🏆 Победы недели:</b>
• {win 1}
• {win 2}
• {win 3}
<b>⚔️ Вызовы:</b>
• {challenge 1}
• {challenge 2}
<b>📊 Статистика:</b>
• Задач выполнено: {N}
• Заметок сохранено: {M}
• Голосовых сообщений: {K}
<b>📈 Прогресс по целям:</b>
• {goal}: {old}% → {new}% {delta_emoji}
• {goal}: {old}% → {new}% {delta_emoji}
<b>⚠️ Требует внимания:</b>
• {stale goals or overdue items}
<b>🎯 ONE Big Thing на следующую неделю:</b>
{suggested ONE thing}
<b>⚡ Топ-3 приоритета:</b>
1. {task}
2. {task}
3. {task}
---
<i>Неделя {week_number} завершена</i>
```
## Progress Delta Emojis
| Change | Emoji |
|--------|-------|
| +10% or more | 🚀 |
| +1% to +9% | 📈 |
| No change | ➡️ |
| -1% to -9% | 📉 |
| -10% or more | 🔻 |
## Update Files
After generating digest:
1. **Archive current weekly:**
```
Rename goals/3-weekly.md → goals/archive/3-weekly-{WEEK}.md
```
2. **Create new weekly:**
```
Create goals/3-weekly.md with new ONE Big Thing
```
3. **Update monthly if needed:**
```
Update progress in goals/2-monthly.md
```
@@ -0,0 +1,280 @@
---
type: note
title: NotebookLM MCP CLI - Quick Start
---
# NotebookLM MCP CLI - Quick Start
> **Установлено:** 1 февраля 2026
> **Версия:** 0.2.10
> **GitHub:** https://github.com/jacob-bd/notebooklm-mcp-cli
---
## Зачем нужен NotebookLM
**Для обработки больших массивов данных:**
- Клиентские исследования и анализ
- Подготовка презентаций и брифингов
- Генерация подкастов из документации
- Создание обучающих материалов (флэшкарты, майндмэпы)
- Анализ конкурентов
---
## 🚀 Быстрый старт
### 1. Установка
```bash
uv tool install notebooklm-mcp-cli
```
**Установлены компоненты:**
- `nlm` — CLI команда
- `notebooklm-mcp` — MCP сервер (уже в конфиге)
- `notebooklm-mcp-auth` — аутентификация
### 2. Аутентификация
```bash
notebooklm-mcp-auth --file
```
**Инструкция:**
1. Открой Chrome → https://notebooklm.google.com
2. Открой DevTools (Cmd+Option+I)
3. Вкладка **Network** → фильтр: `batchexecute`
4. Кликни на любой ноутбук (появится запрос)
5. Найди **Request Headers** → строку `cookie:`
6. Скопируй значение (правый клик → Copy value)
7. Создай файл `~/cookies.txt` и вставь туда
8. Запусти: `notebooklm-mcp-auth --file ~/cookies.txt`
**Проверка:**
```bash
nlm list notebook
```
---
## 📚 Основные команды
### Управление ноутбуками
```bash
# Список всех ноутбуков
nlm list notebook
# Создать ноутбук
nlm create notebook "Название"
# Детали ноутбука
nlm get notebook "Название"
# Удалить ноутбук
nlm delete notebook "Название"
# Переименовать
nlm rename notebook "Старое" --new-name "Новое"
```
### Добавление источников
```bash
# URL
nlm add source --url https://example.com --notebook "My Research"
# YouTube видео
nlm add source --youtube https://youtube.com/watch?v=VIDEO_ID --notebook "My Research"
# Текст
nlm add source --text "Ваш текст здесь" --notebook "My Research"
# Google Drive файл
nlm add source --drive-file "FILE_ID" --notebook "My Research"
# Список источников
nlm list source --notebook "My Research"
```
### Запросы и анализ
```bash
# Задать вопрос к ноутбуку
nlm query "В чём основные инсайты?" --notebook "My Research"
# Получить описание
nlm describe notebook "My Research"
# Получить raw контент из источника
nlm content source "SOURCE_ID"
```
### Генерация контента
```bash
# Audio overview (подкаст)
nlm audio create --notebook "My Research"
# Video overview
nlm video create --notebook "My Research"
# Slides (презентация)
nlm slides create --notebook "My Research"
# Mind map
nlm mindmap create --notebook "My Research"
# Infographic
nlm infographic create --notebook "My Research"
# Flashcards
nlm flashcards create --notebook "My Research"
# Briefing document
nlm report create --notebook "My Research"
# Quiz
nlm quiz create --notebook "My Research"
```
### Синхронизация
```bash
# Синхронизировать Google Drive источники
nlm sync --notebook "My Research"
# Список устаревших источников
nlm stale --notebook "My Research"
```
### Шеринг
```bash
# Сделать ноутбук публичным
nlm share notebook "My Research" --public
# Поделиться с конкретным пользователем
nlm share notebook "My Research" --email user@example.com
```
---
## 🔧 Использование через MCP
### Через mcp-cli (рекомендуется)
```bash
# Список инструментов
mcp-cli info notebooklm
# Создать ноутбук
mcp-cli call notebooklm create_notebook '{"title": "Research"}'
# Добавить источник
mcp-cli call notebooklm add_source '{
"notebook_id": "...",
"url": "https://example.com"
}'
# Запрос
mcp-cli call notebooklm query '{
"notebook_id": "...",
"query": "What are the main points?"
}'
# Генерация подкаста
mcp-cli call notebooklm create_audio '{
"notebook_id": "..."
}'
```
### Из Claude Code
```markdown
Используй NotebookLM для анализа этих статей:
- https://example.com/article1
- https://example.com/article2
Создай ноутбук "Competitor Analysis" и сгенерируй:
1. Briefing document
2. Mind map
3. Audio overview (подкаст)
```
---
## 💡 Use Cases
### 1. Client Research
```bash
nlm create notebook "Client Research: Acme Campaign"
nlm add source --url https://competitor1.com --notebook "Client Research: Acme Campaign"
nlm add source --url https://competitor2.com --notebook "Client Research: Acme Campaign"
nlm query "What patterns in mechanics?" --notebook "Client Research: Acme Campaign"
nlm slides create --notebook "Client Research: Acme Campaign"
nlm report create --notebook "Client Research: Acme Campaign"
```
### 2. Training Materials
```bash
nlm create notebook "AI Training Materials"
nlm add source --url https://docs.anthropic.com --notebook "AI Training Materials"
nlm add source --youtube https://youtube.com/watch?v=... --notebook "AI Training Materials"
nlm flashcards create --notebook "AI Training Materials"
nlm mindmap create --notebook "AI Training Materials"
nlm quiz create --notebook "AI Training Materials"
```
### 3. Content Generation
```bash
nlm create notebook "Content Ideas"
nlm add source --url https://research-article.com --notebook "Content Ideas"
nlm audio create --notebook "Content Ideas" # Podcast
nlm infographic create --notebook "Content Ideas" # Infographic
```
---
## ⚠️ Важно
- **Cookie-based auth** — токены хранятся локально, обновляются автоматически
- **Undocumented API** — может сломаться после обновлений Google
- **Personal use** — не для продакшена, только эксперименты
- **Rate limits** — Google может ограничить при частых запросах
---
## 📝 Профили
Если нужно несколько Google аккаунтов:
```bash
# Аутентификация с профилем
nlm login --profile work
nlm login --profile personal
# Переключение
nlm login switch work
# Список профилей
nlm login profile list
# Использование конкретного профиля
nlm list notebook --profile work
```
---
## 🔗 Ссылки
- **GitHub:** https://github.com/jacob-bd/notebooklm-mcp-cli
- **MEMORY.md:** `vault/MEMORY.md` — секция "NotebookLM"
- **MCP Config:** `~/.config/mcp/mcp_servers.json`
---
*Created: 2026-02-01*
+72
View File
@@ -0,0 +1,72 @@
---
paths: "daily/**/*.md"
---
# Daily Notes Format
Rules for daily capture files in `daily/` folder.
## File Naming
- Format: `YYYY-MM-DD.md`
- Example: `2024-12-20.md`
- One file per day
## Entry Format
Each entry follows this structure:
```markdown
## HH:MM [type]
Content of the entry
```
### Entry Types
| Type | Description |
|------|-------------|
| `[voice]` | Transcribed voice message |
| `[text]` | Direct text message |
| `[forward from: Name]` | Forwarded message with source |
| `[photo]` | Image with embed |
### Photo Entries
Photos include Obsidian embed:
```markdown
## 14:30 [photo]
![[attachments/2024-12-20/img-143025.jpg]]
Optional description or transcribed text from photo
```
## Processing Rules
When processing daily files:
1. **Read chronologically** — entries are timestamped
2. **Classify each entry** — task, idea, reflection, learning, project
3. **Check for photos** — analyze with vision if present
4. **Extract actionable items** — create tasks in Todoist
5. **Save valuable thoughts** — move to `thoughts/` categories
6. **Mark as processed** — after successful processing
## Do NOT
- Modify original entries
- Delete entries before archiving
- Change timestamps
- Add content between entries
## After Processing
Add processing marker at end of file:
```markdown
---
processed: 2024-12-20T21:00:00
thoughts: 3
tasks: 2
---
```
+103
View File
@@ -0,0 +1,103 @@
---
paths: "goals/**/*.md"
---
# Goals Format
Rules for goal files in `goals/` folder.
## File Structure
```
goals/
├── 0-vision-3y.md # 3-year vision by life areas
├── 1-yearly-2025.md # Annual goals with quarterly breakdown
├── 2-monthly.md # Current month priorities
└── 3-weekly.md # This week's focus + ONE Big Thing
```
## Hierarchy Principle
Goals cascade from long-term to daily:
```
3-Year Vision (life direction)
→ Yearly Goals (annual objectives)
→ Monthly Focus (current priorities)
→ Weekly Plan (this week's actions)
→ Daily Tasks (today in Todoist)
```
## Required Frontmatter
```yaml
---
type: vision | yearly | monthly | weekly
period: 2025 | 2024-12 | 2024-W51
updated: YYYY-MM-DD
---
```
## Progress Tracking
Use consistent progress format:
| Symbol | Meaning |
|--------|---------|
| 🔴 | 0-25% — Not started |
| 🟡 | 26-50% — In progress |
| 🟢 | 51-75% — Good progress |
| ✅ | 76-100% — Complete |
Example:
```markdown
| Goal | Progress | Status |
|------|----------|--------|
| Ship MVP | 65% | 🟢 |
| Fitness routine | 30% | 🟡 |
```
## ONE Big Thing
Weekly file MUST contain ONE Big Thing:
```markdown
## ONE Big Thing
> **If I accomplish nothing else, I will:**
> [Single most important outcome]
```
This is read by dbrain-processor for context.
## Goal Limits
- **Yearly:** Max 3 goals per life area
- **Monthly:** Max 3 top priorities
- **Weekly:** ONE Big Thing + 3 Must Do tasks
## Linking Goals to Tasks
When creating tasks, reference goals:
```markdown
- [ ] [Task] — Связь: [[1-yearly-2025#Career]]
```
## Stale Goal Warning
Goals without activity for 7+ days trigger warning in report.
Track "last touched" via:
- Task completion in Todoist
- Note saved related to goal
- Progress % update
## Review Cadence
| Level | Review Frequency |
|-------|------------------|
| Vision | Quarterly |
| Yearly | Monthly |
| Monthly | Weekly |
| Weekly | Daily |
+154
View File
@@ -0,0 +1,154 @@
---
type: note
title: Obsidian Markdown Rules
---
# Obsidian Markdown Rules
Rules for writing valid Obsidian Flavored Markdown in vault files.
Source: adapted from kepano/obsidian-skills (MIT).
## Wiki-Links
```markdown
[[Note Name]] Basic link
[[Note Name|Display Text]] Link with alias
[[Note Name#Heading]] Link to heading
[[#Heading in same note]] Same-note heading link
[[Note Name#^block-id]] Link to block
```
### Block References
Add `^block-id` at end of any paragraph to make it linkable:
```markdown
This paragraph can be linked to. ^my-block
> Quote block content
^quote-id
```
Then link with `[[Note#^my-block]]`.
## Embeds
```markdown
![[Note Name]] Embed full note
![[Note Name#Heading]] Embed section
![[image.png]] Embed image
![[image.png|300]] Image with width
![[image.png|640x480]] Image with dimensions
![[document.pdf#page=3]] PDF page
```
## Callouts
```markdown
> [!note]
> Basic note callout.
> [!warning] Custom Title
> Warning with title.
> [!tip]- Collapsed by default
> Foldable content.
```
### Types we should use in vault:
| Type | When to use |
|------|-------------|
| `[!warning]` | Blockers, risks, urgent items |
| `[!info]` | Context, background info |
| `[!tip]` | Recommendations, best practices |
| `[!todo]` | Action items |
| `[!success]` | Wins, completed milestones |
| `[!question]` | Open questions |
| `[!example]` | Examples, templates |
## Tables with Wiki-Links
Escape pipes inside wiki-links in tables:
```markdown
| Client | Link |
|--------|------|
| Client | [[business/crm/acme-corp\|Acme Corp]] |
```
## Comments
Obsidian-native comments (hidden in reading view):
```markdown
%%This is hidden in reading view%%
%%
Multi-line hidden block.
Only visible in edit mode.
%%
```
Use `%%` for Obsidian, `<!-- -->` for HTML-compatible comments.
Our processing markers (`<!-- processed -->`) stay as HTML comments since they're parsed by scripts.
## Tags
Valid tag characters:
- Letters (any language), numbers, `_`, `-`, `/`
- Numbers cannot be first character
- `/` creates nested tags: `#business/client`
```markdown
#tag #nested/tag #tag-with-dashes
# In frontmatter:
tags:
- tag1
- nested/tag2
```
## Properties (Frontmatter)
### Types
| Type | Example |
|------|---------|
| Text | `title: My Title` |
| Number | `rating: 4.5` |
| Checkbox | `completed: true` |
| Date | `date: 2024-01-15` |
| Date+Time | `due: 2024-01-15T14:30:00` |
| List | `tags: [one, two]` |
| Links | `related: "[[Other Note]]"` |
### Default properties (special meaning in Obsidian)
- `tags` — searchable tags
- `aliases` — alternative names (found via search/link autocomplete)
- `cssclasses` — custom CSS classes
## Escaping
```markdown
\*not italic\*
\#not heading
1\. not a list
```
## Footnotes
```markdown
Text with footnote[^1].
[^1]: Footnote content.
Inline footnote^[content here].
```
## Do NOT
- Use `%%` comments for processing markers (keep `<!-- -->` for scripts)
- Use block references (`^id`) in daily notes (too granular)
- Add `aliases` to CRM files (use wiki-link aliases instead)
- Use Mermaid/LaTeX unless specifically needed
+136
View File
@@ -0,0 +1,136 @@
---
paths: "**/REPORT*.md"
---
# Telegram Report Formatting
Rules for generating HTML reports for Telegram.
## CRITICAL: Output Format
**Return RAW HTML only. No markdown wrappers.**
WRONG:
```html
<b>Title</b>
```
CORRECT:
<b>Title</b>
The output goes directly to Telegram `parse_mode=HTML`. Any markdown syntax will break parsing.
## Allowed Tags
- `<b>` or `<strong>` — bold (section headers)
- `<i>` or `<em>` — italic (metadata, clarifications)
- `<code>` — inline code (commands, paths)
- `<pre>` — code blocks (rarely needed)
- `<s>`, `<strike>`, `<del>` — strikethrough
- `<u>` — underline
- `<a href="url">text</a>` — links
## FORBIDDEN
- Markdown syntax: `**`, `##`, `-`, `*`, backticks
- Markdown code blocks: triple backticks
- Tables (not supported by Telegram)
- Unsupported tags: `<div>`, `<span>`, `<br>`, `<p>`, `<table>`
- Unescaped `<` and `>` in text (use `&lt;` `&gt;`)
- Nested same tags: `<b><b>text</b></b>`
## Report Template
📊 <b>Обработка за {DATE}</b>
<b>🎯 Текущий фокус:</b>
{ONE_BIG_THING from goals/3-weekly.md}
<b>📓 Сохранено мыслей:</b> {N}
• {emoji} {title} → {category}/
<b>✅ Создано задач:</b> {M}
• {task_name} <i>({priority}, {due_date})</i>
<b>📅 Загрузка на неделю:</b>
Пн: {n} | Вт: {n} | Ср: {n} | Чт: {n} | Пт: {n} | Сб: {n} | Вс: {n}
<b>⚠️ Требует внимания:</b>
• {count} просроченных задач
• Цель "{goal}" без активности {days} дней
<b>🔗 Новые связи:</b>
• [[Note A]] ↔ [[Note B]]
<b>⚡ Топ-3 приоритета на завтра:</b>
1. {task} <i>({goal link if exists})</i>
2. {task}
3. {task}
<b>📈 Прогресс по целям:</b>
• {goal}: {progress}% {status_emoji}
---
<i>Обработано за {time}</i>
## Section Emojis
📊 Title
🎯 Focus
📓 Thoughts saved
✅ Tasks created
📅 Week load
⚠️ Attention needed
🔗 New links
⚡ Priorities
📈 Goal progress
## Category Emojis (Thoughts)
💡 idea
🪞 reflection
🎯 project
📚 learning
## Priority Format
p1 → <i>(p1, urgent)</i>
p2 → <i>(p2, {date})</i>
p3 → <i>(p3, {date})</i>
p4 → <i>(no priority)</i>
## Progress Emojis
🔴 0-25%
🟡 26-50%
🟢 51-75%
✅ 76-100%
## Error Report
❌ <b>Ошибка обработки</b>
<b>Причина:</b> {error_message}
<b>Файл:</b> <code>{file_path}</code>
<i>Попробуйте /process снова или проверьте логи</i>
## Empty Report
📭 <b>Нет записей для обработки</b>
Файл <code>daily/{date}.md</code> пуст или не найден.
<i>Добавьте голосовые сообщения или текст в течение дня</i>
## Validation Rules
Before sending report:
1. All tags are properly closed
2. No raw < or > in text
3. No markdown syntax anywhere
4. No tables
5. Total length under 4096 characters
If over 4096 chars, truncate "Новые связи" section first.
+109
View File
@@ -0,0 +1,109 @@
---
paths: "thoughts/**/*.md"
---
# Thoughts Format
Rules for notes in `thoughts/` folder and its subfolders.
## Folder Structure
```
thoughts/
├── ideas/ # Creative ideas, concepts
├── reflections/ # Personal reflections, lessons
├── projects/ # Project-related notes
└── learnings/ # Knowledge, discoveries
```
## File Naming
- Format: `YYYY-MM-DD-slug.md`
- Slug: lowercase, hyphens, descriptive
- Example: `2024-12-20-voice-agent-architecture.md`
## Frontmatter (Required)
```yaml
---
date: 2024-12-20
type: idea | reflection | project | learning
tags: [relevant, tags]
source: daily/2024-12-20.md
related: []
---
```
## Content Structure
```markdown
# Title
## Summary
One paragraph summary of the key insight.
## Details
Full content of the thought.
## Action Items
- [ ] Any tasks that emerged
- [ ] Follow-up actions
## Related
- [[Link to related note]]
- [[goals/1-yearly-2025#Section]]
```
## Tags Convention
Use hierarchical tags:
```
#type/idea
#type/learning
#topic/ai
#topic/productivity
#project/d-brain
#status/active
```
## Wiki-Links
When saving a thought:
1. **Search for related notes** in thoughts/
2. **Check MOC indexes** for topic clusters
3. **Link to relevant goals** in goals/
4. **Add backlinks** to source daily note
Example:
```markdown
Extracted from [[daily/2024-12-20]].
Related to [[Voice Agents]] and [[goals/1-yearly-2025#AI Development]].
```
## Category Guidelines
### ideas/
- Novel concepts, inventions
- Business ideas
- Creative solutions
- "What if..." thoughts
### reflections/
- Personal insights
- Lessons learned
- Emotional processing
- Gratitude, wins
### projects/
- Project-specific notes
- Meeting notes
- Status updates
- Decisions made
### learnings/
- New knowledge
- Book/article insights
- Technical discoveries
- "TIL" moments
+82
View File
@@ -0,0 +1,82 @@
---
type: note
paths: "thoughts/reflections/YYYY-W*"
---
# Weekly Reflection Format
Rules for weekly system reflections (triggered on Sundays or by `/weekly`).
## Purpose
Analyze accumulated observations → find patterns → propose improvements.
This is the **operational learning loop** — the system learns from its own friction.
## When to Generate
- Every Sunday (automatically or via `/weekly`)
- When observations in `.session/handoff.md` reach ≥10
## File Location
`thoughts/reflections/YYYY-WNN-system-reflection.md`
## Template
```markdown
---
date: YYYY-MM-DD
type: reflection
description: "Week NN system analysis: N friction signals, M patterns found, K proposals"
tags: [system, reflection, weekly]
source: .session/handoff.md
related: []
---
# Week NN System Reflection
## Friction Patterns
<!-- Group similar observations from handoff.md -->
- **mcp-cli timeouts:** N occurrences — [root cause hypothesis]
- **Empty daily files:** N of 7 days — [pattern: weekends?]
- **Broken links:** N new this week — [source: CRM imports?]
## Improvements Applied
<!-- What was fixed this week -->
- [fix] Description of what was improved
- [fix] Another improvement
## Proposals
<!-- Concrete proposals for system improvements -->
1. [proposal] Description — target file: `path/to/file`
2. [proposal] Another proposal — target: `scripts/process.sh`
## Graph Health
Score: NN/100 (↑/↓ N vs last week)
- Orphans: N (was M)
- Broken links: N (was M)
- Avg links/file: X.XX
- Description coverage: Y%
## Observations Cleared
<!-- After reflection, clear processed observations from handoff.md -->
Moved N observations to this reflection file.
```
## Process
1. Read `.session/handoff.md` → collect `## Observations`
2. Read `.graph/health-history.json` → get this week's trend
3. Group observations by type (friction/pattern/idea)
4. Find recurring patterns (same issue >2 times)
5. Propose concrete improvements (file + change)
6. Write reflection file
7. Clear processed observations from handoff.md (keep unprocessed)
8. Add reflection to daily log
## Tags
Use `#system` tag for all system reflections.
Cross-reference with:
- `[[MEMORY.md]]` — if proposals become decisions
- `[[goals/3-weekly]]` — if proposals affect weekly focus
+206
View File
@@ -0,0 +1,206 @@
---
type: note
description: >-
last_accessed: 2026-02-26
relevance: 1.0
tier: active
name: agent-memory
Use when: (1) setting up memory for a new agent, (2) diagnosing memory bloat or context
Triggers: "memory management", "organize vault", "memory decay", "forgetting curve",
---
# Agent Memory Management
Memory system with automatic decay, tiered search, and creative recall.
Works with any directory of markdown files.
## Quick Start
### 1. Scan existing files
```bash
python3 scripts/memory-engine.py scan <directory>
```
Reports: file count, YAML coverage, size, recommendations.
### 2. Bootstrap YAML frontmatter
```bash
python3 scripts/memory-engine.py init <directory> [--dry-run]
```
Adds `relevance`, `last_accessed`, `tier` to files missing frontmatter.
Infers `type` from directory path. Infers dates from YAML fields, git log, or file mtime.
### 3. Run decay
```bash
python3 scripts/memory-engine.py decay <directory> [--dry-run]
```
Updates all cards: recalculates relevance scores and reassigns tiers.
Schedule daily via cron for automatic forgetting.
### 4. Touch on read
```bash
python3 scripts/memory-engine.py touch <filepath>
```
Resets card to active (relevance=1.0). Call this when reading a card to answer a question.
### 5. Creative recall
```bash
python3 scripts/memory-engine.py creative <N> <directory>
```
Random sample from cold/archive tiers. Read these cards and look for unexpected connections.
### 6. Health check
```bash
python3 scripts/memory-engine.py stats <directory>
```
Shows tier distribution, context budget, stale card count.
## Core Concepts
### Three-Layer Architecture
| Layer | What | Size Target | Loaded |
|-------|------|-------------|--------|
| Hot context | State file (volatile focus, blockers) | <4KB | Every turn |
| Searchable vault | Cards with YAML, one per entity | Unlimited | On demand |
| Archive | Old logs, completed work | Unlimited | Deep/creative only |
**Rule:** Each fact lives in ONE place. If it's in a card, don't also put it in the state file.
See [references/architecture.md](references/architecture.md) for full design rationale.
### Forgetting Curve
Cards have `relevance: 0.0-1.0` that decays linearly over time:
- Day 0: 1.0 (just accessed)
- Day 7: 0.90 → tier: active
- Day 21: 0.69 → tier: warm
- Day 33: 0.50 → tier: cold
- Day 60+: 0.10 (floor) → tier: archive
`core` tier is manual-only — for identity, security, pricing. Never auto-demoted.
### Tier-Aware Search
| Mode | Tiers searched | When |
|------|---------------|------|
| heartbeat | core + active | Quick checks, monitoring |
| normal | active + warm | Most questions |
| deep | all tiers | Strategy, OSINT, complex analysis |
| creative | random cold+archive | Brainstorming, ideation |
See [references/search-protocols.md](references/search-protocols.md) for detailed protocols.
### YAML Frontmatter
Minimum required fields (managed by engine):
```yaml
---
relevance: 0.85
last_accessed: 2026-02-25
tier: active
---
```
See [references/yaml-schema.md](references/yaml-schema.md) for full schema with domain-specific fields.
## Daily Files (Episodic Memory)
Daily files (`memory/YYYY-MM-DD.md`) are the agent's episodic memory — what happened each day.
They follow the same decay system as vault cards. **Never delete them.**
### Lifecycle
```
Day 0: Created (end of day cron or manual) → tier: active, relevance: 1.0
Day 1-7: Auto-loaded at session start (today+yesterday) → tier: active
Day 8-21: Searchable but not auto-loaded → tier: warm
Day 22-60: Deep search only → tier: cold
Day 60+: Creative mode or explicit recall → tier: archive
```
### YAML Frontmatter for Daily Files
Add to each daily file (engine handles this via `init` or `decay`):
```yaml
---
type: daily
date: 2026-02-18
relevance: 0.76
last_accessed: 2026-02-18
tier: warm
---
```
### Session Loading Protocol
At session start, load only active-tier daily files:
```
1. Read today's daily file (if exists)
2. Read yesterday's daily file (if exists)
3. Stop. Don't load older files.
```
For questions about the past ("what happened last week?"), search warm/cold tier dailies on demand.
### Why Never Delete
1. **Disk cost ≈ zero.** 30 daily files ≈ 300KB. Irrelevant savings.
2. **Context is lost forever.** A knowledge graph captures entities but not reasoning, tone, or "why."
3. **Semantic search works on old files.** A query about "Red Bull tender" finds the relevant daily file regardless of age.
4. **Creative mode surfaces old context.** Forgotten daily entries become unexpected inspiration.
5. **Re-reading from source (Telegram, email) is expensive.** 100+ messages per day × API calls × LLM summarization > keeping a 10KB file.
### Compression (Optional)
If daily files grow large (>20KB), compress old ones instead of deleting:
1. Extract key decisions, contacts, and outcomes into vault cards
2. Trim the daily file to a 20-line summary
3. Keep the summary with its YAML frontmatter intact
This preserves searchability while reducing storage. But even without compression, a year of daily files is ~4MB — negligible.
## Configuration
Generate default config:
```bash
python3 scripts/memory-engine.py config <directory>
```
Creates `.memory-config.json`:
```json
{
"tiers": {"active": 7, "warm": 21, "cold": 60},
"decay_rate": 0.015,
"relevance_floor": 0.1,
"skip_patterns": ["_index.md"],
"type_inference": {"crm/": "crm", "leads/": "lead"},
"use_git_dates": true
}
```
Adjust tier thresholds and decay rate to match your domain's natural rhythm.
Fast-moving domains (sales): tighter thresholds (active=3, warm=10, cold=30).
Slow domains (research): wider thresholds (active=14, warm=45, cold=120).
## Cron Integration
Add decay to daily maintenance (OpenClaw example):
```json
{
"name": "memory-decay",
"schedule": {"kind": "cron", "expr": "0 22 * * *", "tz": "UTC"},
"payload": {"kind": "agentTurn", "message": "Run: python3 scripts/memory-engine.py decay vault/crm/"}
}
```
## Anti-Patterns
| Don't | Do Instead |
|-------|------------|
| Load all contacts into state file | Keep them in vault cards, search on demand |
| Create "knowledge graph" that duplicates vault | Vault IS the graph. Use index files for navigation |
| Store same fact in 3 files | One card per entity, reference via links |
| Delete old daily files to "save space" | Keep all dailies, let tier decay handle visibility |
| Auto-load all daily files at session start | Load only today + yesterday; search older on demand |
| Search all 500 cards for every question | Check index first, filter by tier, then search |
| Touch every card during bulk operations | Only touch on meaningful read/update |
| Build elaborate review systems | Let decay handle it — if you don't use it, it fades |
@@ -0,0 +1,198 @@
---
type: note
title: Memory Architecture
last_accessed: 2026-02-26
relevance: 1.0
tier: active
---
# Memory Architecture
## The Problem
AI agents forget everything between sessions. Common solutions (dump everything into context, vector-search everything) create bloat and noise. Human memory works differently: it has layers, it decays, and it surprises you with random connections.
## Design Principles
### Single Source of Truth (DRY)
Each fact lives in ONE place. If a contact exists in a CRM card, don't also list them in a "key contacts" section of your state file. Instead, reference them: `see vault/crm/alice.md`.
**Violation test:** Search for any person/project name. If it appears in 3+ files with substantive detail, you have a DRY violation.
### Context is a Shared Resource (KISS)
Every byte loaded per turn costs tokens. An agent loading 40KB of context files is burning ~10,000 tokens before the conversation starts. Measure your context budget:
- State file (volatile): target <4KB
- Config files: target <15KB total
- Per-turn overhead = sum of all always-loaded files
### Build Only What You Use (YAGNI)
Don't create "knowledge graphs," "daily digests," or "weekly reviews" unless you actively query them. If a cron job generates a report nobody reads, it's waste.
## Three-Layer Architecture
```
Layer 1: HOT CONTEXT (always loaded, <4KB)
└── State file — volatile: active focus, blockers, reminders
NOT: contacts, history, reference, tools
Layer 2: SEARCHABLE VAULT (on-demand, unlimited)
└── Cards with YAML frontmatter — one file per entity
Searched via: semantic search, grep, graph traversal
Organized by: domain directories + index files (MOC)
Layer 3: ARCHIVE (deep search only)
└── Old daily logs, completed projects, cold contacts
Still searchable but excluded from default queries
```
### Layer 1: Hot Context
This is what's loaded every turn. Must be ruthlessly slim.
**Include:** Current week's focus, active blockers, 3-5 pending items, security rules, navigation hints.
**Exclude:** Contact lists (use vault), tool docs (separate file), event history (daily files), anything searchable.
**Audit:** If your state file exceeds 80 lines, something belongs in Layer 2.
### Layer 2: Searchable Vault
One markdown file per entity (person, project, company, idea). YAML frontmatter enables filtering and automation.
**Directory structure:**
```
vault/
├── crm/ # contacts and companies
│ ├── clients/
│ ├── leads/
│ └── personal/
├── projects/ # active and past projects
├── MOC/ # Maps of Content (index files)
└── .graph/ # computed graph data
```
**Why one file per entity:** Enables granular decay, individual relevance scoring, and precise search results. A single "contacts.md" with 200 entries can't decay — the whole file is either loaded or not.
### Layer 2b: Daily Files (Episodic Memory)
Daily logs (`memory/YYYY-MM-DD.md`) sit between vault and archive. They capture the raw narrative of each day — conversations, decisions, reasoning, context that doesn't fit neatly into entity cards.
**Never delete daily files.** The decay system handles visibility:
- Active (0-7 days): loaded at session start
- Warm (8-21 days): searchable, not auto-loaded
- Cold (22-60 days): deep search only
- Archive (60+): creative mode, explicit queries
**Why keep everything:**
- Disk: 365 daily files ≈ 4MB. Irrelevant cost.
- Context: knowledge graphs capture entities but lose reasoning and tone.
- Search: semantic search finds old dailies just as well as new ones.
- Source rebuild: re-reading 100+ Telegram messages is far more expensive than keeping a 10KB summary.
**Compression:** If a daily file exceeds 20KB, extract key facts into vault cards and trim the daily to a 20-line summary. Keep the YAML frontmatter intact.
### Layer 3: Archive
One-off analysis reports. Completed project retrospectives. Generated artifacts that served a temporary purpose. These are still searchable but excluded from default queries. Daily files are NOT archive — they stay in `memory/` with tier-based visibility.
## Forgetting Curve
Inspired by Ebbinghaus (1885): memory strength decays over time without reinforcement.
### Relevance Score
Each card has `relevance: 0.0-1.0` in its frontmatter. Decays linearly:
```
relevance = max(floor, 1.0 - days_since_access × rate)
Default: rate=0.015, floor=0.1
→ After 7 days: 0.90
→ After 21 days: 0.69
→ After 33 days: 0.50
→ After 60 days: 0.10 (floor)
```
### Tier Assignment
Based on days since `last_accessed`:
| Tier | Days | Description |
|------|------|-------------|
| core | manual | Never auto-assigned. Identity, security, pricing. |
| active | 0-7 | Hot context. Searched in all modes. |
| warm | 8-21 | Default search radius. Gradually fading. |
| cold | 22-60 | Deep search only. Mostly forgotten. |
| archive | 60+ | Creative mode or explicit recall only. |
### Touch Protocol
When an agent reads or references a card, it should reset the card:
```bash
python3 memory-engine.py touch <filepath>
```
This sets `last_accessed` to today, `relevance` to 1.0, and `tier` to active.
**When to touch:**
- Agent reads card content to answer a question
- Agent updates card with new information
- User explicitly mentions the entity
**When NOT to touch:**
- Card appears in search results but isn't opened
- Automated scan (decay script itself)
- Bulk operations
## Search Protocols
Different tasks need different search depths:
### Heartbeat Mode (fast checks)
Search: core + active only.
Use for: quick status checks, routine monitoring, simple questions.
Cost: minimal — only hot cards in scope.
### Normal Mode (default)
Search: core + active + warm.
Use for: most questions, task execution, lookups.
Cost: moderate — includes fading but recent cards.
### Deep Mode (complex tasks)
Search: all tiers.
Use for: strategy, OSINT, complex analysis, "find everything about X."
Cost: high — full vault scan.
### Creative Mode (divergent thinking)
Method: random sample from cold + archive tiers.
Use for: brainstorming, finding unexpected connections, "what if" scenarios.
Not semantic search — deliberately random to surface forgotten associations.
```bash
python3 memory-engine.py creative 5 vault/
```
## Multi-Agent Shared Memory
When multiple agents share a vault:
1. **Shared YAML schema** — all agents use same frontmatter fields
2. **Each agent touches on read** — keeps decay accurate across agents
3. **One vault, one truth** — don't fork the vault per agent
4. **Conflict resolution** — last write wins for metadata; append-only for history sections
## Context Budget Calculator
Measure your actual per-turn cost:
```
Always-loaded files:
STATE.md _____ bytes
CONFIG.md _____ bytes
IDENTITY.md _____ bytes
RULES.md _____ bytes
─────────────────────────
Total context: _____ bytes ÷ 4 ≈ _____ tokens
Target: <25KB (6,000 tokens) for always-loaded context
```
Every 1KB saved = ~250 tokens freed per turn for actual conversation.
@@ -0,0 +1,125 @@
---
type: note
title: Search Protocols
last_accessed: 2026-02-26
relevance: 1.0
tier: active
---
# Search Protocols
## Protocol Selection
Before searching, classify the task:
| Signal | Mode | Search Radius |
|--------|------|---------------|
| Quick status check, monitoring | heartbeat | core + active |
| Normal question, lookup | normal | active + warm |
| "Find everything about X" | deep | all tiers |
| Strategy, OSINT, complex analysis | deep | all tiers |
| Brainstorm, "what if", ideation | creative | random from cold+archive |
## Search Order (All Modes)
1. **Index files first** — MOC or `_index.md` files are pre-built navigation. Check them before searching.
2. **Follow links** — If an index points to `[[crm/acme]]`, read the card directly. Don't search for "Acme."
3. **Semantic search** — Only when indexes don't cover the query.
4. **Grep** — Last resort for exact strings, IDs, phone numbers.
## Tier Filtering
### Pre-filter with grep
```bash
# Find all active cards
grep -rl "^tier: active" vault/crm/
# Find all cold+ cards for deep search
grep -rl "^tier: \(cold\|archive\)" vault/crm/
# Find high-relevance cards
grep -l "^relevance: 0\.9" vault/crm/
```
### Combine with semantic search
1. Grep for tier → get file list
2. Read relevant files → answer question
This is cheaper than searching all 400+ cards semantically.
## Heartbeat Protocol
Heartbeats are frequent, automated checks. Minimize cost:
1. Read state file (always loaded)
2. Check only `core` + `active` tier cards matching current projects
3. Skip warm/cold/archive entirely
4. Total reads: 0-5 files per heartbeat
## Normal Protocol
Default for user questions:
1. Check index/MOC for direct link
2. If not found: semantic search with default radius (active + warm)
3. Read top 3-5 results
4. Touch any card you read: `memory-engine.py touch <file>`
## Deep Protocol
For complex, multi-step analysis:
1. Check indexes
2. Semantic search across ALL tiers (no filtering)
3. Read all relevant results (up to 10-15 files)
4. Cross-reference cards for connections
5. Touch all read cards
## Creative Protocol
Deliberately non-directed. Goal: surface unexpected connections.
```bash
python3 memory-engine.py creative 5 vault/
```
1. Get 5 random cards from cold/archive
2. Read each one
3. For each card, ask: "How could this connect to my current task?"
4. If a connection exists → touch the card (promotes it back to active)
5. If no connection → leave it (continues to decay)
### When to use creative mode
- Stuck on a problem
- Looking for new business angles
- User says "brainstorm" or "what if"
- Exploring forgotten knowledge
- Weekly reflection sessions
### What makes it work
Human creativity often comes from random associations — shower thoughts, dreams, serendipitous encounters. Creative mode simulates this by pulling forgotten cards back into working memory. The randomness is the feature, not a bug.
## Touch Discipline
Touching a card resets its decay. Over-touching defeats the purpose.
**Touch when:**
- You read the card's content to answer a question
- You update the card with new information
- User explicitly discusses the entity
**Don't touch when:**
- Card appears in search results but you didn't open it
- Running automated scans or reports
- Bulk migration or formatting changes
- Card mentioned in passing but not substantively used
## Cost Awareness
| Mode | Typical reads | Token cost |
|------|---------------|------------|
| Heartbeat | 0-5 files | ~2K tokens |
| Normal | 3-8 files | ~5K tokens |
| Deep | 10-20 files | ~15K tokens |
| Creative | 5 files | ~3K tokens |
Optimize by reading index files first — they're cheap navigation that prevents expensive full-text searches.
@@ -0,0 +1,189 @@
---
type: note
title: YAML Frontmatter Schema
last_accessed: 2026-02-26
relevance: 1.0
tier: active
---
# YAML Frontmatter Schema
## Canonical Schema (all card types)
Every card MUST have this structure. Fields marked (auto) are managed by memory-engine.py.
Fields marked (required) must be written by the agent when creating a card.
```yaml
---
# ── identity ──
type: crm # (required) crm | lead | contact | project | personal | daily | note
description: >- # (required) One-line summary. What is this card about?
Key client in [industry], active deal $XXK, [project description]
# ── classification ──
tags: [fmcg, active-deal, uz] # (required) 2-5 freeform tags for grep filtering
status: active # (required) universal: active|draft|pending|done|inactive; CRM-only: prospect|negotiation|won|lost
industry: FMCG # (optional) For CRM/leads
region: UZ # (optional) ISO country codes
source: referral # (optional) How this entity entered the system
priority: High # (optional) High | Medium | Low
# ── ownership ──
owner: [Your Name] # (optional) Who owns this relationship
responsible: [Your Name] # (optional) Who is doing the work
# ── dates ──
created: 2026-01-15 # (recommended) When card was first created
updated: 2026-02-20 # (recommended) When content was last meaningfully changed
# ── deal tracking ──
deal_status: negotiation # (optional) For active deals
deal_deadline: 2026-03-15 # (optional) Deal close date
# ── memory system (auto) ──
last_accessed: 2026-02-25 # (auto) When card was last read/touched
relevance: 0.85 # (auto) 0.0-1.0, decays over time
tier: active # (auto) core | active | warm | cold | archive
---
```
## Required Fields Explained
### `description` (string, one line)
The single most important field for search quality. Write a concise summary that answers:
"If someone searches for this entity, what should they see in results?"
Good: `"Event Specialist, [Company] [Country], tender 2026"`
Bad: `"контакт"` (too vague)
Bad: (empty — defeats the purpose of the entire system)
### `tags` (list, 2-5 items)
Cross-cutting labels for fast grep filtering. Use lowercase, hyphens.
```yaml
tags: [hot-lead, ai-training, enterprise, follow-up]
```
Search: `grep -rl "hot-lead" vault/crm/`
### `type` (enum)
| Type | When |
|------|------|
| crm | Existing client/company |
| lead | Potential client |
| contact | Person (not a lead/client) |
| project | Active or past project |
| personal | Family, friends |
| daily | Daily log file |
| note | Everything else |
### `status` (enum, normalized)
Domain-specific lifecycle. NOT the same as `tier` (which is memory-system lifecycle).
**Universal (all card types):**
| Status | Meaning |
|--------|---------|
| `active` | Currently relevant, in use, engaged |
| `draft` | Work in progress, not finalized |
| `pending` | Waiting for external input or decision |
| `done` | Completed, kept for reference |
| `inactive` | Was active, went quiet or outdated |
**CRM-specific (only for type: crm, lead, crm-lead, client):**
| Status | Meaning |
|--------|---------|
| `prospect` | Identified lead, no deep engagement yet |
| `negotiation` | Proposal/KP sent, in talks |
| `won` | Deal closed positively |
| `lost` | Rejected, didn't pursue, conflict |
**ONLY these 9 values.** No Russian, no mixed case, no free-text.
Typical lifecycle by type:
- **crm/lead:** prospect → active → negotiation → won/lost
- **project:** draft → active → done
- **contact:** active → inactive
- **note/knowledge:** draft → active → inactive (outdated)
- **personal:** active → inactive
- **daily:** no status needed (has `date` field)
When in doubt: CRM → `prospect`, everything else → `active`.
## Memory System Fields (auto-managed)
### `relevance` (float, 0.0-1.0)
Computed by decay engine. Do not manually edit unless marking as `core`.
- 1.0 = just accessed
- 0.5 = ~33 days old
- 0.1 = floor (60+ days)
### `tier` (enum)
Computed by decay engine based on `last_accessed`.
- `core` — only manually assigned, never auto-demoted. Use for: identity, security rules, pricing.
- `active` — 0-7 days since access. Searched in all modes.
- `warm` — 8-21 days. Searched in normal+ modes.
- `cold` — 22-60 days. Deep search only.
- `archive` — 60+ days. Creative mode or explicit queries.
### `last_accessed` (ISO date)
Updated by `touch` command (graduated: +1 tier per touch).
## Agent Protocol for New Cards
When creating ANY new card:
1. ALWAYS include: `type`, `description`, `tags`, `status`
2. Write `description` as if it's a search result snippet — concise, informative
3. Add 2-5 `tags` that cross-cut directory structure
4. Run `memory-engine.py touch <file>` after creation
5. The engine will auto-add `relevance`, `last_accessed`, `tier` on next decay run
## Field Semantics
### `relevance` (float, 0.0-1.0)
Computed by decay engine. Do not manually edit unless marking as `core`.
- 1.0 = just accessed
- 0.5 = ~33 days old
- 0.1 = floor (60+ days)
### `tier` (enum)
Computed by decay engine based on `last_accessed`.
- `core` — only manually assigned, never auto-demoted. Use for: identity, security rules, pricing, critical reference.
- `active` — 0-7 days since access. Searched in all modes.
- `warm` — 8-21 days. Searched in normal+ modes.
- `cold` — 22-60 days. Deep search only.
- `archive` — 60+ days. Creative mode or explicit queries.
### `last_accessed` (ISO date)
Updated by `touch` command when agent reads the card. Also updated by decay engine on first run (inferred from `updated`, `created`, git log, or file mtime).
### `type` (string)
Auto-inferred from directory path if not present. Configurable via `type_inference` in `.memory-config.json`.
### `tags` (list)
Freeform. Useful for cross-cutting concerns that don't fit directory structure.
```yaml
tags: [hot-lead, ai-training, enterprise, follow-up]
```
Search: `grep -rl "hot-lead" vault/crm/`
## Configuration
Type inference mapping in `.memory-config.json`:
```json
{
"type_inference": {
"crm/clients/": "crm",
"crm/leads/": "lead",
"crm/personal/": "personal",
"projects/": "project"
}
}
```
When `memory-engine.py init` encounters a file without `type`, it checks the file path against these patterns.
## Frontmatter Tips
1. **Don't duplicate content.** If the H1 heading says "# Acme Corp", you don't need `title: Acme Corp` — the engine infers it.
2. **Tags > nested directories.** A flat `crm/` with tags is more flexible than `crm/hot/enterprise/ai/`.
3. **Status is domain-specific.** The memory system uses `tier` for lifecycle; `status` is for your business logic (active/won/lost/churned).
4. **`updated` vs `last_accessed`**: `updated` = when content changed; `last_accessed` = when anyone read it. Both matter for decay; the engine uses whichever is most recent.
@@ -0,0 +1,645 @@
#!/usr/bin/env python3
"""
memory-engine.py — Universal memory management for AI agents.
Implements Ebbinghaus-inspired forgetting curve with tiered recall.
Works with any directory of markdown files.
Commands:
scan [dir] Analyze files, report stats (no changes)
init [dir] Add YAML frontmatter to files missing it
decay [dir] Update relevance scores and tiers
touch <file> Reset file to active (on read/use)
creative <N> [dir] Random N cards from cold/archive tiers
stats [dir] Show tier distribution and health metrics
Options:
--config <path> Config JSON (default: .memory-config.json in target dir)
--dry-run Preview changes without writing
--verbose Show per-file details
Config (.memory-config.json):
{
"tiers": {
"active": 7, // days threshold
"warm": 21,
"cold": 60
// beyond cold = archive
},
"decay_rate": 0.015, // relevance loss per day (linear)
"relevance_floor": 0.1, // minimum relevance
"skip_patterns": ["_index.md", "MOC-*"],
"type_inference": {
"crm/": "crm",
"leads/": "lead",
"personal/": "personal"
},
"use_git_dates": true
}
"""
import os
import re
import sys
import json
import random
import subprocess
from datetime import datetime, date
from pathlib import Path
from typing import Optional
# ─── defaults ───────────────────────────────────────────────────
DEFAULT_CONFIG = {
"tiers": {"active": 7, "warm": 21, "cold": 60},
"decay_rate": 0.015,
"relevance_floor": 0.1,
"skip_patterns": ["_index.md"],
"type_inference": {},
"use_git_dates": True,
}
TODAY = date.today()
# ─── YAML frontmatter parsing ──────────────────────────────────
def parse_frontmatter(content: str) -> tuple[dict, str, bool]:
"""Parse YAML frontmatter. Returns (fields, body, had_yaml)."""
if content.startswith("---\n"):
end = content.find("\n---\n", 4)
if end != -1:
yaml_block = content[4:end]
body = content[end + 5:]
fields = {}
for line in yaml_block.split("\n"):
if ":" in line:
key, _, val = line.partition(":")
fields[key.strip()] = val.strip()
return fields, body, True
return {}, content, False
def build_frontmatter(fields: dict, field_order: list[str] | None = None) -> str:
"""Build YAML frontmatter from dict, preserving field order."""
if field_order is None:
field_order = [
"type", "title", "description", "tags",
"industry", "source", "priority", "status", "region",
"owner", "responsible", "domain", "related", "client",
"deal_status", "deal_deadline", "deadline",
"created", "updated", "last_accessed", "relevance", "tier",
]
lines = []
used = set()
for key in field_order:
if key in fields:
lines.append(f"{key}: {fields[key]}")
used.add(key)
for key, val in fields.items():
if key not in used:
lines.append(f"{key}: {val}")
return "---\n" + "\n".join(lines) + "\n---\n"
# ─── date resolution ───────────────────────────────────────────
def get_git_date(filepath: Path) -> date | None:
"""Last git commit date for file."""
try:
result = subprocess.run(
["git", "log", "-1", "--format=%aI", "--", str(filepath)],
capture_output=True, text=True,
cwd=filepath.parent, timeout=5,
)
if result.returncode == 0 and result.stdout.strip():
return date.fromisoformat(result.stdout.strip()[:10])
except Exception:
pass
return None
def get_best_date(fields: dict, filepath: Path, use_git: bool = True) -> date:
"""Most recent date from YAML fields, git history, or file mtime."""
candidates = []
for field in ["last_accessed", "updated", "created"]:
val = fields.get(field, "")
try:
candidates.append(date.fromisoformat(val[:10]))
except (ValueError, IndexError):
continue
if use_git:
git_date = get_git_date(filepath)
if git_date:
candidates.append(git_date)
if not candidates:
mtime = os.path.getmtime(filepath)
candidates.append(date.fromtimestamp(mtime))
return max(candidates)
# ─── core logic ─────────────────────────────────────────────────
def calc_relevance(days: int, rate: float, floor: float) -> float:
"""Linear decay with floor."""
return round(max(floor, 1.0 - days * rate), 2)
def calc_tier(days: int, tiers: dict, current_tier: str = "") -> str:
"""Assign tier based on days since last access."""
if current_tier == "core":
return "core" # never auto-demote core
sorted_tiers = sorted(tiers.items(), key=lambda x: x[1])
for tier_name, threshold in sorted_tiers:
if days <= threshold:
return tier_name
return "archive"
def infer_type(filepath: Path, type_map: dict) -> str:
"""Infer card type from path using configurable mapping."""
path_str = str(filepath)
for pattern, card_type in type_map.items():
if pattern in path_str:
return card_type
return "note"
def should_skip(filepath: Path, patterns: list[str]) -> bool:
"""Check if file matches skip patterns."""
import fnmatch
name = filepath.name
for pattern in patterns:
if fnmatch.fnmatch(name, pattern):
return True
return False
def infer_title(body: str) -> str:
"""Extract title from first H1 heading."""
for line in body.split("\n")[:10]:
if line.startswith("# "):
return line[2:].strip()
return ""
# ─── config ─────────────────────────────────────────────────────
def load_config(target_dir: Path, config_path: str | None = None) -> dict:
"""Load config from file or return defaults."""
if config_path:
p = Path(config_path)
else:
p = target_dir / ".memory-config.json"
if p.exists():
with open(p) as f:
user = json.load(f)
# Merge with defaults
config = {**DEFAULT_CONFIG, **user}
config["tiers"] = {**DEFAULT_CONFIG["tiers"], **user.get("tiers", {})}
return config
return DEFAULT_CONFIG.copy()
def save_default_config(target_dir: Path):
"""Write default config file."""
p = target_dir / ".memory-config.json"
with open(p, "w") as f:
json.dump(DEFAULT_CONFIG, f, indent=2)
print(f" wrote default config: {p}")
# ─── commands ───────────────────────────────────────────────────
def find_cards(target_dir: Path, config: dict) -> list[Path]:
"""Find all markdown files, respecting skip patterns."""
cards = sorted(target_dir.rglob("*.md"))
return [c for c in cards if c.exists() and not c.is_symlink() and not should_skip(c, config["skip_patterns"])]
def cmd_scan(target_dir: Path, config: dict, verbose: bool = False):
"""Analyze files without changes."""
cards = find_cards(target_dir, config)
with_yaml = 0
without_yaml = 0
has_relevance = 0
has_tier = 0
total_bytes = 0
for card in cards:
content = card.read_text(encoding="utf-8", errors="replace")
total_bytes += len(content.encode("utf-8"))
fields, body, had_yaml = parse_frontmatter(content)
if had_yaml:
with_yaml += 1
else:
without_yaml += 1
if "relevance" in fields:
has_relevance += 1
if "tier" in fields:
has_tier += 1
if verbose and not had_yaml:
print(f" no yaml: {card.relative_to(target_dir)}")
print(f"\n scan results for {target_dir}:")
print(f" total files: {len(cards)}")
print(f" with yaml: {with_yaml}")
print(f" without yaml: {without_yaml}")
print(f" has relevance: {has_relevance}")
print(f" has tier: {has_tier}")
print(f" total size: {total_bytes / 1024:.0f} KB")
print(f" avg file size: {total_bytes / max(len(cards), 1) / 1024:.1f} KB")
if without_yaml:
print(f"\n → run 'init' to add YAML frontmatter to {without_yaml} files")
if not has_relevance:
print(f" → run 'decay' to add relevance scores and tiers")
def cmd_init(target_dir: Path, config: dict, dry_run: bool = False, verbose: bool = False):
"""Add YAML frontmatter to files missing it."""
cards = find_cards(target_dir, config)
added = 0
for card in cards:
content = card.read_text(encoding="utf-8", errors="replace")
fields, body, had_yaml = parse_frontmatter(content)
if had_yaml:
continue
# Create minimal frontmatter
new_fields = {
"type": infer_type(card, config["type_inference"]),
}
title = infer_title(body)
if title:
new_fields["title"] = title
ref_date = get_best_date({}, card, config["use_git_dates"])
new_fields["last_accessed"] = ref_date.isoformat()
days = max(0, (TODAY - ref_date).days)
new_fields["relevance"] = str(calc_relevance(days, config["decay_rate"], config["relevance_floor"]))
new_fields["tier"] = calc_tier(days, config["tiers"])
new_content = build_frontmatter(new_fields) + body
if not dry_run:
card.write_text(new_content, encoding="utf-8")
added += 1
if verbose:
print(f" {'[dry] ' if dry_run else ''}init: {card.relative_to(target_dir)} → {new_fields['tier']}")
print(f"\n {'DRY RUN — ' if dry_run else ''}init results:")
print(f" files processed: {len(cards)}")
print(f" frontmatter added: {added}")
def cmd_decay(target_dir: Path, config: dict, dry_run: bool = False, verbose: bool = False):
"""Update relevance and tiers based on time decay."""
cards = find_cards(target_dir, config)
results = []
for card in cards:
content = card.read_text(encoding="utf-8", errors="replace")
fields, body, had_yaml = parse_frontmatter(content)
ref_date = get_best_date(fields, card, config["use_git_dates"])
days = max(0, (TODAY - ref_date).days)
old_tier = fields.get("tier", "")
new_relevance = calc_relevance(days, config["decay_rate"], config["relevance_floor"])
new_tier = calc_tier(days, config["tiers"], old_tier)
if "last_accessed" not in fields:
fields["last_accessed"] = ref_date.isoformat()
if "type" not in fields:
fields["type"] = infer_type(card, config["type_inference"])
fields["relevance"] = str(new_relevance)
fields["tier"] = new_tier
new_content = build_frontmatter(fields) + body
changed = new_content != content
if changed and not dry_run:
card.write_text(new_content, encoding="utf-8")
results.append({
"path": str(card.relative_to(target_dir)),
"days": days,
"relevance": new_relevance,
"tier": new_tier,
"changed": changed,
})
if verbose and changed:
print(f" {'[dry] ' if dry_run else ''}{card.relative_to(target_dir)}: {old_tier or '?'}→{new_tier} r={new_relevance}")
# Stats
tiers = {}
changed_count = sum(1 for r in results if r["changed"])
for r in results:
tiers[r["tier"]] = tiers.get(r["tier"], 0) + 1
avg_rel = sum(r["relevance"] for r in results) / max(len(results), 1)
print(f"\n {'DRY RUN — ' if dry_run else ''}decay results:")
print(f" total: {len(results)}, changed: {changed_count}")
print(f" avg relevance: {avg_rel:.2f}")
for tier in ["core", "active", "warm", "cold", "archive"]:
count = tiers.get(tier, 0)
bar = "█" * (count // 3)
if count:
print(f" {tier:8s}: {count:4d} {bar}")
def cmd_touch(filepath: str, config: dict):
"""Promote a file one tier up (graduated recall).
archive → cold → warm → active → active (refresh)
Each touch promotes one level, not straight to top.
Natural spaced repetition: multiple reads = stronger memory.
"""
p = Path(filepath)
if not p.exists():
print(f" error: {filepath} not found")
sys.exit(1)
content = p.read_text(encoding="utf-8", errors="replace")
fields, body, had_yaml = parse_frontmatter(content)
if fields.get("tier") == "core":
fields["last_accessed"] = TODAY.isoformat()
fields["relevance"] = "1.0"
new_content = build_frontmatter(fields) + body
p.write_text(new_content, encoding="utf-8")
print(f" touched: {filepath} → core (refreshed)")
return
tiers_cfg = config["tiers"]
# Promotion targets: set last_accessed to midpoint of next-higher tier
# archive → cold: midpoint of cold range
# cold → warm: midpoint of warm range
# warm → active: midpoint of active range
# active → active: today (refresh)
cold_threshold = tiers_cfg.get("cold", 60)
warm_threshold = tiers_cfg.get("warm", 21)
active_threshold = tiers_cfg.get("active", 7)
current_tier = fields.get("tier", "archive")
if current_tier == "archive":
# Promote to cold: set last_accessed to midpoint of cold range
target_days = (warm_threshold + cold_threshold) // 2
new_tier = "cold"
elif current_tier == "cold":
# Promote to warm: midpoint of warm range
target_days = (active_threshold + warm_threshold) // 2
new_tier = "warm"
elif current_tier == "warm":
# Promote to active: midpoint of active range
target_days = active_threshold // 2
new_tier = "active"
else:
# Already active: refresh to today
target_days = 0
new_tier = "active"
from datetime import timedelta
new_date = TODAY - timedelta(days=target_days)
new_relevance = calc_relevance(target_days, config["decay_rate"], config["relevance_floor"])
fields["last_accessed"] = new_date.isoformat()
fields["relevance"] = str(new_relevance)
fields["tier"] = new_tier
new_content = build_frontmatter(fields) + body
p.write_text(new_content, encoding="utf-8")
print(f" touched: {filepath} → {current_tier}→{new_tier}, relevance={new_relevance}")
def cmd_creative(n: int, target_dir: Path, config: dict):
"""Random sample from cold/archive tiers for divergent thinking."""
cards = find_cards(target_dir, config)
cold_cards = []
for card in cards:
content = card.read_text(encoding="utf-8", errors="replace")
fields, body, had_yaml = parse_frontmatter(content)
tier = fields.get("tier", "")
if tier in ("cold", "archive", "warm"):
title = fields.get("title", "") or infer_title(body)
cold_cards.append({
"path": str(card.relative_to(target_dir)),
"tier": tier,
"relevance": fields.get("relevance", "?"),
"title": title,
"last_accessed": fields.get("last_accessed", "?"),
})
if not cold_cards:
print(" no cold/archive cards found — memory is too fresh")
return
sample = random.sample(cold_cards, min(n, len(cold_cards)))
print(f"\n 🎲 creative recall — {len(sample)} random cards:")
for card in sample:
print(f" [{card['tier']}] {card['title'] or card['path']}")
print(f" {card['path']} (r={card['relevance']}, last={card['last_accessed']})")
print(f"\n read these cards and look for unexpected connections to your current task")
def cmd_daily(target_dir: Path, config: dict, dry_run: bool = False, verbose: bool = False):
"""Bootstrap and decay daily files (YYYY-MM-DD.md pattern)."""
date_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}\.md$")
daily_files = sorted(
f for f in target_dir.rglob("*.md")
if date_pattern.match(f.name)
)
if not daily_files:
print(f" no daily files (YYYY-MM-DD.md) found in {target_dir}")
return
results = []
for f in daily_files:
content = f.read_text(encoding="utf-8", errors="replace")
fields, body, had_yaml = parse_frontmatter(content)
# Extract date from filename
file_date = date.fromisoformat(f.stem)
days = max(0, (TODAY - file_date).days)
# Use file_date as reference (not git/mtime — daily files are date-intrinsic)
la = fields.get("last_accessed", "")
try:
last_acc = date.fromisoformat(la[:10])
# Use most recent of: file_date, last_accessed
ref_days = max(0, (TODAY - max(file_date, last_acc)).days)
except (ValueError, IndexError):
ref_days = days
new_relevance = calc_relevance(ref_days, config["decay_rate"], config["relevance_floor"])
old_tier = fields.get("tier", "")
new_tier = calc_tier(ref_days, config["tiers"], old_tier)
fields["type"] = "daily"
fields["date"] = file_date.isoformat()
if "last_accessed" not in fields:
fields["last_accessed"] = file_date.isoformat()
fields["relevance"] = str(new_relevance)
fields["tier"] = new_tier
new_content = build_frontmatter(fields) + body
changed = new_content != content
if changed and not dry_run:
f.write_text(new_content, encoding="utf-8")
results.append({
"file": f.name,
"date": file_date.isoformat(),
"days": ref_days,
"relevance": new_relevance,
"tier": new_tier,
"changed": changed,
})
if verbose:
print(f" {'[dry] ' if dry_run else ''}{f.name}: {old_tier or '?'}→{new_tier} r={new_relevance} ({ref_days}d)")
# Summary
tiers = {}
for r in results:
tiers[r["tier"]] = tiers.get(r["tier"], 0) + 1
changed_count = sum(1 for r in results if r["changed"])
print(f"\n {'DRY RUN — ' if dry_run else ''}daily results:")
print(f" files: {len(results)}, changed: {changed_count}")
for tier in ["active", "warm", "cold", "archive"]:
count = tiers.get(tier, 0)
if count:
dates = [r["date"] for r in results if r["tier"] == tier]
print(f" {tier:8s}: {count:3d} ({dates[0]}..{dates[-1]})")
def cmd_stats(target_dir: Path, config: dict):
"""Show comprehensive memory health stats."""
cards = find_cards(target_dir, config)
tiers = {}
total_bytes = 0
stale_count = 0
no_yaml = 0
for card in cards:
content = card.read_text(encoding="utf-8", errors="replace")
total_bytes += len(content.encode("utf-8"))
fields, body, had_yaml = parse_frontmatter(content)
if not had_yaml:
no_yaml += 1
tier = fields.get("tier", "unknown")
tiers[tier] = tiers.get(tier, 0) + 1
try:
la = date.fromisoformat(fields.get("last_accessed", "")[:10])
if (TODAY - la).days > 90:
stale_count += 1
except (ValueError, IndexError):
pass
print(f"\n memory health — {target_dir}")
print(f" {'─' * 40}")
print(f" total cards: {len(cards)}")
print(f" total size: {total_bytes / 1024:.0f} KB")
print(f" without yaml: {no_yaml}")
print(f" stale (>90 days): {stale_count}")
print(f" {'─' * 40}")
print(f" tier distribution:")
for tier in ["core", "active", "warm", "cold", "archive", "unknown"]:
count = tiers.get(tier, 0)
if count:
pct = count / len(cards) * 100
bar = "█" * int(pct / 2)
print(f" {tier:8s}: {count:4d} ({pct:4.1f}%) {bar}")
# Context budget estimate (assuming ~4 chars per token)
active_bytes = 0
for card in cards:
content = card.read_text(encoding="utf-8", errors="replace")
fields, _, _ = parse_frontmatter(content)
if fields.get("tier") in ("core", "active"):
active_bytes += len(content.encode("utf-8"))
print(f" {'─' * 40}")
print(f" active context: {active_bytes / 1024:.0f} KB (~{active_bytes // 4:,} tokens)")
print(f" total context: {total_bytes / 1024:.0f} KB (~{total_bytes // 4:,} tokens)")
# ─── main ───────────────────────────────────────────────────────
def main():
args = sys.argv[1:]
if not args or args[0] in ("-h", "--help"):
print(__doc__)
sys.exit(0)
cmd = args[0]
dry_run = "--dry-run" in args
verbose = "--verbose" in args
# Find config path
config_path = None
if "--config" in args:
idx = args.index("--config")
config_path = args[idx + 1] if idx + 1 < len(args) else None
# Find target directory (first non-flag argument after command)
target = None
for a in args[1:]:
if not a.startswith("-") and a != config_path:
target = a
break
if cmd == "touch":
if not target:
print(" error: touch requires a file path")
sys.exit(1)
config = load_config(Path(target).parent, config_path)
cmd_touch(target, config)
return
if cmd == "creative":
n = 5
creative_dir = None
for a in args[1:]:
if not a.startswith("-"):
try:
n = int(a)
except ValueError:
creative_dir = a
target_dir = Path(creative_dir) if creative_dir else Path(".")
config = load_config(target_dir, config_path)
cmd_creative(n, target_dir, config)
return
target_dir = Path(target) if target else Path(".")
if not target_dir.is_dir():
print(f" error: {target_dir} is not a directory")
sys.exit(1)
config = load_config(target_dir, config_path)
if cmd == "scan":
cmd_scan(target_dir, config, verbose)
elif cmd == "init":
cmd_init(target_dir, config, dry_run, verbose)
elif cmd == "decay":
cmd_decay(target_dir, config, dry_run, verbose)
elif cmd == "daily":
cmd_daily(target_dir, config, dry_run, verbose)
elif cmd == "stats":
cmd_stats(target_dir, config)
elif cmd == "config":
save_default_config(target_dir)
else:
print(f" unknown command: {cmd}")
print(" commands: scan, init, decay, daily, touch, creative, stats, config")
sys.exit(1)
if __name__ == "__main__":
main()
@@ -0,0 +1,620 @@
---
type: note
description: Personal assistant for processing daily voice/text entries from Telegram. Classifies content, creates Todoist tasks aligned with goals, saves thoughts to Obsidian with wiki-links, generates HTML reports. Integrates Your Business context (clients, projects, CRM). Triggers on /process command or daily 21:00 cron.
name: dbrain-processor
allowed-tools: Bash(mcp-cli:*)
depends_on: [graph-builder, todoist-ai, agent-memory, vault-health]
---
# d-brain Processor
Process daily entries → tasks (Todoist) + thoughts (Obsidian) + HTML report (Telegram).
Integrates with Your Business data for business context.
## CRITICAL: Output Format
**ALWAYS return RAW HTML. No exceptions. No markdown. Ever.**
Your final output goes directly to Telegram with `parse_mode=HTML`.
Rules:
1. ALWAYS return HTML report — even if entries already processed
2. ALWAYS use the template below — no free-form text
3. NEVER use markdown syntax (**, ##, ```, -)
4. NEVER explain what you did in plain text — put it in HTML report
WRONG:
```html
<b>Title</b>
```
CORRECT:
<b>Title</b>
## Todoist через mcp-cli
**ВСЕГДА используй mcp-cli для Todoist.** Не используй прямые MCP tools.
### Базовые команды:
```bash
# Задачи на сегодня (проверка workload)
mcp-cli call todoist find-tasks-by-date '{"startDate": "today"}'
# Создать задачу
mcp-cli call todoist add-tasks '{"tasks": [{"content": "Task", "dueString": "tomorrow", "priority": 2}]}'
# Найти задачи по label
mcp-cli call todoist find-tasks '{"labels": ["process-goal"]}'
# Завершить задачи
mcp-cli call todoist complete-tasks '{"ids": ["task_id"]}'
# Обзор
mcp-cli call todoist get-overview '{}'
```
### Приоритеты:
- 1 = p1 (highest)
- 2 = p2 (high)
- 3 = p3 (medium)
- 4 = p4 (default)
## CRITICAL: mcp-cli Usage
**СНАЧАЛА ВЫЗОВИ КОМАНДУ. ПОТОМ ДУМАЙ.**
### Обязательный алгоритм:
```
1. ВЫЗОВИ: mcp-cli call todoist find-tasks-by-date '{"startDate": "today"}'
↓
Получил результат? → Продолжай
↓
Ошибка? → Читай файлы 30 секунд, потом ВЫЗОВИ СНОВА
↓
3 ошибки подряд? → Покажи ТОЧНЫЙ текст ошибки
```
### ЗАПРЕЩЕНО:
- ❌ "Todoist недоступен"
- ❌ "mcp-cli не работает"
- ❌ "добавь вручную"
- ❌ Решать что не работает БЕЗ вызова команды
### ОБЯЗАТЕЛЬНО:
- ✅ ВЫЗВАТЬ команду через Bash
- ✅ Если ошибка — подождать, вызвать снова
- ✅ 3 retry перед любыми выводами
- ✅ Показать task ID если создан
## Processing Flow
1. **Load personal context** — Read goals/1-yearly, goals/2-monthly, goals/3-weekly
2. **Load business context**:
- Read `business/_index.md` — Your Business (клиенты, проекты, CRM)
- Read `projects/_index.md` — личные проекты (если релевантно)
3. **Read daily** — daily/YYYY-MM-DD.md
4. **Check workload** — `mcp-cli call todoist find-tasks-by-date '{"startDate": "today", "daysCount": 7}'`
5. **CHECK PROCESS GOALS** — `mcp-cli call todoist find-tasks '{"labels": ["process-goal"]}'`
→ If empty or stale: generate from goals, create recurring tasks
6. **Process entries** — Classify → task or thought, detect business mentions
7. **Build links** — Connect notes with [[wiki-links]], link to business entities
8. **Generate HTML report** — include process goals status + business activity
9. **Log actions to daily** — append action log entry (see below)
10. **Evolve MEMORY.md** — update long-term memory if needed (see below)
11. **Capture observations** — record friction signals to handoff.md (see below)
## ОБЯЗАТЕЛЬНО: Логирование в daily/
**После ЛЮБЫХ изменений в vault — СРАЗУ пиши в `daily/YYYY-MM-DD.md`:**
Формат:
```
## HH:MM [text]
{Описание действий}
**Создано/Обновлено:**
- [[path/to/file|Name]] — описание
```
**Что логировать:**
- Создание файлов в thoughts/
- Обновление business/ или projects/
- Создание задач в Todoist (с task ID)
- Синхронизация с внешними системами
**Пример:**
```
## 14:30 [text]
Обработка ежедневных записей
**Создано задач:** 3
- "Follow-up Acme Corp" (id: 8501234567, p2, завтра)
- "Подготовить КП Unilever" (id: 8501234568, p2, пятница)
**Сохранено мыслей:** 1
- [[thoughts/ideas/product-launch|Product Launch]] — идея запуска
```
**Зачем:** Audit trail + контекст для будущих обработок.
## Evolve MEMORY.md (Step 10 Detail)
**ЦЕЛЬ:** Поддерживать MEMORY.md актуальным. Не добавлять, а ЭВОЛЮЦИОНИРОВАТЬ.
### Когда обновлять MEMORY.md
Проверь после обработки entries — есть ли информация достойная долгосрочной памяти?
### Write Rules: Что достойно MEMORY.md
**ПИСАТЬ:**
- ✅ Key decisions с impact (pivot, tool choice, architecture change)
- ✅ Изменения в pipeline (новый лид, закрытая сделка, изменение статуса)
- ✅ Финансовые изменения (оплаты получены, долги, новые контракты)
- ✅ Новые паттерны/инсайты (learnings)
- ✅ Изменения в Active Context (новый ONE Big Thing, Hot Projects)
- ✅ Новые ключевые контакты (с context)
**НЕ ПИСАТЬ:**
- ❌ Ежедневные мелочи (встречи, звонки без impact)
- ❌ Временные заметки (оставить в daily/)
- ❌ Дубликаты того что уже есть
- ❌ Детали проектов (оставить в business/crm/, projects/)
- ❌ Тривиальные задачи
### Как обновлять (evolve, не append)
**Принцип:** Новое ЗАМЕНЯЕТ устаревшее, не добавляется рядом.
| Ситуация | Действие |
|----------|----------|
| Новое противоречит старому | ЗАМЕНИТЬ старую информацию |
| Новое дополняет старое | Добавить в существующую секцию |
| Информация устарела | Удалить или архивировать |
**Пример 1 — Изменение статуса проекта:**
```
Old: "| Acme Corp NCP Meals | p1 | Активная разработка | $XXK |"
New info: "Acme Corp NCP Meals сдан клиенту"
→ ЗАМЕНИТЬ на: "| Acme Corp NCP Meals | ✅ | Завершён | $XXK |"
```
**Пример 2 — Новое решение:**
```
Добавить в Key Decisions таблицу:
| 2026-02-01 | Отказ от X в пользу Y | причина | impact |
```
**Пример 3 — Изменение в pipeline:**
```
Old: "| LogisticsLead | Hot | $XXK |"
New info: "LogisticsLead подписал контракт"
→ Удалить из Pipeline
→ Добавить в Hot Projects или Financial Context
```
### Секции MEMORY.md для обновления
| Секция | Когда обновлять |
|--------|-----------------|
| Active Context | Изменение ONE Big Thing, Hot Projects, Pipeline |
| Key Decisions | Новое решение с impact |
| Financial Context | Оплаты, долги, контракты |
| Key People | Новый важный контакт |
| Learnings | Новый паттерн/инсайт |
| Current Crisis | Изменение в текущей критической ситуации |
### Формат Edit
Используй Edit tool для точечных изменений:
```
Edit MEMORY.md:
old_string: "| LogisticsLead | Hot | $XXK |"
new_string: "| LogisticsLead | ✅ Signed | $XXK |"
```
### В отчёте
Если обновил MEMORY.md, добавь секцию:
```html
<b>🧠 MEMORY.md обновлён:</b>
• Active Context → Hot Projects updated
• Key Decisions → +1 новое решение
```
## Capture Observations (Step 11 Detail)
**ЦЕЛЬ:** Записывать friction signals, паттерны и идеи для улучшения системы.
### Когда записывать
После обработки проверь — были ли проблемы или наблюдения?
| Тип | Когда |
|-----|-------|
| `[friction]` | mcp-cli errors, timeouts, empty daily, broken links, unexpected data |
| `[pattern]` | Повторяющийся паттерн (задачи всегда overdue, daily пустой по выходным) |
| `[idea]` | Идея для улучшения pipeline, schema, отчёта |
### Формат
Append в `vault/.session/handoff.md` секцию `## Observations`:
```markdown
## Observations
- [friction] YYYY-MM-DD: mcp-cli timeout 3x на todoist — retry спас, но -60 сек
- [pattern] YYYY-MM-DD: daily без entries 2 дня подряд — выходные?
- [idea] YYYY-MM-DD: CRM карточки без deal_deadline = невидимые дедлайны
```
### Правила
- Одна строка на наблюдение (конкретика, не абстракции)
- Дата обязательна
- Не повторять уже записанные observations
- Когда observations ≥10 → сигнал для system improvement session
### В отчёте
Если записаны observations, добавь:
```html
<b>👁 Observations:</b>
• [friction] mcp-cli timeout 3x
```
---
## Process Goals Check (Step 5 Detail)
**ОБЯЗАТЕЛЬНО выполни этот шаг при каждом /process:**
### 1. Проверь существующие process goals
```bash
mcp-cli call todoist find-tasks '{"labels": ["process-goal"], "limit": 20}'
```
### 2. Если process goals ОТСУТСТВУЮТ — создай их
Читай goals файлы и генерируй process commitments:
| Goal Level | Source | Process Pattern |
|------------|--------|-----------------|
| Weekly ONE Big Thing | goals/3-weekly.md | 2h deep work ежедневно |
| Monthly Top 3 | goals/2-monthly.md | 1 action/день на приоритет |
| Yearly Focus | goals/1-yearly-*.md | 30 мин/день на стратегию |
**Создай recurring tasks:**
```bash
mcp-cli call todoist add-tasks '{"tasks": [
{"content": "2h deep work: [ONE Big Thing]", "dueString": "every weekday at 6am", "priority": 2, "labels": ["process-goal"]},
{"content": "1 outreach/день: [monthly priority]", "dueString": "every weekday", "priority": 3, "labels": ["process-goal"]},
{"content": "30 мин продуктовые идеи", "dueString": "every day", "priority": 4, "labels": ["process-goal"]}
]}'
```
**Лимит:** Max 5-7 активных process goals.
### 3. Если process goals ЕСТЬ — проверь статус
- Активные (upcoming) → ✅ показать в отчёте
- Просроченные (overdue) → ⚠️ предупредить
- Устаревшие (не связаны с текущими целями) → рекомендовать удалить
### 4. Включи в отчёт
```html
<b>📋 Process Goals:</b>
• 2h deep work: [Client Project] → ✅ активен
• 1 outreach/день → ⚠️ просрочен
{N} активных | {M} требуют внимания
```
## Entry Format
## HH:MM [type]
Content
Types: [voice], [text], [forward from: Name], [photo]
## Business Context Integration
**ТОЧКА ВХОДА:** `business/_index.md` — читай для понимания бизнес-контекста.
### Структура:
```
business/
├── _index.md ← Статистика, обзор
├── crm/ ← ВСЁ: компании + сделки + проекты в одном файле
├── network/ ← Структура холдинга
└── events/ ← Мероприятия
```
### Распознавание упоминаний
При обработке entries ищи упоминания клиентов и проектов:
| Паттерн | Действие |
|---------|----------|
| "звонил [Client]" | Найти `business/crm/{client}.md`, добавить связь |
| "по проекту [Client]" | Найти `business/crm/{client}.md` |
| "встреча с [Client]" | Создать задачу + связать с `business/crm/{client}.md` |
| "отправил КП для [Client]" | Связать с `business/crm/{client}.md` |
### Поиск клиента по имени
1. Имя → kebab-case: "Acme Corp" → `acme-corp`, "Bi Group" → `bi-group`
2. Искать: `business/crm/{kebab-case}.md`
3. Если не найден — fuzzy search по `grep -l "{name}" business/crm/`
### Создание связей
Когда упомянут клиент/проект, добавляй wiki-links:
**В задачу:**
```
"Follow-up [[business/crm/acme-corp|Acme Corp]] по снекам"
```
**В thought:**
```
Связано с: [[business/crm/techco|TechCo]], [[business/crm/phonebrand-smm|PhoneBrand SMM]]
```
### Приоритет задач с бизнесом
| Условие | Приоритет |
|---------|-----------|
| Клиент с priority: High + deadline | p1 |
| Активный проект (In progress) | p2 |
| Клиент с priority: High | p2 |
| Клиент с priority: Mid | p3 |
| Prospect без срочности | p4 |
## Classification
task → Todoist (see references/todoist.md)
idea/reflection/learning → thoughts/ (see references/classification.md)
client/project mention → link to Business/Projects + create task if actionable
## Projects Context Integration
**Точка входа:** `projects/_index.md`
### Структура:
```
projects/
├── _index.md # Clients overview
├── clients/ # Clients
└── leads/ # Leads
```
### Распознавание упоминаний
| Паттерн | Файл |
|---------|------|
| "[Client A]" | projects/clients/{client-a}.md |
| "[Client B]" | projects/clients/{client-b}.md |
| "AI обучение", "воркшоп" | projects/ контекст |
### Отличие от Business
- **Business** = основной бизнес
- **Projects** = личные проекты (консалтинг, обучение)
Если entry упоминает AI/ML обучение — ищи в projects/ сначала.
## Contacts Context Integration
**Точка входа:** `contacts/_index.md`
### Распознавание имён в entries
Ищи паттерны:
- "созвонился с [Contact] из [Client]"
- "встреча с @username"
- "Имя Фамилия написал"
### Классификация
| Индикатор | Категория | Vault Link |
|-----------|-----------|------------|
| Known business clients | business | `business/crm/{client}` |
| AI/обучение expertise, known leads | projects | `projects/leads/{name}` |
| Остальные | personal | — |
### В отчёте
Если в entries упомянуты люди, добавь секцию:
```html
<b>👤 Упомянуто контактов:</b>
• [Contact Name] (business → [[business/crm/acme-corp]])
• [Contact Name] (personal)
```
## Priority Rules
p1 — Client deadline, urgent
p2 — Aligns with ONE Big Thing or monthly priority
p3 — Aligns with yearly goal
p4 — Operational, no goal alignment
## Process Goals Preference
When creating tasks, prefer PROCESS over OUTCOME formulations.
**Outcome (less effective):**
- "Закрыть сделку с X"
- "Запустить продукт"
- "Подготовить программу"
**Process (more effective):**
- "Отправить follow-up клиенту X" (actionable, controllable)
- "2h deep work на MVP" (time-bounded)
- "Показать драфт программы коллеге" (checkpoint)
**When to transform:**
- Entry sounds vague/outcome-focused → make it specific/process-focused
- User says "нужно сделать X" → create actionable next step, not X itself
- Goal mentioned → create task that MOVES TOWARD goal, not goal itself
See: references/process-goals.md for patterns and examples.
## Thought Categories
💡 idea → thoughts/ideas/
🪞 reflection → thoughts/reflections/
🎯 project → thoughts/projects/
📚 learning → thoughts/learnings/
## HTML Report Template
Output RAW HTML (no markdown, no code blocks):
📊 <b>Обработка за {DATE}</b>
<b>🎯 Текущий фокус:</b>
{ONE_BIG_THING}
<b>📓 Сохранено мыслей:</b> {N}
• {emoji} {title} → {category}/
<b>✅ Создано задач:</b> {M}
• {task} <i>({priority}, {due})</i>
<b>🏢 Business Activity:</b>
• {client} — {action}
• {project} — {status update}
<i>Упомянуто клиентов: {N} | Проектов: {M}</i>
<b>📋 Process Goals:</b>
• {process goal 1} → {status}
• {process goal 2} → {status}
{N} активных | {M} требуют внимания
<i>Создано новых: {K}</i>
<b>📅 Загрузка на неделю:</b>
Пн: {n} | Вт: {n} | Ср: {n} | Чт: {n} | Пт: {n} | Сб: {n} | Вс: {n}
<b>⚠️ Требует внимания:</b>
• {overdue or stale goals}
<b>🔗 Новые связи:</b>
• [[Note A]] ↔ [[Note B]]
<b>⚡ Топ-3 приоритета:</b>
1. {task}
2. {task}
3. {task}
<b>📈 Прогресс:</b>
• {goal}: {%} {emoji}
<b>🧠 MEMORY.md:</b>
• {section} → {change description}
<i>(если обновлено)</i>
---
<i>Обработано за {duration}</i>
## If Already Processed
If all entries have `<!-- ✓ processed -->` marker, return status report:
📊 <b>Статус за {DATE}</b>
<b>🎯 Текущий фокус:</b>
{ONE_BIG_THING}
<b>📋 Process Goals:</b>
• {process goal 1} → {status}
• {process goal 2} → {status}
{N} активных | {M} требуют внимания
<b>📅 Загрузка на неделю:</b>
Пн: {n} | Вт: {n} | Ср: {n} | Чт: {n} | Пт: {n} | Сб: {n} | Вс: {n}
<b>⚠️ Требует внимания:</b>
• {overdue count} просроченных
• {today count} на сегодня
<b>⚡ Топ-3 приоритета:</b>
1. {task}
2. {task}
3. {task}
---
<i>Записи уже обработаны ранее</i>
## Allowed HTML Tags
<b> — bold (headers)
<i> — italic (metadata)
<code> — commands, paths
<s> — strikethrough
<u> — underline
<a href="url">text</a> — links
## FORBIDDEN in Output
NO markdown: **, ##, -, *, backticks
NO code blocks (triple backticks)
NO tables
NO unsupported tags: div, span, br, p, table
Max length: 4096 characters.
## References
Read these files as needed:
- references/about.md — User profile, decision filters
- references/classification.md — Entry classification rules
- references/todoist.md — Task creation details + recurring patterns
- references/goals.md — Goal alignment logic
- references/process-goals.md — Process vs outcome goals, transformation patterns
- references/links.md — Wiki-links building
- references/rules.md — Mandatory processing rules
- references/report-template.md — Full HTML report spec
- references/business.md — Business client/project context, search patterns
- references/contacts.md — Contacts search and classification
## Business Quick Reference
**Точка входа:** `business/_index.md`
**Поиск клиента:**
```
grep -l "Acme Corp" business/crm/
→ business/crm/acme-corp.md
```
**Активные сделки:**
```
grep -l "deal_status:" business/crm/
```
**High priority клиенты:**
```
grep -l "priority: High" business/crm/
```
**Frontmatter полей:**
- type: crm
- industry, priority, status, region, owner, responsible
- deal_status, deal_deadline (для активных сделок)
- updated
## Relevant Skills
- [[vault/.claude/skills/graph-builder/SKILL|graph-builder]] — Vault graph analysis
- [[vault/.claude/skills/todoist-ai/SKILL|todoist-ai]] — Todoist task management
@@ -0,0 +1,98 @@
# Phase 1: CAPTURE
Read daily entries, classify them, and output structured JSON.
## Input
- `daily/{DATE}.md` — today's entries
- `goals/3-weekly.md` — current week focus
- `goals/2-monthly.md` — monthly priorities
- `goals/1-yearly-2026.md` — yearly goals
## Task
1. Read `daily/{DATE}.md`
2. For each entry (## HH:MM [type] block), classify:
- **task** — actionable item → will become Todoist task
- **idea** → will be saved to thoughts/ideas/
- **reflection** → thoughts/reflections/
- **learning** → thoughts/learnings/
- **project** → thoughts/projects/
- **crm_update** — mentions business client → update CRM
- **skip** — already processed or not actionable
3. Detect entity mentions (company names, people, projects)
4. Align with goals (which goal does this serve?)
## Output Format
Print ONLY valid JSON (no markdown, no explanation):
```json
{
"date": "2026-02-19",
"one_big_thing": "[Client A] NCP: POST-LAUNCH stabilization",
"entries": [
{
"time": "10:30",
"type": "voice",
"content": "Called Acme Corp about the project, discussed KPI",
"classification": "task",
"task_content": "Follow-up Acme Corp: send KPI report",
"task_priority": 2,
"task_due": "tomorrow",
"entities": ["business/crm/acme-corp"],
"goal_alignment": "ONE Big Thing"
},
{
"time": "14:00",
"type": "text",
"content": "AI agents need layered memory",
"classification": "idea",
"title": "AI agents need layered memory with decay scoring",
"description": "Pattern from analysis. Active memories decay if unused.",
"category": "ideas",
"tags": ["ai", "agents", "memory"],
"entities": [],
"goal_alignment": "yearly/AI Development"
}
],
"stats": {
"total_entries": 5,
"tasks": 2,
"thoughts": 2,
"crm_updates": 1,
"skipped": 0
}
}
```
## Classification Rules
### Task indicators
- "нужно", "надо", "сделать", "позвонить", "отправить", "подготовить"
- Deadline mentions (завтра, в пятницу, до конца недели)
- Follow-up mentions
### Thought indicators
- Insights, patterns, observations
- "понял что", "интересно что", "заметил"
- No clear action required
### CRM indicators
- Company name mention (known clients from CRM)
- Deal/project status change
- Meeting/call with client
### Process goal formulation
When creating task_content, prefer PROCESS over OUTCOME:
- WRONG: "Закрыть сделку с Acme Corp"
- RIGHT: "Отправить follow-up Acme Corp: KPI отчёт за февраль"
### Prose-as-title for thoughts
When creating thought titles, use CLAIMS not topic labels:
- WRONG: "Agent Memory System" (topic label)
- RIGHT: "AI agents need layered memory with decay scoring" (specific claim)
Test: "Since [[title]], ..." should read naturally.
## Important
- Mark entries with `<!-- ✓ processed -->` as "skip"
- Output ONLY JSON — no explanation, no markdown wrapping
@@ -0,0 +1,101 @@
# Phase 2: EXECUTE
Read capture.json from Phase 1. Create Todoist tasks, save thoughts, update CRM.
## Input
- `.session/capture.json` — output from Phase 1
- `business/_index.md` — business context
- `projects/_index.md` — projects context
## Task
### 1. Create Todoist tasks
For each entry with `classification: "task"`:
```bash
mcp-cli call todoist add-tasks '{"tasks": [{"content": "...", "dueString": "...", "priority": N}]}'
```
Record created task IDs.
### 2. Check process goals
```bash
mcp-cli call todoist find-tasks '{"labels": ["process-goal"]}'
```
If missing or stale → create from goals.
### 3. Save thoughts
For each entry with classification idea/reflection/learning/project:
- Create file in `thoughts/{category}/YYYY-MM-DD-slug.md`
- Include frontmatter with description field (retrieval filter, ~150 chars)
- Add wiki-links to related entities
- Add typed relationships in Related section:
```markdown
## Related
- [[business/crm/acme-corp|Acme Corp]] — context: discussed during project review
```
### 4. Update CRM
For entries with `classification: "crm_update"`:
- Update relevant `business/crm/*.md` or `projects/clients/*.md`
- Update deal_status, status, or add notes
### 5. Build links
For all created/updated files:
- Search for related notes in vault
- Add wiki-links with context phrases
- Update frontmatter `related:[]`
### 6. Check workload
```bash
mcp-cli call todoist find-tasks-by-date '{"startDate": "today", "daysCount": 7}'
```
## mcp-cli retry algorithm
```
1. Call mcp-cli
2. Error? Wait 10 sec, read vault files
3. Call again
4. Error? Wait 20 sec
5. Call third time — GUARANTEED to work
```
NEVER say "MCP unavailable". Always retry 3x.
## Output Format
Print ONLY valid JSON:
```json
{
"tasks_created": [
{"id": "8501234567", "content": "Follow-up Acme Corp", "priority": 2, "due": "tomorrow"}
],
"thoughts_saved": [
{"path": "thoughts/ideas/2026-02-19-layered-memory.md", "title": "AI agents need layered memory", "category": "ideas"}
],
"crm_updated": [
{"path": "business/crm/acme-corp.md", "change": "Added meeting note"}
],
"links_created": [
{"from": "thoughts/ideas/2026-02-19-layered-memory.md", "to": "business/crm/acme-corp.md", "context": "discussed during project review"}
],
"process_goals": {
"active": 5,
"overdue": 1,
"created": 0
},
"workload": {
"mon": 3, "tue": 2, "wed": 4, "thu": 1, "fri": 2, "sat": 0, "sun": 0
},
"observations": []
}
```
@@ -0,0 +1,94 @@
# Phase 3: REFLECT
Read execute results. Generate HTML report. Update MEMORY. Write observations. Log to daily.
## Input
- `.session/capture.json` — from Phase 1
- `.session/execute.json` — from Phase 2
- `MEMORY.md` — long-term memory
- `.session/handoff.md` — session context
- `.graph/health-history.json` — vault health trend
## Task
### 1. Generate HTML report
Use the template from SKILL.md. Include:
- ONE Big Thing (from capture.json)
- Thoughts saved (from execute.json)
- Tasks created (with IDs)
- Process goals status
- Workload by day
- Vault Health score (from latest health-history.json entry)
- Top 3 priorities
- Observations (if any)
### 2. Log actions to daily
Append to `daily/{DATE}.md`:
```markdown
## HH:MM [text]
d-brain processing
**Tasks created:** N
- "Task content" (id: XXXX, priority, due)
**Thoughts saved:** M
- [[path/to/thought|Title]] — category
**CRM updated:** K
- [[business/crm/client]] — change description
```
### 3. Evolve MEMORY.md
Check if any information from today deserves long-term memory:
- New key decisions
- Pipeline changes (new lead, closed deal, status change)
- Financial changes
- Active Context updates
Rules:
- New info REPLACES outdated (don't append duplicates)
- Only write significant changes
### 4. Capture observations
If problems occurred during processing, append to `.session/handoff.md` under `## Observations`:
```markdown
- [friction] 2026-02-19: mcp-cli timeout on todoist — retried 3x
- [pattern] 2026-02-19: daily had only 2 entries — low activity day
```
### 5. Update handoff.md
Update session context:
- Last Session: what was processed
- Key Decisions: if any
- In Progress: incomplete items
- Next Steps: what to do next
## Output Format
Return RAW HTML report (no markdown, no code blocks). Goes directly to Telegram.
Follow the HTML template exactly:
- Only use: `<b>`, `<i>`, `<code>`, `<s>`, `<u>`, `<a>`
- NO: `<div>`, `<br>`, `<table>`, markdown syntax
- Max 4096 characters
### Vault Health section (add to report):
```html
<b>📊 Vault Health:</b> {score}/100
Orphans: {N} | Broken: {M} | Avg links: {X} | Desc: {Y}%
```
## CRITICAL
- Output is RAW HTML only
- No markdown syntax anywhere
- All HTML tags must be properly closed
@@ -0,0 +1,28 @@
# About [Your Name]
## Who I Am
[Your Name], [age]. [Your role/title] at [Your Company].
## What I Do
- [Main business activity]
- [Side projects/interests]
## My Team
| Name | Role |
|------|------|
| [Your Name] | [Your Role] |
| [Team Member] | [Their Role] |
## Working Style
- Timezone: [Your Timezone]
- Working hours: [Your preferred hours]
- Languages: [Your languages]
## Values
- [Value 1]
- [Value 2]
- [Value 3]
## Key Clients/Projects
- [Client/Project 1] — [Brief description]
- [Client/Project 2] — [Brief description]
@@ -0,0 +1,26 @@
# Business Context
## Company Overview
[Your Company Name] — [what the company does].
## CRM Structure
```
business/
├── _index.md ← Start here (stats, overview)
├── crm/ ← Client records (companies + deals)
└── network/ ← Company structure, partners
```
## Key Metrics
- Total CRM records: [N]
- Active deals: [N]
- Industries: [list your industries]
## Deal Tracking Fields
| Field | Values |
|-------|--------|
| status | Active, Prospect, Dormant |
| deal_status | In Progress, Tender, Proposal Sent |
| priority | High, Mid, Low |
| region | [Your regions] |
| owner | [Your Name] |
@@ -0,0 +1,201 @@
# Entry Classification
## Work Domains → Categories
Based on user's work context (see [ABOUT.md](ABOUT.md)):
### Client Work
Брифы, стратегии, креатив, кампании, KPI, предложения
**Keywords:** [Client A], [Client B], [Client C], клиент, бриф, презентация, дедлайн, KPI
**→ Category:** task (p1-p2) → Todoist
### AI & Tech
Инструменты, модели, промпты, пайплайны, агенты
**Keywords:** GPT, Claude, модель, агент, API, пайплайн, автоматизация, интеграция
**→ Category:** learning или project → thoughts/
### Product
Идеи, гипотезы, MVP, юнит-экономика
**Keywords:** продукт, SaaS, MVP, гипотеза, монетизация, юнит-экономика, стартап
**→ Category:** idea или project → thoughts/
### Company Ops
Команда, процессы, автоматизация, найм, управление, финансы
**Keywords:** команда, найм, процесс, HR, финансы, [Your Business], агентство
**→ Category:** task или project (depends on urgency)
### Content
Посты, идеи, тезисы для Telegram и LinkedIn
**Keywords:** пост, @yourbrand, LinkedIn, контент, тезис, статья
**→ Category:** idea → thoughts/ideas/ или task если с дедлайном
---
## Decision Tree
```
Entry text contains...
│
├─ Client brand or deadline? ────────────────────> TASK (p1-p2)
│ ([Client A], [Client B], клиент, дедлайн, презентация)
│
├─ Operational/urgent? ──────────────────────────> TASK (p2-p3)
│ (нужно сделать, не забыть, позвонить, встреча)
│
├─ AI/tech learning? ────────────────────────────> LEARNING
│ (узнал, модель, агент, интеграция)
│
├─ Product/SaaS idea? ───────────────────────────> IDEA или PROJECT
│ (продукт, MVP, гипотеза, SaaS)
│
├─ Strategic thinking? ──────────────────────────> PROJECT
│ (стратегия, план, R&D, долгосрочно)
│
├─ Personal insight? ────────────────────────────> REFLECTION
│ (понял, осознал, философия)
│
└─ Content idea? ────────────────────────────────> IDEA
(пост, тезис, контент)
```
---
## Business Client Detection
Entry mentions a known client (see business-context.md)?
```
├─ + deadline/urgency? → TASK (p1-p2) + client label
├─ + статус ("отправили КП", "выиграли")? → TASK + flag for CRM note
├─ + встреча/звонок? → TASK (p2) + [[client]] link
└─ просто упоминание? → Add [[client]] link only
```
### CRM Status Keywords (для информации в отчёте)
| Keywords | Интерпретация |
|----------|---------------|
| "подписали", "выиграли", "получили" | Позитивный исход |
| "отказали", "проиграли", "не пошли" | Негативный исход |
| "отправили КП", "подали" | В процессе |
| "ждём ответ", "на рассмотрении" | Ожидание |
---
## Apply Decision Filters
Перед сохранением спроси:
- Это масштабируется?
- Это можно автоматизировать?
- Это усиливает экспертизу или бренд?
- Это приближает к продукту или SaaS?
Если да на 2+ вопроса → повысить приоритет.
---
## Photo Entries
For `[photo]` entries:
1. Analyze image content via vision
2. Determine domain:
- Screenshot клиентского материала → Client Work
- Схема/диаграмма → AI & Tech или Product
- Текст/статья → Learning
3. Add description to daily file
---
## Output Locations
| Category | Destination | Priority |
|----------|-------------|----------|
| task (client) | Todoist | p1-p2 |
| task (ops) | Todoist | p2-p3 |
| task (content) | Todoist | p3-p4 |
| idea | thoughts/ideas/ | — |
| reflection | thoughts/reflections/ | — |
| project | thoughts/projects/ | — |
| learning | thoughts/learnings/ | — |
---
## File Naming
```
thoughts/{category}/{YYYY-MM-DD}-short-title.md
```
Examples:
```
thoughts/ideas/2024-12-16-saas-pricing-model.md
thoughts/projects/2024-12-16-ai-agents-pipeline.md
thoughts/learnings/2024-12-16-claude-mcp-setup.md
```
---
## Thought Structure
Use preferred format:
```markdown
---
date: {YYYY-MM-DD}
type: {category}
domain: {Client Work|AI & Tech|Product|Agency Ops|Content}
tags: [tag1, tag2]
---
## Context
[Что привело к мысли]
## Insight
[Ключевая идея]
## Implication
[Что это значит для [Your Business]/продукта/стратегии]
## Next Action
[Конкретный шаг — не абстрактный]
```
---
## Anti-Patterns (ИЗБЕГАТЬ)
При создании мыслей НЕ делать:
- Абстрактные рассуждения без Next Action
- Академическая теория без применения к [Your Business]/продукту
- Повторы без синтеза (кластеризуй похожие!)
- Хаотичные списки без приоритетов
- Задачи типа "подумать о..." (конкретизируй!)
---
## MOC Updates
After creating thought file, add link to:
```
MOC/MOC-{category}s.md
```
Group by domain when relevant:
```markdown
## AI & Tech
- [[2024-12-16-claude-mcp-setup]] - MCP integration
## Product
- [[2024-12-16-saas-pricing-model]] - Pricing research
```
@@ -0,0 +1,12 @@
# Contacts
## Search Protocol
When looking for a person or contact:
1. Search vault CRM files by name
2. Check daily files for recent mentions
3. Search by company association
## Contact Sources
- CRM cards in `business/crm/`
- Project records in `projects/`
- Daily logs for recent interactions
@@ -0,0 +1,135 @@
# Goals Integration
## ALWAYS Do First
Before processing daily entries:
1. **Read current focus:**
```
Read goals/3-weekly.md → Extract ONE Big Thing
```
2. **Read yearly goals:**
```
Read goals/1-yearly-2025.md → Know active goals by area
```
3. **Check monthly priorities:**
```
Read goals/2-monthly.md → Top 3 priorities
```
## Goal Alignment
When creating a task, ask:
1. **Does it connect to ONE Big Thing?**
- Yes → add to task description: `→ Weekly focus`
- No → continue checking
2. **Does it connect to monthly priority?**
- Yes → add: `→ Monthly: [Priority name]`
- No → continue checking
3. **Does it connect to yearly goal?**
- Yes → add: `→ Goal: [Goal name]`
- No → mark as "operational"
## Task Priority Boost
If task aligns with goals, consider priority bump:
| Alignment | Default | Boost to |
|-----------|---------|----------|
| ONE Big Thing | p3 | p2 |
| Monthly priority | p3 | p2-p3 |
| Yearly goal | p4 | p3 |
| No alignment | p4 | p4 |
## Saving Thoughts
When saving to thoughts/:
1. **Check goal relevance:**
- Scan goals/1-yearly-2025.md for matching areas
- If matches → add link in frontmatter:
```yaml
related:
- "[[goals/1-yearly-2025#Career & Business]]"
```
2. **Tag with goal area:**
```
#goal/career
#goal/health
#goal/learning
```
## Goal Progress Tracking
Track goal activity by:
- Task created → goal is "active"
- Thought saved → goal is "active"
- No activity 7+ days → "stale"
- No activity 14+ days → "warning"
## Report Section
Add to report:
```
<b>📈 Прогресс по целям:</b>
{for each active yearly goal with recent activity:}
• {goal}: {progress}% {status_emoji}
{if stale goals:}
<b>⚠️ Требует внимания:</b>
• Цель "{goal}" без активности {days} дней
```
## Goal File Parsing
### 3-weekly.md — Find ONE Big Thing
Look for pattern:
```markdown
> **If I accomplish nothing else, I will:**
> [THE ONE THING]
```
### 1-yearly-2025.md — Find Active Goals
Look for tables:
```markdown
| Goal | Progress | Status |
|------|----------|--------|
| Goal name | X% | 🟡 |
```
### 2-monthly.md — Find Top 3
Look for section:
```markdown
## Top 3 Priorities
1. **[Priority 1]**
2. **[Priority 2]**
3. **[Priority 3]**
```
## Example Alignment
Entry: "Нужно подготовить презентацию для клиента X"
Check:
- ONE Big Thing: "Ship MVP" → Not related
- Monthly #1: "Client deliverables" → Related
- Yearly: "Client Revenue" → Related
Result:
```
Task: Подготовить презентацию для клиента X
Description: → Monthly: Client deliverables → Goal: Client Revenue
Priority: p2 (boosted from p3)
```
@@ -0,0 +1,209 @@
# Wiki-Links Building
## Purpose
Build connections between notes to create a knowledge graph.
## When Saving a Thought
### Step 1: Search for Related Notes
Search thoughts/ for related content:
```
Grep "keyword1" in thoughts/**/*.md
Grep "keyword2" in thoughts/**/*.md
```
Keywords to search:
- Main topic of the thought
- Key entities (people, projects, technologies)
- Domain terms
### Step 2: Check MOC Indexes
Read relevant MOC files:
```
MOC/
├── MOC-ideas.md
├── MOC-projects.md
├── MOC-learnings.md
└── MOC-reflections.md
```
Find related entries.
### Step 3: Link to Goals
Check if thought relates to goals:
```
Read goals/1-yearly-2025.md
Find matching goal areas
```
### Step 4: Add Links to Note (with context)
In the thought file, add **typed relationships** — each link explains WHY it's connected:
**In frontmatter (for graph analysis):**
```yaml
related:
- "[[thoughts/ideas/2024-12-15-voice-agents]]"
- "[[goals/1-yearly-2026#AI Development]]"
```
**In content (inline):**
```markdown
This connects to [[Voice Agents Architecture]] we explored earlier.
```
**In Related section (with context phrases):**
```markdown
## Related
- [[thoughts/ideas/voice-agents-architecture|Voice Agents]] — extends: real-time TTS pipeline
- [[business/crm/acme-corp|Acme Corp]] — context: NCP campaign uses similar approach
- [[goals/1-yearly-2026#AI Development]] — supports: yearly AI skill goal
```
### Relationship Types
Use context phrases after `—` to explain the connection:
| Type | When to use | Example |
|------|------------|---------|
| extends | Builds on another idea | `— extends: adds TTS to voice pipeline` |
| context | Background/origin of idea | `— context: emerged from client project` |
| supports | Aligns with a goal | `— supports: Q1 revenue target` |
| contradicts | Challenges existing note | `— contradicts: previous approach was sync` |
| enables | Makes something possible | `— enables: automated daily reports` |
| requires | Dependency | `— requires: mcp-cli working` |
### Step 5: Update MOC Index
Add new note to appropriate MOC:
```markdown
# MOC: Ideas
## Recent
- [[thoughts/ideas/2024-12-20-new-idea.md]] — Brief description
## By Topic
### AI & Voice
- [[thoughts/ideas/2024-12-20-new-idea.md]]
- [[thoughts/ideas/2024-12-15-voice-agents.md]]
```
### Step 6: Add Backlinks
In related notes, add backlink to new note if highly relevant.
## Link Format
### Internal Links
```markdown
[[Note Name]] # Simple link
[[Note Name|Display Text]] # With alias
[[folder/Note Name]] # With path
[[Note Name#Section]] # To heading
```
### Link to Goals
```markdown
[[goals/1-yearly-2025#Career & Business]]
[[goals/3-weekly]] — ONE Big Thing
```
---
## Business Entity Links
### Формат связей
| Тип | Формат | Пример |
|-----|--------|--------|
| Клиент | `[[business/crm/{name}\|Display]]` | `[[business/crm/acme-corp\|Acme Corp]]` |
| Проект | `[[projects/{name}\|Display]]` | `[[projects/project-alpha\|Project Alpha]]` |
| CRM Lead | `[[business/crm/{name}\|Display]]` | `[[business/crm/techco\|TechCo]]` |
### Где добавлять связи (с typed context)
**В daily file (комментарий):**
```markdown
## 10:30 [voice]
Позвонил в Acme Corp по проекту
<!-- связь: [[business/crm/acme-corp]] -->
```
**В thoughts (Related section с context phrases):**
```markdown
## Related
- [[business/crm/techco|TechCo]] — context: обсуждение BTL стратегии
- [[business/crm/phonebrand|PhoneBrand]] — extends: SMM стратегия 2026
```
**В задаче Todoist (description):**
```
Description: "Клиент: [[business/crm/acme-corp|Acme Corp]]"
```
---
## Report Section
Track new links created:
```
<b>🔗 Новые связи:</b>
• [[Note A]] ↔ [[Note B]]
• [[New Thought]] → [[Related Project]]
```
## Example Workflow
New thought: "Chatterbox TTS can be used for voice agents"
1. **Search:**
- Grep "voice" in thoughts/ → finds [[Voice Agents Architecture]]
- Grep "TTS" in thoughts/ → no results
- Grep "Chatterbox" → no results
2. **Check MOC:**
- MOC-learnings.md has "AI & Voice" section
3. **Goals:**
- 1-yearly-2025.md has "AI Development" goal
4. **Create links:**
```yaml
related:
- "[[thoughts/ideas/voice-agents-architecture.md]]"
- "[[goals/1-yearly-2025#AI Development]]"
```
5. **Update MOC-learnings.md:**
```markdown
### AI & Voice
- [[thoughts/learnings/2024-12-20-chatterbox-tts.md]] — TTS for voice agents
```
6. **Report:**
```
<b>🔗 Новые связи:</b>
• [[Chatterbox TTS]] ↔ [[Voice Agents Architecture]]
```
## Orphan Detection
A note is "orphan" if:
- No incoming links from other notes
- No related notes in frontmatter
- Not listed in any MOC
Flag orphans for review:
```
<b>⚠️ Изолированные заметки:</b>
• [[thoughts/ideas/orphan-note.md]]
```
@@ -0,0 +1,108 @@
# Process Goals
## Concept
**Outcome goals** focus on WHAT you want to achieve:
- "Close the deal"
- "Hit $1M ARR"
- "Launch the product"
**Process goals** focus on HOW you do it:
- "Reach out to 100 potential clients"
- "Send 5 proposals per week"
- "Conduct 3 customer interviews this week"
## Why Process Goals Work Better
Based on research (meta-analysis of 27 experiments in sports):
1. **Control** — You control actions, not outcomes. "Close deal" creates anxiety; "send 3 follow-ups" is actionable.
2. **Confidence** — Process goals turn challenge into achievable steps, boosting self-efficacy.
3. **Focus** — Daily clarity on what to do, not vague aspiration.
## How to Transform
| Outcome Goal | Process Goal |
|--------------|--------------|
| "Закрыть сделку с [Client A]" | "Отправлять 1 follow-up в день клиенту [Client A]" |
| "Запустить продукт" | "2h deep work на MVP каждое утро" |
| "Привлечь 10 клиентов" | "Написать 5 outreach сообщений в день" |
| "Подготовить программу" | "30 мин research аналогов ежедневно" |
| "Найти партнёра" | "1 нетворкинг сообщение в день" |
## Patterns for Process Goals
### Time Blocks
Regular dedicated time for deep work:
- "2h deep work на [project] каждое утро 6-8am"
- "1h research [topic] после обеда"
### Frequency Commitments
Consistent action cadence:
- "1 outreach message в день"
- "3 customer calls в неделю"
- "5 proposals в неделю"
### Checkpoints
Review milestones:
- "Показать драфт 1 человеку до пятницы"
- "Review прогресс с ментором в среду"
### Streaks
Daily habits:
- "30 мин движения каждый день"
- "10 мин journaling утром"
## When Processing Voice Entries
If user says outcome goal, consider transforming:
```
User: "Нужно закрыть сделку с [Client A]"
BAD: Create task "Закрыть сделку с [Client A]" p1
→ Vague, creates anxiety, unclear next action
GOOD: Create task "Отправить follow-up [Client A] с обновлённым КП" p1 due:tomorrow
→ Specific, actionable, controllable
```
## For Weekly Planning
When generating Process Commitments for ONE Big Thing:
1. **Ask:** What daily/weekly habits would make this inevitable?
2. **Limit:** 3-5 process commitments max
3. **Prioritize:** Time blocks > Frequency > Checkpoints
4. **Create:** Recurring tasks in Todoist with appropriate patterns
## Recurring Task Patterns
Map process goals to Todoist dueString:
| Process | dueString |
|---------|-----------|
| "каждое утро" | "every day at 6am" |
| "каждый день" | "every day" |
| "каждый рабочий день" | "every weekday" |
| "3 раза в неделю" | "every monday, wednesday, friday" |
| "раз в неделю" | "every week" |
| "до пятницы" | "friday" (one-time) |
## Anti-Patterns
Avoid creating process goals that are:
- Too vague: "Работать над проектом" (how much? when?)
- Too ambitious: "4h deep work 5 days a week" (unsustainable)
- Untrackable: "Думать о стратегии" (not measurable)
Good process goals are:
- Specific in action
- Bounded in time/frequency
- Trackable (done/not done)
## Reference
Based on: Meta-analysis of 27 experiments in sports showing process goals significantly outperform outcome/performance goals.
See also: "The Success Equation" by Mauboussin — Results = Skill + Luck. Focus on skill (process) is the only controllable strategy.
@@ -0,0 +1,141 @@
# HTML Report Template
## CRITICAL: Output Format
**Return RAW HTML text only. No markdown wrappers.**
WRONG (markdown code block):
```html
<b>Title</b>
```
CORRECT (raw HTML):
<b>Title</b>
Output goes directly to Telegram `parse_mode=HTML`.
## Allowed Tags
<b> or <strong> — bold
<i> or <em> — italic
<code> — inline code
<pre> — code blocks
<s> or <strike> or <del> — strikethrough
<u> — underline
<a href="url">text</a> — links
## FORBIDDEN
NO markdown: **, ##, -, *, backticks
NO code blocks with triple backticks
NO tables (Telegram doesn't support)
NO unsupported tags: div, span, br, p, table, tr, td
## Template
📊 <b>Обработка за {DATE}</b>
<b>🎯 Текущий фокус:</b>
{ONE_BIG_THING from goals/3-weekly.md}
<b>📓 Сохранено мыслей:</b> {N}
• {emoji} {title} → {category}/
<b>✅ Создано задач:</b> {M}
• {task_name} <i>({priority}, {due})</i>
<b>🏢 Business:</b>
• {client_name} — {action/status}
<i>{N} клиентов упомянуто</i>
<b>📅 Загрузка на неделю:</b>
Пн: {n} | Вт: {n} | Ср: {n} | Чт: {n} | Пт: {n} | Сб: {n} | Вс: {n}
<b>⚠️ Требует внимания:</b>
• {count} просроченных задач
• Цель "{goal}" без активности {days} дней
<b>🔗 Новые связи:</b>
• [[Note A]] ↔ [[Note B]]
<b>⚡ Топ-3 приоритета на завтра:</b>
1. {task} <i>({goal if aligned})</i>
2. {task}
3. {task}
<b>📈 Прогресс по целям:</b>
• {goal_name}: {progress}% {emoji}
---
<i>Обработано за {duration}</i>
## Section Rules
### Focus (🎯)
Read from goals/3-weekly.md, find "ONE Big Thing" section.
If not found: "Не задан — обновите goals/3-weekly.md"
### Thoughts (📓)
Count saved, list with category emoji:
💡 idea, 🪞 reflection, 🎯 project, 📚 learning
### Tasks (✅)
Count created, list with priority and due date.
Format: • Task name <i>(p2, friday)</i>
### Business Activity (🏢)
Show ONLY if client/project mentions exist.
- Max 5 clients
- If CRM status changed → add note
- Format: • {Client} — {action}
- Footer: <i>{N} клиентов упомянуто</i>
### Week Load (📅)
Call find-tasks-by-date for 7 days.
Format: Пн: 4 | Вт: 2 | ...
### Attention (⚠️)
Show only if issues exist.
Check overdue tasks and stale goals (7+ days no activity).
### Links (🔗)
Show only if new links created.
Format: • [[Note A]] ↔ [[Note B]]
### Priorities (⚡)
Get tomorrow's tasks from Todoist, sort by priority, show top 3.
### Goals Progress (📈)
Read goals/1-yearly-2026.md, show goals with recent activity.
Emojis: 🔴 0-25%, 🟡 26-50%, 🟢 51-75%, ✅ 76-100%
## Error Report
❌ <b>Ошибка обработки</b>
<b>Причина:</b> {error_message}
<b>Файл:</b> <code>{file_path}</code>
<i>Попробуйте /process снова</i>
## Empty Report
📭 <b>Нет записей для обработки</b>
Файл <code>daily/{date}.md</code> пуст.
<i>Добавьте записи в течение дня</i>
## Length Limit
Telegram max: 4096 characters.
If exceeds: truncate "Новые связи" first, then keep only top 3 goals.
## Validation Checklist
Before returning report:
1. All tags closed
2. No raw < or > in text (use &lt; &gt;)
3. No markdown syntax
4. No tables
5. Length under 4096 chars
@@ -0,0 +1,85 @@
# Critical Processing Rules
See [ABOUT.md](ABOUT.md) for user context and preferences.
## Rule 1: Skip Processed Entries
```
If entry contains `<!-- ✓ processed` → SKIP COMPLETELY
```
Check AFTER each `## HH:MM` header for the marker.
## Rule 2: Every Task = Date
**NEVER create a task without `dueString`:**
| Text | dueString |
|------|-----------|
| завтра | tomorrow |
| в пятницу | friday |
| на этой неделе | friday |
| в четверг | thursday |
| 15 января | January 15 |
| NOT SPECIFIED | in 3 days |
## Rule 3: Check Duplicates
**BEFORE creating any task:**
1. Call `find-tasks` with key words from task
2. If similar task exists → **DO NOT CREATE**
3. Mark as: `<!-- ✓ processed: task (duplicate) -->`
## Rule 4: Consider Workload
**BEFORE creating tasks:**
1. Call `find-tasks-by-date` with `startDate: "today"`, `daysCount: 7`
2. Count tasks per day
3. If target day has 3+ tasks → shift to next day with less load
## Rule 5: Mark After Processing
After EACH processed entry, add marker:
```markdown
<!-- ✓ processed: {category} -->
```
For tasks with details:
```markdown
<!-- ✓ processed: task → Todoist: {name} {priority} {date} -->
```
## Rule 6: Apply Decision Filters
Before saving any thought or task, check:
- Это масштабируется?
- Это можно автоматизировать?
- Это усиливает экспертизу [Your Business]?
- Это приближает к продукту/SaaS?
If 2+ yes → boost priority.
## Rule 7: Avoid Anti-Patterns
NEVER create:
- Абстрактные задачи без Next Action ("Подумать о...")
- Хаотичные списки без приоритетов
- Повторы без синтеза
- Академическая теория без применения
See [ABOUT.md](ABOUT.md) → Anti-Patterns section.
---
## Checklist Before Completion
- [ ] All new entries processed
- [ ] No duplicates in Todoist
- [ ] All tasks have dates and concrete actions
- [ ] Decision filters applied
- [ ] Anti-patterns avoided
- [ ] MOC files updated
- [ ] Report generated
@@ -0,0 +1,280 @@
# Todoist Integration
## Task Links Format
ВАЖНО: Todoist изменил формат ссылок. Используй НОВЫЙ формат:
✅ Правильно: `https://app.todoist.com/app/task/{task_id}`
❌ Устарело: `https://todoist.com/showTask?id={task_id}`
❌ Устарело: `https://todoist.com/app/task/{task_id}`
Если MCP tool вернул task с `url` полем — используй его напрямую.
Если нужно построить ссылку из task_id — используй формат выше.
---
## Todoist через mcp-cli
**ВСЕГДА используй mcp-cli. НЕ используй MCP tools напрямую.**
### Reading Tasks
```bash
# Обзор всех проектов
mcp-cli call todoist get-overview '{}'
# Поиск по тексту, проекту, секции
mcp-cli call todoist find-tasks '{"searchText": "keyword"}'
# Задачи по дате
mcp-cli call todoist find-tasks-by-date '{"startDate": "today", "daysCount": 7}'
```
### Writing Tasks
```bash
# Создать задачу
mcp-cli call todoist add-tasks '{"tasks": [{"content": "Task", "dueString": "tomorrow", "priority": 2}]}'
# Завершить задачу
mcp-cli call todoist complete-tasks '{"ids": ["task_id"]}'
# Обновить задачу
mcp-cli call todoist update-tasks '{"tasks": [{"id": "task_id", "content": "New title"}]}'
```
---
## Pre-Creation Checklist
### 1. Check Workload (REQUIRED)
```bash
mcp-cli call todoist find-tasks-by-date '{"startDate": "today", "daysCount": 7, "limit": 50}'
```
Build workload map:
```
Mon: 2 tasks
Tue: 4 tasks ← overloaded
Wed: 1 task
Thu: 3 tasks ← at limit
Fri: 2 tasks
Sat: 0 tasks
Sun: 0 tasks
```
### 2. Check Duplicates (REQUIRED)
```bash
mcp-cli call todoist find-tasks '{"searchText": "key words from new task"}'
```
If similar exists → mark as duplicate, don't create.
---
## Priority by Domain
Based on user's work context (see [ABOUT.md](ABOUT.md)):
| Domain | Default Priority | Override |
|--------|-----------------|----------|
| Client Work | p1-p2 | — |
| Agency Ops (urgent) | p2 | — |
| Agency Ops (regular) | p3 | — |
| Content (with deadline) | p2-p3 | — |
| Product/R&D | p4 | масштабируемость → p3 |
| AI & Tech | p4 | автоматизация → p3 |
### Priority Keywords
| Keywords in text | Priority |
|-----------------|----------|
| срочно, критично, дедлайн клиента | p1 |
| важно, приоритет, до конца недели | p2 |
| нужно, надо, не забыть | p3 |
| (strategic, R&D, long-term) | p4 |
### Apply Decision Filters for Priority Boost
If entry matches 2+ filters → boost priority by 1 level:
- Это масштабируется?
- Это можно автоматизировать?
- Это усиливает экспертизу [Your Business]?
- Это приближает к продукту/SaaS?
---
## Date Mapping
| Context | dueString |
|---------|-----------|
| **Client deadline** | exact date |
| **Urgent ops** | today / tomorrow |
| **This week** | friday |
| **Next week** | next monday |
| **Strategic/R&D** | in 7 days |
| **Not specified** | in 3 days |
### Russian → dueString
| Russian | dueString |
|---------|-----------|
| сегодня | today |
| завтра | tomorrow |
| послезавтра | in 2 days |
| в понедельник | monday |
| в пятницу | friday |
| на этой неделе | friday |
| на следующей неделе | next monday |
| через неделю | in 7 days |
| 15 января | January 15 |
---
## Task Creation
```bash
mcp-cli call todoist add-tasks '{"tasks": [{"content": "Task title", "dueString": "friday", "priority": 4}]}'
```
С projectId:
```bash
mcp-cli call todoist add-tasks '{"tasks": [{"content": "Task title", "dueString": "friday", "priority": 4, "projectId": "..."}]}'
```
### Task Title Style
User prefers: прямота, ясность, конкретика
✅ Good:
- "Отправить презентацию [Client A]"
- "Созвон с командой по AI-агентам"
- "Написать пост про Claude MCP"
❌ Bad:
- "Подумать о презентации"
- "Что-то с клиентом"
- "Разобраться с AI"
### Workload Balancing
If target day has 3+ tasks:
1. Find next day with < 3 tasks
2. Use that day instead
3. Mention in report: "сдвинуто на {day} (перегрузка)"
---
## Project Detection
Based on work domains:
| Keywords | Project |
|----------|---------|
| [Client A], [Client B], клиент, бренд | Client Work |
| [Your Business], агентство, команда, найм | Agency Ops |
| продукт, SaaS, MVP | Product |
| пост, @yourbrand, контент | Content |
If unclear → use Inbox (no projectId).
---
## Client Labels
При создании задач связанных с клиентом, добавляй label.
### Format
`client:{kebab-case-name}`
### Примеры
- client:acme-corp
- client:techco
- client:phonebrand
### Использование
```bash
mcp-cli call todoist add-tasks '{"tasks": [{"content": "Follow-up [Client A] по проекту", "labels": ["client:acme-corp", "deadline"]}]}'
```
### Фильтр в Todoist
`@client:acme-corp` — все задачи по [Client A]
---
## Anti-Patterns (НЕ СОЗДАВАТЬ)
Based on user preferences:
- ❌ "Подумать о..." → конкретизируй действие
- ❌ "Разобраться с..." → что именно сделать?
- ❌ Абстрактные задачи без Next Action
- ❌ Дубликаты существующих задач
- ❌ Задачи без дат
---
## Error Handling
CRITICAL: Никогда не предлагай "добавить вручную".
If `add-tasks` fails:
1. Include EXACT error message in report
2. Continue with next entry
3. Don't mark as processed
4. User will see error and can debug
WRONG output:
"Не удалось добавить (MCP недоступен). Добавь вручную: Task title"
CORRECT output:
"Ошибка создания задачи: [exact error from MCP tool]"
---
## Recurring Tasks for Process Goals
When creating process commitments → use dueString with recurring pattern.
### Recurring Patterns
| Process Description | dueString |
|---------------------|-----------|
| каждое утро в 6 | every day at 6am |
| каждый день | every day |
| каждый рабочий день | every weekday |
| 3 раза в неделю | every monday, wednesday, friday |
| раз в неделю | every week |
| каждый понедельник | every monday |
| каждую пятницу | every friday |
### Example: Creating Process Goal Tasks
```bash
mcp-cli call todoist add-tasks '{"tasks": [
{"content": "2h deep work: программа [Client B]", "dueString": "every day at 6am", "priority": 2, "labels": ["process-goal"]},
{"content": "1 outreach для поиска 2го спикера", "dueString": "every weekday", "priority": 3, "labels": ["process-goal"]}
]}'
```
### Label for Process Goals
Use label `process-goal` for recurring tasks created from Process Commitments.
This allows easy filtering and cleanup.
### When to Create Recurring
Create recurring tasks when:
- Generating weekly digest (new week planning)
- User explicitly asks for process goal setup
- Transforming outcome goal to process (if user confirms)
### Cleanup Stale Recurring
In weekly digest, check:
```bash
mcp-cli call todoist find-tasks '{"labels": ["process-goal"]}'
```
If task from previous week → warn user to complete or delete
+210
View File
@@ -0,0 +1,210 @@
---
name: graph-builder
description: Analyze and build knowledge graph links in Obsidian vault. Runs a deterministic script for analysis, then the agent adds semantic links to orphan files. Three domains: Personal, Business, Projects.
allowed-tools: Bash(uv run:*), Bash(rg:*), Read, Edit
depends_on: []
---
# Graph Builder
Analyze vault link structure and build meaningful connections between notes.
## Architecture
```
+------------------------------------------+
| 1. SCRIPT analyze.py (deterministic) |
| -> vault-graph.json + report.md |
+-----------------+------------------------+
|
v
+------------------------------------------+
| 2. AGENT (you) |
| -> orphan analysis |
| -> semantic links |
| -> frontmatter updates |
| -> HTML report |
+------------------------------------------+
```
## Trigger
- `/graph` -- manual run
- After `dbrain-processor` in chain (optional)
- Weekly: full rebuild
---
## STEP 1: Run the script
```bash
uv run vault/.claude/skills/graph-builder/scripts/analyze.py
```
**Script does:**
1. Traverses all .md files in vault/
2. Parses frontmatter
3. Extracts wiki-links `[[path]]` and `[[path|alias]]`
4. Determines domain (business, projects, personal)
5. Finds orphan files (no links)
6. Finds broken links
7. Generates `vault/.graph/vault-graph.json`
8. Generates `vault/.graph/report.md`
**CRITICAL:** Always run the script first! It provides up-to-date data.
---
## STEP 2: Read script output
Read `vault/.graph/vault-graph.json`:
```json
{
"stats": {
"total_files": 331,
"orphan_files": 147,
"broken_links": 167
},
"orphans": ["path/to/file.md", ...],
"broken_links": [{"from": "...", "to": "..."}, ...]
}
```
---
## STEP 3: Analyze orphan files
For each orphan file (start with **non-daily** files):
1. **Read the file content**
2. **Find potential links:**
- Company mentions -> `business/crm/{company}.md`
- People mentions -> search in contacts/
- Tags -> files with matching tags
- Dates -> daily/ for that day
- Topics -> thoughts/learnings/, MOC/
3. **Suggest links** -- add to frontmatter `related: []`
### Link search patterns
| Mention | Link |
|---------|------|
| Acme Corp, Acme | `[[business/crm/acme-corp]]` |
| PhoneBrand | `[[business/crm/phone-brand]]` |
| TechCo | `[[business/crm/tech-co]]` |
| SchoolCo | `[[projects/leads/school-co]]` |
| AutoDealer | `[[projects/leads/auto-dealer]]` |
| AI, Claude, GPT | thoughts/learnings/ with AI topic |
---
## STEP 4: Update frontmatter
**Link format in frontmatter:**
```yaml
---
type: learning
domain: personal
tags: [ai, marketing]
related:
- "[[business/crm/acme-corp]]"
- "[[projects/leads/school-co]]"
- "[[thoughts/learnings/agent-memory-system]]"
---
```
**Rules:**
- Only add real links (file exists)
- Do not duplicate existing links
- Maximum 5-7 links per file
- Use `"[[path]]"` format with quotes
---
## STEP 5: Update MOC (if needed)
Check MOC files:
- `MOC/MOC-learnings.md` -- add new learnings
- `MOC/MOC-projects.md` -- create if missing
---
## STEP 6: HTML report
**Return RAW HTML for Telegram:**
<b>Graph Builder Report</b>
<b>Analyzed:</b>
- Files: {total_files}
- Links: {total_links}
- Orphans: {orphan_files}
- Broken links: {broken_links}
<b>Business:</b> {files} files, {links} links
<b>Projects:</b> {files} files, {links} links
<b>Personal:</b> {files} files, {links} links
<b>Links added:</b> {count}
- {file1} -> {file2}
- {file3} -> {file4}
<b>Needs attention:</b>
- {broken_count} broken links
- {orphan_count} orphan files
<i>Details: vault/.graph/report.md</i>
---
## Three domains
### Personal
- `thoughts/` -- learnings, ideas, reflections
- `goals/` -- yearly, monthly, weekly
- `daily/` -- raw entries
- **Hub:** `MEMORY.md`
### Business
- `business/crm/` -- clients + deals (N files)
- `business/network/` -- org structure
- **Hub:** `business/_index.md`
### Projects
- `projects/clients/` -- project clients
- `projects/leads/` -- leads
- **Hub:** `projects/_index.md`
---
## Orphan processing priority
1. **business/crm/** -- business-critical, many orphans
2. **thoughts/learnings/** -- valuable knowledge
3. **projects/** -- active projects
4. **daily/** -- old entries (low priority)
---
## Do not
- Do not change file content (only frontmatter)
- Do not add links to non-existent files
- Do not process files in .obsidian/, attachments/, backup/
- Do not create new files without reason
---
## References
- `references/domains.md` -- domain details
- `references/entities.md` -- entity patterns
- `references/frontmatter.md` -- frontmatter schema
## Relevant Skills
- [[vault/.claude/skills/vault-health/SKILL|vault-health]] -- Health scoring, MOC generation, link repair (depends on this skill)
- [[vault/.claude/skills/dbrain-processor/SKILL|dbrain-processor]] -- Daily entry processing
@@ -0,0 +1,123 @@
# Domains
Three knowledge organization domains in the vault.
## Personal
**Path:** `thoughts/`, `goals/`, `daily/`, `MOC/`, `MEMORY.md`
**Content:**
- Personal thoughts and reflections
- Goals (yearly -> monthly -> weekly)
- Daily entries
- Learnings and ideas
**Hub:** `MEMORY.md` -- central context
**Frontmatter:**
```yaml
domain: personal
type: learning | reflection | idea | project
```
---
## Business
**Path:** `business/`
**Structure:**
```
business/
+-- _index.md # Entry point, dataview queries
+-- crm/ # Clients + deals
| +-- acme-corp.md
| +-- client-b.md
| +-- ...
+-- network/ # Org structure (Your Holding)
| +-- founders.md
| +-- partner-a.md
| +-- partner-b.md
+-- events/ # Events
```
**Hub:** `business/_index.md`
**Frontmatter (CRM):**
```yaml
domain: business
type: crm
industry: FMCG | Electronics | Banks | Pharma | Retail
priority: High | Mid | Low
status: Active | Prospect | Dormant | Declined
region: UZ | KZ | BY
owner: [Your Name] | [Team Member]
deal_status: In progress | Tender | Proposal sent
deal_deadline: YYYY-MM-DD
```
**Key clients:**
- Client-A (FMCG, High, Active)
- Client-B (Electronics, High, Active)
- Client-C (Electronics, Mid, Active)
- Client-D (FMCG, Mid, Prospect)
---
## Projects
**Path:** `projects/`
**Structure:**
```
projects/
+-- _index.md # Entry point
+-- clients/ # Project clients
| +-- client-a.md
| +-- client-b.md
| +-- client-c.md
| +-- client-d.md
+-- leads/ # Leads
+-- lead-a.md
+-- lead-b.md
```
**Hub:** `projects/_index.md`
**Frontmatter:**
```yaml
domain: projects
type: client | lead
company: Name
industry: Auto | IT | Retail | Education
status: APPROVED | Proposal sent | Hot | Cold
responsible: Name
```
**Difference from Business:**
- Business = main business (agency, services)
- Projects = personal side projects (consulting, training)
---
## Cross-domain links
| Link | Example |
|------|---------|
| Projects -> Business | `lead-a` -> `partner-b` (partner) |
| Personal -> Business | `learning` -> `acme-corp` (case from practice) |
| Personal -> Projects | `learning` -> `client-a` (insight from training) |
| Business -> Contacts | `acme-corp` -> contacts (contacts) |
---
## Determining domain by path
```python
def get_domain(path: Path) -> str:
if "business" in path.parts:
return "business"
elif "projects" in path.parts:
return "projects"
return "personal"
```
@@ -0,0 +1,157 @@
# Entity Extraction Patterns
Patterns for finding entities in text.
## Companies (Business CRM)
### Exact matches
| Pattern | File |
|---------|------|
| Client-A, ClientA | `business/crm/client-a.md` |
| Client-B | `business/crm/client-b.md` |
| Client-C | `business/crm/client-c.md` |
| Client-D | `business/crm/client-d.md` |
| Client-E | `business/crm/client-e.md` |
| Client-F | `business/crm/client-f.md` |
| Client-G | `business/crm/client-g.md` |
| Client-H | `business/crm/client-h.md` |
| Client-I | `business/crm/client-i.md` |
| Client-J | `business/crm/client-j.md` |
### Regex for companies
```python
COMPANY_PATTERNS = [
r'\b(Client-A|ClientA)\b',
r'\b(Client-B)\b',
r'\b(Client-C)\b',
r'\b(Client-D)\b',
r'\b(Client-E)\b',
r'\bClient-F\b',
r'\b(Client-G)\b',
r'\bClient-H\b',
r'\bClient-I\b',
]
```
---
## Companies (Projects)
| Pattern | File |
|---------|------|
| Project-Client-A | `projects/clients/project-client-a.md` |
| Project-Client-B | `projects/clients/project-client-b.md` |
| Project-Client-C | `projects/clients/project-client-c.md` |
| Project-Client-D | `projects/clients/project-client-d.md` |
| Lead-A | `projects/leads/lead-a.md` |
| Lead-B | `projects/leads/lead-b.md` |
---
## People
### Name format
```python
# Names in your language
LOCAL_NAME = r'[A-Z][a-z]+\s+[A-Z][a-z]+'
# Examples: [First Name] [Last Name]
# English names
ENGLISH_NAME = r'[A-Z][a-z]+\s+[A-Z][a-z]+'
# Examples: [First Name] [Last Name]
```
### Telegram handles
```python
TELEGRAM_HANDLE = r'@([a-zA-Z0-9_]+)'
# Examples: @username1, @username2, @username3
```
---
## Projects
### Project patterns
```python
PROJECT_PATTERNS = [
r'project\s+([A-Za-z0-9\s]+)',
r'(?:NCP|SMM|BTL|ATL)\s+([A-Za-z]+)',
r'tender\s+([A-Za-z]+)',
]
```
### Active projects
| Mention | Link |
|---------|------|
| Client-A Campaign | `business/crm/client-a.md` |
| Client-B SMM | `business/crm/client-b.md` |
| Client-C Project | `business/crm/client-c.md` |
---
## Topics (for learnings)
| Keywords | Links to |
|----------|----------|
| Claude, AI agent, LLM | `thoughts/learnings/` with AI |
| Second Brain, Obsidian, PKM | Methodology |
| Zettelkasten, graph | Knowledge organization |
| Prompt, prompt engineering | AI techniques |
| Marketing, SMM, content | Business |
---
## Finding file for entity
```python
def find_file_for_entity(entity: str, vault_path: Path) -> Path | None:
"""Find file for an entity."""
# Normalize: Client-A -> client-a
slug = entity.lower().replace(" ", "-")
# Search in CRM
crm_path = vault_path / "business" / "crm" / f"{slug}.md"
if crm_path.exists():
return crm_path
# Search in Projects
for subdir in ["clients", "leads"]:
path = vault_path / "projects" / subdir / f"{slug}.md"
if path.exists():
return path
# Fuzzy search by filename
for f in vault_path.rglob("*.md"):
if slug in f.stem.lower():
return f
return None
```
---
## Link normalization
```python
def normalize_link(link: str) -> str:
"""Normalize wiki-link."""
# Remove section: [[file#section]] -> file
link = link.split("#")[0]
# Remove alias: [[file|alias]] -> file
link = link.split("|")[0]
# Add .md if missing
if not link.endswith(".md"):
link = link + ".md"
return link
```
@@ -0,0 +1,252 @@
# Frontmatter Schema
YAML frontmatter schema for vault files.
## Basic schema (all files)
```yaml
---
type: string # Record type (see below)
domain: string # business | projects | personal
description: string # Retrieval filter ~150 chars (NOT summary -- adds scope/mechanism/implication beyond title)
tags: [string] # Tags for categorization
related: [string] # Wiki-links to related files
created: date # Creation date (YYYY-MM-DD)
updated: date # Update date
---
```
### Description field
**NOT a summary** -- description adds information BEYOND the title, does not repeat it.
This is a **retrieval filter**: the agent reads title + description and decides whether to open the file.
**Rules:**
- ~150 characters max
- Adds scope, mechanism or implication
- Does NOT repeat the title
- Specifics > abstractions
**Examples:**
```yaml
# CRM (title = acme-corp.md):
description: "Major FMCG client, Project $XXK active deal, promo codes in progress"
# Thought (title = 2026-02-05-hormonal-agent-algorithm.md):
description: "4 hormones as sine waves + noise -> mood -> intentions. Gives agent free will."
# Learning (title = 2026-01-30-session-persistence.md):
description: "JSONL append-only files for interaction history. Pattern from Clawdbot."
```
---
## Record types
### Personal domain
| type | Folder | Description |
|------|--------|-------------|
| learning | thoughts/learnings/ | Knowledge, discoveries, TIL |
| idea | thoughts/ideas/ | Ideas, concepts |
| reflection | thoughts/reflections/ | Reflections, conclusions |
| project | thoughts/projects/ | Project notes |
### Business domain
| type | Folder | Description |
|------|--------|-------------|
| crm | business/crm/ | Client + deals |
| network | business/network/ | Org structure |
| event | business/events/ | Events |
### Projects domain
| type | Folder | Description |
|------|--------|-------------|
| client | projects/clients/ | Project client |
| lead | projects/leads/ | Lead |
---
## CRM Schema (business/crm/)
```yaml
---
type: crm
domain: business
description: string # Retrieval filter: key client context (~150 chars)
industry: FMCG | Electronics | Banks | Pharma | Retail | Auto | IT | Telecom
priority: High | Mid | Low
status: Active | Prospect | Dormant | Declined
region: UZ | KZ | BY | Global
owner: [Your Name] | [Team Member]
responsible: string # Responsible person on client side
# Active deal (if any)
deal_status: In progress | Tender | Proposal sent | Meeting held
deal_deadline: YYYY-MM-DD
# Links
related:
- "[[thoughts/learnings/...]]"
updated: YYYY-MM-DD
---
```
**Example:**
```yaml
---
type: crm
domain: business
industry: FMCG
priority: High
status: Active
region: UZ, KZ
owner: [Your Name]
deal_status: In progress
deal_deadline: 2026-02-09
updated: 2026-01-29
---
```
---
## Learning Schema (thoughts/learnings/)
```yaml
---
type: learning
domain: personal
description: string # Retrieval filter: key insight (~150 chars)
tags: [ai, marketing, automation, ...]
source: daily/YYYY-MM-DD.md | URL | @mention
related:
- "[[business/crm/acme-corp]]"
- "[[projects/leads/lead-a]]"
created: YYYY-MM-DD
---
```
**Example:**
```yaml
---
type: learning
domain: personal
tags: [ai, marketing, panel]
source: event
related:
- "[[projects/leads/lead-a]]"
- "[[business/network/partner-a]]"
created: 2026-01-27
---
```
---
## Projects Client Schema
```yaml
---
type: client
domain: projects
description: string # Retrieval filter: client type and status (~150 chars)
company: string
industry: Auto | IT | Retail | Pharma | Education | Finance
region: BY | UZ | KZ | RU
status: APPROVED | Proposal sent | In progress | Completed
responsible: string
budget: string # Optional
related:
- "[[thoughts/learnings/...]]"
updated: YYYY-MM-DD
---
```
---
## Projects Lead Schema
```yaml
---
type: lead
domain: projects
description: string # Retrieval filter: who and why (~150 chars)
company: string
industry: Education | IT | ...
region: UZ | ...
status: Hot | Warm | Cold | Contacted | Proposal sent
source: string # Where lead came from
responsible: string
next_action: string # Next step
related: []
updated: YYYY-MM-DD
---
```
---
## Related format
**Correct:**
```yaml
related:
- "[[business/crm/acme-corp]]"
- "[[thoughts/learnings/agent-memory-system]]"
```
**Incorrect:**
```yaml
# Without quotes (may break YAML)
related:
- [[business/crm/acme-corp]]
# With alias in frontmatter (redundant)
related:
- "[[business/crm/acme-corp|Acme Corp]]"
```
---
## Adding links by agent
When updating frontmatter:
1. **Read** existing frontmatter
2. **Get** current `related: []`
3. **Add** new links (no duplicates)
4. **Verify** that files exist
5. **Write** updated frontmatter
```python
def add_related(content: str, new_links: list[str]) -> str:
"""Add links to frontmatter."""
# Parse frontmatter
match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
if not match:
return content
fm = yaml.safe_load(match.group(1)) or {}
# Get current links
existing = set(fm.get("related", []))
# Add new (format with quotes)
for link in new_links:
formatted = f'[[{link}]]' if not link.startswith('[[') else link
existing.add(formatted)
# Update
fm["related"] = sorted(list(existing))
# Write
new_fm = yaml.dump(fm, allow_unicode=True, default_flow_style=False)
return f"---\n{new_fm}---\n" + content[match.end():]
```
@@ -0,0 +1,247 @@
#!/usr/bin/env python3
"""
Link Builder for Obsidian Vault
Suggests and adds wiki-links based on content analysis.
Run with: uv run add_links.py [vault_path] [--dry-run]
"""
import re
import sys
from pathlib import Path
from collections import defaultdict
def extract_existing_links(content: str) -> set[str]:
"""Extract existing [[wiki-links]] from content."""
pattern = r'\[\[([^\]|]+)(?:\|[^\]]+)?\]\]'
return set(re.findall(pattern, content))
def find_mentions(content: str, note_titles: set[str]) -> list[tuple[str, int]]:
"""Find mentions of note titles in content without existing links."""
existing = extract_existing_links(content)
mentions = []
for title in note_titles:
if title in existing:
continue
if len(title) < 3: # Skip very short titles
continue
# Case-insensitive search for title
pattern = rf'\b{re.escape(title)}\b'
for match in re.finditer(pattern, content, re.IGNORECASE):
mentions.append((title, match.start()))
return mentions
def suggest_moc_links(note_path: Path, moc_mapping: dict[str, str]) -> list[str]:
"""Suggest MOC links based on domain/tags."""
suggestions = []
domain = note_path.parts[0] if len(note_path.parts) > 1 else None
if domain and domain in moc_mapping:
suggestions.append(moc_mapping[domain])
return suggestions
def build_moc_mapping(vault_path: Path) -> dict[str, str]:
"""Build mapping from domains to their MOC files."""
mapping = {}
moc_dir = vault_path / "MOC"
if moc_dir.exists():
for moc_file in moc_dir.glob("*.md"):
moc_name = moc_file.stem
# Map common domain patterns
domain_patterns = {
"ideas": "thoughts",
"learnings": "thoughts",
"reflections": "thoughts",
"projects": "projects",
"goals": "goals",
}
for pattern, domain in domain_patterns.items():
if pattern.lower() in moc_name.lower():
mapping[domain] = moc_name
return mapping
def analyze_and_suggest(vault_path: Path) -> dict:
"""Analyze vault and suggest new links."""
suggestions: dict[str, list[dict]] = defaultdict(list)
# Collect all note titles
md_files = list(vault_path.rglob("*.md"))
md_files = [
f for f in md_files
if not any(part.startswith('.') for part in f.relative_to(vault_path).parts)
]
note_titles = {f.stem for f in md_files}
moc_mapping = build_moc_mapping(vault_path)
for md_file in md_files:
rel_path = md_file.relative_to(vault_path)
title = md_file.stem
content = md_file.read_text(encoding="utf-8", errors="ignore")
# Find unlinked mentions
mentions = find_mentions(content, note_titles - {title})
for mentioned_title, position in mentions:
suggestions[title].append({
"type": "mention",
"target": mentioned_title,
"position": position,
"reason": f"'{mentioned_title}' mentioned but not linked",
})
# Suggest MOC links for orphan notes
existing_links = extract_existing_links(content)
moc_suggestions = suggest_moc_links(rel_path, moc_mapping)
for moc in moc_suggestions:
if moc not in existing_links:
suggestions[title].append({
"type": "moc",
"target": moc,
"reason": f"Should link to [[{moc}]] MOC",
})
return dict(suggestions)
def apply_link(file_path: Path, target: str, dry_run: bool = True) -> bool:
"""Add a link to a note's related section."""
content = file_path.read_text(encoding="utf-8")
# Check if link already exists
if f"[[{target}]]" in content:
return False
# Find or create "Related" section
related_pattern = r'^## Related\s*$'
match = re.search(related_pattern, content, re.MULTILINE)
if match:
# Add to existing Related section
insert_pos = match.end()
new_content = content[:insert_pos] + f"\n- [[{target}]]" + content[insert_pos:]
else:
# Add Related section at end
new_content = content.rstrip() + f"\n\n## Related\n\n- [[{target}]]\n"
if dry_run:
print(f"[DRY RUN] Would add [[{target}]] to {file_path.name}")
return True
file_path.write_text(new_content, encoding="utf-8")
print(f"Added [[{target}]] to {file_path.name}")
return True
def format_suggestions(suggestions: dict) -> str:
"""Format suggestions as readable report."""
if not suggestions:
return "No link suggestions found. Vault is well-connected!"
lines = [
"# Link Suggestions",
"",
f"Found suggestions for {len(suggestions)} notes:",
"",
]
for note, items in sorted(suggestions.items()):
lines.append(f"## [[{note}]]")
for item in items:
lines.append(f"- {item['type'].upper()}: Link to [[{item['target']}]]")
lines.append(f" - Reason: {item['reason']}")
lines.append("")
return "\n".join(lines)
def format_html(suggestions: dict) -> str:
"""Format suggestions as Telegram HTML."""
if not suggestions:
return "✅ <b>No link suggestions</b>\n\nVault is well-connected!"
total = sum(len(v) for v in suggestions.values())
lines = [
f"🔗 <b>Link Suggestions</b>",
"",
f"<b>Found:</b> {total} suggestions for {len(suggestions)} notes",
"",
]
# Show top 10 suggestions
count = 0
for note, items in sorted(suggestions.items(), key=lambda x: -len(x[1])):
if count >= 10:
remaining = total - count
lines.append(f"\n<i>... and {remaining} more suggestions</i>")
break
for item in items:
lines.append(f"• [[{note}]] → [[{item['target']}]]")
count += 1
if count >= 10:
break
return "\n".join(lines)
def main():
dry_run = "--dry-run" in sys.argv or "-n" in sys.argv
apply_mode = "--apply" in sys.argv
# Get vault path
vault_path = None
for arg in sys.argv[1:]:
if not arg.startswith("-"):
vault_path = Path(arg)
break
if vault_path is None:
# Default: assume script is in vault/.claude/skills/graph-builder/scripts/
vault_path = Path(__file__).parent.parent.parent.parent.parent
if not vault_path.exists():
print(f"Error: Vault path not found: {vault_path}", file=sys.stderr)
sys.exit(1)
suggestions = analyze_and_suggest(vault_path)
if apply_mode:
# Apply all suggestions
applied = 0
for note, items in suggestions.items():
note_path = vault_path / f"{note}.md"
# Try to find the actual file
matches = list(vault_path.rglob(f"{note}.md"))
matches = [m for m in matches if not str(m).startswith('.')]
if matches:
note_path = matches[0]
for item in items:
if apply_link(note_path, item["target"], dry_run):
applied += 1
print(f"\n{'[DRY RUN] Would apply' if dry_run else 'Applied'} {applied} links")
else:
# Just report
if "--html" in sys.argv:
print(format_html(suggestions))
elif "--json" in sys.argv:
import json
print(json.dumps(suggestions, indent=2))
else:
print(format_suggestions(suggestions))
if __name__ == "__main__":
main()
@@ -0,0 +1,219 @@
#!/usr/bin/env python3
"""
Graph Analyzer for Obsidian Vault
Analyzes wiki-link structure and generates statistics.
Run with: uv run analyze.py [vault_path]
"""
import re
import sys
from collections import defaultdict
from pathlib import Path
def extract_links(content: str) -> list[str]:
"""Extract [[wiki-links]] from content."""
pattern = r'\[\[([^\]|]+)(?:\|[^\]]+)?\]\]'
return re.findall(pattern, content)
def get_note_title(path: Path) -> str:
"""Get note title from filename."""
return path.stem
def analyze_vault(vault_path: Path) -> dict:
"""Analyze vault link structure."""
notes: dict[str, dict] = {}
links_from: dict[str, set] = defaultdict(set) # note -> set of linked notes
links_to: dict[str, set] = defaultdict(set) # note -> set of notes linking to it
# Collect all markdown files
md_files = list(vault_path.rglob("*.md"))
# Skip hidden directories and .claude
md_files = [
f for f in md_files
if not any(part.startswith('.') for part in f.relative_to(vault_path).parts)
]
# Build note index
for md_file in md_files:
rel_path = md_file.relative_to(vault_path)
title = get_note_title(md_file)
domain = str(rel_path.parts[0]) if len(rel_path.parts) > 1 else "root"
notes[title] = {
"path": str(rel_path),
"domain": domain,
"size": md_file.stat().st_size,
}
# Analyze links
for md_file in md_files:
title = get_note_title(md_file)
content = md_file.read_text(encoding="utf-8", errors="ignore")
for link in extract_links(content):
# Handle links with paths like [[folder/note]]
link_title = link.split("/")[-1] if "/" in link else link
links_from[title].add(link_title)
links_to[link_title].add(title)
# Calculate statistics
orphans = []
for title, info in notes.items():
incoming = len(links_to.get(title, set()))
outgoing = len(links_from.get(title, set()))
info["incoming"] = incoming
info["outgoing"] = outgoing
info["total_links"] = incoming + outgoing
# Orphan: no incoming AND no outgoing links
# Exclude MOC and root-level files from orphan detection
if incoming == 0 and outgoing == 0:
if info["domain"] not in ("MOC", "root"):
orphans.append(title)
# Domain statistics
domain_stats: dict[str, dict] = defaultdict(lambda: {"count": 0, "links": 0})
for title, info in notes.items():
domain = info["domain"]
domain_stats[domain]["count"] += 1
domain_stats[domain]["links"] += info["total_links"]
for domain in domain_stats:
count = domain_stats[domain]["count"]
if count > 0:
domain_stats[domain]["avg_links"] = domain_stats[domain]["links"] / count
# Most connected notes
most_connected = sorted(
notes.items(),
key=lambda x: x[1]["total_links"],
reverse=True
)[:10]
return {
"total_notes": len(notes),
"total_links": sum(len(v) for v in links_from.values()),
"orphans": orphans,
"orphan_count": len(orphans),
"domain_stats": dict(domain_stats),
"most_connected": [(t, n["total_links"]) for t, n in most_connected],
"notes": notes,
"links_from": {k: list(v) for k, v in links_from.items()},
"links_to": {k: list(v) for k, v in links_to.items()},
}
def format_report(stats: dict) -> str:
"""Format analysis as readable report."""
lines = [
"# Vault Graph Analysis",
"",
"## Overview",
"",
f"- **Total notes:** {stats['total_notes']}",
f"- **Total links:** {stats['total_links']}",
f"- **Orphan notes:** {stats['orphan_count']}",
"",
]
# Most connected
if stats["most_connected"]:
lines.append("## Most Connected Notes")
lines.append("")
for title, count in stats["most_connected"][:5]:
lines.append(f"- [[{title}]] ({count} links)")
lines.append("")
# Domain stats
lines.append("## Domain Statistics")
lines.append("")
lines.append("| Domain | Notes | Avg Links |")
lines.append("|--------|-------|-----------|")
for domain, data in sorted(stats["domain_stats"].items()):
avg = data.get("avg_links", 0)
lines.append(f"| {domain}/ | {data['count']} | {avg:.1f} |")
lines.append("")
# Orphans
if stats["orphans"]:
lines.append("## Orphan Notes (need links)")
lines.append("")
for title in stats["orphans"][:20]:
note = stats["notes"][title]
lines.append(f"- [[{title}]] ({note['domain']}/)")
if len(stats["orphans"]) > 20:
lines.append(f"- ... and {len(stats['orphans']) - 20} more")
lines.append("")
return "\n".join(lines)
def format_html(stats: dict) -> str:
"""Format analysis as Telegram HTML."""
orphan_count = stats["orphan_count"]
orphan_emoji = "⚠️" if orphan_count > 10 else "✅"
lines = [
f"📊 <b>Vault Graph Analysis</b>",
"",
f"<b>📝 Total notes:</b> {stats['total_notes']}",
f"<b>🔗 Total links:</b> {stats['total_links']}",
f"<b>{orphan_emoji} Orphan notes:</b> {orphan_count}",
"",
]
# Most connected
if stats["most_connected"]:
lines.append("<b>🏆 Most connected:</b>")
for title, count in stats["most_connected"][:3]:
lines.append(f"• [[{title}]] ({count})")
lines.append("")
# Weakest domain
weakest = min(
stats["domain_stats"].items(),
key=lambda x: x[1].get("avg_links", 0)
)
lines.append(f"<b>⚡ Weakest domain:</b> {weakest[0]}/ (avg {weakest[1].get('avg_links', 0):.1f} links)")
# Orphan preview
if stats["orphans"]:
lines.append("")
lines.append("<b>📋 Sample orphans:</b>")
for title in stats["orphans"][:5]:
lines.append(f"• {title}")
return "\n".join(lines)
def main():
if len(sys.argv) > 1:
vault_path = Path(sys.argv[1])
else:
# Default: assume script is in vault/.claude/skills/graph-builder/scripts/
vault_path = Path(__file__).parent.parent.parent.parent.parent
if not vault_path.exists():
print(f"Error: Vault path not found: {vault_path}", file=sys.stderr)
sys.exit(1)
stats = analyze_vault(vault_path)
# Output format based on args
if "--html" in sys.argv:
print(format_html(stats))
elif "--json" in sys.argv:
import json
print(json.dumps(stats, indent=2))
else:
print(format_report(stats))
if __name__ == "__main__":
main()
+81
View File
@@ -0,0 +1,81 @@
---
name: todoist-ai
description: Todoist integration via mcp-cli for task management
depends_on: []
---
# todoist-ai
Todoist integration via mcp-cli.
## CRITICAL
**ALWAYS use mcp-cli. DO NOT use MCP tools directly.**
```bash
# Today's tasks
mcp-cli call todoist find-tasks-by-date '{"startDate": "today"}'
# Create task
mcp-cli call todoist add-tasks '{"tasks": [{"content": "Task", "dueString": "tomorrow", "priority": 2}]}'
# Complete task
mcp-cli call todoist complete-tasks '{"ids": ["task_id"]}'
# Overview
mcp-cli call todoist get-overview '{}'
```
## Description
A set of tools to connect to AI agents, to allow them to use Todoist on a user's behalf. Uses mcp-cli wrapper for stable connections.
**Repository:** [Doist/todoist-ai](https://github.com/Doist/todoist-ai)
**Language:** TypeScript
**Stars:** 212
**License:** MIT License
## When to Use This Skill
Use this skill when you need to:
- Create, update, or complete tasks in Todoist
- Check workload or task status
- Look up API documentation
- Find usage examples
## Quick Reference
### Repository Info
- **Homepage:**
- **Topics:**
- **Open Issues:** 18
- **Last Updated:** 2025-12-13
### Languages
- **TypeScript:** 98.0%
- **JavaScript:** 2.0%
### Recent Releases
- **v5.2.0** (2025-11-27): v5.2.0
- **v5.1.1** (2025-11-27): v5.1.1
- **v5.1.0** (2025-11-20): v5.1.0
## Available References
- `references/README.md` - Complete README documentation
- `references/CHANGELOG.md` - Version history and changes
- `references/issues.md` - Recent GitHub issues
- `references/releases.md` - Release notes
- `references/file_structure.md` - Repository structure
## Usage
See README.md for complete usage instructions and examples.
---
**Generated by Skill Seeker** | GitHub Repository Scraper
## Relevant Skills
- [[vault/.claude/skills/dbrain-processor/SKILL|dbrain-processor]] — Daily entry processing
@@ -0,0 +1,461 @@
# Changelog
## [5.2.0](https://github.com/Doist/todoist-ai/compare/v5.1.1...v5.2.0) (2025-11-27)
### Features
* Add isUncompletable parameter support to add/update tools ([#230](https://github.com/Doist/todoist-ai/issues/230)) ([0c295ac](https://github.com/Doist/todoist-ai/commit/0c295ac7d7d1b81f5512b1c782eaba4ef24aeafd))
## [5.1.1](https://github.com/Doist/todoist-ai/compare/v5.1.0...v5.1.1) (2025-11-27)
### Bug Fixes
* **deps:** Update `@doist/todoist-api-typescript` to 6.1.12 ([#229](https://github.com/Doist/todoist-ai/issues/229)) ([54e3552](https://github.com/Doist/todoist-ai/commit/54e3552b68d648a042bac9991cb600fd8f8f5be1))
* **deps:** update dependency @modelcontextprotocol/sdk to v1.22.0 ([#227](https://github.com/Doist/todoist-ai/issues/227)) ([b20c05e](https://github.com/Doist/todoist-ai/commit/b20c05e3273ff6a565380cdddb9be5743ba7bb66))
## [5.1.0](https://github.com/Doist/todoist-ai/compare/v5.0.2...v5.1.0) (2025-11-20)
### Features
* add read-only and destructive hints to all tools ([#222](https://github.com/Doist/todoist-ai/issues/222)) ([5d8ce22](https://github.com/Doist/todoist-ai/commit/5d8ce225c92a688834881bde13d5956bbe7e59ff))
## [5.0.2](https://github.com/Doist/todoist-ai/compare/v5.0.1...v5.0.2) (2025-11-19)
### Bug Fixes
* **find-projects:** resolve search pagination issue and update PROJECTS_MAX ([#223](https://github.com/Doist/todoist-ai/issues/223)) ([b0772d1](https://github.com/Doist/todoist-ai/commit/b0772d1dd688188cc70dcdd50989208fd18f9c39))
## [5.0.1](https://github.com/Doist/todoist-ai/compare/v5.0.0...v5.0.1) (2025-11-18)
### Bug Fixes
* **deps:** update production dependencies ([#220](https://github.com/Doist/todoist-ai/issues/220)) ([f6121b0](https://github.com/Doist/todoist-ai/commit/f6121b0fcc7bf432e07df7a8ef9c11291ba09dfb))
## [5.0.0](https://github.com/Doist/todoist-ai/compare/v4.17.4...v5.0.0) (2025-11-14)
### ⚠ BREAKING CHANGES
* semantic priority values (P1, P2, P3, P4) instead of numeric ([#217](https://github.com/Doist/todoist-ai/issues/217))
### Features
* semantic priority values (P1, P2, P3, P4) instead of numeric ([#217](https://github.com/Doist/todoist-ai/issues/217)) ([9bb906b](https://github.com/Doist/todoist-ai/commit/9bb906b48d836898bf616df60cef38aaa7ae2894))
## [4.17.4](https://github.com/Doist/todoist-ai/compare/v4.17.3...v4.17.4) (2025-11-13)
### Bug Fixes
* correct priority inversion for task outputs ([#216](https://github.com/Doist/todoist-ai/issues/216)) ([b4b4809](https://github.com/Doist/todoist-ai/commit/b4b4809f129d6aa029f0ef4aa28352760c879aee))
* **deps:** pin dependencies ([#212](https://github.com/Doist/todoist-ai/issues/212)) ([2049ebf](https://github.com/Doist/todoist-ai/commit/2049ebf4e5eedd2465650c79c16e39f04a5e4ddd))
## [4.17.3](https://github.com/Doist/todoist-ai/compare/v4.17.2...v4.17.3) (2025-11-06)
### Bug Fixes
* **deps:** Bump `@doist/todoist-api-typescript` package ([#210](https://github.com/Doist/todoist-ai/issues/210)) ([85fbfb5](https://github.com/Doist/todoist-ai/commit/85fbfb591f2e4ee165b71ff1386a39ab96d7e31a))
## [4.17.2](https://github.com/Doist/todoist-ai/compare/v4.17.1...v4.17.2) (2025-11-06)
### Bug Fixes
* enforce output schemas for tools (follow-up) ([#208](https://github.com/Doist/todoist-ai/issues/208)) ([c83772a](https://github.com/Doist/todoist-ai/commit/c83772a7c29314891b1e031dce9f07d954b4e4a5))
## [4.17.1](https://github.com/Doist/todoist-ai/compare/v4.17.0...v4.17.1) (2025-11-06)
### Bug Fixes
* enforce output schemas for tools ([#205](https://github.com/Doist/todoist-ai/issues/205)) ([9b1d593](https://github.com/Doist/todoist-ai/commit/9b1d59317dbe5277b6f4126388a2402cf3c35e8e))
## [4.17.0](https://github.com/Doist/todoist-ai/compare/v4.16.1...v4.17.0) (2025-11-05)
### Features
* Add output schema to all tools ([#203](https://github.com/Doist/todoist-ai/issues/203)) ([7663388](https://github.com/Doist/todoist-ai/commit/76633886dde65880cd049733431aa9d4a5038b84))
## [4.16.1](https://github.com/Doist/todoist-ai/compare/v4.16.0...v4.16.1) (2025-11-05)
### Bug Fixes
* Show next steps only for paginated tools and clarify as suggestions ([#201](https://github.com/Doist/todoist-ai/issues/201)) ([f969615](https://github.com/Doist/todoist-ai/commit/f9696155fe931b6c40859c1a2f7e82a859253288))
## [4.16.0](https://github.com/Doist/todoist-ai/compare/v4.15.1...v4.16.0) (2025-11-03)
### Features
* Extend "inbox" project ID support to 7 additional tools ([#198](https://github.com/Doist/todoist-ai/issues/198)) ([5bab0f9](https://github.com/Doist/todoist-ai/commit/5bab0f94ab2d997d71870202294af3c5d3ac7784))
## [4.15.1](https://github.com/Doist/todoist-ai/compare/v4.15.0...v4.15.1) (2025-10-31)
### Bug Fixes
* Allow `inbox` as a project id ([#193](https://github.com/Doist/todoist-ai/issues/193)) ([fe4a91f](https://github.com/Doist/todoist-ai/commit/fe4a91fe2daa7f97473b97de54385e03358a8122))
## [4.15.0](https://github.com/Doist/todoist-ai/compare/v4.14.5...v4.15.0) (2025-10-26)
### Features
* Add deadline support to add-tasks and update-tasks ([#186](https://github.com/Doist/todoist-ai/issues/186)) ([8f795c8](https://github.com/Doist/todoist-ai/commit/8f795c8949f40d10bf629933793d8cb4607dcb58))
* Add parentId support to update-projects tool ([#184](https://github.com/Doist/todoist-ai/issues/184)) ([0185b83](https://github.com/Doist/todoist-ai/commit/0185b836fff1359c8303de20bcc37c8f86138180))
## [4.14.5](https://github.com/Doist/todoist-ai/compare/v4.14.4...v4.14.5) (2025-10-25)
### Bug Fixes
* Remove nullable type from update_tasks to fix Gemini API compatibility ([#181](https://github.com/Doist/todoist-ai/issues/181)) ([c97be7f](https://github.com/Doist/todoist-ai/commit/c97be7f39ae48d837562fd303b67ed81e8935c18))
## [4.14.4](https://github.com/Doist/todoist-ai/compare/v4.14.3...v4.14.4) (2025-10-24)
### Bug Fixes
* Add actions: write permission to trigger workflows ([6863953](https://github.com/Doist/todoist-ai/commit/6863953b6e92fd8b35f4692b5c609ad42631722a))
## [4.14.3](https://github.com/Doist/todoist-ai/compare/v4.14.2...v4.14.3) (2025-10-24)
### Bug Fixes
* Add --repo flag to gh workflow run command ([f61caa8](https://github.com/Doist/todoist-ai/commit/f61caa8c7aabce166484b95b70886aa4049c904c))
## [4.14.2](https://github.com/Doist/todoist-ai/compare/v4.14.1...v4.14.2) (2025-10-24)
### Bug Fixes
* Trigger publish workflow automatically from release-please ([#174](https://github.com/Doist/todoist-ai/issues/174)) ([081bc2b](https://github.com/Doist/todoist-ai/commit/081bc2ba5abfdc3bf4bfe3c282f29570877b977c))
## [4.14.1](https://github.com/Doist/todoist-ai/compare/v4.14.0...v4.14.1) (2025-10-24)
### Bug Fixes
* Update todoist-typescript-sdk to 5.7.1 (follow-up) ([#172](https://github.com/Doist/todoist-ai/issues/172)) ([b4f8dc3](https://github.com/Doist/todoist-ai/commit/b4f8dc3ffa4c3dd7489ece03be5a0f391130a2ce))
## [4.14.0](https://github.com/Doist/todoist-ai/compare/v4.13.5...v4.14.0) (2025-10-23)
### Features
* Add find-activity tool ([#169](https://github.com/Doist/todoist-ai/issues/169)) ([1abf67f](https://github.com/Doist/todoist-ai/commit/1abf67f3a99191582cf0b5ea2516420f1278dc9a))
## [4.13.5](https://github.com/Doist/todoist-ai/compare/v4.13.4...v4.13.5) (2025-10-23)
### Bug Fixes
* clarify find-completed-tasks scope ([#167](https://github.com/Doist/todoist-ai/issues/167)) ([f110669](https://github.com/Doist/todoist-ai/commit/f11066934d4f6b790599d0f89db416a32437edd3))
## [4.13.4](https://github.com/Doist/todoist-ai/compare/v4.13.3...v4.13.4) (2025-10-23)
### Bug Fixes
* Test publish workflow (no functional changes) ([#164](https://github.com/Doist/todoist-ai/issues/164)) ([68afb4c](https://github.com/Doist/todoist-ai/commit/68afb4ce06366cc022a1718e6cd0c3525c5aab48))
## [4.13.3](https://github.com/Doist/todoist-ai/compare/v4.13.2...v4.13.3) (2025-10-23)
### Bug Fixes
* Switch to using `moveTask` instead of `moveTasks` ([#160](https://github.com/Doist/todoist-ai/issues/160)) ([34e3fc6](https://github.com/Doist/todoist-ai/commit/34e3fc67922379bf0aef39a9e7f1939ded5f0e08))
## [4.13.2](https://github.com/Doist/todoist-ai/compare/v4.13.1...v4.13.2) (2025-10-22)
### Bug Fixes
* Output `checked` for the `fetch` tool ([#158](https://github.com/Doist/todoist-ai/issues/158)) ([f0a6eaf](https://github.com/Doist/todoist-ai/commit/f0a6eaf62a915cfab289f1b5181770ccd11d0bdb))
## [4.13.1](https://github.com/Doist/todoist-ai/compare/v4.13.0...v4.13.1) (2025-10-22)
### Bug Fixes
* Remove `updatedAt` ([#155](https://github.com/Doist/todoist-ai/issues/155)) ([3f3f345](https://github.com/Doist/todoist-ai/commit/3f3f3458f9d54f4f347dfb7c34892fb3cda7ff3b))
## [4.13.0](https://github.com/Doist/todoist-ai/compare/v4.12.0...v4.13.0) (2025-10-21)
### Features
* Expose completion and modification metadata in task mapping ([#153](https://github.com/Doist/todoist-ai/issues/153)) ([1e2d3b3](https://github.com/Doist/todoist-ai/commit/1e2d3b3f461e75be8cc63ae3a4e070d113f5c4da))
* extend responsibleUser filtering to more tools ([#149](https://github.com/Doist/todoist-ai/issues/149)) ([c146d74](https://github.com/Doist/todoist-ai/commit/c146d749eb097e1d383dda00e6a09e05389969dd))
## [4.12.0](https://github.com/Doist/todoist-ai/compare/v4.11.0...v4.12.0) (2025-10-14)
### Features
* In find-tasks-by-date use backend filtering for responsible user ([#145](https://github.com/Doist/todoist-ai/issues/145)) ([5d1e140](https://github.com/Doist/todoist-ai/commit/5d1e1400f639e8c802019421eb0437ef39c67a64))
## [4.11.0](https://github.com/Doist/todoist-ai/compare/v4.10.0...v4.11.0) (2025-10-13)
### Features
* Improve findCompletedTasks to handle user timezones ([#143](https://github.com/Doist/todoist-ai/issues/143)) ([c27d897](https://github.com/Doist/todoist-ai/commit/c27d8973d0ea9342f8b1e56659fca900f920ddb3))
## [4.10.0](https://github.com/Doist/todoist-ai/compare/v4.9.4...v4.10.0) (2025-10-10)
### Features
* add OpenAI-compliant `search` and `fetch` tools ([#134](https://github.com/Doist/todoist-ai/issues/134)) ([153289c](https://github.com/Doist/todoist-ai/commit/153289c5cf02b2da6b3f4cf6e8a7c681b3ee3aec))
* Clarify content vs description usage and Markdown support ([#139](https://github.com/Doist/todoist-ai/issues/139)) ([cb410a2](https://github.com/Doist/todoist-ai/commit/cb410a2c16670ec07ee2d812ba961075c3f20dda))
## [4.9.4](https://github.com/Doist/todoist-ai/compare/v4.9.3...v4.9.4) (2025-10-06)
### Bug Fixes
* Ensures null fields are not returned ([#130](https://github.com/Doist/todoist-ai/issues/130)) ([a016011](https://github.com/Doist/todoist-ai/commit/a0160115b6fff4b96751056506494e43f582527c))
## [4.9.3](https://github.com/Doist/todoist-ai/compare/v4.9.2...v4.9.3) (2025-10-02)
### Bug Fixes
* dayCount and overdue only fixes ([#128](https://github.com/Doist/todoist-ai/issues/128)) ([d020c06](https://github.com/Doist/todoist-ai/commit/d020c0622fb5c9a71b5f666406529236db76bdef))
## [4.9.2](https://github.com/Doist/todoist-ai/compare/v4.9.1...v4.9.2) (2025-10-02)
### Bug Fixes
* allow add-tasks to work with only content parameter ([#126](https://github.com/Doist/todoist-ai/issues/126)) ([27bda34](https://github.com/Doist/todoist-ai/commit/27bda346f465a1a2ab7a0ab833c151093a4d7044))
## [4.9.1](https://github.com/Doist/todoist-ai/compare/v4.9.0...v4.9.1) (2025-10-01)
### Bug Fixes
* Enhance task filtering by responsible user and update related tools ([#121](https://github.com/Doist/todoist-ai/issues/121)) ([cea0917](https://github.com/Doist/todoist-ai/commit/cea0917a8b2bd1f056e1b08f14e9cb858b9711a5))
* preserve markdown in tasks content and description ([#124](https://github.com/Doist/todoist-ai/issues/124)) ([0cc48fe](https://github.com/Doist/todoist-ai/commit/0cc48fe93595213729d794b7b6c92d54072cf6d5))
## [4.9.0](https://github.com/Doist/todoist-ai/compare/v4.8.0...v4.9.0) (2025-09-30)
### Features
* add parentId support to add-projects tool ([#122](https://github.com/Doist/todoist-ai/issues/122)) ([84019d1](https://github.com/Doist/todoist-ai/commit/84019d1403fff67d33de5bf756a40da28b88171e))
## [4.8.0](https://github.com/Doist/todoist-ai/compare/v4.7.1...v4.8.0) (2025-09-29)
### Features
* merge overdue into today's tasks in find-tasks-by-date tool ([#108](https://github.com/Doist/todoist-ai/issues/108)) ([f86e69d](https://github.com/Doist/todoist-ai/commit/f86e69d3ac4861a1b99ebdc8f25f135c6d6adeeb))
## [4.7.1](https://github.com/Doist/todoist-ai/compare/v4.7.0...v4.7.1) (2025-09-29)
### Bug Fixes
* Convert the API priorities into a consumable priority ([#115](https://github.com/Doist/todoist-ai/issues/115)) ([e4cc62f](https://github.com/Doist/todoist-ai/commit/e4cc62f5e456c517995aaf9b8e22153923a55ff7))
## [4.7.0](https://github.com/Doist/todoist-ai/compare/v4.6.1...v4.7.0) (2025-09-25)
### Features
* Document the MCP setup better, including the remote endpoint ([#109](https://github.com/Doist/todoist-ai/issues/109)) ([e1e69e2](https://github.com/Doist/todoist-ai/commit/e1e69e27e91675775e7f4ea0bef709a17722131c))
## [4.6.1](https://github.com/Doist/todoist-ai/compare/v4.6.0...v4.6.1) (2025-09-24)
### Bug Fixes
* Update package.json with `mcpName` ([#106](https://github.com/Doist/todoist-ai/issues/106)) ([df19306](https://github.com/Doist/todoist-ai/commit/df19306adb13ff6416a37e4b49a6d2e5ab5c459f))
## [4.6.0](https://github.com/Doist/todoist-ai/compare/v4.5.2...v4.6.0) (2025-09-24)
### Features
* add label support for add-tasks and update-tasks tools ([#103](https://github.com/Doist/todoist-ai/issues/103)) ([a4bc708](https://github.com/Doist/todoist-ai/commit/a4bc7085b5a63402970841e586ce985cab9022d0))
## [4.5.2](https://github.com/Doist/todoist-ai/compare/v4.5.1...v4.5.2) (2025-09-24)
### Miscellaneous Chores
* Release 4.5.2 ([11df6f2](https://github.com/Doist/todoist-ai/commit/11df6f2c03e31bffd02a6c4f1a5176158e434e05))
## [4.5.1](https://github.com/Doist/todoist-ai/compare/v4.5.0...v4.5.1) (2025-09-23)
### Bug Fixes
* fix priority levels ([#98](https://github.com/Doist/todoist-ai/issues/98)) ([64db2ff](https://github.com/Doist/todoist-ai/commit/64db2ff97f3ede0c5cff14d1c58f8fed63a9d742))
## [4.5.0](https://github.com/Doist/todoist-ai/compare/v4.4.0...v4.5.0) (2025-09-11)
### Features
* add task assignment management ([#81](https://github.com/Doist/todoist-ai/issues/81)) ([b9b1691](https://github.com/Doist/todoist-ai/commit/b9b16916dec8f18efc37631d77f97354fae2194a))
## [4.4.0](https://github.com/Doist/todoist-ai/compare/v4.3.0...v4.4.0) (2025-09-10)
### Features
* Add user's id to user_info tool ([#84](https://github.com/Doist/todoist-ai/issues/84)) ([706ed8f](https://github.com/Doist/todoist-ai/commit/706ed8fdfd11199808ca9824d4c66e8211d773c1))
## [4.3.0](https://github.com/Doist/todoist-ai/compare/v4.2.0...v4.3.0) (2025-09-09)
### Features
* Add user-info tool and upgrade Todoist API ([#82](https://github.com/Doist/todoist-ai/issues/82)) ([b583fe1](https://github.com/Doist/todoist-ai/commit/b583fe1045ea38fbe25dfa804df9ebe958f2881d))
## [4.2.0](https://github.com/Doist/todoist-ai/compare/v4.1.0...v4.2.0) (2025-08-29)
### Features
* Add support for filtering by label ([#71](https://github.com/Doist/todoist-ai/issues/71)) ([b608d32](https://github.com/Doist/todoist-ai/commit/b608d32f7636a175dc62ca388892e9aef0834712))
## [4.1.0](https://github.com/Doist/todoist-ai/compare/v4.0.0...v4.1.0) (2025-08-23)
### Features
* export comment tools ([#63](https://github.com/Doist/todoist-ai/issues/63)) ([cec2999](https://github.com/Doist/todoist-ai/commit/cec2999b8ca1f660f26b37cffb3803e863f60be0))
## [4.0.0](https://github.com/Doist/todoist-ai/compare/v3.0.0...v4.0.0) (2025-08-22)
### ⚠ BREAKING CHANGES
* restructure management tools into specialized add/update tools ([#59](https://github.com/Doist/todoist-ai/issues/59))
### Features
* add comment tools ([#58](https://github.com/Doist/todoist-ai/issues/58)) ([7d6ffca](https://github.com/Doist/todoist-ai/commit/7d6ffcacd326ef755aba691436d44d6b534f6b4b))
* add todoist base url to dev setup, plus doc improvements ([#62](https://github.com/Doist/todoist-ai/issues/62)) ([e0e5a78](https://github.com/Doist/todoist-ai/commit/e0e5a78d1358b82d5f2661a41ffe193015296154))
* parallelize add-tasks with per-task context ([#60](https://github.com/Doist/todoist-ai/issues/60)) ([816d099](https://github.com/Doist/todoist-ai/commit/816d099551974bad3e0663c1d77334b692aaa76a))
* restructure management tools into specialized add/update tools ([#59](https://github.com/Doist/todoist-ai/issues/59)) ([0c4dcf7](https://github.com/Doist/todoist-ai/commit/0c4dcf7c4e420eadea15bf825599f4c3cd72cbfc))
## [3.0.0](https://github.com/Doist/todoist-ai/compare/v2.2.2...v3.0.0) (2025-08-21)
### ⚠ BREAKING CHANGES
* verb-first tool names, unify find-by-container into find-tasks ([#53](https://github.com/Doist/todoist-ai/issues/53))
* Remove single update task and replace with multiple ([#47](https://github.com/Doist/todoist-ai/issues/47))
### Features
* Improve tool output UX with LLM-readable responses ([#49](https://github.com/Doist/todoist-ai/issues/49)) ([7c25696](https://github.com/Doist/todoist-ai/commit/7c25696926bbaee158482cbc75595e80959e1c12))
* Remove single update task and replace with multiple ([#47](https://github.com/Doist/todoist-ai/issues/47)) ([8a9b7cf](https://github.com/Doist/todoist-ai/commit/8a9b7cf119a405a2849ab95c437a344961790686))
* verb-first tool names, unify find-by-container into find-tasks ([#53](https://github.com/Doist/todoist-ai/issues/53)) ([dbada71](https://github.com/Doist/todoist-ai/commit/dbada719d98df4bb91a52a0a7af8afb6ad6f3fae))
## [2.2.2](https://github.com/Doist/todoist-ai/compare/v2.2.1...v2.2.2) (2025-08-16)
### Bug Fixes
* correct bin path in package.json for npx support ([#39](https://github.com/Doist/todoist-ai/issues/39)) ([816021d](https://github.com/Doist/todoist-ai/commit/816021dc3572dd476818981388fac634794d7e21))
## [2.2.1](https://github.com/Doist/todoist-ai/compare/v2.2.0...v2.2.1) (2025-08-16)
### Bug Fixes
* correct bin field format in package.json for npx support ([#37](https://github.com/Doist/todoist-ai/issues/37)) ([a50fa75](https://github.com/Doist/todoist-ai/commit/a50fa75d737bc6f4503442830565c3d4a942c9af))
## [2.2.0](https://github.com/Doist/todoist-ai/compare/v2.1.0...v2.2.0) (2025-08-16)
### Features
* Add npx support for MCP server usage ([#33](https://github.com/Doist/todoist-ai/issues/33)) ([5ed0c5f](https://github.com/Doist/todoist-ai/commit/5ed0c5f40615ab4afb61d0fcd9796c97e666b1f9))
## [2.1.0](https://github.com/Doist/todoist-ai/compare/v2.0.1...v2.1.0) (2025-08-15)
### Features
* add support for task duration when adding or updating tasks ([#28](https://github.com/Doist/todoist-ai/issues/28)) ([a0c6702](https://github.com/Doist/todoist-ai/commit/a0c6702dd446173c86675ecadd975506ce594c42))
## [2.0.1](https://github.com/Doist/todoist-ai/compare/v2.0.0...v2.0.1) (2025-08-14)
### Bug Fixes
* convert project from CommonJS to ES modules to resolve MCP initialization ([#24](https://github.com/Doist/todoist-ai/issues/24)) ([f817e04](https://github.com/Doist/todoist-ai/commit/f817e045a711f90b4f74464a480dd1aa8f7e1027))
* resolve task move operations using correct Todoist API methods ([#22](https://github.com/Doist/todoist-ai/issues/22)) ([3b8f509](https://github.com/Doist/todoist-ai/commit/3b8f50943f517ae76b754923f7a8c5563880e9ba))
## [2.0.0](https://github.com/Doist/todoist-ai/compare/v1.1.0...v2.0.0) (2025-08-13)
### ⚠ BREAKING CHANGES
* Consolidate MCP tools to reduce tool count ([#14](https://github.com/Doist/todoist-ai/issues/14))
### Features
* Consolidate MCP tools to reduce tool count ([#14](https://github.com/Doist/todoist-ai/issues/14)) ([f0ccdf8](https://github.com/Doist/todoist-ai/commit/f0ccdf8fd17f046fdb8d0938dea94163fd916a7c))
### Bug Fixes
* update release-please action to googleapis/release-please-action@v4 ([7fbb5fd](https://github.com/Doist/todoist-ai/commit/7fbb5fdd3f435e68a9b2ba054247d29e82fcc465))
## [1.1.0](https://github.com/Doist/todoist-ai/compare/v1.0.0...v1.1.0) (2025-08-13)
### Features
* Adds completed tasks tool ([#8](https://github.com/Doist/todoist-ai/issues/8)) ([d0ffad1](https://github.com/Doist/todoist-ai/commit/d0ffad10a331c16f14b4d738ed7ac368fd8e44b4))
### Bug Fixes
* add issues permission for release-please workflow ([0974fa4](https://github.com/Doist/todoist-ai/commit/0974fa45aa8578eafd2e9e1355a997ee09dce391))
## 1.0.0 (2025-08-12)
### Features
* add tasks-add-multiple and tasks-update-one tools ([f7432e7](https://github.com/Doist/todoist-ai/commit/f7432e7f8c4121ed2bf71b424fe17d03e59aed23))
* add tasks-complete-one and tasks-delete-one tools ([1ef6a99](https://github.com/Doist/todoist-ai/commit/1ef6a99e2733226d85932b930a41dc9ff92d0ef9))
* allow configuring the base URL for the Todoist API ([332c11a](https://github.com/Doist/todoist-ai/commit/332c11aec34ace9890fda36ef9356a7c417b22d1))
* allow configuring the base URL for the Todoist API ([c56b3a3](https://github.com/Doist/todoist-ai/commit/c56b3a36207fb211188737f05f472ebcee6e7fc5))
## [0.1.4](https://github.com/doist/todoist-ai/compare/v0.1.3...v0.1.4) (2025-01-XX)
### Features
* allow configuring the base URL for the Todoist API ([332c11a](https://github.com/doist/todoist-ai/commit/332c11a))
### Bug Fixes
* remove esm build, use single tsconfig for cjs ([24a1336](https://github.com/doist/todoist-ai/commit/24a1336))
* remove tools subpath, export tools from index.ts ([2e13489](https://github.com/doist/todoist-ai/commit/2e13489))
### Miscellaneous Chores
* rename tool files to match the tool name ([997780a](https://github.com/doist/todoist-ai/commit/997780a))
---
*Note: This changelog will be automatically maintained by [release-please](https://github.com/googleapis/release-please) starting from the next release.*
@@ -0,0 +1,189 @@
# Todoist AI and MCP SDK
Library for connecting AI agents to Todoist. Includes tools that can be integrated into LLMs,
enabling them to access and modify a Todoist account on the user's behalf.
These tools can be used both through an MCP server, or imported directly in other projects to
integrate them to your own AI conversational interfaces.
## Using tools
### 1. Add this repository as a dependency
```sh
npm install @doist/todoist-ai
```
### 2. Import the tools and plug them to an AI
Here's an example using [Vercel's AI SDK](https://ai-sdk.dev/docs/ai-sdk-core/generating-text#streamtext).
```js
import { findTasksByDate, addTasks } from "@doist/todoist-ai";
import { TodoistApi } from "@doist/todoist-api-typescript";
import { streamText } from "ai";
// Create Todoist API client
const client = new TodoistApi(process.env.TODOIST_API_KEY);
// Helper to wrap tools with the client
function wrapTool(tool, todoistClient) {
return {
...tool,
execute(args) {
return tool.execute(args, todoistClient);
},
};
}
const result = streamText({
model: yourModel,
system: "You are a helpful Todoist assistant",
tools: {
findTasksByDate: wrapTool(findTasksByDate, client),
addTasks: wrapTool(addTasks, client),
},
});
```
## Using as an MCP server
### Quick Start
You can run the MCP server directly with npx:
```bash
npx @doist/todoist-ai
```
### Setup Guide
The Todoist AI MCP server is available as a streamable HTTP service for easy integration with various AI clients:
**Primary URL (Streamable HTTP):** `https://ai.todoist.net/mcp`
#### Claude Desktop
1. Open Settings → Connectors → Add custom connector
2. Enter `https://ai.todoist.net/mcp` and complete OAuth authentication
#### Cursor
Create a configuration file:
- **Global:** `~/.cursor/mcp.json`
- **Project-specific:** `.cursor/mcp.json`
```json
{
"mcpServers": {
"todoist": {
"command": "npx",
"args": ["-y", "mcp-remote", "https://ai.todoist.net/mcp"]
}
}
}
```
Then enable the server in Cursor settings if prompted.
#### Claude Code (CLI)
Firstly configure Claude so it has a new MCP available using this command:
```bash
claude mcp add --transport http todoist https://ai.todoist.net/mcp
```
Then launch `claude`, execute `/mcp`, then select the `todoist` MCP server.
This will take you through a wizard to authenticate using your browser with Todoist. Once complete you will be able to use todoist in `claude`.
#### Visual Studio Code
1. Open Command Palette → MCP: Add Server
2. Select HTTP transport and use:
```json
{
"servers": {
"todoist": {
"type": "http",
"url": "https://ai.todoist.net/mcp"
}
}
}
```
#### Other MCP Clients
```bash
npx -y mcp-remote https://ai.todoist.net/mcp
```
For more details on setting up and using the MCP server, including creating custom servers, see [docs/mcp-server.md](docs/mcp-server.md).
## Features
A key feature of this project is that tools can be reused, and are not written specifically for use in an MCP server. They can be hooked up as tools to other conversational AI interfaces (e.g. Vercel's AI SDK).
This project is in its early stages. Expect more and/or better tools soon.
Nevertheless, our goal is to provide a small set of tools that enable complete workflows, rather than just atomic actions, striking a balance between flexibility and efficiency for LLMs.
For our design philosophy, guidelines, and development patterns, see [docs/tool-design.md](docs/tool-design.md).
### Available Tools
For a complete list of available tools, see the [src/tools](src/tools) directory.
#### OpenAI MCP Compatibility
This server includes `search` and `fetch` tools that follow the [OpenAI MCP specification](https://platform.openai.com/docs/mcp), enabling seamless integration with OpenAI's MCP protocol. These tools return JSON-encoded results optimized for OpenAI's requirements while maintaining compatibility with the broader MCP ecosystem.
## Dependencies
- MCP server using the official [@modelcontextprotocol/sdk](https://github.com/modelcontextprotocol/typescript-sdk?tab=readme-ov-file#installation)
- Todoist Typescript API client [@doist/todoist-api-typescript](https://github.com/Doist/todoist-api-typescript)
## MCP Server Setup
See [docs/mcp-server.md](docs/mcp-server.md) for full instructions on setting up the MCP server.
## Local Development Setup
See [docs/dev-setup.md](docs/dev-setup.md) for full instructions on setting up this repository locally for development and contributing.
### Quick Start
After cloning and setting up the repository:
- `npm start` - Build and run the MCP inspector for testing
- `npm run dev` - Development mode with auto-rebuild and restart
## Releasing
This project uses [release-please](https://github.com/googleapis/release-please) to automate version management and package publishing.
### How it works
1. Make your changes using [Conventional Commits](https://www.conventionalcommits.org/):
- `feat:` for new features (minor version bump)
- `fix:` for bug fixes (patch version bump)
- `feat!:` or `fix!:` for breaking changes (major version bump)
- `docs:` for documentation changes
- `chore:` for maintenance tasks
- `ci:` for CI changes
2. When commits are pushed to `main`:
- Release-please automatically creates/updates a release PR
- The PR includes version bump and changelog updates
- Review the PR and merge when ready
3. After merging the release PR:
- A new GitHub release is automatically created
- A new tag is created
- The `publish` workflow is triggered
- The package is published to npm
@@ -0,0 +1,139 @@
# Repository File Structure
Total items: 133
```
📁 .claude
📁 .cursor
📄 .cursorrules
📄 .env.example
📁 .github
📄 .gitignore
📁 .husky
📄 .nvmrc
📁 .vscode
📄 CHANGELOG.md
📄 LICENSE.txt
📄 README.md
📄 biome.json
📁 docs
📄 openai-mcp-tools.md
📄 package-lock.json
📄 package.json
📄 renovate.json
📁 scripts
📁 src
📄 tsconfig.json
📄 vite.config.ts
📄 claude.md
📄 settings.json
📄 mcp.json
📁 rules
📄 PULL_REQUEST_TEMPLATE.md
📄 release-please-config.json
📄 release-please-manifest.json
📁 workflows
📄 pre-commit
📄 pre-push
📄 extensions.json
📄 settings.json
📄 dev-setup.md
📄 mcp-server.md
📄 tool-design.md
📄 test-executable.cjs
📄 validate-schemas.ts
📄 filter-helpers.ts
📄 index.ts
📄 main.ts
📄 mcp-helpers.ts
📄 mcp-server.ts
📄 todoist-tool.ts
📄 tool-helpers.test.ts
📄 tool-helpers.ts
📁 tools
📁 utils
📄 context7.mdc
📄 typescript.mdc
📄 check-semantic-pull-request.yml
📄 ci.yml
📄 publish.yml
📄 release-please.yml
📁 __tests__
📄 add-comments.ts
📄 add-projects.ts
📄 add-sections.ts
📄 add-tasks.ts
📄 complete-tasks.ts
📄 delete-object.ts
📄 fetch.ts
📄 find-activity.ts
📄 find-comments.ts
📄 find-completed-tasks.ts
📄 find-project-collaborators.ts
📄 find-projects.ts
📄 find-sections.ts
📄 find-tasks-by-date.ts
📄 find-tasks.ts
📄 get-overview.ts
📄 manage-assignments.ts
📄 search.ts
📄 update-comments.ts
📄 update-projects.ts
📄 update-sections.ts
📄 update-tasks.ts
📄 user-info.ts
📄 assignment-validator.ts
📄 constants.ts
📄 duration-parser.test.ts
📄 duration-parser.ts
📄 labels.ts
📄 output-schemas.ts
📄 priorities.ts
📄 response-builders.ts
📄 sanitize-data.test.ts
📄 sanitize-data.ts
📄 test-helpers.ts
📄 tool-names.ts
📄 user-resolver.ts
📁 __snapshots__
📄 add-comments.test.ts
📄 add-projects.test.ts
📄 add-sections.test.ts
📄 add-tasks.test.ts
📄 assignment-integration.test.ts
📄 complete-tasks.test.ts
📄 delete-object.test.ts
📄 fetch.test.ts
📄 find-activity.test.ts
📄 find-comments.test.ts
📄 find-completed-tasks.test.ts
📄 find-projects.test.ts
📄 find-sections.test.ts
📄 find-tasks-by-date.test.ts
📄 find-tasks.test.ts
📄 get-overview.test.ts
📄 search.test.ts
📄 tool-annotations.test.ts
📄 update-comments.test.ts
📄 update-projects.test.ts
📄 update-sections.test.ts
📄 update-tasks.test.ts
📄 user-info.test.ts
📄 add-comments.test.ts.snap
📄 add-projects.test.ts.snap
📄 add-sections.test.ts.snap
📄 add-tasks.test.ts.snap
📄 complete-tasks.test.ts.snap
📄 delete-object.test.ts.snap
📄 find-activity.test.ts.snap
📄 find-comments.test.ts.snap
📄 find-completed-tasks.test.ts.snap
📄 find-projects.test.ts.snap
📄 find-sections.test.ts.snap
📄 find-tasks-by-date.test.ts.snap
📄 find-tasks.test.ts.snap
📄 get-overview.test.ts.snap
📄 update-comments.test.ts.snap
📄 update-projects.test.ts.snap
📄 update-sections.test.ts.snap
```
@@ -0,0 +1,65 @@
# GitHub Issues
Recent issues from the repository (18 total).
## Open Issues (4)
### #26: Dependency Dashboard
**Labels:** No labels | **Created:** 2025-08-14
[View on GitHub](https://github.com/Doist/todoist-ai/issues/26)
### #241: Is there a OpenAPI json spec available?
**Labels:** No labels | **Created:** 2025-12-12
[View on GitHub](https://github.com/Doist/todoist-ai/issues/241)
### #239: server times out frequently, needs frequent reauthentication in claude code
**Labels:** No labels | **Created:** 2025-12-08
[View on GitHub](https://github.com/Doist/todoist-ai/issues/239)
### #162: Remove Zod v4 dependency blocker
**Labels:** No labels | **Created:** 2025-10-23
[View on GitHub](https://github.com/Doist/todoist-ai/issues/162)
## Recently Closed Issues (14)
### #240: Cannot connect with mcp-remote@0.1.31
**Labels:** No labels | **Closed:** 2025-12-08
[View on GitHub](https://github.com/Doist/todoist-ai/issues/240)
### #192: Claude Code requires reconnection too frequently
**Labels:** No labels | **Closed:** 2025-11-13
[View on GitHub](https://github.com/Doist/todoist-ai/issues/192)
### #215: Claude Code : Adding Task "P1" vs reading tasks are inverted
**Labels:** No labels | **Closed:** 2025-11-13
[View on GitHub](https://github.com/Doist/todoist-ai/issues/215)
### #206: MCPs are not working
**Labels:** No labels | **Closed:** 2025-11-06
[View on GitHub](https://github.com/Doist/todoist-ai/issues/206)
### #94: This MCP server can't be used by ChatGPT to search information because it doesn't implement our specification: search action not found
**Labels:** No labels | **Closed:** 2025-09-17
[View on GitHub](https://github.com/Doist/todoist-ai/issues/94)
### #76: parentId parameter ignored in add-projects and update-projects - fails to create/update project hierarchy
**Labels:** No labels | **Closed:** 2025-10-26
[View on GitHub](https://github.com/Doist/todoist-ai/issues/76)
### #179: Bug: update_tasks tool schema appears incompatible with Gemini API
**Labels:** No labels | **Closed:** 2025-10-25
[View on GitHub](https://github.com/Doist/todoist-ai/issues/179)
### #35: Release-Please v4 publish workflow not triggering automatically - requires manual re-tagging
**Labels:** No labels | **Closed:** 2025-10-26
[View on GitHub](https://github.com/Doist/todoist-ai/issues/35)
### #42: # Feature Request: Add Deadline Support
**Labels:** enhancement, good first issue | **Closed:** 2025-10-26
[View on GitHub](https://github.com/Doist/todoist-ai/issues/42)
### #136: TypeError: client.getUser is not a function when following Vercel AI SDK example
**Labels:** No labels | **Closed:** 2025-10-26
[View on GitHub](https://github.com/Doist/todoist-ai/issues/136)
@@ -0,0 +1,688 @@
# Releases
Version history for this repository (47 releases).
## v5.2.0: v5.2.0
**Published:** 2025-11-27
## [5.2.0](https://github.com/Doist/todoist-ai/compare/v5.1.1...v5.2.0) (2025-11-27)
### Features
* Add isUncompletable parameter support to add/update tools ([#230](https://github.com/Doist/todoist-ai/issues/230)) ([0c295ac](https://github.com/Doist/todoist-ai/commit/0c295ac7d7d1b81f5512b1c782eaba4ef24aeafd))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v5.2.0)
---
## v5.1.1: v5.1.1
**Published:** 2025-11-27
## [5.1.1](https://github.com/Doist/todoist-ai/compare/v5.1.0...v5.1.1) (2025-11-27)
### Bug Fixes
* **deps:** Update `@doist/todoist-api-typescript` to 6.1.12 ([#229](https://github.com/Doist/todoist-ai/issues/229)) ([54e3552](https://github.com/Doist/todoist-ai/commit/54e3552b68d648a042bac9991cb600fd8f8f5be1))
* **deps:** update dependency @modelcontextprotocol/sdk to v1.22.0 ([#227](https://github.com/Doist/todoist-ai/issues/227)) ([b20c05e](https://github.com/Doist/todoist-ai/commit/b20c05e3273ff6a565380cdddb9be5743ba7bb66))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v5.1.1)
---
## v5.1.0: v5.1.0
**Published:** 2025-11-20
## [5.1.0](https://github.com/Doist/todoist-ai/compare/v5.0.2...v5.1.0) (2025-11-20)
### Features
* add read-only and destructive hints to all tools ([#222](https://github.com/Doist/todoist-ai/issues/222)) ([5d8ce22](https://github.com/Doist/todoist-ai/commit/5d8ce225c92a688834881bde13d5956bbe7e59ff))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v5.1.0)
---
## v5.0.2: v5.0.2
**Published:** 2025-11-19
## [5.0.2](https://github.com/Doist/todoist-ai/compare/v5.0.1...v5.0.2) (2025-11-19)
### Bug Fixes
* **find-projects:** resolve search pagination issue and update PROJECTS_MAX ([#223](https://github.com/Doist/todoist-ai/issues/223)) ([b0772d1](https://github.com/Doist/todoist-ai/commit/b0772d1dd688188cc70dcdd50989208fd18f9c39))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v5.0.2)
---
## v5.0.1: v5.0.1
**Published:** 2025-11-18
## [5.0.1](https://github.com/Doist/todoist-ai/compare/v5.0.0...v5.0.1) (2025-11-18)
### Bug Fixes
* **deps:** update production dependencies ([#220](https://github.com/Doist/todoist-ai/issues/220)) ([f6121b0](https://github.com/Doist/todoist-ai/commit/f6121b0fcc7bf432e07df7a8ef9c11291ba09dfb))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v5.0.1)
---
## v5.0.0: v5.0.0
**Published:** 2025-11-14
## [5.0.0](https://github.com/Doist/todoist-ai/compare/v4.17.4...v5.0.0) (2025-11-14)
### ⚠ BREAKING CHANGES
* semantic priority values (P1, P2, P3, P4) instead of numeric ([#217](https://github.com/Doist/todoist-ai/issues/217))
### Features
* semantic priority values (P1, P2, P3, P4) instead of numeric ([#217](https://github.com/Doist/todoist-ai/issues/217)) ([9bb906b](https://github.com/Doist/todoist-ai/commit/9bb906b48d836898bf616df60cef38aaa7ae2894))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v5.0.0)
---
## v4.17.4: v4.17.4
**Published:** 2025-11-13
## [4.17.4](https://github.com/Doist/todoist-ai/compare/v4.17.3...v4.17.4) (2025-11-13)
### Bug Fixes
* correct priority inversion for task outputs ([#216](https://github.com/Doist/todoist-ai/issues/216)) ([b4b4809](https://github.com/Doist/todoist-ai/commit/b4b4809f129d6aa029f0ef4aa28352760c879aee))
* **deps:** pin dependencies ([#212](https://github.com/Doist/todoist-ai/issues/212)) ([2049ebf](https://github.com/Doist/todoist-ai/commit/2049ebf4e5eedd2465650c79c16e39f04a5e4ddd))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.17.4)
---
## v4.17.3: v4.17.3
**Published:** 2025-11-06
## [4.17.3](https://github.com/Doist/todoist-ai/compare/v4.17.2...v4.17.3) (2025-11-06)
### Bug Fixes
* **deps:** Bump `@doist/todoist-api-typescript` package ([#210](https://github.com/Doist/todoist-ai/issues/210)) ([85fbfb5](https://github.com/Doist/todoist-ai/commit/85fbfb591f2e4ee165b71ff1386a39ab96d7e31a))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.17.3)
---
## v4.17.2: v4.17.2
**Published:** 2025-11-06
## [4.17.2](https://github.com/Doist/todoist-ai/compare/v4.17.1...v4.17.2) (2025-11-06)
### Bug Fixes
* enforce output schemas for tools (follow-up) ([#208](https://github.com/Doist/todoist-ai/issues/208)) ([c83772a](https://github.com/Doist/todoist-ai/commit/c83772a7c29314891b1e031dce9f07d954b4e4a5))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.17.2)
---
## v4.17.1: v4.17.1
**Published:** 2025-11-06
## [4.17.1](https://github.com/Doist/todoist-ai/compare/v4.17.0...v4.17.1) (2025-11-06)
### Bug Fixes
* enforce output schemas for tools ([#205](https://github.com/Doist/todoist-ai/issues/205)) ([9b1d593](https://github.com/Doist/todoist-ai/commit/9b1d59317dbe5277b6f4126388a2402cf3c35e8e))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.17.1)
---
## v4.17.0: v4.17.0
**Published:** 2025-11-05
## [4.17.0](https://github.com/Doist/todoist-ai/compare/v4.16.1...v4.17.0) (2025-11-05)
### Features
* Add output schema to all tools ([#203](https://github.com/Doist/todoist-ai/issues/203)) ([7663388](https://github.com/Doist/todoist-ai/commit/76633886dde65880cd049733431aa9d4a5038b84))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.17.0)
---
## v4.16.1: v4.16.1
**Published:** 2025-11-05
## [4.16.1](https://github.com/Doist/todoist-ai/compare/v4.16.0...v4.16.1) (2025-11-05)
### Bug Fixes
* Show next steps only for paginated tools and clarify as suggestions ([#201](https://github.com/Doist/todoist-ai/issues/201)) ([f969615](https://github.com/Doist/todoist-ai/commit/f9696155fe931b6c40859c1a2f7e82a859253288))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.16.1)
---
## v4.16.0: v4.16.0
**Published:** 2025-11-03
## [4.16.0](https://github.com/Doist/todoist-ai/compare/v4.15.1...v4.16.0) (2025-11-03)
### Features
* Extend "inbox" project ID support to 7 additional tools ([#198](https://github.com/Doist/todoist-ai/issues/198)) ([5bab0f9](https://github.com/Doist/todoist-ai/commit/5bab0f94ab2d997d71870202294af3c5d3ac7784))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.16.0)
---
## v4.15.1: v4.15.1
**Published:** 2025-10-31
## [4.15.1](https://github.com/Doist/todoist-ai/compare/v4.15.0...v4.15.1) (2025-10-31)
### Bug Fixes
* Allow `inbox` as a project id ([#193](https://github.com/Doist/todoist-ai/issues/193)) ([fe4a91f](https://github.com/Doist/todoist-ai/commit/fe4a91fe2daa7f97473b97de54385e03358a8122))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.15.1)
---
## v4.15.0: v4.15.0
**Published:** 2025-10-26
## [4.15.0](https://github.com/Doist/todoist-ai/compare/v4.14.5...v4.15.0) (2025-10-26)
### Features
* Add deadline support to add-tasks and update-tasks ([#186](https://github.com/Doist/todoist-ai/issues/186)) ([8f795c8](https://github.com/Doist/todoist-ai/commit/8f795c8949f40d10bf629933793d8cb4607dcb58))
* Add parentId support to update-projects tool ([#184](https://github.com/Doist/todoist-ai/issues/184)) ([0185b83](https://github.com/Doist/todoist-ai/commit/0185b836fff1359c8303de20bcc37c8f86138180))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.15.0)
---
## v4.14.5: v4.14.5
**Published:** 2025-10-25
## [4.14.5](https://github.com/Doist/todoist-ai/compare/v4.14.4...v4.14.5) (2025-10-25)
### Bug Fixes
* Remove nullable type from update_tasks to fix Gemini API compatibility ([#181](https://github.com/Doist/todoist-ai/issues/181)) ([c97be7f](https://github.com/Doist/todoist-ai/commit/c97be7f39ae48d837562fd303b67ed81e8935c18))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.14.5)
---
## v4.14.4: v4.14.4
**Published:** 2025-10-24
## [4.14.4](https://github.com/Doist/todoist-ai/compare/v4.14.3...v4.14.4) (2025-10-24)
### Bug Fixes
* Add actions: write permission to trigger workflows ([6863953](https://github.com/Doist/todoist-ai/commit/6863953b6e92fd8b35f4692b5c609ad42631722a))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.14.4)
---
## v4.14.3: v4.14.3
**Published:** 2025-10-24
## [4.14.3](https://github.com/Doist/todoist-ai/compare/v4.14.2...v4.14.3) (2025-10-24)
### Bug Fixes
* Add --repo flag to gh workflow run command ([f61caa8](https://github.com/Doist/todoist-ai/commit/f61caa8c7aabce166484b95b70886aa4049c904c))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.14.3)
---
## v4.14.2: v4.14.2
**Published:** 2025-10-24
## [4.14.2](https://github.com/Doist/todoist-ai/compare/v4.14.1...v4.14.2) (2025-10-24)
### Bug Fixes
* Trigger publish workflow automatically from release-please ([#174](https://github.com/Doist/todoist-ai/issues/174)) ([081bc2b](https://github.com/Doist/todoist-ai/commit/081bc2ba5abfdc3bf4bfe3c282f29570877b977c))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.14.2)
---
## v4.14.1: v4.14.1
**Published:** 2025-10-24
## [4.14.1](https://github.com/Doist/todoist-ai/compare/v4.14.0...v4.14.1) (2025-10-24)
### Bug Fixes
* Update todoist-typescript-sdk to 5.7.1 (follow-up) ([#172](https://github.com/Doist/todoist-ai/issues/172)) ([b4f8dc3](https://github.com/Doist/todoist-ai/commit/b4f8dc3ffa4c3dd7489ece03be5a0f391130a2ce))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.14.1)
---
## v4.14.0: v4.14.0
**Published:** 2025-10-23
## [4.14.0](https://github.com/Doist/todoist-ai/compare/v4.13.5...v4.14.0) (2025-10-23)
### Features
* Add find-activity tool ([#169](https://github.com/Doist/todoist-ai/issues/169)) ([1abf67f](https://github.com/Doist/todoist-ai/commit/1abf67f3a99191582cf0b5ea2516420f1278dc9a))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.14.0)
---
## v4.13.5: v4.13.5
**Published:** 2025-10-23
## [4.13.5](https://github.com/Doist/todoist-ai/compare/v4.13.4...v4.13.5) (2025-10-23)
### Bug Fixes
* clarify find-completed-tasks scope ([#167](https://github.com/Doist/todoist-ai/issues/167)) ([f110669](https://github.com/Doist/todoist-ai/commit/f11066934d4f6b790599d0f89db416a32437edd3))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.13.5)
---
## v4.13.4: v4.13.4
**Published:** 2025-10-23
## [4.13.4](https://github.com/Doist/todoist-ai/compare/v4.13.3...v4.13.4) (2025-10-23)
### Bug Fixes
* Test publish workflow (no functional changes) ([#164](https://github.com/Doist/todoist-ai/issues/164)) ([68afb4c](https://github.com/Doist/todoist-ai/commit/68afb4ce06366cc022a1718e6cd0c3525c5aab48))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.13.4)
---
## v4.13.3: v4.13.3
**Published:** 2025-10-23
## [4.13.3](https://github.com/Doist/todoist-ai/compare/v4.13.2...v4.13.3) (2025-10-23)
### Bug Fixes
* Switch to using `moveTask` instead of `moveTasks` ([#160](https://github.com/Doist/todoist-ai/issues/160)) ([34e3fc6](https://github.com/Doist/todoist-ai/commit/34e3fc67922379bf0aef39a9e7f1939ded5f0e08))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.13.3)
---
## v4.13.2: v4.13.2
**Published:** 2025-10-22
## [4.13.2](https://github.com/Doist/todoist-ai/compare/v4.13.1...v4.13.2) (2025-10-22)
### Bug Fixes
* Output `checked` for the `fetch` tool ([#158](https://github.com/Doist/todoist-ai/issues/158)) ([f0a6eaf](https://github.com/Doist/todoist-ai/commit/f0a6eaf62a915cfab289f1b5181770ccd11d0bdb))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.13.2)
---
## v4.13.1: v4.13.1
**Published:** 2025-10-22
## [4.13.1](https://github.com/Doist/todoist-ai/compare/v4.13.0...v4.13.1) (2025-10-22)
### Bug Fixes
* Remove `updatedAt` ([#155](https://github.com/Doist/todoist-ai/issues/155)) ([3f3f345](https://github.com/Doist/todoist-ai/commit/3f3f3458f9d54f4f347dfb7c34892fb3cda7ff3b))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.13.1)
---
## v4.13.0: v4.13.0
**Published:** 2025-10-21
## [4.13.0](https://github.com/Doist/todoist-ai/compare/v4.12.0...v4.13.0) (2025-10-21)
### Features
* Expose completion and modification metadata in task mapping ([#153](https://github.com/Doist/todoist-ai/issues/153)) ([1e2d3b3](https://github.com/Doist/todoist-ai/commit/1e2d3b3f461e75be8cc63ae3a4e070d113f5c4da))
* extend responsibleUser filtering to more tools ([#149](https://github.com/Doist/todoist-ai/issues/149)) ([c146d74](https://github.com/Doist/todoist-ai/commit/c146d749eb097e1d383dda00e6a09e05389969dd))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.13.0)
---
## v4.12.0: v4.12.0
**Published:** 2025-10-14
## [4.12.0](https://github.com/Doist/todoist-ai/compare/v4.11.0...v4.12.0) (2025-10-14)
### Features
* In find-tasks-by-date use backend filtering for responsible user ([#145](https://github.com/Doist/todoist-ai/issues/145)) ([5d1e140](https://github.com/Doist/todoist-ai/commit/5d1e1400f639e8c802019421eb0437ef39c67a64))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.12.0)
---
## v4.11.0: v4.11.0
**Published:** 2025-10-13
## [4.11.0](https://github.com/Doist/todoist-ai/compare/v4.10.0...v4.11.0) (2025-10-13)
### Features
* Improve findCompletedTasks to handle user timezones ([#143](https://github.com/Doist/todoist-ai/issues/143)) ([c27d897](https://github.com/Doist/todoist-ai/commit/c27d8973d0ea9342f8b1e56659fca900f920ddb3))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.11.0)
---
## v4.10.0: v4.10.0
**Published:** 2025-10-10
## [4.10.0](https://github.com/Doist/todoist-ai/compare/v4.9.4...v4.10.0) (2025-10-10)
### Features
* add OpenAI-compliant `search` and `fetch` tools ([#134](https://github.com/Doist/todoist-ai/issues/134)) ([153289c](https://github.com/Doist/todoist-ai/commit/153289c5cf02b2da6b3f4cf6e8a7c681b3ee3aec))
* Clarify content vs description usage and Markdown support ([#139](https://github.com/Doist/todoist-ai/issues/139)) ([cb410a2](https://github.com/Doist/todoist-ai/commit/cb410a2c16670ec07ee2d812ba961075c3f20dda))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.10.0)
---
## v4.9.4: v4.9.4
**Published:** 2025-10-06
## [4.9.4](https://github.com/Doist/todoist-ai/compare/v4.9.3...v4.9.4) (2025-10-06)
### Bug Fixes
* Ensures null fields are not returned ([#130](https://github.com/Doist/todoist-ai/issues/130)) ([a016011](https://github.com/Doist/todoist-ai/commit/a0160115b6fff4b96751056506494e43f582527c))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.9.4)
---
## v4.9.3: v4.9.3
**Published:** 2025-10-02
## [4.9.3](https://github.com/Doist/todoist-ai/compare/v4.9.2...v4.9.3) (2025-10-02)
### Bug Fixes
* dayCount and overdue only fixes ([#128](https://github.com/Doist/todoist-ai/issues/128)) ([d020c06](https://github.com/Doist/todoist-ai/commit/d020c0622fb5c9a71b5f666406529236db76bdef))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.9.3)
---
## v4.9.2: v4.9.2
**Published:** 2025-10-02
## [4.9.2](https://github.com/Doist/todoist-ai/compare/v4.9.1...v4.9.2) (2025-10-02)
### Bug Fixes
* allow add-tasks to work with only content parameter ([#126](https://github.com/Doist/todoist-ai/issues/126)) ([27bda34](https://github.com/Doist/todoist-ai/commit/27bda346f465a1a2ab7a0ab833c151093a4d7044))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.9.2)
---
## v4.9.1: v4.9.1
**Published:** 2025-10-01
## [4.9.1](https://github.com/Doist/todoist-ai/compare/v4.9.0...v4.9.1) (2025-10-01)
### Bug Fixes
* Enhance task filtering by responsible user and update related tools ([#121](https://github.com/Doist/todoist-ai/issues/121)) ([cea0917](https://github.com/Doist/todoist-ai/commit/cea0917a8b2bd1f056e1b08f14e9cb858b9711a5))
* preserve markdown in tasks content and description ([#124](https://github.com/Doist/todoist-ai/issues/124)) ([0cc48fe](https://github.com/Doist/todoist-ai/commit/0cc48fe93595213729d794b7b6c92d54072cf6d5))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.9.1)
---
## v4.8.0: v4.8.0
**Published:** 2025-09-29
## [4.8.0](https://github.com/Doist/todoist-ai/compare/v4.7.1...v4.8.0) (2025-09-29)
### Features
* merge overdue into today's tasks in find-tasks-by-date tool ([#108](https://github.com/Doist/todoist-ai/issues/108)) ([f86e69d](https://github.com/Doist/todoist-ai/commit/f86e69d3ac4861a1b99ebdc8f25f135c6d6adeeb))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.8.0)
---
## v4.7.1: v4.7.1
**Published:** 2025-09-29
## [4.7.1](https://github.com/Doist/todoist-ai/compare/v4.7.0...v4.7.1) (2025-09-29)
### Bug Fixes
* Convert the API priorities into a consumable priority ([#115](https://github.com/Doist/todoist-ai/issues/115)) ([e4cc62f](https://github.com/Doist/todoist-ai/commit/e4cc62f5e456c517995aaf9b8e22153923a55ff7))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.7.1)
---
## v4.7.0: v4.7.0
**Published:** 2025-09-25
## [4.7.0](https://github.com/Doist/todoist-ai/compare/v4.6.1...v4.7.0) (2025-09-25)
### Features
* Document the MCP setup better, including the remote endpoint ([#109](https://github.com/Doist/todoist-ai/issues/109)) ([e1e69e2](https://github.com/Doist/todoist-ai/commit/e1e69e27e91675775e7f4ea0bef709a17722131c))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.7.0)
---
## v4.6.1: v4.6.1
**Published:** 2025-09-24
## [4.6.1](https://github.com/Doist/todoist-ai/compare/v4.6.0...v4.6.1) (2025-09-24)
### Bug Fixes
* Update package.json with `mcpName` ([#106](https://github.com/Doist/todoist-ai/issues/106)) ([df19306](https://github.com/Doist/todoist-ai/commit/df19306adb13ff6416a37e4b49a6d2e5ab5c459f))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.6.1)
---
## v4.6.0: v4.6.0
**Published:** 2025-09-24
## [4.6.0](https://github.com/Doist/todoist-ai/compare/v4.5.2...v4.6.0) (2025-09-24)
### Features
* add label support for add-tasks and update-tasks tools ([#103](https://github.com/Doist/todoist-ai/issues/103)) ([a4bc708](https://github.com/Doist/todoist-ai/commit/a4bc7085b5a63402970841e586ce985cab9022d0))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.6.0)
---
## v4.5.2: v4.5.2
**Published:** 2025-09-24
## [4.5.2](https://github.com/Doist/todoist-ai/compare/v4.5.1...v4.5.2) (2025-09-24)
### Miscellaneous Chores
* Release 4.5.2 ([11df6f2](https://github.com/Doist/todoist-ai/commit/11df6f2c03e31bffd02a6c4f1a5176158e434e05))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.5.2)
---
## v4.5.0: v4.5.0
**Published:** 2025-09-11
## [4.5.0](https://github.com/Doist/todoist-ai/compare/v4.4.0...v4.5.0) (2025-09-11)
### Features
* add task assignment management ([#81](https://github.com/Doist/todoist-ai/issues/81)) ([b9b1691](https://github.com/Doist/todoist-ai/commit/b9b16916dec8f18efc37631d77f97354fae2194a))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.5.0)
---
## v4.4.0: v4.4.0
**Published:** 2025-09-10
## [4.4.0](https://github.com/Doist/todoist-ai/compare/v4.3.0...v4.4.0) (2025-09-10)
### Features
* Add user's id to user_info tool ([#84](https://github.com/Doist/todoist-ai/issues/84)) ([706ed8f](https://github.com/Doist/todoist-ai/commit/706ed8fdfd11199808ca9824d4c66e8211d773c1))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.4.0)
---
## v4.3.0: v4.3.0
**Published:** 2025-09-09
## [4.3.0](https://github.com/Doist/todoist-ai/compare/v4.2.0...v4.3.0) (2025-09-09)
### Features
* Add user-info tool and upgrade Todoist API ([#82](https://github.com/Doist/todoist-ai/issues/82)) ([b583fe1](https://github.com/Doist/todoist-ai/commit/b583fe1045ea38fbe25dfa804df9ebe958f2881d))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.3.0)
---
## v4.2.0: v4.2.0
**Published:** 2025-08-29
## [4.2.0](https://github.com/Doist/todoist-ai/compare/v4.1.0...v4.2.0) (2025-08-29)
### Features
* Add support for filtering by label ([#71](https://github.com/Doist/todoist-ai/issues/71)) ([b608d32](https://github.com/Doist/todoist-ai/commit/b608d32f7636a175dc62ca388892e9aef0834712))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v4.2.0)
---
## v3.0.0: v3.0.0
**Published:** 2025-08-22
## [3.0.0](https://github.com/Doist/todoist-ai/compare/v2.2.2...v3.0.0) (2025-08-21)
### ⚠ BREAKING CHANGES
* verb-first tool names, unify find-by-container into find-tasks ([#53](https://github.com/Doist/todoist-ai/issues/53))
* Remove single update task and replace with multiple ([#47](https://github.com/Doist/todoist-ai/issues/47))
### Features
* Improve tool output UX with LLM-readable responses ([#49](https://github.com/Doist/todoist-ai/issues/49)) ([7c25696](https://github.com/Doist/todoist-ai/commit/7c25696926bbaee158482cbc75595e80959e1c12))
* Remove single update task and replace with multiple ([#47](https://github.com/Doist/todoist-ai/issues/47)) ([8a9b7cf](https://github.com/Doist/todoist-ai/commit/8a9b7cf119a405a2849ab95c437a344961790686))
* verb-first tool names, unify find-by-container into find-tasks ([#53](https://github.com/Doist/todoist-ai/issues/53)) ([dbada71](https://github.com/Doist/todoist-ai/commit/dbada719d98df4bb91a52a0a7af8afb6ad6f3fae))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v3.0.0)
---
## v2.0.0: v2.0.0
**Published:** 2025-08-13
## [2.0.0](https://github.com/Doist/todoist-ai/compare/v1.1.0...v2.0.0) (2025-08-13)
### ⚠ BREAKING CHANGES
* Consolidate MCP tools to reduce tool count ([#14](https://github.com/Doist/todoist-ai/issues/14))
### Features
* Consolidate MCP tools to reduce tool count ([#14](https://github.com/Doist/todoist-ai/issues/14)) ([f0ccdf8](https://github.com/Doist/todoist-ai/commit/f0ccdf8fd17f046fdb8d0938dea94163fd916a7c))
### Bug Fixes
* update release-please action to googleapis/release-please-action@v4 ([7fbb5fd](https://github.com/Doist/todoist-ai/commit/7fbb5fdd3f435e68a9b2ba054247d29e82fcc465))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v2.0.0)
---
## v1.1.0: v1.1.0
**Published:** 2025-08-13
## [1.1.0](https://github.com/Doist/todoist-ai/compare/v1.0.0...v1.1.0) (2025-08-13)
### Features
* Adds completed tasks tool ([#8](https://github.com/Doist/todoist-ai/issues/8)) ([d0ffad1](https://github.com/Doist/todoist-ai/commit/d0ffad10a331c16f14b4d738ed7ac368fd8e44b4))
[View on GitHub](https://github.com/Doist/todoist-ai/releases/tag/v1.1.0)
---
+249
View File
@@ -0,0 +1,249 @@
---
type: note
description: "Vault health monitoring, MOC generation, link repair, and system evolution. Use this skill when checking vault quality metrics, regenerating MOC indexes, fixing broken links, finding backlinks, or triggering weekly system reflections. Also use it when the user mentions health score, link density, orphans, dead-ends, or description coverage."
name: vault-health
depends_on: [graph-builder]
---
# Vault Health
Monitoring and improving knowledge graph health. Built on patterns from [arscontexta](https://github.com/agenticnotetaking/arscontexta) — derivation engine for Claude Code.
## Origin
Skill based on arscontexta analysis (Heinrich's derivation engine, 249 research claims).
Key adopted patterns:
- **Health scoring** — composite metric for quantitative vault assessment
- **Explicit wikilinks in MOC** — instead of dataview (invisible to agents)
- **Operational learning loop** — observations → patterns → improvements
- **Typed relationships** — links with context phrases, not bare `related:[]`
- **Description as retrieval filter** — progressive disclosure for agents
---
## Quick Start
```bash
# Full diagnostics (health score, orphans, broken links, dead-ends)
uv run vault/.claude/skills/graph-builder/scripts/analyze.py
# Regenerate MOC with explicit wikilinks
uv run vault/.claude/skills/vault-health/scripts/generate_moc.py
# Find who links to a file
bash vault/.claude/skills/vault-health/scripts/backlinks.sh "business/crm/acme-corp"
# Find and fix broken links (dry run)
uv run vault/.claude/skills/vault-health/scripts/fix_links.py
# Apply fixes
uv run vault/.claude/skills/vault-health/scripts/fix_links.py --apply
```
---
## Health Score
Composite metric in analyze.py. Formula:
```
health_score = 100
- (orphan_ratio × 30) # orphans = knowledge loss
- (broken_ratio × 30) # broken links = fragmentation
- max(0, (3 - avg_links) × 15) # target: 3+ links/file
- ((1 - desc_ratio) × 10) # description coverage
```
### Metrics and targets
| Metric | Target | How to improve |
|--------|--------|----------------|
| Health Score | >80 | All other metrics |
| Avg links/file | >3.0 | generate_moc.py, typed relationships |
| Broken links | <50 | fix_links.py, manual review |
| Orphans | <30 | graph-builder orphan resolution |
| Dead-ends | <100 | Add backlinks to CRM |
| Desc coverage | >50% | Add description to frontmatter |
### Trend tracking
History stored in `.graph/health-history.json` (up to 90 entries). Each analyze.py run adds a data point.
```bash
# View trend
cat vault/.graph/health-history.json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for d in data[-10:]:
print(f\"{d['date']}: {d['health_score']}/100 | links: {d['total_links']} | broken: {d['broken_links']}\")
"
```
---
## MOC Generation
`generate_moc.py` creates Maps of Content with **explicit wikilinks and context phrases** (arscontexta pattern). Dataview queries preserved at end of files.
### What it generates
**MOC-business.md:**
- Active Deals (with deadline and deal value)
- High Priority clients
- Grouping by industry (FMCG, Banks, Retail, ...)
- Within industry: Active first, then Prospect
**MOC-projects.md:**
- Hot/Active leads
- Clients
- Projects, Resources
### Wikilink format
```markdown
- [[business/crm/acme-corp\|Acme Corp]] — Active, p1, Project $XXK, deadline YYYY-MM-DD
```
Each link contains: status, priority, deal info, region, deadline — agent sees context without opening file.
### When to run
- After adding new CRM files
- After updating status/deal_status in CRM
- Recommended: weekly or when changes in `business/crm/` / `projects/`
---
## Link Repair
### fix_links.py
Finds broken links and suggests fixes via fuzzy stem matching.
**Strategies:**
1. **Trailing backslash** — Obsidian table escaping artifact (`\|`)
2. **Wrong prefix** — `crm/company` → `business/crm/company`
3. **Stem match** — `old-name` → finds `new-name.md` by stem match
**Exclusions:** backup directories, attachment embeds, directory links.
```bash
# Dry run — shows suggestions
uv run vault/.claude/skills/vault-health/scripts/fix_links.py
# Apply
uv run vault/.claude/skills/vault-health/scripts/fix_links.py --apply
```
### backlinks.sh
Find files linking TO specified file (incoming links).
```bash
# Who links to Acme Corp?
bash vault/.claude/skills/vault-health/scripts/backlinks.sh "business/crm/acme-corp"
# Who links to MEMORY.md?
bash vault/.claude/skills/vault-health/scripts/backlinks.sh "MEMORY"
```
### Dead-end detection
Dead-end = file with outgoing links but no incoming (knows about others, but nobody knows about it). Detected by analyze.py, output in report.md.
---
## Weekly Reflection
Operational learning loop: observations → patterns → proposals.
### Trigger
- Every Sunday
- When observations in `.session/handoff.md` reach ≥10
### Process
1. Read `.session/handoff.md` → collect `## Observations`
2. Read `.graph/health-history.json` → week's trend
3. Group observations by type (friction/pattern/idea)
4. Find recurring patterns (>2 occurrences)
5. Propose concrete improvements (file + change)
6. Write reflection file
7. Clear processed observations from handoff.md
### Output
```
thoughts/reflections/YYYY-WNN-system-reflection.md
```
Detailed template: `.claude/rules/weekly-reflection.md`
### Observation format
In `.session/handoff.md`, section `## Observations`:
```markdown
- [friction] 2026-02-19: mcp-cli timeout 3x — retry saved, -60 sec
- [pattern] 2026-02-19: 65 "broken links" were attachment embeds
- [idea] 2026-02-19: generate_moc.py in process.sh chain
```
Types: `friction` (something broke/slow), `pattern` (recurring), `idea` (improvement).
---
## Typed Relationships
When adding links between files, use context phrases (arscontexta pattern):
| Type | When | Example |
|------|------|---------|
| **extends** | Develops an idea | `[[note]] — extends: deepens analysis` |
| **context** | Background info | `[[note]] — context: meeting where discussed` |
| **supports** | Supports a goal | `[[goal]] — supports: annual target` |
| **contradicts** | Contradicts | `[[note]] — contradicts: different approach` |
| **enables** | Makes possible | `[[tool]] — enables: workflow` |
| **requires** | Dependency | `[[resource]] — requires: API key` |
---
## Description Guidelines
Description = retrieval filter, NOT summary. Adds information BEYOND title.
```yaml
# WRONG (repeats title):
# title: "Acme Corp"
description: "Company Acme Corp"
# RIGHT (adds retrieval info):
# title: "Acme Corp"
description: "Key client in [industry], active deal $XXK, [project] in progress"
```
Target: ~150 chars. Scope, mechanism, implication — not retelling.
---
## Automation in process.sh
analyze.py runs **automatically** every day through `scripts/process.sh`:
- If daily is empty → graph-only rebuild
- After full processing → final rebuild
generate_moc.py, fix_links.py, backlinks.sh — manual run as needed.
---
## References
- `references/arscontexta-patterns.md` — patterns from arscontexta, adapted for agent-second-brain
- `.claude/rules/weekly-reflection.md` — template for weekly reflections
## Relevant Skills
- [[vault/.claude/skills/graph-builder/SKILL|graph-builder]] — core graph analysis (analyze.py)
- [[vault/.claude/skills/dbrain-processor/SKILL|dbrain-processor]] — daily processing pipeline
@@ -0,0 +1,105 @@
---
type: note
title: Arscontexta Patterns for dbrain
last_accessed: 2026-02-19
relevance: 0.91
tier: active
---
# Arscontexta Patterns for dbrain
Паттерны из [arscontexta](https://github.com/agenticnotetaking/arscontexta), адаптированные для dbrain vault.
## Source
arscontexta — derivation engine для Claude Code (Heinrich). 249 research claims из cognitive science, network theory, Zettelkasten, agent architecture. Каждое архитектурное решение трейсится к конкретному claim.
## Adopted Patterns
### 1. Health Scoring (quantitative vault assessment)
**Claim:** Системы без метрик деградируют незаметно.
**Реализация:** `analyze.py` → `health_score` → `health-history.json`
Формула: 100 - orphan_penalty(30) - broken_penalty(30) - density_penalty(15) - desc_penalty(10)
### 2. Phase Isolation (fresh context per phase)
**Claim:** `[[LLM attention degrades as context fills]]`
**Реализация:** 3-phase pipeline в process.sh:
- CAPTURE: classify entries → JSON (minimal context)
- EXECUTE: create tasks, save thoughts → JSON (MCP tools)
- REFLECT: generate report, update MEMORY (read-only)
JSON handoff между фазами. Fallback на монолит при ошибке.
### 3. Operational Learning Loop (observations → improvements)
**Claim:** `[[operational-learning-loop]]` (INVARIANT primitive в arscontexta)
**Реализация:**
- `handoff.md` → `## Observations` (friction/pattern/idea)
- dbrain-processor Step 11: автоматический capture
- Weekly reflection: анализ observations → proposals
### 4. Description as Retrieval Filter
**Claim:** `[[descriptions are retrieval filters not summaries]]`
**Реализация:** `description: string` в frontmatter schema. Adds scope/mechanism beyond title. ~150 chars.
### 5. Prose-as-Title (claims, not labels)
**Claim:** `[[note titles should function as APIs enabling sentence transclusion]]`
**Реализация:** Для thoughts/ (не CRM): title = specific claim.
Test: `Since [[title]], ...` reads naturally.
### 6. Explicit Wikilinks in MOC
**Claim:** MOC должен быть видим для agents и graph analysis, не только для Obsidian renderer.
**Реализация:** `generate_moc.py` — 286 explicit wikilinks с context phrases.
Dataview сохранён для Obsidian UX.
### 7. Typed Relationships
**Claim:** `related:[]` без контекста = бесполезно. Нужен тип связи.
**Реализация:** 6 типов: extends, context, supports, contradicts, enables, requires.
### 8. Orient Phase (OODA loop)
**Claim:** Не тратить ресурсы на обработку пустого.
**Реализация:** Pre-flight checks в process.sh: daily exists, size > 50 bytes, handoff exists, graph freshness.
## Consciously NOT Adopted
| Pattern | Why not |
|---------|---------|
| Three-space restructure (self/notes/ops) | dbrain already has functional equivalent |
| Full 6Rs pipeline | 6 Claude calls too expensive for automated daily pipeline |
| PostToolUse hooks (schema validation) | analyze.py on rebuild sufficient for 655 files |
| Per-claim task queue (ops/queue/) | Todoist is our task manager |
| Semantic search (qmd MCP) | Hub navigation + rg sufficient at current scale |
| Personality layer | Not needed for automated processor |
| Derivation manifest | System grown organically, not derived |
## 8 Architectural Dimensions
arscontexta projects each system onto 8 axes. dbrain position:
| Axis | dbrain | Notes |
|------|--------|-------|
| Granularity | Mixed | CRM=entity (coarse), thoughts=atomic |
| Organization | Hierarchical | 3 domains with _index.md hubs |
| Linking | Explicit | Wikilinks |
| Processing | Medium | 3 phases (not 6Rs) |
| Navigation | Medium | MOC + _index hubs |
| Maintenance | Automated | systemd timer |
| Schema | Dense | 3 typed schemas (CRM, Learning, Aimasters) |
| Automation | Convention + script | No hooks, process.sh + analyze.py |
Key constraint: Atomic granularity REQUIRES explicit linking + deep navigation. Our mixed approach (CRM coarse + thoughts atomic) = conscious trade-off, compensated by hub navigation.
@@ -0,0 +1,318 @@
#!/usr/bin/env python3
"""
Add description field to frontmatter of vault files.
Strategy by file type:
- CRM files: "{title} — {type}, {industry}, {status}, {deal_status}"
- Thoughts: first non-empty paragraph after frontmatter, truncated to 150 chars
- MOC: "Map of Content: {topic}, N entries"
- Goals: from first paragraph
- Summaries: "Weekly summary for {week}"
- Other: first paragraph, truncated to 150 chars
Skips:
- daily/ files (don't need descriptions per convention)
- Files that already have description field
Usage:
uv run vault/.claude/skills/vault-health/scripts/add_descriptions.py # dry-run
uv run vault/.claude/skills/vault-health/scripts/add_descriptions.py --apply # apply
"""
import json
import re
import sys
from pathlib import Path
SCRIPT_DIR = Path(__file__).parent
VAULT_PATH = SCRIPT_DIR.parents[3]
GRAPH_PATH = VAULT_PATH / ".graph" / "vault-graph.json"
IGNORE_DIRS = {".obsidian", "attachments", ".git", ".graph", ".claude", ".trash"}
IGNORE_PATTERNS = {"backup", ".backup", "archive"}
def load_graph():
if not GRAPH_PATH.exists():
print("Error: vault-graph.json not found. Run analyze.py first.")
sys.exit(1)
return json.loads(GRAPH_PATH.read_text(encoding="utf-8"))
def parse_frontmatter(content: str) -> dict[str, str]:
"""Extract YAML frontmatter as simple key-value pairs."""
match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
if not match:
return {}
fm = {}
for line in match.group(1).split("\n"):
if ":" in line and not line.strip().startswith("-") and not line.strip().startswith("#"):
key, _, value = line.partition(":")
key = key.strip()
value = value.strip().strip('"').strip("'")
if key and value and not value.startswith("[") and not value.startswith("{"):
fm[key] = value
return fm
def get_body_after_frontmatter(content: str) -> str:
"""Get content after frontmatter."""
match = re.match(r"^---\n.*?\n---\n?", content, re.DOTALL)
if match:
return content[match.end():]
return content
def extract_first_paragraph(body: str) -> str:
"""Extract first non-empty, non-heading paragraph from body."""
lines = body.split("\n")
paragraph_lines = []
in_paragraph = False
for line in lines:
stripped = line.strip()
# Skip empty lines before paragraph starts
if not stripped and not in_paragraph:
continue
# Skip headings, callouts, code blocks, links-only lines
if stripped.startswith(("#", ">", "```", "---", "| ", "- [[", "![")):
if in_paragraph:
break
continue
if stripped:
in_paragraph = True
paragraph_lines.append(stripped)
elif in_paragraph:
break
text = " ".join(paragraph_lines)
# Remove wikilinks: [[path|text]] → text, [[path]] → path
text = re.sub(r"\[\[([^\]|]+)\|([^\]]+)\]\]", r"\2", text)
text = re.sub(r"\[\[([^\]]+)\]\]", r"\1", text)
# Remove markdown formatting
text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text)
text = re.sub(r"\*([^*]+)\*", r"\1", text)
text = re.sub(r"`([^`]+)`", r"\1", text)
return text.strip()
def truncate(text: str, max_len: int = 150) -> str:
"""Truncate text to max_len on word boundary."""
if len(text) <= max_len:
return text
truncated = text[:max_len]
# Find last space
last_space = truncated.rfind(" ")
if last_space > max_len // 2:
truncated = truncated[:last_space]
return truncated.rstrip(".,;: ") + "..."
def generate_description(rel_path: str, content: str, fm: dict) -> str | None:
"""Generate a description for a file based on its type and content."""
# CRM files (business/crm/, projects/crm/)
if any(rel_path.startswith(p) for p in ("business/crm/", "projects/crm/")):
# Extract title from H1 or filename
title_match = re.search(r"^# (.+)$", content, re.MULTILINE)
title = title_match.group(1).strip() if title_match else Path(rel_path).stem.replace("-", " ").title()
parts = []
if fm.get("type"):
parts.append(fm["type"])
if fm.get("industry"):
parts.append(fm["industry"])
if fm.get("status"):
parts.append(fm["status"])
if fm.get("deal_status"):
parts.append(fm["deal_status"])
if fm.get("region"):
parts.append(fm["region"])
if parts:
return truncate(f"{title} — {', '.join(parts)}")
return truncate(f"{title} — CRM record")
# Projects files
if rel_path.startswith("projects/"):
title_match = re.search(r"^# (.+)$", content, re.MULTILINE)
title = title_match.group(1).strip() if title_match else Path(rel_path).stem.replace("-", " ").title()
parts = []
if fm.get("type"):
parts.append(fm["type"])
if fm.get("industry"):
parts.append(fm["industry"])
if fm.get("status"):
parts.append(fm["status"])
if parts:
return truncate(f"{title} — {', '.join(parts)}")
body = get_body_after_frontmatter(content)
para = extract_first_paragraph(body)
if para:
return truncate(para)
return truncate(f"{title} — Projects")
# MOC files
if rel_path.startswith("MOC/"):
topic = Path(rel_path).stem.removeprefix("MOC-").replace("-", " ").title()
link_count = content.count("[[")
return f"Map of Content: {topic}, {link_count} entries"
# Thoughts
if rel_path.startswith("thoughts/"):
body = get_body_after_frontmatter(content)
para = extract_first_paragraph(body)
if para:
return truncate(para)
# Fallback: use filename
stem = Path(rel_path).stem
# Remove date prefix if present
stem = re.sub(r"^\d{4}-\d{2}-\d{2}-", "", stem)
return stem.replace("-", " ").capitalize()
# Goals
if rel_path.startswith("goals/"):
body = get_body_after_frontmatter(content)
para = extract_first_paragraph(body)
if para:
return truncate(para)
return f"Goal: {Path(rel_path).stem.replace('-', ' ')}"
# Summaries
if rel_path.startswith("summaries/"):
stem = Path(rel_path).stem
week_match = re.search(r"(\d{4}-W\d{2})", stem)
if week_match:
return f"Weekly summary for {week_match.group(1)}"
return f"Summary: {stem.replace('-', ' ')}"
# Contacts
if rel_path.startswith("contacts/"):
body = get_body_after_frontmatter(content)
para = extract_first_paragraph(body)
if para:
return truncate(para)
return f"Contacts: {Path(rel_path).stem.replace('-', ' ')}"
# _index files
if Path(rel_path).stem == "_index":
parent = Path(rel_path).parent.name
return f"Index and entry point for {parent}"
# MEMORY.md
if Path(rel_path).name == "MEMORY.md":
return "Long-term memory and key decisions"
# Default: first paragraph
body = get_body_after_frontmatter(content)
para = extract_first_paragraph(body)
if para:
return truncate(para)
return None
def add_description_to_frontmatter(content: str, description: str) -> str:
"""Add description field to frontmatter."""
# Escape quotes in description
safe_desc = description.replace('"', '\\"')
if content.startswith("---\n"):
match = re.match(r"^(---\n)(.*?)(\n---)", content, re.DOTALL)
if match:
before = match.group(1)
fm_body = match.group(2)
after = match.group(3)
rest = content[match.end():]
return f'{before}description: "{safe_desc}"\n{fm_body}{after}{rest}'
else:
# Create minimal frontmatter
return f'---\ndescription: "{safe_desc}"\n---\n{content}'
return content
def main():
apply = "--apply" in sys.argv
graph = load_graph()
nodes = graph.get("nodes", {})
# Get all non-daily files
all_files = [
f for f in VAULT_PATH.rglob("*.md")
if not any(d in f.parts for d in IGNORE_DIRS)
and not any(p in str(f) for p in IGNORE_PATTERNS)
]
print(f"Total markdown files: {len(all_files)}")
print(f"Mode: {'APPLY' if apply else 'DRY-RUN'}")
print()
added = 0
skipped_daily = 0
already_has = 0
no_description = 0
errors = 0
for file_path in sorted(all_files):
rel_path = str(file_path.relative_to(VAULT_PATH))
# Skip daily files
if rel_path.startswith("daily/"):
skipped_daily += 1
continue
try:
content = file_path.read_text(encoding="utf-8")
except Exception:
errors += 1
continue
# Check if already has description
fm = parse_frontmatter(content)
if fm.get("description"):
already_has += 1
continue
# Also check raw frontmatter for description: field
fm_match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
if fm_match and "description:" in fm_match.group(1):
already_has += 1
continue
description = generate_description(rel_path, content, fm)
if not description:
no_description += 1
if "--verbose" in sys.argv:
print(f" NO DESC: {rel_path}")
continue
print(f" {rel_path}: \"{description[:80]}{'...' if len(description) > 80 else ''}\"")
added += 1
if apply:
new_content = add_description_to_frontmatter(content, description)
file_path.write_text(new_content, encoding="utf-8")
non_daily = len(all_files) - skipped_daily
coverage = (already_has + added) / max(non_daily, 1) * 100
print(f"\n{'='*50}")
print(f"Non-daily files: {non_daily}")
print(f"Already had description: {already_has}")
print(f"Descriptions added: {added}")
print(f"Could not generate: {no_description}")
print(f"Errors: {errors}")
print(f"Projected coverage: {coverage:.1f}%")
if apply:
print(f"Files modified: {added}")
if __name__ == "__main__":
main()
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# Find all files that link to a given target
# Usage: bash backlinks.sh "business/crm/acme-corp"
# bash backlinks.sh "thoughts/ideas/sample-idea"
set -e
VAULT_DIR="$(cd "$(dirname "$0")/../../.." && pwd)"
TARGET="${1%.md}"
if [ -z "$TARGET" ]; then
echo "Usage: backlinks.sh <note-path>"
echo "Example: backlinks.sh business/crm/acme-corp"
exit 1
fi
# Search for wikilinks to target (with or without .md, with or without alias)
rg -l "\[\[$TARGET" "$VAULT_DIR" --glob '*.md' 2>/dev/null | \
sed "s|$VAULT_DIR/||" | \
sort
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""
Connect orphan and weakly-connected files by adding related links to hub files.
Strategy:
- business/crm/* → related: ["[[business/_index]]"]
- projects/crm/* → related: ["[[projects/_index]]"]
- daily/* (old) → skip (expected orphans)
- templates/* → skip
- projects/* → related: ["[[projects/_index]]"]
- business/* → related: ["[[business/_index]]"]
- thoughts/* → related: ["[[MEMORY]]"]
- Other → related: ["[[MEMORY]]"]
Also processes weakly_connected files (total_links < 2) with same logic.
Usage:
uv run vault/.claude/skills/vault-health/scripts/connect_orphans.py # dry-run
uv run vault/.claude/skills/vault-health/scripts/connect_orphans.py --apply # apply
"""
import json
import re
import sys
from pathlib import Path
SCRIPT_DIR = Path(__file__).parent
VAULT_PATH = SCRIPT_DIR.parents[3]
GRAPH_PATH = VAULT_PATH / ".graph" / "vault-graph.json"
# Hub mapping by path prefix
HUB_MAP = [
("business/crm/", '[[business/_index]]'),
("projects/crm/", '[[projects/_index]]'),
("business/network/", '[[business/_index]]'),
("business/events/", '[[business/_index]]'),
("business/", '[[business/_index]]'),
("projects/clients/", '[[projects/_index]]'),
("projects/leads/", '[[projects/_index]]'),
("projects/", '[[projects/_index]]'),
("thoughts/", '[[MEMORY]]'),
("goals/", '[[MEMORY]]'),
("contacts/", '[[MEMORY]]'),
("MOC/", '[[MEMORY]]'),
("summaries/", '[[MEMORY]]'),
(".session/", '[[MEMORY]]'),
]
SKIP_PREFIXES = ("daily/", "templates/", ".claude/", ".graph/")
def load_graph():
if not GRAPH_PATH.exists():
print("Error: vault-graph.json not found. Run analyze.py first.")
sys.exit(1)
return json.loads(GRAPH_PATH.read_text(encoding="utf-8"))
def get_hub_for_path(rel_path: str) -> str | None:
"""Determine the hub link for a given file path."""
if any(rel_path.startswith(p) for p in SKIP_PREFIXES):
return None
for prefix, hub in HUB_MAP:
if rel_path.startswith(prefix):
return hub
return '[[MEMORY]]'
def has_frontmatter(content: str) -> bool:
"""Check if content has YAML frontmatter."""
return content.startswith("---\n")
def has_related_field(content: str) -> bool:
"""Check if frontmatter already has a related field."""
match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
if match:
return "related:" in match.group(1)
return False
def has_description_field(content: str) -> bool:
"""Check if frontmatter already has a description field."""
match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
if match:
return "description:" in match.group(1)
return False
def add_related_to_frontmatter(content: str, hub_link: str) -> str:
"""Add related field to existing frontmatter or create new frontmatter."""
if has_related_field(content):
return content # Already has related
if has_frontmatter(content):
# Insert related before closing ---
match = re.match(r"^(---\n)(.*?)(\n---)", content, re.DOTALL)
if match:
before = match.group(1)
fm_body = match.group(2)
after = match.group(3)
rest = content[match.end():]
return f"{before}{fm_body}\nrelated:\n - \"{hub_link}\"{after}{rest}"
else:
# Create minimal frontmatter
return f"---\nrelated:\n - \"{hub_link}\"\n---\n{content}"
return content
def main():
apply = "--apply" in sys.argv
graph = load_graph()
orphans = graph.get("orphans", [])
weakly_connected = graph.get("weakly_connected", [])
# Combine: orphans + weakly_connected for maximum link density improvement
targets = set(orphans + weakly_connected)
print(f"Orphans: {len(orphans)}")
print(f"Weakly connected: {len(weakly_connected)}")
print(f"Total targets: {len(targets)}")
print(f"Mode: {'APPLY' if apply else 'DRY-RUN'}")
print()
connected = 0
skipped = 0
already_has = 0
errors = 0
for rel_path in sorted(targets):
hub_link = get_hub_for_path(rel_path)
if hub_link is None:
skipped += 1
continue
file_path = VAULT_PATH / rel_path
if not file_path.exists():
errors += 1
print(f" MISSING: {rel_path}")
continue
content = file_path.read_text(encoding="utf-8")
if has_related_field(content):
already_has += 1
continue
new_content = add_related_to_frontmatter(content, hub_link)
if new_content != content:
tag = "ORPHAN" if rel_path in orphans else "WEAK"
print(f" [{tag}] {rel_path} → {hub_link}")
connected += 1
if apply:
file_path.write_text(new_content, encoding="utf-8")
print(f"\n{'='*50}")
print(f"Connected: {connected}")
print(f"Skipped (daily/template/internal): {skipped}")
print(f"Already has related: {already_has}")
print(f"Missing files: {errors}")
if apply:
print(f"Files modified: {connected}")
if __name__ == "__main__":
main()
@@ -0,0 +1,393 @@
#!/usr/bin/env python3
"""
Fix broken wiki-links in vault using pattern matching and heuristics.
Patterns handled:
1. Trailing backslash: [[business/crm/acme-corp]] with trailing backslash → clean
2. Wrong prefix: [[crm/projects/X]] → [[projects/clients/X]] or [[projects/leads/X]]
3. Stem match: [[acme-corp]] → [[business/crm/acme-corp]] (when unique match exists)
4. CRM sub-project → parent: [[business/crm/client-a-smm]] → [[business/crm/client-a]]
5. business/projects/ → parent CRM: [[business/projects/brand-x-campaign-2026]] → [[business/crm/brand-x]]
6. Plaintext company names (self-refs): [[Acme]] inside acme.md → remove wikilink
7. Goals aliases: [[3-weekly-2026-W05]] → remove
8. Internal paths (.claude/, vault/, scripts/): [[.claude/CLAUDE]] → `code ref`
9. Stub/concept links: [[craftsmanship]], [[ai-philosophy]] → plain text
10. Misc: attachments, meals.md, etc. → remove wikilink
Usage:
uv run vault/.claude/skills/vault-health/scripts/fix_links.py # dry-run
uv run vault/.claude/skills/vault-health/scripts/fix_links.py --apply # apply fixes
"""
import json
import re
import sys
from pathlib import Path
from collections import defaultdict
SCRIPT_DIR = Path(__file__).parent
VAULT_PATH = SCRIPT_DIR.parents[3]
GRAPH_PATH = VAULT_PATH / ".graph" / "vault-graph.json"
IGNORE_DIRS = {".obsidian", "attachments", ".git", ".graph", ".claude", ".trash"}
EXCLUDE_PATTERNS = {"backup", ".backup", "business.backup"}
# Pattern A: CRM sub-project → parent CRM file
CRM_PARENT_MAP = {
"client-a-smm": "client-a",
"brand-x-meals-ncp": "brand-x",
"brand-x-smm-region": "brand-x",
"client-b-smm": "client-b",
"client-c-wh": "client-c",
"client-d-smm": "client-d",
"client-e-influencers": "client-e",
"techco-region": "techco",
"brand-x-sub-smm": "brand-x",
"brand-x-snacks-2026": "brand-x",
"techco-eats-city": None, # no parent — remove link
"techco-eats-tc": None, # no parent — remove link
"brand-y": "brand-y-campaign",
}
# Pattern B: business/projects/ → parent CRM
PROJECT_CLIENT_MAP = {
"brand-x-meals-ncp-2026": "brand-x",
"client-a-smm-strategy-2026": "client-a",
"client-a-smm": "client-a",
"client-c-wellness": "client-c",
"client-f-budget-2026": "client-f",
"automaker-a-strategy-2026": "automaker-a",
"client-d-smm-tender": "client-d",
"automaker-b-bot-smm": "automaker-b",
"client-b-baby-2026": "client-b",
"brand-x-snacks-2026": "brand-x",
"fmcg-co-region-rfi": "fmcg-co",
"automaker-c-smm-tender": "automaker-c",
"tobacco-co-hr-brand": "tobacco-co",
"retailer-a-comstrat": "retailer-a",
}
# Pattern F: Stub/concept links that won't become files → remove wikilink
STUB_LINKS = {
"craftsmanship", "ai-philosophy", "quality", "second-brain", "telegram-bot",
"note", "title", "frontend-design", "accessibility", "vault-processor",
"wikilinks", "sample-stub-link",
}
# Direct replacements for known mismatches
DIRECT_REPLACE_MAP = {
"business/network/partner-alias": "business/network/partner-full-name",
"thoughts/ideas/sample-algorithm": "thoughts/ideas/2026-02-05-sample-agent-algorithm",
}
# Pattern F extended: Long sentence-links from external sources
SENTENCE_LINK_PREFIXES = [
"LLM attention degrades",
"fresh context per task",
"note titles should function",
"Agent Memory System",
"AI agents need layered memory",
]
def load_graph():
"""Load vault-graph.json."""
if not GRAPH_PATH.exists():
print("Error: vault-graph.json not found. Run analyze.py first.")
sys.exit(1)
return json.loads(GRAPH_PATH.read_text(encoding="utf-8"))
def build_stem_index():
"""Build index: stem → [full_paths]."""
index = defaultdict(list)
md_files = [
f for f in VAULT_PATH.rglob("*.md")
if not any(d in f.parts for d in IGNORE_DIRS)
and not any(p in str(f) for p in EXCLUDE_PATTERNS)
]
for f in md_files:
rel = str(f.relative_to(VAULT_PATH))
stem = f.stem
index[stem].append(rel)
# Also index by path without .md
index[rel.removesuffix(".md")].append(rel)
return index
def find_crm_file(client_name: str) -> str | None:
"""Find CRM file for a client name in business/crm/."""
for prefix in ["business/crm/"]:
candidate = VAULT_PATH / f"{prefix}{client_name}.md"
if candidate.exists():
return f"{prefix}{client_name}"
return None
def suggest_fix(broken_from: str, broken_to: str, stem_index: dict) -> tuple[str | None, str]:
"""Suggest a fix for a broken link target.
Returns (suggestion, action) where action is:
- 'replace': replace the wikilink target
- 'remove': remove the wikilink, keep display text
- 'none': no fix found
"""
target = broken_to
# Direct replacement map (known mismatches)
if target in DIRECT_REPLACE_MAP:
replacement = DIRECT_REPLACE_MAP[target]
# Verify the target file exists
if (VAULT_PATH / f"{replacement}.md").exists():
return replacement, "replace"
# Pattern 1: Trailing backslash
if target.endswith("\\"):
clean = target.rstrip("\\")
if clean in stem_index:
return clean, "replace"
if clean + ".md" in stem_index:
return clean, "replace"
stem = Path(clean).stem
if stem in stem_index and len(stem_index[stem]) == 1:
return stem_index[stem][0].removesuffix(".md"), "replace"
# Pattern 2: Wrong prefix (crm/projects/X → projects/clients/X or projects/leads/X)
if target.startswith("crm/projects/"):
name = target.removeprefix("crm/projects/").rstrip("\\")
for prefix in ["projects/clients/", "projects/leads/"]:
candidate = prefix + name
if candidate in stem_index or candidate + ".md" in stem_index:
return candidate, "replace"
# Pattern A: CRM sub-project → parent
for crm_prefix in ["business/crm/"]:
if target.startswith(crm_prefix):
sub_name = target.removeprefix(crm_prefix)
if sub_name in CRM_PARENT_MAP:
parent = CRM_PARENT_MAP[sub_name]
if parent is None:
return None, "remove"
parent_path = find_crm_file(parent)
if parent_path:
return parent_path, "replace"
# Pattern B: business/projects/ → parent CRM
if target.startswith("business/projects/"):
project_name = target.removeprefix("business/projects/")
if project_name in PROJECT_CLIENT_MAP:
client = PROJECT_CLIENT_MAP[project_name]
parent_path = find_crm_file(client)
if parent_path:
return parent_path, "replace"
# Pattern C: Plaintext company names (self-references inside CRM files)
# e.g. business/crm/acme-corp.md has [[Acme Corp]] — remove the wikilink
if not "/" in target and target[0:1].isupper() and broken_from.startswith(("business/crm/", "projects/crm/")):
return None, "remove"
# Pattern D: Goals aliases (3-weekly-2026-W05 etc.)
if re.match(r"3-weekly-2026-W\d+", target):
return None, "remove"
# Pattern E: Internal paths (.claude/, vault/, scripts/, ~/)
if any(target.startswith(p) for p in [".claude/", "vault/", "scripts/", "../", "~/"]):
return None, "remove"
# Pattern F: Stub/concept links
if target in STUB_LINKS:
return None, "remove"
# Pattern F extended: Sentence-links from external sources
for prefix in SENTENCE_LINK_PREFIXES:
if target.startswith(prefix):
return None, "remove"
# Pattern G: Known unmatchable files → remove
known_removable = {
"contacts/partner-org.json", "meals.md", "brand-x-tasks-handoff.md",
"thoughts/reflections/2026-01-03-data-backup",
"2026-01-05-project-ssr-migration",
}
if target in known_removable:
return None, "remove"
# Attachments → remove wikilink (they're embeds, not graph nodes)
if target.startswith("attachments/"):
return None, "remove"
# thoughts/ references that don't exist → check if stem exists
if target.startswith("thoughts/"):
stem = Path(target).stem
if stem in stem_index and len(stem_index[stem]) == 1:
return stem_index[stem][0].removesuffix(".md"), "replace"
# Pattern 3: Stem-only match (e.g. "acme-corp" → "business/crm/acme-corp")
stem = Path(target.rstrip("\\")).stem
if stem in stem_index:
matches = stem_index[stem]
if len(matches) == 1:
return matches[0].removesuffix(".md"), "replace"
# Projects paths that might resolve differently
if target.startswith("projects/"):
stem = Path(target).stem
if stem in stem_index and len(stem_index[stem]) == 1:
return stem_index[stem][0].removesuffix(".md"), "replace"
# business/network/ that doesn't exist
if target.startswith("business/network/"):
stem = Path(target).stem
if stem in stem_index and len(stem_index[stem]) == 1:
return stem_index[stem][0].removesuffix(".md"), "replace"
# Final fallback: if the link has a path (contains /) and target doesn't exist → remove
# This catches remaining broken paths like projects/leads/contact-name, etc.
if "/" in target:
target_path = VAULT_PATH / f"{target}.md"
if not target_path.exists():
return None, "remove"
return None, "none"
def apply_replace(file_path: Path, old_link: str, new_link: str) -> bool:
"""Replace broken link target in file."""
content = file_path.read_text(encoding="utf-8")
# Match [[old_link]], [[old_link|alias]], [[old_link#section]], [[old_link\|alias]] (table-escaped)
escaped = re.escape(old_link)
pattern = rf"\[\[{escaped}(\\?[|\]#])"
replacement = f"[[{new_link}\\1"
new_content = re.sub(pattern, replacement, content)
if new_content != content:
file_path.write_text(new_content, encoding="utf-8")
return True
return False
def apply_remove(file_path: Path, old_link: str) -> bool:
"""Remove wikilink, keeping display text or link target as plain text."""
content = file_path.read_text(encoding="utf-8")
escaped = re.escape(old_link)
# [[old_link|Display Text]] → Display Text
pattern_with_alias = rf"\[\[{escaped}\|([^\]]+)\]\]"
new_content = re.sub(pattern_with_alias, r"\1", content)
if new_content != content:
file_path.write_text(new_content, encoding="utf-8")
return True
# [[old_link]] → old_link (just the text)
# For paths, use just the stem; for names, use as-is
if "/" in old_link:
display = Path(old_link).stem.replace("-", " ").title()
else:
display = old_link
pattern_plain = rf"\[\[{escaped}\]\]"
new_content = re.sub(pattern_plain, display, content)
if new_content != content:
file_path.write_text(new_content, encoding="utf-8")
return True
return False
def main():
apply = "--apply" in sys.argv
graph = load_graph()
broken_links = graph.get("broken_links", [])
stem_index = build_stem_index()
print(f"Broken links: {len(broken_links)}")
print(f"Mode: {'APPLY' if apply else 'DRY-RUN'}")
print()
# Group by source file
by_source = defaultdict(list)
for bl in broken_links:
by_source[bl["from"]].append(bl["to"])
replacements = []
removals = []
unfixable = []
for source, targets in sorted(by_source.items()):
for target in targets:
suggestion, action = suggest_fix(source, target, stem_index)
if action == "replace" and suggestion:
replacements.append((source, target, suggestion))
elif action == "remove":
removals.append((source, target))
else:
unfixable.append((source, target))
# Deduplicate
seen = set()
unique_replacements = []
for src, old, new in replacements:
key = (src, old, new)
if key not in seen:
seen.add(key)
unique_replacements.append((src, old, new))
replacements = unique_replacements
seen_removals = set()
unique_removals = []
for src, old in removals:
key = (src, old)
if key not in seen_removals:
seen_removals.add(key)
unique_removals.append((src, old))
removals = unique_removals
print(f"Replacements: {len(replacements)}")
print(f"Removals: {len(removals)}")
print(f"Unfixable: {len(unfixable)}")
print()
if replacements:
print("=== REPLACEMENTS ===")
applied = 0
for src, old, new in replacements:
print(f" {src}: [[{old}]] → [[{new}]]")
if apply:
src_path = VAULT_PATH / src
if src_path.exists() and apply_replace(src_path, old, new):
applied += 1
if apply:
print(f"\nApplied: {applied}/{len(replacements)} replacements")
if removals:
print("\n=== REMOVALS (wikilink → plain text) ===")
removed = 0
for src, old in removals:
print(f" {src}: [[{old}]] → plain text")
if apply:
src_path = VAULT_PATH / src
if src_path.exists() and apply_remove(src_path, old):
removed += 1
if apply:
print(f"\nRemoved: {removed}/{len(removals)} wikilinks")
if unfixable:
print("\n=== UNFIXABLE (manual review needed) ===")
for src, target in unfixable:
print(f" {src} → {target}")
# Summary
total_fixed = len(replacements) + len(removals)
print(f"\n{'='*50}")
print(f"Total fixable: {total_fixed}/{len(broken_links)}")
print(f"Unfixable: {len(unfixable)}")
if __name__ == "__main__":
main()
@@ -0,0 +1,534 @@
#!/usr/bin/env python3
"""
Generate explicit-wikilinks MOC files for Business and Projects.
Reads CRM/client/lead files, extracts frontmatter, groups by industry,
and generates MOC markdown with explicit wikilinks:
- [[business/crm/acme-corp|Acme Corp]] — Active, High priority, POST-LAUNCH deal
Output:
- vault/MOC/MOC-business.md — Business CRM Map of Content
- vault/MOC/MOC-projects.md — Projects Map of Content
Usage:
uv run vault/.claude/skills/graph-builder/scripts/generate_moc.py
"""
import re
from pathlib import Path
from collections import defaultdict
from datetime import datetime
# Paths
SCRIPT_DIR = Path(__file__).parent
VAULT_PATH = SCRIPT_DIR.parents[3] # vault/.claude/skills/graph-builder/scripts -> vault
MOC_DIR = VAULT_PATH / "MOC"
BUSINESS_CRM_DIR = VAULT_PATH / "business" / "crm"
PROJECTS_DIR = VAULT_PATH / "projects"
def parse_frontmatter(content: str) -> dict[str, str]:
"""Extract YAML frontmatter as simple key-value pairs."""
match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
if not match:
return {}
fm = {}
for line in match.group(1).split("\n"):
if ":" in line and not line.strip().startswith("-") and not line.strip().startswith("#"):
key, _, value = line.partition(":")
key = key.strip()
value = value.strip().strip('"').strip("'")
if key and value and not value.startswith("[") and not value.startswith("{"):
fm[key] = value
return fm
def extract_title(content: str) -> str | None:
"""Extract first H1 heading from markdown content."""
match = re.search(r"^# (.+)$", content, re.MULTILINE)
if match:
return match.group(1).strip()
return None
def build_context_phrase(fm: dict[str, str]) -> str:
"""Build a context phrase from frontmatter fields.
Pattern: status, priority, deal_status, region
Example: "Active, High priority, POST-LAUNCH deal"
"""
parts = []
status = fm.get("status", "")
if status:
parts.append(status)
priority = fm.get("priority", "")
if priority:
parts.append(f"{priority} priority")
deal_status = fm.get("deal_status", "")
if deal_status:
parts.append(f"{deal_status} deal")
region = fm.get("region", "")
if region:
parts.append(region)
return ", ".join(parts)
def relative_path(file_path: Path) -> str:
"""Get vault-relative path without .md extension."""
rel = file_path.relative_to(VAULT_PATH)
return str(rel).removesuffix(".md")
def generate_business_moc() -> str:
"""Generate MOC-business.md content with explicit wikilinks grouped by industry."""
# Collect all CRM files
records: list[dict] = []
for md_file in sorted(BUSINESS_CRM_DIR.glob("*.md")):
content = md_file.read_text(encoding="utf-8")
fm = parse_frontmatter(content)
title = extract_title(content) or md_file.stem.replace("-", " ").title()
rel = relative_path(md_file)
records.append({
"path": rel,
"title": title,
"industry": fm.get("industry", "Unknown"),
"status": fm.get("status", ""),
"priority": fm.get("priority", ""),
"deal_status": fm.get("deal_status", ""),
"region": fm.get("region", ""),
"updated": fm.get("updated", ""),
"fm": fm,
})
# Group by industry
by_industry: dict[str, list[dict]] = defaultdict(list)
for rec in records:
by_industry[rec["industry"]].append(rec)
# Sort industries by count (descending), then alphabetically
sorted_industries = sorted(
by_industry.keys(),
key=lambda ind: (-len(by_industry[ind]), ind),
)
# Count active deals and high priority
active_deals = [r for r in records if r["deal_status"] and r["deal_status"] not in ("StandBy", "Отказано")]
high_priority = [r for r in records if r["priority"] == "High"]
now = datetime.now().strftime("%Y-%m-%d")
lines = [
"# MOC - Business",
"",
"> Map of Content for Business CRM data",
f"> Generated: {now} | {len(records)} records, {len(active_deals)} active deals, {len(high_priority)} high priority",
"",
"[[business/_index|Business Data Overview]]",
"",
"---",
"",
]
# Active Deals section (explicit wikilinks)
if active_deals:
lines.append(f"## Active Deals ({len(active_deals)})")
lines.append("")
# Sort by deal_deadline if available, then by title
for rec in sorted(active_deals, key=lambda r: (r.get("fm", {}).get("deal_deadline", "9999"), r["title"])):
ctx = build_context_phrase(rec["fm"])
deadline = rec["fm"].get("deal_deadline", "")
deadline_str = f", deadline {deadline}" if deadline else ""
lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}{deadline_str}")
lines.append("")
lines.append("---")
lines.append("")
# High Priority section (explicit wikilinks)
if high_priority:
lines.append(f"## High Priority ({len(high_priority)})")
lines.append("")
for rec in sorted(high_priority, key=lambda r: (r["industry"], r["title"])):
ctx = build_context_phrase(rec["fm"])
lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}")
lines.append("")
lines.append("---")
lines.append("")
# By Industry sections
lines.append("## By Industry")
lines.append("")
for industry in sorted_industries:
industry_records = by_industry[industry]
lines.append(f"### {industry} ({len(industry_records)})")
lines.append("")
# Sort: active/in-work first, then by title
def sort_key(r: dict) -> tuple:
status_order = 0
s = r["status"].lower()
if s in ("active", "в работе"):
status_order = 0
elif "tender" in s or "negotiation" in s:
status_order = 1
elif s == "prospect":
status_order = 2
else:
status_order = 3
return (status_order, r["title"])
for rec in sorted(industry_records, key=sort_key):
ctx = build_context_phrase(rec["fm"])
if ctx:
lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}")
else:
lines.append(f"- [[{rec['path']}|{rec['title']}]]")
lines.append("")
# Dataview blocks (preserved at the end)
lines.extend([
"---",
"",
"## Dataview: Active Deals",
"",
"```dataview",
'TABLE deal_status as "Status", deal_deadline as "Deadline", industry',
'FROM "business/crm"',
'WHERE deal_status != null AND deal_status != "StandBy" AND deal_status != "Отказано"',
"SORT deal_deadline ASC",
"LIMIT 15",
"```",
"",
"## Dataview: High Priority",
"",
"```dataview",
"TABLE industry, status, deal_status",
'FROM "business/crm"',
'WHERE priority = "High"',
"SORT deal_status DESC",
"LIMIT 20",
"```",
"",
"## Dataview: By Industry",
"",
"```dataview",
"TABLE WITHOUT ID",
' industry as "Industry",',
' length(rows) as "Count"',
'FROM "business/crm"',
"GROUP BY industry",
"SORT length(rows) DESC",
"```",
"",
"## Dataview: By Status",
"",
"```dataview",
"TABLE WITHOUT ID",
' status as "Status",',
' length(rows) as "Count"',
'FROM "business/crm"',
"GROUP BY status",
"SORT length(rows) DESC",
"```",
"",
"## Dataview: Recently Updated",
"",
"```dataview",
"TABLE industry, status, priority",
'FROM "business/crm"',
"SORT file.mtime DESC",
"LIMIT 20",
"```",
"",
])
return "\n".join(lines)
def generate_projects_moc() -> str:
"""Generate MOC-projects.md with explicit wikilinks."""
now = datetime.now().strftime("%Y-%m-%d")
# Collect clients
clients: list[dict] = []
clients_dir = PROJECTS_DIR / "clients"
if clients_dir.exists():
for md_file in sorted(clients_dir.glob("*.md")):
content = md_file.read_text(encoding="utf-8")
fm = parse_frontmatter(content)
title = extract_title(content) or md_file.stem.replace("-", " ").title()
rel = relative_path(md_file)
clients.append({
"path": rel,
"title": title,
"industry": fm.get("industry", "Unknown"),
"status": fm.get("status", ""),
"region": fm.get("region", ""),
"company": fm.get("company", title),
"fm": fm,
})
# Collect leads
leads: list[dict] = []
leads_dir = PROJECTS_DIR / "leads"
if leads_dir.exists():
for md_file in sorted(leads_dir.glob("*.md")):
content = md_file.read_text(encoding="utf-8")
fm = parse_frontmatter(content)
title = extract_title(content) or md_file.stem.replace("-", " ").title()
rel = relative_path(md_file)
leads.append({
"path": rel,
"title": title,
"industry": fm.get("industry", "Unknown"),
"status": fm.get("status", ""),
"company": fm.get("company", title),
"potential": fm.get("potential", ""),
"region": fm.get("region", ""),
"fm": fm,
})
# Collect projects
projects: list[dict] = []
projects_dir = PROJECTS_DIR / "projects"
if projects_dir.exists():
for md_file in sorted(projects_dir.glob("*.md")):
content = md_file.read_text(encoding="utf-8")
fm = parse_frontmatter(content)
title = extract_title(content) or md_file.stem.replace("-", " ").title()
rel = relative_path(md_file)
projects.append({
"path": rel,
"title": title,
"status": fm.get("status", ""),
"fm": fm,
})
# Collect standalone files (resources, reports, etc.)
standalone: list[dict] = []
for md_file in sorted(PROJECTS_DIR.glob("*.md")):
if md_file.name == "_index.md":
continue
content = md_file.read_text(encoding="utf-8")
fm = parse_frontmatter(content)
title = extract_title(content) or md_file.stem.replace("-", " ").title()
rel = relative_path(md_file)
standalone.append({
"path": rel,
"title": title,
"fm": fm,
})
# Collect events
events: list[dict] = []
events_dir = PROJECTS_DIR / "events"
if events_dir.exists():
for md_file in sorted(events_dir.glob("*.md")):
content = md_file.read_text(encoding="utf-8")
fm = parse_frontmatter(content)
title = extract_title(content) or md_file.stem.replace("-", " ").title()
rel = relative_path(md_file)
events.append({
"path": rel,
"title": title,
"status": fm.get("status", ""),
"fm": fm,
})
# Collect reports
reports: list[dict] = []
reports_dir = PROJECTS_DIR / "reports"
if reports_dir.exists():
for md_file in sorted(reports_dir.glob("*.md")):
content = md_file.read_text(encoding="utf-8")
fm = parse_frontmatter(content)
title = extract_title(content) or md_file.stem.replace("-", " ").title()
rel = relative_path(md_file)
reports.append({
"path": rel,
"title": title,
"fm": fm,
})
total = len(clients) + len(leads) + len(projects) + len(standalone) + len(events) + len(reports)
lines = [
"# MOC - Projects",
"",
"> Map of Content for Projects",
f"> Generated: {now} | {len(clients)} clients, {len(leads)} leads, {len(projects)} projects",
"",
"[[projects/_index|Projects Overview]]",
"",
"---",
"",
]
# Clients
if clients:
lines.append(f"## Clients ({len(clients)})")
lines.append("")
for rec in sorted(clients, key=lambda r: r["title"]):
parts = []
if rec["status"]:
parts.append(rec["status"])
if rec["industry"] and rec["industry"] != "Unknown":
parts.append(rec["industry"])
if rec["region"]:
parts.append(rec["region"])
ctx = ", ".join(parts)
if ctx:
lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}")
else:
lines.append(f"- [[{rec['path']}|{rec['title']}]]")
lines.append("")
# Leads
if leads:
# Split into hot/active and others
hot_leads = [l for l in leads if l["status"].lower() in ("hot", "qualified", "follow-up sent", "proposal sent")]
other_leads = [l for l in leads if l not in hot_leads]
lines.append(f"## Leads ({len(leads)})")
lines.append("")
if hot_leads:
lines.append("### Hot / Active")
lines.append("")
for rec in sorted(hot_leads, key=lambda r: r["title"]):
parts = []
if rec["status"]:
parts.append(rec["status"])
if rec["company"] and rec["company"] != rec["title"]:
parts.append(rec["company"])
if rec["potential"]:
parts.append(rec["potential"])
if rec["region"]:
parts.append(rec["region"])
ctx = ", ".join(parts)
if ctx:
lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}")
else:
lines.append(f"- [[{rec['path']}|{rec['title']}]]")
lines.append("")
if other_leads:
lines.append("### Other Leads")
lines.append("")
for rec in sorted(other_leads, key=lambda r: r["title"]):
parts = []
if rec["status"]:
parts.append(rec["status"])
if rec["company"] and rec["company"] != rec["title"]:
parts.append(rec["company"])
if rec["potential"]:
parts.append(rec["potential"])
if rec["region"]:
parts.append(rec["region"])
ctx = ", ".join(parts)
if ctx:
lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}")
else:
lines.append(f"- [[{rec['path']}|{rec['title']}]]")
lines.append("")
# Projects
if projects:
lines.append(f"## Projects ({len(projects)})")
lines.append("")
for rec in sorted(projects, key=lambda r: r["title"]):
status = rec["status"]
if status:
lines.append(f"- [[{rec['path']}|{rec['title']}]] — {status}")
else:
lines.append(f"- [[{rec['path']}|{rec['title']}]]")
lines.append("")
# Events
if events:
lines.append(f"## Events ({len(events)})")
lines.append("")
for rec in sorted(events, key=lambda r: r["path"]):
status = rec["status"]
if status:
lines.append(f"- [[{rec['path']}|{rec['title']}]] — {status}")
else:
lines.append(f"- [[{rec['path']}|{rec['title']}]]")
lines.append("")
# Reports
if reports:
lines.append(f"## Reports ({len(reports)})")
lines.append("")
for rec in sorted(reports, key=lambda r: r["path"]):
lines.append(f"- [[{rec['path']}|{rec['title']}]]")
lines.append("")
# Standalone files
if standalone:
lines.append(f"## Resources ({len(standalone)})")
lines.append("")
for rec in sorted(standalone, key=lambda r: r["title"]):
lines.append(f"- [[{rec['path']}|{rec['title']}]]")
lines.append("")
# Dataview blocks (preserved)
lines.extend([
"---",
"",
"## Dataview: Leads",
"",
"```dataview",
"TABLE company, industry, status, responsible",
'FROM "projects/leads"',
"SORT updated DESC",
"```",
"",
"## Dataview: Clients",
"",
"```dataview",
"TABLE company, industry, status",
'FROM "projects/clients"',
"SORT updated DESC",
"```",
"",
])
return "\n".join(lines)
def main():
"""Generate both MOC files."""
MOC_DIR.mkdir(exist_ok=True)
# Generate Business MOC
biz_content = generate_business_moc()
biz_path = MOC_DIR / "MOC-business.md"
biz_path.write_text(biz_content, encoding="utf-8")
print(f"Generated: {biz_path.relative_to(VAULT_PATH)}")
# Generate Projects MOC
proj_content = generate_projects_moc()
proj_path = MOC_DIR / "MOC-projects.md"
proj_path.write_text(proj_content, encoding="utf-8")
print(f"Generated: {proj_path.relative_to(VAULT_PATH)}")
# Stats
biz_links = biz_content.count("[[")
proj_links = proj_content.count("[[")
print(f"\nStats:")
print(f" Business: {biz_links} wikilinks")
print(f" Projects: {proj_links} wikilinks")
print(f" Total: {biz_links + proj_links} explicit wikilinks")
if __name__ == "__main__":
main()
+13
View File
@@ -0,0 +1,13 @@
{
"tiers": {"active": 7, "warm": 21, "cold": 60},
"decay_rate": 0.015,
"relevance_floor": 0.1,
"skip_patterns": ["_index.md"],
"type_inference": {
"crm/": "crm",
"leads/": "lead",
"clients/": "client",
"projects/": "project"
},
"use_git_dates": true
}
+75
View File
@@ -0,0 +1,75 @@
# Long-term Memory
Curated knowledge that persists across sessions. Part of the 3-layer memory architecture (hot context → searchable vault → archive). See `.claude/skills/agent-memory/SKILL.md` for details.
## User Profile
| Field | Value |
|-------|-------|
| Name | [Your name] |
| Timezone | [Your timezone, e.g., UTC+5] |
| Location | [City/Country] |
| Primary language | [e.g., Russian/English] |
## Preferences
### Tech Stack
- Languages: [e.g., Python, TypeScript]
- Frameworks: [e.g., React, FastAPI]
- Tools: [e.g., Cursor, Claude Code]
### Communication Style
- Preferred response language: [Russian/English/Mixed]
- Detail level: [Brief/Detailed]
- Code comments: [Minimal/Verbose]
### Habits
- Morning routine: [if relevant]
- Work hours: [e.g., 10:00-19:00]
- Planning cadence: [weekly/daily]
## Key Decisions
| Date | Decision | Context |
|------|----------|---------|
| YYYY-MM-DD | Example: Use uv instead of pip | Better dependency management |
## Active Context
### ONE Big Thing (This Week)
<!-- From goals/3-weekly.md -->
- [ ] [Current week's main focus]
### Hot Projects
1. [Project name] — [status/next action]
### Pipeline/Leads
<!-- If applicable -->
- [Lead name] — [status]
## Key People
| Name | Role | Contact | Notes |
|------|------|---------|-------|
| [Name] | [Role] | [Telegram/Email] | [Context] |
## Learnings
### What Worked
- [Pattern/approach that was successful]
### What Didn't Work
- [Anti-pattern to avoid]
### Rules to Remember
- [Important rule discovered during work]
## Quick Links
- [[goals/3-weekly]] — Weekly focus
- [[goals/2-monthly]] — Monthly priorities
- [[MOC/index]] — Maps of Content
---
*Last updated: YYYY-MM-DD*

Some files were not shown because too many files have changed in this diff Show More