feat(swarm): async LLM bridge + bounded-concurrency research swarm in deep synthesize
E3: llm bridge now uses async spawn (non-blocking) instead of spawnSync, so agent calls run concurrently. Deep synthesize processes clusters through a bounded pool (MNEMAZINE_CONCURRENCY, default 4) — cheap and fast. Each task is isolated (inner + outer try/catch): one cluster failing never blocks the swarm. Docs cover recognition fallback, swarm, concurrency. 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
b92328837e
commit
73cbc0d30c
@@ -36,8 +36,17 @@ All LLM calls go through one provider-abstracted module: `scripts/mnemazine-llm.
|
|||||||
| `MNEMAZINE_DEEP` | unset | `1` enables deep mode (enrich + atomize + verify + digest). |
|
| `MNEMAZINE_DEEP` | unset | `1` enables deep mode (enrich + atomize + verify + digest). |
|
||||||
| `MNEMAZINE_ENRICH` | `1` within deep | `0` (or `--no-enrich`) skips the enrichment stage. |
|
| `MNEMAZINE_ENRICH` | `1` within deep | `0` (or `--no-enrich`) skips the enrichment stage. |
|
||||||
| `MNEMAZINE_MAX_ATOMS` | `20` | Cap on atoms produced per source cluster. |
|
| `MNEMAZINE_MAX_ATOMS` | `20` | Cap on atoms produced per source cluster. |
|
||||||
|
| `MNEMAZINE_CONCURRENCY` | `4` | Swarm size for deep research (parallel agents, bounded). |
|
||||||
| `MNEMAZINE_OWNER_CONTEXT` | generic | Personal project context for the digest's "why it matters". Or put it in the gitignored `.mnemazine/owner-context.txt`. |
|
| `MNEMAZINE_OWNER_CONTEXT` | generic | Personal project context for the digest's "why it matters". Or put it in the gitignored `.mnemazine/owner-context.txt`. |
|
||||||
|
|
||||||
|
### Recognition (local-first, LLM fallback)
|
||||||
|
|
||||||
|
Extraction tries local engines first at **0 tokens**: Apple Vision OCR (images), markitdown (PDF/DOCX/PPTX/XLSX/HTML), whisper + frame OCR (video). Only when local yields nothing usable **and** `--deep` is on does a vision-capable LLM transcribe the file. Each file is isolated — one recognition failure logs an error, leaves the file in inbox, and never breaks the rest of the batch.
|
||||||
|
|
||||||
|
### Swarm
|
||||||
|
|
||||||
|
In deep mode, files/clusters are researched concurrently by a bounded pool of agents (`MNEMAZINE_CONCURRENCY`, default 4) — cheap and fast. A failing task never blocks the others.
|
||||||
|
|
||||||
### Enrichment (knowledge expansion)
|
### Enrichment (knowledge expansion)
|
||||||
|
|
||||||
Before atomization, deep mode runs a web-capable LLM agent that **researches and expands** the captured material "as much as is genuinely useful" — primary sources, current facts/versions, practitioner experience — with every added fact tied to a fetched URL (anti-hallucination). Atoms are then built from the **expanded** knowledge, not just the raw capture. Disable with `--no-enrich` / `MNEMAZINE_ENRICH=0`.
|
Before atomization, deep mode runs a web-capable LLM agent that **researches and expands** the captured material "as much as is genuinely useful" — primary sources, current facts/versions, practitioner experience — with every added fact tied to a fetched URL (anti-hallucination). Atoms are then built from the **expanded** knowledge, not just the raw capture. Disable with `--no-enrich` / `MNEMAZINE_ENRICH=0`.
|
||||||
|
|||||||
@@ -36,8 +36,17 @@ npm run synthesize -- --deep
|
|||||||
| `MNEMAZINE_DEEP` | не задано | `1` включает deep-режим (enrich + атомизация + проверка + digest). |
|
| `MNEMAZINE_DEEP` | не задано | `1` включает deep-режим (enrich + атомизация + проверка + digest). |
|
||||||
| `MNEMAZINE_ENRICH` | `1` в deep | `0` (или `--no-enrich`) пропускает стадию обогащения. |
|
| `MNEMAZINE_ENRICH` | `1` в deep | `0` (или `--no-enrich`) пропускает стадию обогащения. |
|
||||||
| `MNEMAZINE_MAX_ATOMS` | `20` | Лимит атомов на один кластер источника. |
|
| `MNEMAZINE_MAX_ATOMS` | `20` | Лимит атомов на один кластер источника. |
|
||||||
|
| `MNEMAZINE_CONCURRENCY` | `4` | Размер роя для deep-исследования (параллельные агенты, ограниченно). |
|
||||||
| `MNEMAZINE_OWNER_CONTEXT` | общий | Контекст личных проектов для блока «почему важно» в справке. Либо положите в gitignored `.mnemazine/owner-context.txt`. |
|
| `MNEMAZINE_OWNER_CONTEXT` | общий | Контекст личных проектов для блока «почему важно» в справке. Либо положите в gitignored `.mnemazine/owner-context.txt`. |
|
||||||
|
|
||||||
|
### Распознавание (локально сперва, LLM-fallback)
|
||||||
|
|
||||||
|
Извлечение сначала пробует локальные движки за **0 токенов**: Apple Vision OCR (картинки), markitdown (PDF/DOCX/PPTX/XLSX/HTML), whisper + OCR кадров (видео). Только если локально ничего пригодного **и** включён `--deep`, файл распознаёт vision-LLM. Каждый файл изолирован — ошибка распознавания логируется, файл остаётся в inbox, остальной батч не ломается.
|
||||||
|
|
||||||
|
### Рой
|
||||||
|
|
||||||
|
В deep-режиме файлы/кластеры исследуются параллельно ограниченным пулом агентов (`MNEMAZINE_CONCURRENCY`, по умолчанию 4) — дёшево и быстро. Упавшая задача не блокирует остальные.
|
||||||
|
|
||||||
### Обогащение (расширение знаний)
|
### Обогащение (расширение знаний)
|
||||||
|
|
||||||
Перед атомизацией deep-режим запускает web-агента LLM, который **исследует и расширяет** захваченный материал «насколько реально полезно» — первоисточники, актуальные факты/версии, опыт практиков — каждый добавленный факт привязан к fetched-URL (антигаллюцинация). Атомы строятся из **расширенного** знания, не только из сырого захвата. Отключение: `--no-enrich` / `MNEMAZINE_ENRICH=0`.
|
Перед атомизацией deep-режим запускает web-агента LLM, который **исследует и расширяет** захваченный материал «насколько реально полезно» — первоисточники, актуальные факты/версии, опыт практиков — каждый добавленный факт привязан к fetched-URL (антигаллюцинация). Атомы строятся из **расширенного** знания, не только из сырого захвата. Отключение: `--no-enrich` / `MNEMAZINE_ENRICH=0`.
|
||||||
|
|||||||
@@ -5,11 +5,28 @@
|
|||||||
// provider: MNEMAZINE_LLM = 'claude' (default) | 'codex'
|
// provider: MNEMAZINE_LLM = 'claude' (default) | 'codex'
|
||||||
// Both run as schema-instructed, web-capable headless agents. Default pipeline
|
// Both run as schema-instructed, web-capable headless agents. Default pipeline
|
||||||
// never calls either — only the opt-in --deep path does.
|
// never calls either — only the opt-in --deep path does.
|
||||||
import { spawnSync } from 'node:child_process'
|
import { spawnSync, spawn } from 'node:child_process'
|
||||||
import { existsSync, readdirSync, promises as fs } from 'node:fs'
|
import { existsSync, readdirSync, promises as fs } from 'node:fs'
|
||||||
import os from 'node:os'
|
import os from 'node:os'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
|
|
||||||
|
// Async process runner — non-blocking (unlike spawnSync), so many agent calls
|
||||||
|
// can run concurrently as a swarm. Never rejects; returns a status/out/err.
|
||||||
|
function runProc(bin, args, { input, timeoutMs, cwd } = {}) {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
let child
|
||||||
|
try { child = spawn(bin, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'] }) }
|
||||||
|
catch (e) { return resolve({ status: 1, stdout: '', stderr: String(e.message) }) }
|
||||||
|
let out = '', err = '', killed = false
|
||||||
|
const t = timeoutMs ? setTimeout(() => { killed = true; child.kill('SIGKILL') }, timeoutMs) : null
|
||||||
|
child.stdout.on('data', d => { out += d })
|
||||||
|
child.stderr.on('data', d => { err += d })
|
||||||
|
child.on('error', e => { if (t) clearTimeout(t); resolve({ status: 1, stdout: out, stderr: String(e.message) }) })
|
||||||
|
child.on('close', code => { if (t) clearTimeout(t); resolve({ status: killed ? 124 : (code ?? 1), stdout: out, stderr: err }) })
|
||||||
|
if (input != null) { child.stdin.on('error', () => {}); child.stdin.write(input); child.stdin.end() }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const DEFAULT_PROVIDER = process.env.MNEMAZINE_LLM || 'claude'
|
const DEFAULT_PROVIDER = process.env.MNEMAZINE_LLM || 'claude'
|
||||||
const TIMEOUT_MS = Number(process.env.MNEMAZINE_LLM_TIMEOUT_MS || '420000')
|
const TIMEOUT_MS = Number(process.env.MNEMAZINE_LLM_TIMEOUT_MS || '420000')
|
||||||
const CODEX_BIN = process.env.MNEMAZINE_CODEX_BIN || '/Applications/Codex.app/Contents/Resources/codex'
|
const CODEX_BIN = process.env.MNEMAZINE_CODEX_BIN || '/Applications/Codex.app/Contents/Resources/codex'
|
||||||
@@ -95,11 +112,11 @@ async function codexJsonCall(prompt, schema, opts) {
|
|||||||
await fs.writeFile(schemaFile, JSON.stringify(schema), { encoding: 'utf8', mode: 0o600 })
|
await fs.writeFile(schemaFile, JSON.stringify(schema), { encoding: 'utf8', mode: 0o600 })
|
||||||
await fs.writeFile(promptFile, prompt, { encoding: 'utf8', mode: 0o600 })
|
await fs.writeFile(promptFile, prompt, { encoding: 'utf8', mode: 0o600 })
|
||||||
try {
|
try {
|
||||||
const res = spawnSync(CODEX_BIN, [
|
const res = await runProc(CODEX_BIN, [
|
||||||
'exec', '-C', cwd, '--skip-git-repo-check',
|
'exec', '-C', cwd, '--skip-git-repo-check',
|
||||||
'--dangerously-bypass-approvals-and-sandbox',
|
'--dangerously-bypass-approvals-and-sandbox',
|
||||||
'--output-schema', schemaFile, '-o', outFile, '-'
|
'--output-schema', schemaFile, '-o', outFile, '-'
|
||||||
], { input: await fs.readFile(promptFile, 'utf8'), encoding: 'utf8', timeout: opts.timeoutMs || TIMEOUT_MS })
|
], { input: await fs.readFile(promptFile, 'utf8'), timeoutMs: opts.timeoutMs || TIMEOUT_MS })
|
||||||
if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
|
if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
|
||||||
const raw = await fs.readFile(outFile, 'utf8').catch(() => '')
|
const raw = await fs.readFile(outFile, 'utf8').catch(() => '')
|
||||||
if (!raw.trim()) throw new Error('codex returned empty output')
|
if (!raw.trim()) throw new Error('codex returned empty output')
|
||||||
@@ -122,7 +139,7 @@ async function claudeJsonCall(prompt, schema, opts) {
|
|||||||
const full = `${prompt}\n\nReturn ONLY a single JSON object matching this JSON Schema (no prose, no code fence):\n${JSON.stringify(schema)}`
|
const full = `${prompt}\n\nReturn ONLY a single JSON object matching this JSON Schema (no prose, no code fence):\n${JSON.stringify(schema)}`
|
||||||
const args = ['-p', '--output-format', 'json']
|
const args = ['-p', '--output-format', 'json']
|
||||||
if (tools.length) args.push('--allowedTools', tools.join(','))
|
if (tools.length) args.push('--allowedTools', tools.join(','))
|
||||||
const res = spawnSync(bin, args, { input: full, encoding: 'utf8', timeout: opts.timeoutMs || TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 })
|
const res = await runProc(bin, args, { input: full, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
|
||||||
if (res.status !== 0) throw new Error(`claude -p failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
|
if (res.status !== 0) throw new Error(`claude -p failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
|
||||||
// --output-format json wraps the turn: { type:'result', result:'<text>', ... }
|
// --output-format json wraps the turn: { type:'result', result:'<text>', ... }
|
||||||
let envelope
|
let envelope
|
||||||
@@ -146,10 +163,10 @@ export async function llmText(prompt, opts = {}) {
|
|||||||
const provider = activeProvider(opts)
|
const provider = activeProvider(opts)
|
||||||
if (provider === 'codex') {
|
if (provider === 'codex') {
|
||||||
if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`)
|
if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`)
|
||||||
const res = spawnSync(CODEX_BIN, [
|
const res = await runProc(CODEX_BIN, [
|
||||||
'exec', '-C', opts.cwd || process.cwd(), '--skip-git-repo-check',
|
'exec', '-C', opts.cwd || process.cwd(), '--skip-git-repo-check',
|
||||||
'--dangerously-bypass-approvals-and-sandbox', '-'
|
'--dangerously-bypass-approvals-and-sandbox', '-'
|
||||||
], { input: prompt, encoding: 'utf8', timeout: opts.timeoutMs || TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 })
|
], { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
|
||||||
if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
|
if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
|
||||||
return String(res.stdout || '').trim()
|
return String(res.stdout || '').trim()
|
||||||
}
|
}
|
||||||
@@ -157,7 +174,7 @@ export async function llmText(prompt, opts = {}) {
|
|||||||
if (!binExists(bin)) throw new Error('claude binary not found: set MNEMAZINE_CLAUDE_BIN')
|
if (!binExists(bin)) throw new Error('claude binary not found: set MNEMAZINE_CLAUDE_BIN')
|
||||||
const args = ['-p', '--output-format', 'json']
|
const args = ['-p', '--output-format', 'json']
|
||||||
if (opts.tools?.length) args.push('--allowedTools', opts.tools.join(','))
|
if (opts.tools?.length) args.push('--allowedTools', opts.tools.join(','))
|
||||||
const res = spawnSync(bin, args, { input: prompt, encoding: 'utf8', timeout: opts.timeoutMs || TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 })
|
const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
|
||||||
if (res.status !== 0) throw new Error(`claude -p failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
|
if (res.status !== 0) throw new Error(`claude -p failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
|
||||||
let envelope
|
let envelope
|
||||||
try { envelope = JSON.parse(res.stdout) } catch { envelope = null }
|
try { envelope = JSON.parse(res.stdout) } catch { envelope = null }
|
||||||
|
|||||||
@@ -479,13 +479,17 @@ const useAtomize = DEEP && llmAvailable()
|
|||||||
if (DEEP && !llmAvailable()) {
|
if (DEEP && !llmAvailable()) {
|
||||||
console.error('[synthesize] --deep requested but LLM unavailable; falling back to local template synthesis')
|
console.error('[synthesize] --deep requested but LLM unavailable; falling back to local template synthesis')
|
||||||
}
|
}
|
||||||
for (const cluster of clusters.values()) {
|
// Bounded-concurrency pool — the research swarm. Each part is an independent
|
||||||
const parts = chunks(cluster.records, 25)
|
// agent task; one failing never blocks the others (each is try/caught inside).
|
||||||
for (let index = 0; index < parts.length; index += 1) {
|
async function mapLimit(items, limit, fn) {
|
||||||
const part = { ...cluster, records: parts[index], part: index + 1, partCount: parts.length }
|
let i = 0
|
||||||
const textSize = part.records.reduce((sum, record) => sum + compact(record.text, 100000).length, 0)
|
const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
|
||||||
if (textSize < MIN_CLUSTER_CHARS) continue
|
while (i < items.length) { const idx = i++; await fn(items[idx]) }
|
||||||
|
})
|
||||||
|
await Promise.all(workers)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function processPart(part, parts, index) {
|
||||||
if (useAtomize) {
|
if (useAtomize) {
|
||||||
try {
|
try {
|
||||||
const sources = publicSources(part.records.map(r => r.text).join('\n\n'))
|
const sources = publicSources(part.records.map(r => r.text).join('\n\n'))
|
||||||
@@ -500,7 +504,7 @@ for (const cluster of clusters.values()) {
|
|||||||
enriched_clusters += 1
|
enriched_clusters += 1
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`[synthesize] enrich failed for cluster ${cluster.id}: ${err.message}; atomizing raw capture`)
|
console.error(`[synthesize] enrich failed for cluster ${part.id}: ${err.message}; atomizing raw capture`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const atoms = await atomizeCluster(part, sources, material)
|
const atoms = await atomizeCluster(part, sources, material)
|
||||||
@@ -508,7 +512,6 @@ for (const cluster of clusters.values()) {
|
|||||||
for (const atom of atoms) {
|
for (const atom of atoms) {
|
||||||
const out = path.join(VAULT, '01 Concepts', `synthesis-${slugify(atom.title)}-${atomFingerprint(atom, part.id)}.md`)
|
const out = path.join(VAULT, '01 Concepts', `synthesis-${slugify(atom.title)}-${atomFingerprint(atom, part.id)}.md`)
|
||||||
if (await fs.access(out).then(() => true).catch(() => false)) { skipped += 1; continue }
|
if (await fs.access(out).then(() => true).catch(() => false)) { skipped += 1; continue }
|
||||||
// --deep also runs the network+LLM verify gate; otherwise local structural verdict.
|
|
||||||
const verdict = DEEP
|
const verdict = DEEP
|
||||||
? await verifyDeep(`${atom.what}\n${atom.why}`, atom.sources)
|
? await verifyDeep(`${atom.what}\n${atom.why}`, atom.sources)
|
||||||
: verifyLocal(atom.sources)
|
: verifyLocal(atom.sources)
|
||||||
@@ -516,27 +519,40 @@ for (const cluster of clusters.values()) {
|
|||||||
atomized += 1
|
atomized += 1
|
||||||
wroteAtom = true
|
wroteAtom = true
|
||||||
}
|
}
|
||||||
if (wroteAtom) continue // atomized this cluster — skip the template note
|
if (wroteAtom) return // atomized this cluster — skip the template note
|
||||||
console.error(`[synthesize] atomize produced no atoms for cluster ${cluster.id}; using template note`)
|
console.error(`[synthesize] atomize produced no atoms for cluster ${part.id}; using template note`)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`[synthesize] atomize failed for cluster ${cluster.id}: ${err.message}; using template note`)
|
console.error(`[synthesize] atomize failed for cluster ${part.id}: ${err.message}; using template note`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const suffix = parts.length > 1 ? `-part-${index + 1}` : ''
|
const suffix = parts.length > 1 ? `-part-${index + 1}` : ''
|
||||||
// Filename keyed by content fingerprint, not date: idempotent across runs
|
// Filename keyed by content fingerprint, not date: idempotent across runs.
|
||||||
// and never clobbers a same-day note or a manual edit. Identical cluster
|
|
||||||
// content -> identical path -> skipped instead of duplicated/overwritten.
|
|
||||||
const fp = fingerprint(part)
|
const fp = fingerprint(part)
|
||||||
const out = path.join(VAULT, '01 Concepts', `synthesis-${slugify(clusterTitle(cluster.id))}${suffix}-${fp}.md`)
|
const out = path.join(VAULT, '01 Concepts', `synthesis-${slugify(clusterTitle(part.id))}${suffix}-${fp}.md`)
|
||||||
if (await fs.access(out).then(() => true).catch(() => false)) {
|
if (await fs.access(out).then(() => true).catch(() => false)) { skipped += 1; return }
|
||||||
skipped += 1
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
await fs.writeFile(out, makeNote(part), 'utf8')
|
await fs.writeFile(out, makeNote(part), 'utf8')
|
||||||
written += 1
|
written += 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const tasks = []
|
||||||
|
for (const cluster of clusters.values()) {
|
||||||
|
const parts = chunks(cluster.records, 25)
|
||||||
|
parts.forEach((recs, index) => {
|
||||||
|
const part = { ...cluster, records: recs, part: index + 1, partCount: parts.length }
|
||||||
|
const textSize = part.records.reduce((sum, record) => sum + compact(record.text, 100000).length, 0)
|
||||||
|
if (textSize < MIN_CLUSTER_CHARS) return
|
||||||
|
tasks.push({ part, parts, index })
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
// Swarm only helps when each task spawns an agent (deep); local template writes
|
||||||
|
// stay serial. Cap concurrency so we are cheap+fast, not a fork bomb.
|
||||||
|
const CONCURRENCY = Number(arg('concurrency', process.env.MNEMAZINE_CONCURRENCY || '4'))
|
||||||
|
await mapLimit(tasks, useAtomize ? CONCURRENCY : 1, async ({ part, parts, index }) => {
|
||||||
|
// Outer guard: a part must never break the swarm, even on an unexpected throw.
|
||||||
|
try { await processPart(part, parts, index) }
|
||||||
|
catch (err) { console.error(`[synthesize] part failed for cluster ${part.id}: ${err.message}`) }
|
||||||
|
})
|
||||||
|
|
||||||
// degraded: --deep was requested but the deep path could not run (codex absent),
|
// degraded: --deep was requested but the deep path could not run (codex absent),
|
||||||
// so the run silently fell back to local templates. Callers can detect this.
|
// so the run silently fell back to local templates. Callers can detect this.
|
||||||
|
|||||||
Reference in New Issue
Block a user