feat(search): orchestrator-led agent swarm to search the vault + Mini App button
Add `npm run search` (mnemazine-kb-search.mjs): a recon → fan-out → fan-in swarm over the live vault that writes a Russian "Справка" Markdown report. Recon keyword-scores notes (0 tokens); --deep/MNEMAZINE_DEEP engages a bounded-pool LLM swarm (one agent per shard, untrusted notes fenced), then the orchestrator dedups + synthesizes. Local fallback keeps it 0-token by default, mirroring the rest of the deep pipeline. Self-test included. Wire it into the Telegram Mini App: the vault is Mac-only and the server is on the VPS, so the button only enqueues. Server gains POST /api/search (queue), GET /api/searches (list reports), GET /api/search?name= (read, with path-escape guard). Mini App gets a search card + report list + text viewer (rendered as text — no markdown XSS sink). The Mac poller drains the queue, runs the swarm locally, and rsyncs reports back to the VPS. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
3b7c85bae5
commit
fbe205f3f1
@@ -10,10 +10,13 @@
|
|||||||
"graph:refresh": "node scripts/mnemazine-refresh-graphify.mjs --json",
|
"graph:refresh": "node scripts/mnemazine-refresh-graphify.mjs --json",
|
||||||
"graph:shards": "node scripts/mnemazine-semantic-shards.mjs",
|
"graph:shards": "node scripts/mnemazine-semantic-shards.mjs",
|
||||||
"graph:semantic-batches": "node scripts/mnemazine-semantic-batches.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:clean": "python3 scripts/graphify_clean.py",
|
||||||
"graph:smoke": "node scripts/mnemazine-refresh-graphify-smoke.mjs",
|
"graph:smoke": "node scripts/mnemazine-refresh-graphify-smoke.mjs",
|
||||||
"ingest:site": "node scripts/mnemazine-ingest-site.mjs",
|
"ingest:site": "node scripts/mnemazine-ingest-site.mjs",
|
||||||
"synthesize": "node scripts/mnemazine-synthesize.mjs",
|
"synthesize": "node scripts/mnemazine-synthesize.mjs",
|
||||||
|
"search": "node scripts/mnemazine-kb-search.mjs",
|
||||||
"weekly": "node scripts/mnemazine-weekly-brief-html.mjs",
|
"weekly": "node scripts/mnemazine-weekly-brief-html.mjs",
|
||||||
"weekly:state": "node scripts/mnemazine-weekly-state.mjs",
|
"weekly:state": "node scripts/mnemazine-weekly-state.mjs",
|
||||||
"digest": "node scripts/mnemazine-digest.mjs",
|
"digest": "node scripts/mnemazine-digest.mjs",
|
||||||
|
|||||||
@@ -0,0 +1,276 @@
|
|||||||
|
#!/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 EXCERPT = 2500 // chars of each note shown to an agent
|
||||||
|
|
||||||
|
// --- 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' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- orchestrator: widen the query (deep only) -------------------------------
|
||||||
|
async function widen(topic) {
|
||||||
|
if (!DEEP || !llmAvailable(PROVIDER)) return tokens(topic)
|
||||||
|
try {
|
||||||
|
const out = await llmJson(
|
||||||
|
`Тема поиска по базе знаний: "${topic}". Дай ключевые слова и синонимы (рус+англ) для полнотекстового поиска по заметкам — только список терминов, без объяснений.`,
|
||||||
|
{ type: 'object', additionalProperties: false, required: ['terms'], properties: { 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)
|
||||||
|
return [...terms]
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[kb-search] query widening failed: ${e.message}; using raw terms`)
|
||||||
|
return tokens(topic)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- worker: extract findings from one shard ---------------------------------
|
||||||
|
async function extractShard(topic, shard) {
|
||||||
|
if (DEEP && llmAvailable(PROVIDER)) {
|
||||||
|
const blob = shard.map(n =>
|
||||||
|
fenceUntrusted('NOTE', `### ${n.rel}\n${n.text.slice(0, EXCERPT)}`)).join('\n\n')
|
||||||
|
const prompt = `Ты агент-исследователь. Тема: "${topic}".
|
||||||
|
Из заметок ниже выбери ТОЛЬКО релевантное теме. Для каждой находки: 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)) }] : []
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- orchestrator: synthesize findings into a report -------------------------
|
||||||
|
async function synthesize(topic, findings) {
|
||||||
|
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 prompt = `Ты оркестратор. Собери из находок агентов справку по теме "${topic}" на РУССКОМ, стиль humanizer — живо, ясно, по делу, без воды и канцелярита. Дедуплицируй, сгруппируй по под-темам (themes), отметь связи (connections), противоречия (contradictions), пробелы знаний (gaps) и следующие шаги (next). Не выдумывай сверх находок.
|
||||||
|
|
||||||
|
Находки:
|
||||||
|
${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)' : 'локальный'}`, '')
|
||||||
|
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 = await widen(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
|
||||||
|
const shards = []
|
||||||
|
for (let i = 0; i < candidates.length; i += SHARD_SIZE) shards.push(candidates.slice(i, i + SHARD_SIZE))
|
||||||
|
const findings = []
|
||||||
|
await mapLimit(shards, DEEP ? CONCURRENCY : 1, async shard => {
|
||||||
|
try { findings.push(...await extractShard(topic, shard)) }
|
||||||
|
catch (e) { console.error(`[kb-search] shard failed: ${e.message}`) }
|
||||||
|
})
|
||||||
|
findings.sort((a, b) => (b.relevance || 0) - (a.relevance || 0))
|
||||||
|
// FAN-IN
|
||||||
|
const report = await synthesize(topic, findings)
|
||||||
|
const md = renderReport(topic, report, { stamp, scanned: files.length, candidates: candidates.length, findings: findings.length, deep: DEEP && llmAvailable(PROVIDER) })
|
||||||
|
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')
|
||||||
|
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) })
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
|
|||||||
VPS="${MNEMAZINE_VPS:-root@YOUR_VPS_HOST}"
|
VPS="${MNEMAZINE_VPS:-root@YOUR_VPS_HOST}"
|
||||||
KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}"
|
KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}"
|
||||||
REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-/var/www/mnemazine-inbox}"
|
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.
|
# ponytail: fail fast if still on the placeholder — beats a confusing ssh error.
|
||||||
if [ "$VPS" = "root@YOUR_VPS_HOST" ]; then
|
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
|
if ! mkdir "$LOCK" 2>/dev/null; then exit 0; fi # previous tick still running
|
||||||
trap 'rmdir "$LOCK" 2>/dev/null' EXIT
|
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
|
run=0; manual=0
|
||||||
# Consume run-now flag atomically: print + delete in one ssh.
|
# 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)"
|
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 INBOX = path.resolve(process.env.MNEMAZINE_INBOX || path.join(process.cwd(), 'inbox'))
|
||||||
const RUN_FLAG = path.join(INBOX, '.run-now')
|
const RUN_FLAG = path.join(INBOX, '.run-now')
|
||||||
const RUN_MARKER = path.join(INBOX, '.last-run')
|
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 PORT = Number(process.env.PORT || 8787)
|
||||||
const ALLOWED = (process.env.ALLOWED_CHAT_IDS || '').split(',').map(s => s.trim()).filter(Boolean)
|
const ALLOWED = (process.env.ALLOWED_CHAT_IDS || '').split(',').map(s => s.trim()).filter(Boolean)
|
||||||
const throttle = new Map() // user.id -> last write ms
|
const throttle = new Map() // user.id -> last write ms
|
||||||
@@ -85,6 +88,32 @@ async function send(text) {
|
|||||||
return name
|
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) => {
|
const server = http.createServer(async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const url = new URL(req.url, 'http://localhost')
|
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/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') {
|
if (req.method === 'POST' && url.pathname === '/api/send') {
|
||||||
const { text } = JSON.parse(await readBody(req) || '{}')
|
const { text } = JSON.parse(await readBody(req) || '{}')
|
||||||
if (!text || !text.trim()) return json(res, 400, { error: 'empty text' })
|
if (!text || !text.trim()) return json(res, 400, { error: 'empty text' })
|
||||||
|
|||||||
+52
-3
@@ -64,8 +64,20 @@
|
|||||||
|
|
||||||
<button class="ghost" id="run">Прогнать протокол сейчас</button>
|
<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="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>
|
<script>
|
||||||
const tg = window.Telegram?.WebApp
|
const tg = window.Telegram?.WebApp
|
||||||
tg?.ready(); tg?.expand()
|
tg?.ready(); tg?.expand()
|
||||||
@@ -127,10 +139,47 @@ $('run').onclick = () => {
|
|||||||
else if (confirm('Запустить прогон протокола сейчас?')) doRun()
|
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.
|
// Keep status fresh while the app is open and visible.
|
||||||
setInterval(() => { if (document.visibilityState === 'visible') refresh() }, 15000)
|
setInterval(() => { if (document.visibilityState === 'visible') { refresh(); loadReports() } }, 15000)
|
||||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') refresh() })
|
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { refresh(); loadReports() } })
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Reference in New Issue
Block a user