Merge pull request #3 from zarubinphil/feat/kb-search
feat(search): vault search swarm + Mini App button
This commit is contained in:
+29
@@ -67,3 +67,32 @@ echo "Root: $ROOT"
|
||||
echo "Inbox: $INBOX"
|
||||
echo "Vault: $VAULT"
|
||||
echo "Open the vault folder in Obsidian."
|
||||
|
||||
cat <<'EOF'
|
||||
|
||||
────────────────────────────────────────────────────────────
|
||||
Привет! Это Philipp — автор Мнемазины.
|
||||
|
||||
Спасибо, что ставите мою разработку. Я делал её, чтобы сырьё
|
||||
превращалось в проверенное, готовое к работе знание — и рад,
|
||||
что теперь она будет помогать и вам.
|
||||
|
||||
★ Если зашло — поставьте звезду на GitHub, мне это правда важно:
|
||||
https://github.com/zarubinphil/Mnemazine
|
||||
💡 Есть идея, как сделать лучше? Откройте issue или PR —
|
||||
предлагайте улучшения, я читаю каждое.
|
||||
|
||||
— — —
|
||||
|
||||
Hi! This is Philipp — the author of Mnemazine.
|
||||
|
||||
Thank you for installing my project. I built it to turn raw
|
||||
input into verified, ready-to-use knowledge — glad it will now
|
||||
help you too.
|
||||
|
||||
★ If you like it, please star it on GitHub — it truly helps:
|
||||
https://github.com/zarubinphil/Mnemazine
|
||||
💡 Got an idea to make it better? Open an issue or PR —
|
||||
improvements are always welcome, I read every one.
|
||||
────────────────────────────────────────────────────────────
|
||||
EOF
|
||||
|
||||
@@ -10,10 +10,14 @@
|
||||
"graph:refresh": "node scripts/mnemazine-refresh-graphify.mjs --json",
|
||||
"graph:shards": "node scripts/mnemazine-semantic-shards.mjs",
|
||||
"graph:semantic-batches": "node scripts/mnemazine-semantic-batches.mjs",
|
||||
"graph:semantic-swarm": "node scripts/mnemazine-semantic-swarm.mjs",
|
||||
"graph:merge-semantic-shards": "node scripts/mnemazine-merge-semantic-shards.mjs",
|
||||
"graph:clean": "python3 scripts/graphify_clean.py",
|
||||
"graph:smoke": "node scripts/mnemazine-refresh-graphify-smoke.mjs",
|
||||
"ingest:site": "node scripts/mnemazine-ingest-site.mjs",
|
||||
"synthesize": "node scripts/mnemazine-synthesize.mjs",
|
||||
"search": "node scripts/mnemazine-kb-search.mjs",
|
||||
"search:eval": "node tests/search-eval.mjs",
|
||||
"weekly": "node scripts/mnemazine-weekly-brief-html.mjs",
|
||||
"weekly:state": "node scripts/mnemazine-weekly-state.mjs",
|
||||
"digest": "node scripts/mnemazine-digest.mjs",
|
||||
|
||||
@@ -4,7 +4,9 @@ set -euo pipefail
|
||||
ROOT="${1:-$(cd "$(dirname "$0")/.." && pwd)}"
|
||||
|
||||
# Private markers (machine paths, IPs, personal/project names) that must never ship publicly.
|
||||
PRIVATE_MARKERS='/Users/fil|72\.56|root@|Полезные знания|_ВХОДЯЩИЕ|TODOCUPS|ПКК|legal-practice|Adventure Book|AthenaOS|Филипп'
|
||||
# `root@` requires a real host char after it (lowercase/digit) so the literal
|
||||
# placeholder `root@YOUR_VPS_HOST` in docs/examples is not a false positive.
|
||||
PRIVATE_MARKERS='/Users/fil|72\.56|root@[a-z0-9]|Полезные знания|_ВХОДЯЩИЕ|TODOCUPS|ПКК|legal-practice|Adventure Book|AthenaOS|Филипп'
|
||||
# Token-like values across common providers. Require realistic lengths and a
|
||||
# non-word boundary before `sk-` to avoid false positives like `risk-or-x`.
|
||||
# Covers: GitHub OAuth/PAT (gho_/ghp_/ghu_/ghs_/ghr_), OpenAI/Anthropic sk-,
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
#!/usr/bin/env node
|
||||
// KB topic search — an orchestrator-led agent swarm over the live vault.
|
||||
// Pipeline (mirrors the swarm playbook: recon -> fan-out -> fan-in):
|
||||
// 1. RECON (0 tokens): keyword-score every note, keep the top candidates.
|
||||
// --deep also asks the orchestrator to widen the query first.
|
||||
// 2. FAN-OUT (swarm): shard candidates; a bounded pool of agents reads each
|
||||
// shard and returns findings (note / source / insight / relevance).
|
||||
// Workers write to a shared store (the result), never chat. One
|
||||
// failing worker never blocks the swarm (inner+outer try/catch).
|
||||
// 3. FAN-IN (synthesis): the orchestrator dedups + synthesizes findings into
|
||||
// a Russian "Справка" report. Generator != evaluator — workers
|
||||
// extract, the orchestrator judges and writes.
|
||||
// node scripts/mnemazine-kb-search.mjs --topic "..." [--vault <p>] [--deep]
|
||||
// Default is conservative (0 tokens, local extract). --deep / MNEMAZINE_DEEP=1
|
||||
// engages the LLM swarm. Report written to reports/ as Markdown; path printed.
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const SELFTEST = argv.includes('--selftest')
|
||||
function arg(name, fb = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fb
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fb
|
||||
}
|
||||
|
||||
const DEEP = argv.includes('--deep') || process.env.MNEMAZINE_DEEP === '1'
|
||||
const PROVIDER = arg('provider', process.env.MNEMAZINE_LLM || 'claude')
|
||||
const CONCURRENCY = Number(arg('concurrency', process.env.MNEMAZINE_CONCURRENCY || '4'))
|
||||
const MAX_NOTES = Number(arg('max-notes', '60')) // candidate cap fed to the swarm
|
||||
const SHARD_SIZE = Number(arg('shard-size', '6')) // notes per agent
|
||||
const MAX_SHARDS = Number(arg('max-shards', process.env.MNEMAZINE_SEARCH_MAX_SHARDS || '12')) // deep cost cap: hard limit on agents spawned
|
||||
const EXCERPT = 2500 // chars of each note shown to an agent
|
||||
// 2B perspective-diverse verify: opt-in (extra K agents). Default OFF to keep
|
||||
// the token budget tight — enable when groundedness matters. One call per
|
||||
// top-K finding, judging 3 lenses at once (grounded/relevant/actionable).
|
||||
const VERIFY = argv.includes('--verify') || process.env.MNEMAZINE_SEARCH_VERIFY === '1'
|
||||
const MAX_VERIFY = Number(arg('max-verify', '5')) // top-K findings to verify
|
||||
|
||||
// --- helpers -----------------------------------------------------------------
|
||||
async function walk(dir, out = []) {
|
||||
for (const e of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (e.name.startsWith('.')) continue
|
||||
const full = path.join(dir, e.name)
|
||||
if (e.isDirectory()) await walk(full, out)
|
||||
else if (e.name.endsWith('.md')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const STOP = new Set(['the', 'and', 'для', 'что', 'как', 'это', 'про', 'или', 'был', 'are', 'with', 'из', 'на', 'по', 'не', 'от'])
|
||||
const tokens = s => (String(s).toLowerCase().match(/[\p{L}\p{N}]{3,}/gu) || []).filter(t => !STOP.has(t))
|
||||
|
||||
function scoreNote(text, rel, terms) {
|
||||
const hay = (rel + '\n' + text).toLowerCase()
|
||||
let score = 0
|
||||
for (const t of terms) {
|
||||
let from = 0, n = 0
|
||||
while ((from = hay.indexOf(t, from)) !== -1) { n++; from += t.length; if (n >= 8) break }
|
||||
score += n
|
||||
if (rel.toLowerCase().includes(t)) score += 4 // title/path hit weighs more
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
// Pull a few keyword-centered snippets — the local (0-token) "finding".
|
||||
function snippets(text, terms, max = 3) {
|
||||
const out = []
|
||||
const lower = text.toLowerCase()
|
||||
for (const t of terms) {
|
||||
const i = lower.indexOf(t)
|
||||
if (i === -1) continue
|
||||
const s = Math.max(0, i - 120), e = Math.min(text.length, i + 200)
|
||||
const snip = text.slice(s, e).replace(/\s+/g, ' ').trim()
|
||||
if (snip && !out.includes(snip)) out.push(snip)
|
||||
if (out.length >= max) break
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Bounded-concurrency pool — the swarm. One failing task never blocks the rest.
|
||||
async function mapLimit(items, limit, fn) {
|
||||
let i = 0
|
||||
const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length || 1)) }, async () => {
|
||||
while (i < items.length) { const idx = i++; await fn(items[idx], idx) }
|
||||
})
|
||||
await Promise.all(workers)
|
||||
}
|
||||
|
||||
const FINDINGS_SCHEMA = {
|
||||
type: 'object', additionalProperties: false, required: ['findings'],
|
||||
properties: {
|
||||
findings: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object', additionalProperties: false,
|
||||
required: ['note', 'insight', 'relevance'],
|
||||
properties: {
|
||||
note: { type: 'string' },
|
||||
source: { type: 'string' },
|
||||
insight: { type: 'string' },
|
||||
relevance: { type: 'integer', minimum: 1, maximum: 5 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const SYNTH_SCHEMA = {
|
||||
type: 'object', additionalProperties: false,
|
||||
required: ['summary', 'themes', 'gaps'],
|
||||
properties: {
|
||||
summary: { type: 'string' },
|
||||
themes: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object', additionalProperties: false, required: ['title', 'points'],
|
||||
properties: { title: { type: 'string' }, points: { type: 'array', items: { type: 'string' } } }
|
||||
}
|
||||
},
|
||||
connections: { type: 'array', items: { type: 'string' } },
|
||||
contradictions: { type: 'array', items: { type: 'string' } },
|
||||
gaps: { type: 'array', items: { type: 'string' } },
|
||||
next: { type: 'array', items: { type: 'string' } }
|
||||
}
|
||||
}
|
||||
|
||||
const VERDICT_SCHEMA = {
|
||||
type: 'object', additionalProperties: false,
|
||||
required: ['grounded', 'relevant', 'actionable'],
|
||||
properties: {
|
||||
grounded: { type: 'boolean' }, relevant: { type: 'boolean' },
|
||||
actionable: { type: 'boolean' }, reason: { type: 'string' }
|
||||
}
|
||||
}
|
||||
|
||||
// --- orchestrator: plan the query (deep only) --------------------------------
|
||||
// 2A: one call returns BOTH search terms AND 2-4 facets (the real axes of THIS
|
||||
// query). Facets steer 0-token recon routing, shard-agent focus, and synthesis
|
||||
// themes — perspective diversity for ~free (no extra agents). Local mode skips
|
||||
// it and stays 0-token (facets:[]).
|
||||
async function plan(topic) {
|
||||
if (!DEEP || !llmAvailable(PROVIDER)) return { terms: tokens(topic), facets: [] }
|
||||
try {
|
||||
const out = await llmJson(
|
||||
`Тема поиска по базе знаний: "${topic}".
|
||||
1) terms: ключевые слова и синонимы (рус+англ) для полнотекстового поиска — плоский список.
|
||||
2) facets: 2-4 РЕАЛЬНЫЕ оси/под-вопроса именно этой темы (не общие "плюсы/минусы"). Для каждой: label (короткое имя оси) и terms (свои ключевые слова оси).`,
|
||||
{
|
||||
type: 'object', additionalProperties: false, required: ['terms', 'facets'],
|
||||
properties: {
|
||||
terms: { type: 'array', items: { type: 'string' } },
|
||||
facets: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object', additionalProperties: false, required: ['label', 'terms'],
|
||||
properties: { label: { type: 'string' }, terms: { type: 'array', items: { type: 'string' } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{ provider: PROVIDER }
|
||||
)
|
||||
const terms = new Set(tokens(topic))
|
||||
for (const t of out.terms || []) for (const w of tokens(t)) terms.add(w)
|
||||
const facets = (out.facets || []).slice(0, 4)
|
||||
.map(f => ({ label: String(f.label || '').trim(), terms: [...new Set((f.terms || []).flatMap(tokens))] }))
|
||||
.filter(f => f.label && f.terms.length)
|
||||
for (const f of facets) for (const w of f.terms) terms.add(w)
|
||||
return { terms: [...terms], facets }
|
||||
} catch (e) {
|
||||
console.error(`[kb-search] query planning failed: ${e.message}; using raw terms`)
|
||||
return { terms: tokens(topic), facets: [] }
|
||||
}
|
||||
}
|
||||
|
||||
// Assign a candidate note to its best-matching facet (max facet-term hits).
|
||||
// 0-token. Returns facet label or 'Общее' when no facet wins.
|
||||
function assignFacet(note, facets) {
|
||||
if (!facets.length) return null
|
||||
const hay = (note.rel + '\n' + note.text).toLowerCase()
|
||||
let best = null, bestN = 0
|
||||
for (const f of facets) {
|
||||
let n = 0
|
||||
for (const t of f.terms) if (hay.includes(t)) n++
|
||||
if (n > bestN) { bestN = n; best = f.label }
|
||||
}
|
||||
return best || 'Общее'
|
||||
}
|
||||
|
||||
// --- worker: extract findings from one shard ---------------------------------
|
||||
async function extractShard(topic, shard, facet) {
|
||||
if (DEEP && llmAvailable(PROVIDER)) {
|
||||
const blob = shard.map(n =>
|
||||
fenceUntrusted('NOTE', `### ${n.rel}\n${n.text.slice(0, EXCERPT)}`)).join('\n\n')
|
||||
const focus = facet ? `\nФокус-ось этого шарда: «${facet}» — приоритет находкам по этой оси (но не пропускай иное важное по теме).` : ''
|
||||
const prompt = `Ты агент-исследователь. Тема: "${topic}".${focus}
|
||||
Из заметок ниже выбери ТОЛЬКО релевантное теме. Для каждой находки: note (путь заметки), source (URL/ссылка из заметки, если есть), insight (1-2 предложения по-русски — что важного для темы), relevance (1-5). Ничего не выдумывай сверх заметок.
|
||||
|
||||
${blob}`
|
||||
try {
|
||||
const out = await llmJson(prompt, FINDINGS_SCHEMA, { provider: PROVIDER, tools: [] })
|
||||
return (out.findings || []).filter(f => f.insight && f.relevance >= 2)
|
||||
} catch (e) {
|
||||
console.error(`[kb-search] shard agent failed: ${e.message}; local fallback`)
|
||||
}
|
||||
}
|
||||
// Local (0-token) fallback: snippet extraction.
|
||||
const terms = tokens(topic)
|
||||
return shard.flatMap(n => {
|
||||
const snips = snippets(n.text, terms)
|
||||
return snips.length ? [{ note: n.rel, source: n.url || '', insight: snips.join(' … '), relevance: Math.min(5, 2 + Math.floor(n.score / 4)) }] : []
|
||||
})
|
||||
}
|
||||
|
||||
// --- verify (2B): perspective-diverse check on the top-K findings ------------
|
||||
// One agent per finding, judging 3 lenses at once (grounded/relevant/actionable)
|
||||
// against the note's own text. Bounded (K calls). Drops ungrounded findings —
|
||||
// the anti-hallucination gate (§6 claim->content). Opt-in via VERIFY.
|
||||
async function verifyFindings(topic, findings, textByNote) {
|
||||
if (!VERIFY || !DEEP || !llmAvailable(PROVIDER) || !findings.length) return { kept: findings, dropped: 0 }
|
||||
const top = findings.slice(0, MAX_VERIFY)
|
||||
const rest = findings.slice(MAX_VERIFY)
|
||||
const verdicts = []
|
||||
await mapLimit(top, CONCURRENCY, async (f, idx) => {
|
||||
const note = textByNote.get(f.note) || ''
|
||||
const prompt = `Тема: "${topic}". Находка из заметки «${f.note}»:
|
||||
"${f.insight}"
|
||||
Оцени по 3 осям относительно текста заметки ниже: grounded (находка реально опирается на текст, не выдумана), relevant (по теме), actionable (полезна на практике). Верни булевы + reason.
|
||||
|
||||
${fenceUntrusted('NOTE', note.slice(0, EXCERPT))}`
|
||||
try { verdicts[idx] = await llmJson(prompt, VERDICT_SCHEMA, { provider: PROVIDER, tools: [] }) }
|
||||
catch (e) { console.error(`[kb-search] verify failed for ${f.note}: ${e.message}; keeping finding`); verdicts[idx] = { grounded: true, relevant: true, actionable: true } }
|
||||
})
|
||||
const kept = top.filter((_, i) => verdicts[i]?.grounded !== false).concat(rest)
|
||||
return { kept, dropped: top.length - (kept.length - rest.length) }
|
||||
}
|
||||
|
||||
// --- orchestrator: synthesize findings into a report -------------------------
|
||||
async function synthesize(topic, findings, facets = []) {
|
||||
if (DEEP && llmAvailable(PROVIDER) && findings.length) {
|
||||
const blob = findings.map(f => `- [${f.note}] (rel ${f.relevance}) ${f.insight}${f.source ? ` <${f.source}>` : ''}`).join('\n')
|
||||
const axes = facets.length ? `\nСгруппируй по этим осям темы (themes), в этом порядке: ${facets.map(f => f.label).join(', ')}. Добавь иную ось только если находки не лезут ни в одну.` : ''
|
||||
const prompt = `Ты оркестратор. Собери из находок агентов справку по теме "${topic}" на РУССКОМ, стиль humanizer — живо, ясно, по делу, без воды и канцелярита. Дедуплицируй, сгруппируй по под-темам (themes), отметь связи (connections), противоречия (contradictions), пробелы знаний (gaps) и следующие шаги (next). Не выдумывай сверх находок.${axes}
|
||||
|
||||
Находки:
|
||||
${blob}`
|
||||
try { return await llmJson(prompt, SYNTH_SCHEMA, { provider: PROVIDER }) }
|
||||
catch (e) { console.error(`[kb-search] synthesis failed: ${e.message}; local assembly`) }
|
||||
}
|
||||
// Local assembly: group by note, no LLM.
|
||||
const byNote = new Map()
|
||||
for (const f of findings) {
|
||||
if (!byNote.has(f.note)) byNote.set(f.note, [])
|
||||
byNote.get(f.note).push(f.insight)
|
||||
}
|
||||
const themes = [...byNote.entries()]
|
||||
.sort((a, b) => b[1].length - a[1].length)
|
||||
.slice(0, 12)
|
||||
.map(([note, points]) => ({ title: note, points: [...new Set(points)] }))
|
||||
return {
|
||||
summary: `Найдено ${findings.length} совпадений в ${byNote.size} заметках по теме «${topic}» (локальный поиск без LLM).`,
|
||||
themes, connections: [], contradictions: [], gaps: [], next: []
|
||||
}
|
||||
}
|
||||
|
||||
// --- report rendering --------------------------------------------------------
|
||||
function slugify(s) { return String(s).toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'topic' }
|
||||
|
||||
function renderReport(topic, report, meta) {
|
||||
const L = []
|
||||
L.push(`# Справка: ${topic}`, '')
|
||||
L.push(`> Поиск по базе знаний · ${meta.stamp} · просмотрено ${meta.scanned} заметок, отобрано ${meta.candidates}, находок ${meta.findings} · режим: ${meta.deep ? 'рой агентов (deep)' : 'локальный'}`, '')
|
||||
if (meta.facets?.length) L.push(`> Оси разбора: ${meta.facets.join(' · ')}`, '')
|
||||
if (meta.droppedNotes) L.push(`> ⚠️ Лимит стоимости: ${meta.droppedNotes} заметок-кандидатов не разобраны (--max-shards). Подними лимит для полного охвата.`, '')
|
||||
if (meta.droppedByVerify) L.push(`> 🔎 Verify: ${meta.droppedByVerify} находок отброшено как необоснованные.`, '')
|
||||
L.push('## Главное', '', report.summary || '—', '')
|
||||
if (report.themes?.length) {
|
||||
L.push('## По под-темам', '')
|
||||
for (const t of report.themes) {
|
||||
L.push(`### ${t.title}`)
|
||||
for (const p of t.points || []) L.push(`- ${p}`)
|
||||
L.push('')
|
||||
}
|
||||
}
|
||||
const block = (title, arr) => { if (arr?.length) { L.push(`## ${title}`, ''); for (const x of arr) L.push(`- ${x}`); L.push('') } }
|
||||
block('Связи', report.connections)
|
||||
block('Противоречия', report.contradictions)
|
||||
block('Пробелы', report.gaps)
|
||||
block('Дальше', report.next)
|
||||
return L.join('\n')
|
||||
}
|
||||
|
||||
// --- main --------------------------------------------------------------------
|
||||
async function run(topic, vault, outDir) {
|
||||
const stamp = new Date().toISOString()
|
||||
const { terms, facets } = await plan(topic)
|
||||
// RECON
|
||||
const files = await walk(vault)
|
||||
const scored = []
|
||||
for (const f of files) {
|
||||
const text = await fs.readFile(f, 'utf8').catch(() => '')
|
||||
if (!text) continue
|
||||
const rel = path.relative(vault, f)
|
||||
const score = scoreNote(text, rel, terms)
|
||||
if (score > 0) scored.push({ rel, text, score, url: text.match(/https?:\/\/\S+/)?.[0] || '' })
|
||||
}
|
||||
scored.sort((a, b) => b.score - a.score)
|
||||
const candidates = scored.slice(0, MAX_NOTES)
|
||||
// FAN-OUT — shard within facet groups so each shard carries one focus axis
|
||||
// (2A). No facets (local / planning failed) → flat sharding as before.
|
||||
let shards = [] // each: { notes:[...], facet }
|
||||
if (facets.length) {
|
||||
const groups = new Map()
|
||||
for (const c of candidates) {
|
||||
const f = assignFacet(c, facets)
|
||||
if (!groups.has(f)) groups.set(f, [])
|
||||
groups.get(f).push(c)
|
||||
}
|
||||
for (const [facet, notes] of groups)
|
||||
for (let i = 0; i < notes.length; i += SHARD_SIZE) shards.push({ notes: notes.slice(i, i + SHARD_SIZE), facet })
|
||||
} else {
|
||||
for (let i = 0; i < candidates.length; i += SHARD_SIZE) shards.push({ notes: candidates.slice(i, i + SHARD_SIZE), facet: null })
|
||||
}
|
||||
// Cost cap (deep only): fail-closed on the number of agents spawned. Local
|
||||
// mode is 0-token, so it is uncapped. Dropped shards are logged, never silent.
|
||||
let droppedNotes = 0
|
||||
if (DEEP && llmAvailable(PROVIDER) && shards.length > MAX_SHARDS) {
|
||||
droppedNotes = shards.slice(MAX_SHARDS).reduce((n, s) => n + s.notes.length, 0)
|
||||
console.error(`[kb-search] cost cap: ${shards.length} shards > MNEMAZINE_SEARCH_MAX_SHARDS=${MAX_SHARDS}; dropping ${shards.length - MAX_SHARDS} shards (${droppedNotes} notes). Raise --max-shards to cover more.`)
|
||||
shards = shards.slice(0, MAX_SHARDS)
|
||||
}
|
||||
const findings = []
|
||||
await mapLimit(shards, DEEP ? CONCURRENCY : 1, async shard => {
|
||||
try { findings.push(...await extractShard(topic, shard.notes, shard.facet)) }
|
||||
catch (e) { console.error(`[kb-search] shard failed: ${e.message}`) }
|
||||
})
|
||||
findings.sort((a, b) => (b.relevance || 0) - (a.relevance || 0))
|
||||
// VERIFY (2B, opt-in): drop ungrounded top findings before synthesis.
|
||||
const textByNote = new Map(candidates.map(c => [c.rel, c.text]))
|
||||
const { kept, dropped: droppedByVerify } = await verifyFindings(topic, findings, textByNote)
|
||||
// FAN-IN
|
||||
const report = await synthesize(topic, kept, facets)
|
||||
const md = renderReport(topic, report, { stamp, scanned: files.length, candidates: candidates.length, findings: kept.length, deep: DEEP && llmAvailable(PROVIDER), droppedNotes, droppedByVerify, facets: facets.map(f => f.label) })
|
||||
await fs.mkdir(outDir, { recursive: true })
|
||||
const out = path.join(outDir, `search-${slugify(topic)}-${stamp.slice(0, 10)}-${Date.now()}.md`)
|
||||
await fs.writeFile(out, md, 'utf8')
|
||||
return out
|
||||
}
|
||||
|
||||
async function selftest() {
|
||||
const assert = (c, m) => { if (!c) throw new Error(`selftest: ${m}`) }
|
||||
const tmp = await fs.mkdtemp(path.join((await import('node:os')).tmpdir(), 'kbsearch-'))
|
||||
const vault = path.join(tmp, 'vault'); await fs.mkdir(vault, { recursive: true })
|
||||
await fs.writeFile(path.join(vault, 'harness.md'), '# Agent harness\nСреда важнее модели. Контекст это бюджет. https://example.com/x', 'utf8')
|
||||
await fs.writeFile(path.join(vault, 'coffee.md'), '# Кофе\nЭспрессо и молоко.', 'utf8')
|
||||
const out = await run('agent harness контекст', vault, path.join(tmp, 'reports'))
|
||||
const md = await fs.readFile(out, 'utf8')
|
||||
assert(md.includes('Справка:'), 'report has header')
|
||||
assert(md.includes('harness.md'), 'relevant note surfaced')
|
||||
assert(!md.includes('coffee.md'), 'irrelevant note excluded')
|
||||
assert(!md.includes('Лимит стоимости'), 'no cost-cap warning when nothing dropped')
|
||||
const capped = renderReport('x', { summary: 's', themes: [] }, { stamp: 'now', scanned: 1, candidates: 1, findings: 1, deep: true, droppedNotes: 18 })
|
||||
assert(capped.includes('Лимит стоимости') && capped.includes('18'), 'cost-cap warning surfaced when shards dropped')
|
||||
await fs.rm(tmp, { recursive: true, force: true })
|
||||
console.log('selftest ok')
|
||||
}
|
||||
|
||||
if (SELFTEST) {
|
||||
selftest().catch(e => { console.error(e.message); process.exit(1) })
|
||||
} else {
|
||||
const topic = arg('topic') || argv.find(a => !a.startsWith('--'))
|
||||
if (!topic) { console.error('Usage: mnemazine-kb-search.mjs --topic "<тема>" [--deep] [--vault <p>]'); process.exit(1) }
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const outDir = path.resolve(arg('out', process.env.MNEMAZINE_REPORTS || path.join(process.cwd(), 'reports')))
|
||||
run(topic, vault, outDir)
|
||||
.then(p => console.log(p))
|
||||
.catch(e => { console.error(`[kb-search] ${e.message}`); process.exit(1) })
|
||||
}
|
||||
@@ -56,6 +56,7 @@ async function checkSyntax() {
|
||||
'scripts/mnemazine-semantic-shards.mjs',
|
||||
'scripts/mnemazine-semantic-batches.mjs',
|
||||
'scripts/mnemazine-synthesize.mjs',
|
||||
'scripts/mnemazine-kb-search.mjs',
|
||||
'scripts/mnemazine-llm.mjs',
|
||||
'scripts/mnemazine-codex.mjs',
|
||||
'scripts/mnemazine-verify.mjs',
|
||||
@@ -174,6 +175,13 @@ async function reportQualityGateSmoke() {
|
||||
await must('report quality gate smoke:good', process.execPath, ['scripts/mnemazine-report-quality-gate.mjs', '--report', good])
|
||||
}
|
||||
|
||||
async function searchEvalSmoke() {
|
||||
// Tier A only (0 tokens): recall/anti-noise of the KB search skill. Tier B
|
||||
// (LLM judge) is opt-in via `npm run search:eval -- --deep`, not in the gate.
|
||||
await must('kb-search selftest', process.execPath, ['scripts/mnemazine-kb-search.mjs', '--selftest'])
|
||||
await must('kb-search eval (Tier A)', process.execPath, ['tests/search-eval.mjs'])
|
||||
}
|
||||
|
||||
async function repoMetadataCheck() {
|
||||
const pkg = await readJson(path.join(ROOT, 'package.json'))
|
||||
if (!pkg.description || !/[А-Яа-яЁё]/.test(pkg.description) || !/[A-Za-z]/.test(pkg.description)) {
|
||||
@@ -211,6 +219,7 @@ async function main() {
|
||||
['syntax', checkSyntax],
|
||||
['demo-smoke', demoSmoke],
|
||||
['quality-public', qualityAndPublicChecks],
|
||||
['search-eval', searchEvalSmoke],
|
||||
['repo-metadata', repoMetadataCheck]
|
||||
]
|
||||
const passed = []
|
||||
|
||||
@@ -11,6 +11,7 @@ REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
|
||||
VPS="${MNEMAZINE_VPS:-root@YOUR_VPS_HOST}"
|
||||
KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}"
|
||||
REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-/var/www/mnemazine-inbox}"
|
||||
REMOTE_REPORTS="${MNEMAZINE_REMOTE_REPORTS:-/var/www/mnemazine-reports}"
|
||||
|
||||
# ponytail: fail fast if still on the placeholder — beats a confusing ssh error.
|
||||
if [ "$VPS" = "root@YOUR_VPS_HOST" ]; then
|
||||
@@ -28,6 +29,20 @@ LOCK="$REPO/.mnemazine/poll.lock"
|
||||
if ! mkdir "$LOCK" 2>/dev/null; then exit 0; fi # previous tick still running
|
||||
trap 'rmdir "$LOCK" 2>/dev/null' EXIT
|
||||
|
||||
# Search queue (vault is Mac-only, so searches run here). Drain atomically:
|
||||
# cat + truncate in one ssh. Each line is a JSON {topic}; parse safely in node.
|
||||
queue="$($SSH "$VPS" "f=$REMOTE_INBOX/.search-queue; if [ -f \"\$f\" ]; then cat \"\$f\"; : > \"\$f\"; fi" 2>/dev/null || true)"
|
||||
if [ -n "$queue" ]; then
|
||||
topics="$(printf '%s' "$queue" | node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{for(const l of d.split("\n")){if(!l.trim())continue;try{const t=JSON.parse(l).topic;if(t)process.stdout.write(t.replace(/\n/g," ")+"\n")}catch{}}})' 2>/dev/null || true)"
|
||||
cd "$REPO"
|
||||
while IFS= read -r topic; do
|
||||
[ -z "$topic" ] && continue
|
||||
MNEMAZINE_DEEP=1 npm run --silent search -- --topic "$topic" || echo "search failed: $topic" >&2
|
||||
done <<< "$topics"
|
||||
# Push reports back so the mini app can read them (reverse channel Mac->VPS).
|
||||
[ -d "$REPO/reports" ] && rsync -az -e "$SSH" "$REPO/reports/" "$VPS:$REMOTE_REPORTS/" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
run=0; manual=0
|
||||
# Consume run-now flag atomically: print + delete in one ssh.
|
||||
flag="$($SSH "$VPS" "f=$REMOTE_INBOX/.run-now; if [ -f \"\$f\" ]; then cat \"\$f\"; rm -f \"\$f\"; fi" 2>/dev/null || true)"
|
||||
|
||||
@@ -19,6 +19,9 @@ if (!TOKEN && !SELFTEST) { console.error('FATAL: TELEGRAM_BOT_TOKEN not set'); p
|
||||
const INBOX = path.resolve(process.env.MNEMAZINE_INBOX || path.join(process.cwd(), 'inbox'))
|
||||
const RUN_FLAG = path.join(INBOX, '.run-now')
|
||||
const RUN_MARKER = path.join(INBOX, '.last-run')
|
||||
const SEARCH_QUEUE = path.join(INBOX, '.search-queue')
|
||||
// Reports are produced on the Mac (vault is local there) and rsynced here.
|
||||
const REPORTS = path.resolve(process.env.MNEMAZINE_REPORTS || path.join(process.cwd(), 'reports'))
|
||||
const PORT = Number(process.env.PORT || 8787)
|
||||
const ALLOWED = (process.env.ALLOWED_CHAT_IDS || '').split(',').map(s => s.trim()).filter(Boolean)
|
||||
const throttle = new Map() // user.id -> last write ms
|
||||
@@ -85,6 +88,32 @@ async function send(text) {
|
||||
return name
|
||||
}
|
||||
|
||||
// Queue a topic search. Vault lives on the Mac, so the VPS can only enqueue;
|
||||
// the Mac poller drains this, runs the swarm, and rsyncs reports back here.
|
||||
async function queueSearch(topic, user) {
|
||||
await fs.mkdir(INBOX, { recursive: true })
|
||||
const line = JSON.stringify({ topic, by: user, at: new Date().toISOString() }) + '\n'
|
||||
await fs.appendFile(SEARCH_QUEUE, line, 'utf8')
|
||||
}
|
||||
|
||||
async function listReports() {
|
||||
const names = (await fs.readdir(REPORTS).catch(() => [])).filter(n => n.endsWith('.md'))
|
||||
const out = []
|
||||
for (const n of names.sort().reverse().slice(0, 20)) {
|
||||
const st = await fs.stat(path.join(REPORTS, n)).catch(() => null)
|
||||
if (st) out.push({ name: n, at: st.mtime.toISOString() })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
async function readReport(name) {
|
||||
// Path-escape guard: only a bare *.md filename inside REPORTS, no traversal.
|
||||
if (!name || name !== path.basename(name) || !name.endsWith('.md')) return null
|
||||
const full = path.join(REPORTS, name)
|
||||
if (path.dirname(full) !== REPORTS) return null
|
||||
return fs.readFile(full, 'utf8').catch(() => null)
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
try {
|
||||
const url = new URL(req.url, 'http://localhost')
|
||||
@@ -107,6 +136,18 @@ const server = http.createServer(async (req, res) => {
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && url.pathname === '/api/status') return json(res, 200, await status())
|
||||
if (req.method === 'GET' && url.pathname === '/api/searches') return json(res, 200, { reports: await listReports() })
|
||||
if (req.method === 'GET' && url.pathname === '/api/search') {
|
||||
const md = await readReport(url.searchParams.get('name') || '')
|
||||
if (md == null) return json(res, 404, { error: 'not found' })
|
||||
return json(res, 200, { markdown: md })
|
||||
}
|
||||
if (req.method === 'POST' && url.pathname === '/api/search') {
|
||||
const { topic } = JSON.parse(await readBody(req) || '{}')
|
||||
if (!topic || !topic.trim() || topic.length > 500) return json(res, 400, { error: 'bad topic' })
|
||||
await queueSearch(topic.trim(), user.id)
|
||||
return json(res, 200, { ok: true, queued: true })
|
||||
}
|
||||
if (req.method === 'POST' && url.pathname === '/api/send') {
|
||||
const { text } = JSON.parse(await readBody(req) || '{}')
|
||||
if (!text || !text.trim()) return json(res, 400, { error: 'empty text' })
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env node
|
||||
// Eval harness for the KB search skill (§5: a skill without evals is not a
|
||||
// skill). Two tiers, split by token cost:
|
||||
// Tier A — deterministic, 0 tokens (runs in release-check, every time):
|
||||
// representative queries over a synthetic fixture vault; assert
|
||||
// recall (mustHit) and anti-noise (mustMiss) on the local path.
|
||||
// Tier B — LLM judge, opt-in (`--deep`, pre-merge only): a separate evaluator
|
||||
// agent scores the deep "Справка" for groundedness/relevance/coverage
|
||||
// (generator != evaluator, §4). Bounded: tiny fixture, few queries.
|
||||
// Fixtures are generated inline — reproducible, public-safe, no live-vault PII.
|
||||
// node tests/search-eval.mjs # Tier A only (free)
|
||||
// node tests/search-eval.mjs --deep # + Tier B judge (spends tokens)
|
||||
import { promises as fs } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { spawn } from 'node:child_process'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const SCRIPT = path.join(HERE, '..', 'scripts', 'mnemazine-kb-search.mjs')
|
||||
const DEEP = process.argv.includes('--deep')
|
||||
|
||||
// Synthetic corpus: 3 on-topic clusters + 2 noise notes.
|
||||
const FIXTURES = {
|
||||
'harness-vs-model.md': '# Harness важнее модели\nСреда и workflow дают до 90% выигрыша. Контекст это бюджет, не свалка. Чинить harness, не менять модель.',
|
||||
'context-budget.md': '# Контекст как бюджет\n73% токенов уходят до промпта. CLAUDE.md короткий роутер до 200 строк. Субагенты изолируют контекст.',
|
||||
'swarm-fan-out.md': '# Рой и fan-out\nOrchestrator-worker, recon до fan-out, read параллельно write изолировать. Рой ~15x токенов, оправдан при независимости.',
|
||||
'autonomy-loops.md': '# Автономные петли\nCircuit breaker и cost cap, keep-or-revert, generator не равно evaluator, status-файлы.',
|
||||
'coffee.md': '# Кофе\nЭспрессо, молоко, ростер, обжарка зерна.',
|
||||
'family.md': '# Семья\nДочки, выходные, прогулки в парке, личное время.'
|
||||
}
|
||||
|
||||
const CASES = [
|
||||
{ topic: 'harness важнее модели', mustHit: ['harness-vs-model.md'], mustMiss: ['coffee.md', 'family.md'] },
|
||||
{ topic: 'контекст токены бюджет', mustHit: ['context-budget.md'], mustMiss: ['coffee.md'] },
|
||||
{ topic: 'рой агентов fan-out параллелизм', mustHit: ['swarm-fan-out.md'], mustMiss: ['family.md'] },
|
||||
{ topic: 'автономные петли circuit breaker', mustHit: ['autonomy-loops.md'], mustMiss: ['coffee.md', 'family.md'] }
|
||||
]
|
||||
|
||||
function runSearch(topic, vault, outDir, deep) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const env = { ...process.env, MNEMAZINE_DEEP: deep ? '1' : '' }
|
||||
const child = spawn('node', [SCRIPT, '--topic', topic, '--vault', vault, '--out', outDir], { env, stdio: ['ignore', 'pipe', 'inherit'] })
|
||||
let out = ''
|
||||
child.stdout.on('data', d => { out += d })
|
||||
child.on('error', reject)
|
||||
child.on('close', code => code === 0 ? resolve(out.trim()) : reject(new Error(`search exited ${code}`)))
|
||||
})
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'kbsearch-eval-'))
|
||||
const vault = path.join(tmp, 'vault'), outDir = path.join(tmp, 'reports')
|
||||
await fs.mkdir(vault, { recursive: true })
|
||||
for (const [name, body] of Object.entries(FIXTURES)) await fs.writeFile(path.join(vault, name), body, 'utf8')
|
||||
|
||||
let pass = 0, fail = 0
|
||||
const failures = []
|
||||
|
||||
// --- Tier A: deterministic recall/precision (0 tokens) ---
|
||||
for (const c of CASES) {
|
||||
const reportPath = await runSearch(c.topic, vault, outDir, false)
|
||||
const md = await fs.readFile(reportPath, 'utf8')
|
||||
for (const hit of c.mustHit) {
|
||||
if (md.includes(hit)) pass++
|
||||
else { fail++; failures.push(`[A] "${c.topic}" MISSED ${hit}`) }
|
||||
}
|
||||
for (const miss of c.mustMiss) {
|
||||
if (!md.includes(miss)) pass++
|
||||
else { fail++; failures.push(`[A] "${c.topic}" LEAKED noise ${miss}`) }
|
||||
}
|
||||
}
|
||||
console.log(`Tier A (0-token): ${pass} pass, ${fail} fail`)
|
||||
|
||||
// --- Tier B: LLM judge on the deep report (opt-in) ---
|
||||
if (DEEP) {
|
||||
const { llmAvailable, llmJson, fenceUntrusted } = await import('../scripts/mnemazine-llm.mjs')
|
||||
if (!llmAvailable()) {
|
||||
console.log('Tier B skipped: no LLM available')
|
||||
} else {
|
||||
const corpus = Object.entries(FIXTURES).map(([n, b]) => `### ${n}\n${b}`).join('\n\n')
|
||||
const RUBRIC = {
|
||||
type: 'object', additionalProperties: false,
|
||||
required: ['groundedness', 'relevance', 'coverage'],
|
||||
properties: {
|
||||
groundedness: { type: 'integer', minimum: 1, maximum: 5 },
|
||||
relevance: { type: 'integer', minimum: 1, maximum: 5 },
|
||||
coverage: { type: 'integer', minimum: 1, maximum: 5 },
|
||||
notes: { type: 'string' }
|
||||
}
|
||||
}
|
||||
const THRESHOLD = 3
|
||||
for (const c of CASES.slice(0, 2)) { // bound token cost: 2 deep queries
|
||||
const reportPath = await runSearch(c.topic, vault, outDir, true)
|
||||
const md = await fs.readFile(reportPath, 'utf8')
|
||||
const judge = await llmJson(
|
||||
`Ты строгий судья качества справки по теме "${c.topic}". Оцени 1-5: groundedness (всё опирается на корпус, ничего не выдумано), relevance (по теме), coverage (покрыты ключевые моменты корпуса). Верни числа + notes.
|
||||
|
||||
КОРПУС:
|
||||
${fenceUntrusted('CORPUS', corpus)}
|
||||
|
||||
СПРАВКА:
|
||||
${fenceUntrusted('REPORT', md)}`,
|
||||
RUBRIC, {}
|
||||
)
|
||||
const min = Math.min(judge.groundedness, judge.relevance, judge.coverage)
|
||||
if (min >= THRESHOLD) { pass++; console.log(`Tier B "${c.topic}": g${judge.groundedness}/r${judge.relevance}/c${judge.coverage} ✓`) }
|
||||
else { fail++; failures.push(`[B] "${c.topic}" below threshold: g${judge.groundedness}/r${judge.relevance}/c${judge.coverage} — ${judge.notes || ''}`) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await fs.rm(tmp, { recursive: true, force: true })
|
||||
if (failures.length) { console.error('\nFAILURES:\n' + failures.join('\n')); process.exit(1) }
|
||||
console.log(`\neval ok — ${pass} checks passed`)
|
||||
}
|
||||
|
||||
main().catch(e => { console.error(e.message); process.exit(1) })
|
||||
+52
-3
@@ -64,8 +64,20 @@
|
||||
|
||||
<button class="ghost" id="run">Прогнать протокол сейчас</button>
|
||||
|
||||
<div class="card">
|
||||
<div class="hint" style="margin-bottom:8px">🔍 Поиск по базе знаний</div>
|
||||
<textarea id="topic" style="min-height:54px" placeholder="Тема — рой агентов соберёт справку…"></textarea>
|
||||
<button id="search">Найти</button>
|
||||
<ul id="reports"></ul>
|
||||
</div>
|
||||
|
||||
<div class="toast" id="toast"></div>
|
||||
|
||||
<div class="card" id="viewer" style="display:none">
|
||||
<button class="ghost" id="viewerClose" style="margin:0 0 10px">← Назад</button>
|
||||
<pre id="viewerBody" style="white-space:pre-wrap;word-break:break-word;font:13px/1.5 ui-monospace,monospace;margin:0"></pre>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const tg = window.Telegram?.WebApp
|
||||
tg?.ready(); tg?.expand()
|
||||
@@ -127,10 +139,47 @@ $('run').onclick = () => {
|
||||
else if (confirm('Запустить прогон протокола сейчас?')) doRun()
|
||||
}
|
||||
|
||||
refresh()
|
||||
async function loadReports() {
|
||||
try {
|
||||
const { reports } = await api('searches')
|
||||
const ul = $('reports'); ul.replaceChildren()
|
||||
for (const r of reports) {
|
||||
const li = document.createElement('li')
|
||||
const name = document.createElement('span')
|
||||
// textContent — report names are server-generated but stay safe by default.
|
||||
name.textContent = r.name.replace(/^search-/, '').replace(/\.md$/, '')
|
||||
name.style.cursor = 'pointer'; name.style.color = 'var(--accent)'
|
||||
name.onclick = () => openReport(r.name)
|
||||
const at = document.createElement('span'); at.textContent = fmt(r.at)
|
||||
li.append(name, at); ul.append(li)
|
||||
}
|
||||
} catch (e) { /* reports dir may be empty before first sync */ }
|
||||
}
|
||||
|
||||
async function openReport(name) {
|
||||
try {
|
||||
const { markdown } = await api('search?name=' + encodeURIComponent(name))
|
||||
$('viewerBody').textContent = markdown // render as text — no markdown sink, no XSS
|
||||
$('viewer').style.display = 'block'
|
||||
$('viewer').scrollIntoView({ behavior: 'smooth' })
|
||||
} catch (e) { toast('Ошибка: ' + e.message) }
|
||||
}
|
||||
$('viewerClose').onclick = () => { $('viewer').style.display = 'none' }
|
||||
|
||||
$('search').onclick = async () => {
|
||||
const topic = $('topic').value.trim()
|
||||
if (!topic) return toast('Пусто')
|
||||
tg?.HapticFeedback?.impactOccurred('medium')
|
||||
$('search').disabled = true
|
||||
try { await api('search', { method: 'POST', body: JSON.stringify({ topic }) }); $('topic').value = ''; toast('✓ поиск в очереди') }
|
||||
catch (e) { toast('Ошибка: ' + e.message) }
|
||||
finally { setTimeout(() => $('search').disabled = false, 1500) }
|
||||
}
|
||||
|
||||
refresh(); loadReports()
|
||||
// Keep status fresh while the app is open and visible.
|
||||
setInterval(() => { if (document.visibilityState === 'visible') refresh() }, 15000)
|
||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') refresh() })
|
||||
setInterval(() => { if (document.visibilityState === 'visible') { refresh(); loadReports() } }, 15000)
|
||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { refresh(); loadReports() } })
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user