Initial open source release

This commit is contained in:
tv5171621-source
2026-06-15 02:47:14 +03:00
commit 5c59152c06
44 changed files with 1640 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(cd "$(dirname "$0")/.." && pwd)}"
if rg -n '/Users/fil|72\.56|root@|Полезные знания|_ВХОДЯЩИЕ|TODOCUPS|ПКК|legal-practice|Adventure Book|AthenaOS|Филипп' "$ROOT" -g '!node_modules/**' -g '!.git/**' -g '!scripts/check-public-release.sh'; then
echo "Public release check failed: private marker found." >&2
exit 1
fi
if rg -n 'gho_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[baprs]-[A-Za-z0-9-]+' "$ROOT" -g '!node_modules/**' -g '!.git/**' -g '!scripts/check-public-release.sh'; then
echo "Public release check failed: token-like value found." >&2
exit 1
fi
echo "Public release check passed."
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import path from 'node:path'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')
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 seed = arg('url')
const apply = argv.includes('--apply')
const graphify = argv.includes('--graphify')
const maxPages = Number(arg('max-pages', '40'))
if (!seed) {
console.error('Usage: node scripts/mnemazine-ingest-site.mjs --url https://example.com [--apply] [--graphify] [--max-pages 40]')
process.exit(2)
}
function escMd(s) {
return String(s || '').replace(/\r/g, '').trim()
}
function stripHtml(html) {
return String(html)
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<\/(h[1-4]|p|li|section|article|div)>/gi, '\n')
.replace(/<h([1-4])[^>]*>/gi, '\n### ')
.replace(/<[^>]+>/g, ' ')
.replace(/&nbsp;/g, ' ')
.replace(/&amp;/g, '&')
.replace(/&quot;/g, '"')
.replace(/&#39;|&#x27;/g, "'")
.replace(/\s+\n/g, '\n')
.replace(/[ \t]{2,}/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
function slug(value) {
return String(value || 'site')
.toLowerCase()
.replace(/^https?:\/\//, '')
.replace(/[^a-z0-9а-я]+/gi, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 90) || 'site'
}
async function fetchText(url, optional = false) {
try {
const res = await fetch(url, { headers: { 'user-agent': 'Mnemazine/0.1 local knowledge ingest' } })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return await res.text()
} catch (err) {
if (optional) return ''
throw err
}
}
function links(html, base) {
const out = new Set()
for (const m of html.matchAll(/<a[^>]+href=["']([^"']+)["']/gi)) {
try {
const u = new URL(m[1], base)
if (u.origin === new URL(base).origin) out.add(u.href.replace(/#.*$/, ''))
} catch {}
}
return [...out]
}
async function discover(seedUrl) {
const origin = new URL(seedUrl).origin
const urls = new Set([seedUrl])
const robots = await fetchText(`${origin}/robots.txt`, true)
const sitemaps = [...robots.matchAll(/Sitemap:\s*(\S+)/gi)].map(m => m[1])
for (const sm of sitemaps.length ? sitemaps : [`${origin}/sitemap.xml`]) {
const xml = await fetchText(sm, true)
for (const m of xml.matchAll(/<loc>(.*?)<\/loc>/g)) {
try {
const u = new URL(m[1])
if (u.origin === origin) urls.add(u.href)
} catch {}
}
}
if (urls.size === 1) {
const html = await fetchText(seedUrl, true)
links(html, seedUrl).forEach(u => urls.add(u))
}
return [...urls].slice(0, maxPages)
}
function pageNote(url, html) {
const title = stripHtml(html.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i)?.[1] || html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1] || url)
const text = stripHtml(html)
const github = [...html.matchAll(/https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+/g)].map(m => m[0])
return `# ${title}
## What This Is
This note was created from a public web page and should be refined into smaller durable notes if it contains several topics.
## Source
- URL: ${url}
## Extracted Knowledge
${escMd(text.slice(0, 6000))}
## Public Repositories Mentioned
${github.length ? [...new Set(github)].map(u => `- ${u}`).join('\n') : '- None found on this page.'}
## Verification
- Status: extracted from public page
- Needs: human or agent review before treating as final operational knowledge
`
}
const urls = await discover(seed)
const outDir = path.join(ROOT, '.mnemazine/cache/site-ingest', slug(seed))
await fs.mkdir(outDir, { recursive: true })
const notes = []
for (const url of urls) {
const html = await fetchText(url, true)
if (!html.trim()) continue
const note = pageNote(url, html)
const file = `${new Date().toISOString().slice(0, 10)}-${slug(url)}.md`
const target = apply ? path.join(VAULT, '01 Concepts', file) : path.join(outDir, file)
await fs.mkdir(path.dirname(target), { recursive: true })
await fs.writeFile(target, note, 'utf8')
notes.push(target)
}
if (graphify) {
await import('node:child_process').then(({ spawnSync }) => spawnSync('graphify', ['update', VAULT], { stdio: 'inherit' }))
}
console.log(JSON.stringify({ seed, pages: urls.length, notes: notes.length, applied: apply, output: apply ? VAULT : outDir }, null, 2))
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import { existsSync } from 'node:fs'
import path from 'node:path'
import crypto from 'node:crypto'
import { spawnSync } from 'node:child_process'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')
const CACHE = path.join(ROOT, '.mnemazine/cache/processed-hashes.json')
async function ensureDir(dir) {
await fs.mkdir(dir, { recursive: true })
}
async function sha256(file) {
const hash = crypto.createHash('sha256')
hash.update(await fs.readFile(file))
return hash.digest('hex')
}
async function readJson(file, fallback) {
try { return JSON.parse(await fs.readFile(file, 'utf8')) } catch { return fallback }
}
function slugify(value) {
return String(value || 'note')
.toLowerCase()
.replace(/[^a-zа-я0-9]+/gi, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 80) || 'note'
}
async function extract(file) {
const ext = path.extname(file).toLowerCase()
if (['.md', '.txt', '.json', '.csv'].includes(ext)) return await fs.readFile(file, 'utf8')
const markitdown = spawnSync('markitdown', [file], { encoding: 'utf8' })
if (markitdown.status === 0 && markitdown.stdout.trim()) return markitdown.stdout
const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr')
if (existsSync(ocr) && ['.png', '.jpg', '.jpeg', '.heic', '.webp', '.tiff'].includes(ext)) {
const out = spawnSync(ocr, [file], { encoding: 'utf8' })
if (out.status === 0) return out.stdout
}
return ''
}
function makeNote(source, hash, text) {
const title = path.basename(source, path.extname(source)).replace(/[-_]+/g, ' ')
const clean = text.replace(/\s+/g, ' ').trim()
const summary = clean.slice(0, 1200) || 'No extractable text. Add manual context and rerun enrichment.'
return `# ${title}
## What This Is
${summary}
## Why It Matters
This note was created from a raw inbox item. Review it, verify source claims, and split it into smaller atoms if it contains multiple topics.
## Source
- File: ${path.basename(source)}
- SHA-256: ${hash}
## Verification
- Status: needs review
- Evidence: local source file
## Reuse
- Turn stable procedures into skills.
- Turn repeated decisions into checklists.
- Link related notes after Graphify update.
`
}
async function main() {
await ensureDir(INBOX)
await ensureDir(VAULT)
await ensureDir(path.dirname(CACHE))
const cache = await readJson(CACHE, {})
const entries = (await fs.readdir(INBOX, { withFileTypes: true })).filter(d => d.isFile())
let processed = 0
for (const entry of entries) {
const file = path.join(INBOX, entry.name)
const hash = await sha256(file)
if (cache[hash]) continue
const text = await extract(file)
const noteName = `${new Date().toISOString().slice(0, 10)}-${slugify(entry.name)}.md`
const notePath = path.join(VAULT, '01 Concepts', noteName)
await ensureDir(path.dirname(notePath))
await fs.writeFile(notePath, makeNote(file, hash, text), 'utf8')
cache[hash] = path.relative(VAULT, notePath)
processed += 1
}
await fs.writeFile(CACHE, JSON.stringify(cache, null, 2), 'utf8')
spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs')], { stdio: 'inherit', env: process.env })
if (spawnSync('graphify', ['--version'], { encoding: 'utf8' }).status === 0) {
spawnSync('graphify', ['update', VAULT], { stdio: 'inherit' })
}
console.log(JSON.stringify({ inbox: entries.length, processed, vault: VAULT }, null, 2))
}
main().catch(err => {
console.error(err)
process.exit(1)
})
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import path from 'node:path'
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 = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')))
const badMarkers = [
/raw\s+ocr/i,
/сырой\s+ocr/i,
/распознанный\s+текст\s+без\s+обработки/i,
/lorem ipsum/i,
/TODO:\s*rewrite/i,
/скриншот\s+без\s+контекста/i
]
async function walk(dir) {
const out = []
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
const p = path.join(dir, item.name)
if (item.isDirectory()) out.push(...await walk(p))
else if (item.isFile() && p.endsWith('.md')) out.push(p)
}
return out
}
const files = await walk(VAULT)
const failures = []
for (const file of files) {
const text = await fs.readFile(file, 'utf8')
const hit = badMarkers.find(re => re.test(text))
const hasSource = /## Source|## Источник|source:/i.test(text)
const hasMeaning = /## What This Is|## Что это|## Суть/i.test(text)
if (hit || !hasSource || !hasMeaning) {
failures.push({ file: path.relative(VAULT, file), marker: hit ? String(hit) : 'missing required sections' })
}
}
if (failures.length) {
console.error(JSON.stringify({ ok: false, failures }, null, 2))
process.exit(1)
}
console.log(JSON.stringify({ ok: true, checked: files.length }, null, 2))
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import path from 'node:path'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
async function walk(dir) {
const out = []
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
const p = path.join(dir, item.name)
if (item.isDirectory()) out.push(...await walk(p))
else if (item.isFile() && p.endsWith('.md')) out.push(p)
}
return out
}
function esc(s) {
return String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
}
function titleOf(text, file) {
return text.match(/^#\s+(.+)$/m)?.[1]?.trim() || path.basename(file, '.md')
}
function summaryOf(text) {
const block = text.match(/## (?:What This Is|Что это|Суть)\s+([\s\S]*?)(\n## |$)/i)?.[1] || text
return block.replace(/[#*_`>-]/g, '').replace(/\s+/g, ' ').trim().slice(0, 520)
}
await fs.mkdir(REPORTS, { recursive: true })
await fs.mkdir(STATE, { recursive: true })
const files = await walk(VAULT)
const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
const cards = []
for (const file of files) {
const stat = await fs.stat(file)
if (stat.mtimeMs < weekAgo) continue
const text = await fs.readFile(file, 'utf8')
cards.push({ file: path.relative(VAULT, file), title: titleOf(text, file), summary: summaryOf(text) })
}
const html = `<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mnemazine Weekly</title>
<style>
:root{--blue:#0039a6;--red:#d52b1e;--ink:#111827;--muted:#667085;--line:#e5e7eb;--bg:#f8fafc}
*{box-sizing:border-box}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:var(--bg);color:var(--ink)}
header{min-height:48vh;padding:56px max(24px,8vw);background:linear-gradient(180deg,#fff 0 32%,var(--blue) 32% 66%,var(--red) 66%);color:white;display:flex;align-items:end}
.hero{max-width:980px;text-shadow:0 1px 24px rgba(0,0,0,.22)}h1{font-size:clamp(42px,7vw,92px);line-height:.95;margin:0 0 18px;letter-spacing:0}.lead{font-size:22px;max-width:760px;margin:0;color:#fff}
main{padding:34px max(18px,6vw) 70px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px}
.card{background:#fff;border:1px solid var(--line);border-radius:8px;padding:20px;box-shadow:0 10px 28px rgba(17,24,39,.06)}
.path{font-size:12px;color:var(--muted);margin-bottom:10px}.card h2{font-size:20px;line-height:1.18;margin:0 0 10px}.card p{font-size:15px;line-height:1.55;color:#344054}
.actions{display:flex;gap:8px;margin-top:16px}.actions button{border:1px solid var(--line);background:#fff;border-radius:7px;padding:9px 10px;font-weight:650;cursor:pointer}.actions button[data-v=read]{color:var(--blue)}.actions button[data-v=work]{color:var(--red)}.actions button[data-v=forget]{color:#475467}
.actions button.active{background:var(--ink);color:white;border-color:var(--ink)}
</style>
</head>
<body>
<header><section class="hero"><h1>Mnemazine Weekly</h1><p class="lead">Сводка знаний за последние 7 дней: что появилось, что стоит взять в работу, что можно забыть.</p></section></header>
<main><section class="grid">
${cards.map((c, i) => `<article class="card" data-id="${esc(c.file)}"><div class="path">${esc(c.file)}</div><h2>${esc(c.title)}</h2><p>${esc(c.summary)}</p><div class="actions"><button data-v="read">Прочитал</button><button data-v="work">В работу</button><button data-v="forget">Забыть</button></div></article>`).join('\n') || '<article class="card"><h2>За неделю новых заметок нет</h2><p>Положите материалы в inbox и запустите Mnemazine.</p></article>'}
</section></main>
<script>
const KEY='mnemazine-weekly-state';
const state=JSON.parse(localStorage.getItem(KEY)||'{}');
document.querySelectorAll('.card').forEach(card=>{
const id=card.dataset.id;
card.querySelectorAll('button').forEach(btn=>{
if(state[id]===btn.dataset.v) btn.classList.add('active');
btn.onclick=()=>{state[id]=btn.dataset.v;localStorage.setItem(KEY,JSON.stringify(state));card.querySelectorAll('button').forEach(b=>b.classList.remove('active'));btn.classList.add('active')}
})
})
</script>
</body></html>`
const out = path.join(REPORTS, `${new Date().toISOString().slice(0, 10)}-weekly-mnemazine.html`)
await fs.writeFile(out, html, 'utf8')
await fs.writeFile(path.join(STATE, 'weekly-state.example.json'), JSON.stringify({ note: 'Browser localStorage stores per-card state by default.' }, null, 2), 'utf8')
console.log(out)