#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import path from 'node:path'
import crypto from 'node:crypto'
import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
import { verifyLocal, verifyDeep, isPublicHttpUrl } from './mnemazine-verify.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const argv = process.argv.slice(2)
function arg(name, fallback = '') {
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
if (!hit) return fallback
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
}
const VAULT = resolveVault({ cli: arg('vault') })
const EXTRACTS = path.resolve(arg('extracts', process.env.MNEMAZINE_EXTRACTS || path.join(ROOT, '.mnemazine/cache/extracted')))
const SESSION = arg('session', new Date().toISOString().slice(0, 10))
const MIN_CLUSTER_CHARS = Number(arg('min-cluster-chars', '80'))
// --deep / --atomize: LLM-split one cluster into many focused atoms (README:50).
// Default off — the conservative path (release demo, run.mjs) stays local-only
// and never needs codex. Flag also honoured via MNEMAZINE_DEEP=1.
const DEEP = argv.includes('--deep') || argv.includes('--atomize') || process.env.MNEMAZINE_DEEP === '1'
const MAX_ATOMS = Number(arg('max-atoms', process.env.MNEMAZINE_MAX_ATOMS || '20'))
// Enrichment is on within --deep unless explicitly disabled (it needs the network).
const ENRICH = DEEP && process.env.MNEMAZINE_ENRICH !== '0' && !argv.includes('--no-enrich')
const ENRICH_TIMEOUT_MS = Number(process.env.MNEMAZINE_ENRICH_TIMEOUT_MS || '60000')
const STRICT_ENRICH = DEEP && process.env.MNEMAZINE_STRICT_ENRICH !== '0' && !argv.includes('--allow-raw-atomize')
const MIN_ADDED_FACTS = Number(process.env.MNEMAZINE_MIN_ADDED_FACTS || '2')
const CLUSTER_CHUNK_SIZE = Number(arg('cluster-chunk-size', process.env.MNEMAZINE_CLUSTER_CHUNK_SIZE || '25'))
const SOURCE_REF_FILTER = new Set(String(process.env.MNEMAZINE_SYNTH_SOURCE_REFS || '')
.split(',')
.map(s => s.trim())
.filter(Boolean))
const sourceHints = [
{ re: /supermemory/i, name: 'supermemory GitHub', url: 'https://github.com/supermemoryai/supermemory' },
{ re: /compound\s+engineer|compound-\s*engineering-plugin/i, name: 'Compound Engineering GitHub', url: 'https://github.com/EveryInc/compound-engineering-plugin' },
{ re: /taste\s+skill|taste-skill|anti-slop\s+frontend/i, name: 'Taste Skill GitHub', url: 'https://github.com/Leonxlnx/taste-skill' },
{ re: /mcp|model context protocol|filesystem mcp|memory mcp|zapier/i, name: 'Model Context Protocol docs', url: 'https://modelcontextprotocol.io/docs/getting-started/intro' },
{ re: /skill|skills|claude code|agent skill|subagent/i, name: 'Anthropic Agent Skills', url: 'https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills' },
{ re: /spec|spec-driven|feature forge|requirements/i, name: 'GitHub Spec Kit', url: 'https://github.com/github/spec-kit' },
{ re: /prompt injection|security|secure|guard|review/i, name: 'OWASP LLM01 Prompt Injection', url: 'https://genai.owasp.org/llmrisk/llm01-prompt-injection/' },
{ re: /observability|logs|metrics|traces|otel/i, name: 'OpenTelemetry docs', url: 'https://opentelemetry.io/docs/' },
{ re: /secret|env|credential|api key/i, name: 'Infisical secrets docs', url: 'https://infisical.com/docs/documentation/platform/secrets-mgmt/overview' },
{ re: /design\.md|getdesign|design system|wcag|accessibility|ui|frontend/i, name: 'getdesign.md', url: 'https://getdesign.md/' },
{ re: /browser|playwright|agent-browser|browser-use/i, name: 'Playwright docs', url: 'https://playwright.dev/docs/intro' },
{ re: /obsidian|vault|wiki|memory|knowledge|graph/i, name: 'Karpathy LLM Wiki', url: 'https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f' },
{ re: /terraform|pulumi|infrastructure|iac/i, name: 'Terraform docs', url: 'https://developer.hashicorp.com/terraform/docs' },
{ re: /bff|backend for frontend/i, name: 'Backends for Frontends pattern', url: 'https://learn.microsoft.com/en-us/azure/architecture/patterns/backends-for-frontends' },
{ re: /worktree|git stash/i, name: 'git worktree docs', url: 'https://git-scm.com/docs/git-worktree' },
{ re: /moneyprinter|short-form|reels|tiktok|youtube shorts/i, name: 'MoneyPrinterTurbo', url: 'https://github.com/harry0703/MoneyPrinterTurbo' }
]
const clusterRules = [
{ id: 'agent-systems', title: 'Agent systems and reusable capabilities', re: /agent|claude|skill|subagent|mcp|jarvis|harness|memory|codex/i },
{ id: 'knowledge-memory', title: 'Knowledge memory, vaults, and synthesis loops', re: /obsidian|vault|wiki|knowledge|graph|weekly synthesis|belief|decision/i },
{ id: 'security-review', title: 'Security, review, and trust boundaries', re: /security|secret|prompt injection|review|guard|permission|wcag|accessibility/i },
{ id: 'engineering-ops', title: 'Engineering operations and reproducible delivery', re: /observability|terraform|pulumi|worktree|staging|environment|deploy|bff|backend/i },
{ id: 'design-frontend', title: 'Design systems and frontend quality', re: /design|frontend|ui|component|playwright|browser|layout|wcag/i },
{ id: 'tool-radar', title: 'Open-source tool radar and selection', re: /github\.com|open source|langflow|dify|open-webui|openhands|crawl4ai|coolify|papermark|twenty|crowdsec/i },
{ id: 'content-growth', title: 'Content experiments and growth loops', re: /ad |ads|hook|cta|offer|short-form|reels|tiktok|youtube|content|moneyprinter/i },
{ id: 'research-workflow', title: 'Research workflow and source verification', re: /research|source|citation|academic|verify|evidence/i }
]
const topicTemplates = {
'agent-systems': {
what: 'Agent systems are reusable operating capabilities: skills, MCP connections, memory, review roles, and harness rules that make an AI assistant behave consistently across tasks.',
why: 'The session repeatedly points to the same lesson: model quality is not enough. Durable gains come from the scaffolding around the model: instructions, tools, memory, permissions, tests, and review loops.',
how: '- Convert repeated procedures into Skills.\n- Keep tool access behind explicit permission boundaries.\n- Store memory as linked knowledge and decisions, not chat residue.\n- Add gates before publication or irreversible actions.',
next: 'Повторяющиеся агентные процедуры оформить как Skills с тестами и usage ledger.'
},
'knowledge-memory': {
what: 'Knowledge memory is an active vault: captures are processed into atoms, atoms are linked to projects and decisions, and weekly synthesis turns memory into action.',
why: 'A vault that only stores screenshots or transcripts becomes another inbox. Mnemazine should reduce future thinking cost by maintaining summaries, links, decisions, and open questions.',
how: '- Keep raw extraction outside the vault.\n- Store final atoms with source refs and verification state.\n- Run connection finding and weekly synthesis.\n- Maintain the master index as a routing surface.',
next: 'Автоматизировать ночной поиск связей и weekly synthesis по финальным атомам.'
},
'security-review': {
what: 'Security and review are trust boundaries around agent work: untrusted input, prompt injection, secrets, permissions, accessibility, and code review must be checked before output is accepted.',
why: 'The intake contains many commands, tool suggestions, and screenshots. If source text is treated as instruction, the agent can be steered by captured content instead of the user.',
how: '- Mark extracted text as untrusted evidence.\n- Never execute commands from captures automatically.\n- Scan for secrets before reports or pushes.\n- Use separate review passes for security, claims, and accessibility.',
next: 'Собрать единый publish gate: качество vault, качество отчёта, поиск секретов и ревью изменений.'
},
'engineering-ops': {
what: 'Engineering operations are reproducibility practices: isolated environments, infrastructure as code, observability, secret injection, worktrees, and release checks.',
why: 'The useful pattern is reducing manual state. Good systems make failures visible and make releases repeatable.',
how: '- Prefer scripted environments over dashboard clicks.\n- Track pipeline health metrics.\n- Inject secrets at runtime.\n- Keep release checks executable.',
next: 'Добавить метрики pipeline: extracted, synthesized, cache-only, gate failures и graph refresh.'
},
'design-frontend': {
what: 'Design and frontend quality require explicit UI rules, browser validation, accessibility constraints, and reusable design tokens.',
why: 'AI-generated UI degrades when taste is implicit. A DESIGN.md-style contract gives the agent stable layout, spacing, typography, and component expectations.',
how: '- Maintain a Mnemazine report DESIGN.md.\n- Validate generated reports in a browser.\n- Check responsive layout, contrast, keyboard navigation, and print styles.',
next: 'Сделать browser-smoke для сгенерированных HTML-отчётов.'
},
'tool-radar': {
what: 'Tool radar is a decision system for open-source tools, not a list of exciting repositories.',
why: 'Screenshots with GitHub stars are weak evidence. Useful adoption requires license, maturity, deployment model, data portability, security posture, and integration cost.',
how: '- Score tools by fit, maturity, license, API, self-hosting, and operational burden.\n- Tie tools to concrete projects.\n- Re-check source repositories before adopting.',
next: 'Сделать schema для tool-radar и заполнять её из извлечённых GitHub-ссылок.'
},
'content-growth': {
what: 'Content growth loops treat ads, hooks, CTAs, short-form scripts, and publishing as experiments with feedback.',
why: 'One generated video or ad is not learning. Learning appears when variants, metric, result, and next control are stored.',
how: '- Store hypothesis, channel, variant, metric, result, and decision.\n- Keep winners as controls.\n- Discard weak variants without preserving noise as knowledge.',
next: 'Добавить шаблон заметки для Content Experiment.'
},
'research-workflow': {
what: 'Research workflow means claims are sourced before they become operational knowledge.',
why: 'A source link is not decoration. It should confirm, correct, or constrain the conclusion.',
how: '- Separate extracted claim from verified conclusion.\n- Prefer official docs and primary repositories.\n- Record confidence and what the source changed.',
next: 'Добавить `source_changed_what` в schema финального атома.'
},
misc: {
what: 'Miscellaneous signals are captured items that do not yet form a strong enough reusable cluster.',
why: 'Keeping them separate prevents weak or noisy items from polluting stronger knowledge atoms.',
how: '- Review manually.\n- Promote only recurring or high-value ideas.\n- Move low-signal material to forget/archive.',
next: 'Вручную разобрать misc-сигналы: повысить до знания или забыть.'
}
}
const topicTemplatesRu = {
'agent-systems': {
what: 'Агентная система - это набор повторяемых возможностей вокруг модели: skills, MCP, память, роли ревью, правила harness и release gates.',
why: 'Качество даёт не только модель. Стабильность появляется, когда вокруг неё есть инструменты, память, разрешения, тесты и ревью.',
how: ['Повторяющиеся процедуры превращать в Skills.', 'Доступ к инструментам держать за явными границами разрешений.', 'Память хранить как связанные знания и решения.', 'Перед публикацией держать gate.'],
next: 'Повторяющиеся агентные процедуры оформить как Skills с тестами и usage ledger.'
},
'knowledge-memory': {
what: 'Память знаний - это active vault: сырьё превращается в атомы, атомы связываются с проектами и решениями, weekly synthesis превращает память в действия.',
why: 'Vault со скриншотами быстро становится ещё одним inbox. Польза появляется, когда заметки уменьшают будущую стоимость мышления.',
how: ['Сырой extraction держать вне финального vault.', 'Финальные атомы писать с source refs и verification status.', 'Регулярно строить связи и weekly synthesis.', 'Мастер-индекс держать как routing surface.'],
next: 'Автоматизировать nightly connection finding и weekly synthesis по финальным атомам.'
},
'security-review': {
what: 'Безопасность и ревью - это границы доверия вокруг агентной работы: untrusted input, prompt injection, секреты, permissions, accessibility и code review проверяются до принятия результата.',
why: 'Inbox содержит команды, скриншоты, сайты и tool suggestions. Если принять захваченный текст за инструкцию, агент начнёт слушать источник, а не владельца.',
how: ['Помечать extraction как недоверенное evidence.', 'Не выполнять команды из захваченного текста автоматически.', 'Сканировать секреты перед отчётами и push.', 'Разделять review по security, claims и accessibility.'],
next: 'Собрать единый publish gate: vault quality, report quality, secret scan, diff review.'
},
'engineering-ops': {
what: 'Инженерные операции - это воспроизводимость: окружения, IaC, observability, secret injection, worktrees и release checks.',
why: 'Хорошая система уменьшает ручное состояние: failures видны, delivery повторяемый.',
how: ['Скрипты вместо dashboard-clicks.', 'Метрики здоровья pipeline.', 'Секреты инжектить runtime-способом.', 'Release checks держать исполняемыми.'],
next: 'Добавить метрики pipeline: extracted, synthesized, cache-only, gate failures, graph refresh.'
},
'design-frontend': {
what: 'Качество UI требует явного дизайн-контракта: правила интерфейса, browser validation, accessibility constraints и reusable design tokens.',
why: 'AI UI быстро портится, если вкус не записан. DESIGN.md-style контракт задаёт layout, spacing, типографику и ожидаемое поведение компонентов.',
how: ['Держать DESIGN.md для Mnemazine reports.', 'Проверять generated reports в браузере.', 'Смотреть responsive layout, contrast, keyboard navigation и print styles.'],
next: 'Создать browser smoke для generated HTML reports.'
},
'tool-radar': {
what: 'Tool radar - это система решений по open-source, а не список красивых репозиториев.',
why: 'Скриншот со stars - слабое evidence. Нужны license, maturity, deployment model, data portability, security posture и integration cost.',
how: ['Оценивать fit, maturity, license, API, self-hosting и operational burden.', 'Связывать инструмент с конкретным проектом.', 'Перед adoption перепроверять primary source.'],
next: 'Сделать schema для tool-radar и заполнять её из GitHub links.'
},
'content-growth': {
what: 'Контентные петли роста рассматривают ads, hooks, CTA, scripts и публикации как эксперименты с обратной связью.',
why: 'Один ролик или объявление ещё не обучение. Обучение появляется, когда есть variant, metric, result и next control.',
how: ['Хранить hypothesis, channel, variant, metric, result и decision.', 'Победителей держать как controls.', 'Слабые варианты удалять без превращения шума в знания.'],
next: 'Добавить template для Content Experiment note.'
},
'research-workflow': {
what: 'Research workflow значит: claims получают источники до того, как становятся рабочим знанием.',
why: 'Ссылка должна подтверждать, исправлять или ограничивать вывод. Иначе это декорация.',
how: ['Отделять extracted claim от verified conclusion.', 'Предпочитать official docs и primary repositories.', 'Писать, что именно источник изменил в выводе.'],
next: 'Добавить поле `source_changed_what` в final atom schema.'
},
misc: {
what: 'Прочие сигналы - материалы, которые пока не сложились в сильный reusable cluster.',
why: 'Отдельный misc-кластер защищает сильные знания от слабого шума.',
how: ['Проверить вручную.', 'Повышать до знания только повторяющиеся или ценные идеи.', 'Низкий сигнал отправлять в forget/archive.'],
next: 'Вручную разобрать misc-сигналы: promote или forget.'
}
}
function compact(value, limit = 1200) {
return String(value || '')
.replace(/^#{1,6}\s+/gm, '')
.replace(/\s+/g, ' ')
.trim()
.slice(0, limit)
}
function slugify(value) {
return String(value || 'note')
.toLowerCase()
.replace(/[^a-zа-я0-9]+/gi, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 72) || 'note'
}
function uniq(values) {
return [...new Set(values.filter(Boolean))]
}
// Content fingerprint = stable hash of a cluster's sorted source refs. Same
// inputs -> same fingerprint -> same filename, so re-runs are idempotent and
// exact-duplicate clusters are not rewritten (see write loop skip).
// ponytail: exact-dup only via source-ref hash; near-duplicate (paraphrase)
// dedup needs embeddings — wire fastembed/Ollama here if dup clusters appear.
function fingerprint(cluster) {
const refs = cluster.records.map(record => String(record.source_ref || "")).sort()
const key = [cluster.id || "", cluster.part || 1, ...refs].join(" ")
return crypto.createHash("sha1").update(key).digest("hex").slice(0, 10)
}
function extractUrls(text) {
const raw = String(text || '')
const explicit = raw.match(/\bhttps?:\/\/[^\s)]+/g) || []
const bareGithub = [...raw.matchAll(/\bgithub\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+/g)]
.map(match => `https://${match[0]}`)
return uniq([...explicit, ...bareGithub])
.map(url => url.replace(/[.,;]+$/, ''))
.filter(isPublicHttpUrl)
.slice(0, 8)
}
function bullets(text, max = 8) {
const out = []
const seen = new Set()
for (const part of String(text || '').split(/\n|[•*-]\s+|(?<=[.!?])\s+/)) {
const line = compact(part, 190)
if (line.length < 32) continue
if (/^(video keyframe ocr|video transcript|img_|temp_image|follow|subscribe|save this)/i.test(line)) continue
const key = line.toLowerCase()
if (seen.has(key)) continue
seen.add(key)
out.push(line)
if (out.length >= max) break
}
return out
}
function classify(text) {
const hit = clusterRules.find(rule => rule.re.test(text))
return hit ? hit.id : 'misc'
}
function clusterTitle(id) {
return clusterRules.find(rule => rule.id === id)?.title || 'Miscellaneous knowledge signals'
}
function clusterTitleRu(id) {
const map = {
'agent-systems': 'Агентные системы и переиспользуемые возможности',
'knowledge-memory': 'Память знаний, vault и циклы синтеза',
'security-review': 'Безопасность, ревью и границы доверия',
'engineering-ops': 'Инженерные операции и воспроизводимая доставка',
'design-frontend': 'Дизайн-системы и качество фронтенда',
'tool-radar': 'Радар инструментов и выбор open-source',
'content-growth': 'Контентные эксперименты и петли роста',
'research-workflow': 'Исследовательский workflow и проверка источников',
misc: 'Прочие сигналы знаний'
}
return map[id] || map.misc
}
function publicSources(text) {
const explicit = extractUrls(text).map(url => ({ name: url.includes('github.com') ? 'GitHub source' : 'Source link', url }))
const hinted = sourceHints
.filter(source => source.re.test(text))
.map(({ name, url }) => ({ name, url }))
const byUrl = new Map()
for (const source of [...explicit, ...hinted]) {
if (isPublicHttpUrl(source.url)) byUrl.set(source.url, source)
}
return [...byUrl.values()].slice(0, 10)
}
function githubRepoFromUrl(url) {
let parsed
try { parsed = new URL(url) } catch { return null }
if (parsed.hostname.replace(/^www\./, '') !== 'github.com') return null
const [, owner, repo] = parsed.pathname.split('/')
if (!owner || !repo) return null
const cleanOwner = owner.replace(/^Leonx1nx$/i, 'Leonxlnx')
const cleanRepo = repo.replace(/\.git$/i, '')
if (cleanRepo.endsWith('-')) return null
return { owner: cleanOwner, repo: cleanRepo, url: `https://github.com/${cleanOwner}/${cleanRepo}` }
}
async function fetchJson(url) {
try {
const res = await fetch(url, { headers: { 'User-Agent': 'Mnemazine' } })
if (!res.ok) return null
return await res.json()
} catch {
return null
}
}
async function fetchText(url, limit = 40000) {
try {
const res = await fetch(url, { headers: { 'User-Agent': 'Mnemazine' } })
if (!res.ok) return ''
return (await res.text()).slice(0, limit)
} catch {
return ''
}
}
function readmePoints(readme, max = 6) {
const points = []
for (const line of stripHtmlText(readme).split('\n')) {
const clean = compact(line.replace(/^#+\s*/, '').replace(/^[-*]\s+/, ''), 220)
if (clean.length < 32) continue
if (/^(install|usage|license|contributing|table of contents|badges?)$/i.test(clean)) continue
if (/^!\[|^
/i.test(clean)) continue
points.push(clean)
if (points.length >= max) break
}
return points
}
function htmlDescription(html) {
const raw = String(html || '')
const hit = raw.match(/')
.replace(/ /g, ' ')
}
function stripHtmlText(text) {
return decodeEntities(String(text || '')
.replace(/