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:
Зарубин Филипп
2026-06-18 17:33:11 +03:00
co-authored by Claude Opus 4.8
parent b92328837e
commit 73cbc0d30c
4 changed files with 112 additions and 61 deletions
+24 -7
View File
@@ -5,11 +5,28 @@
// provider: MNEMAZINE_LLM = 'claude' (default) | 'codex'
// Both run as schema-instructed, web-capable headless agents. Default pipeline
// 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 os from 'node:os'
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 TIMEOUT_MS = Number(process.env.MNEMAZINE_LLM_TIMEOUT_MS || '420000')
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(promptFile, prompt, { encoding: 'utf8', mode: 0o600 })
try {
const res = spawnSync(CODEX_BIN, [
const res = await runProc(CODEX_BIN, [
'exec', '-C', cwd, '--skip-git-repo-check',
'--dangerously-bypass-approvals-and-sandbox',
'--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)}`)
const raw = await fs.readFile(outFile, 'utf8').catch(() => '')
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 args = ['-p', '--output-format', 'json']
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)}`)
// --output-format json wraps the turn: { type:'result', result:'<text>', ... }
let envelope
@@ -146,10 +163,10 @@ export async function llmText(prompt, opts = {}) {
const provider = activeProvider(opts)
if (provider === 'codex') {
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',
'--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)}`)
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')
const args = ['-p', '--output-format', 'json']
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)}`)
let envelope
try { envelope = JSON.parse(res.stdout) } catch { envelope = null }
+70 -54
View File
@@ -479,64 +479,80 @@ const useAtomize = DEEP && llmAvailable()
if (DEEP && !llmAvailable()) {
console.error('[synthesize] --deep requested but LLM unavailable; falling back to local template synthesis')
}
// Bounded-concurrency pool — the research swarm. Each part is an independent
// agent task; one failing never blocks the others (each is try/caught inside).
async function mapLimit(items, limit, fn) {
let i = 0
const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
while (i < items.length) { const idx = i++; await fn(items[idx]) }
})
await Promise.all(workers)
}
async function processPart(part, parts, index) {
if (useAtomize) {
try {
const sources = publicSources(part.records.map(r => r.text).join('\n\n'))
// Expand the knowledge first (research), then atomize the EXPANDED material.
let material
if (ENRICH) {
try {
const { enriched, addedSources } = await enrichCluster(part, sources)
if (enriched && enriched.length > 200) {
material = enriched
for (const u of addedSources) if (!sources.some(s => s.url === u)) sources.push({ name: hostOf(u) || 'Source', url: u })
enriched_clusters += 1
}
} catch (err) {
console.error(`[synthesize] enrich failed for cluster ${part.id}: ${err.message}; atomizing raw capture`)
}
}
const atoms = await atomizeCluster(part, sources, material)
let wroteAtom = false
for (const atom of atoms) {
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 }
const verdict = DEEP
? await verifyDeep(`${atom.what}\n${atom.why}`, atom.sources)
: verifyLocal(atom.sources)
await fs.writeFile(out, makeAtomNote(part, atom, verdict), 'utf8')
atomized += 1
wroteAtom = true
}
if (wroteAtom) return // atomized this cluster — skip the template note
console.error(`[synthesize] atomize produced no atoms for cluster ${part.id}; using template note`)
} catch (err) {
console.error(`[synthesize] atomize failed for cluster ${part.id}: ${err.message}; using template note`)
}
}
const suffix = parts.length > 1 ? `-part-${index + 1}` : ''
// Filename keyed by content fingerprint, not date: idempotent across runs.
const fp = fingerprint(part)
const out = path.join(VAULT, '01 Concepts', `synthesis-${slugify(clusterTitle(part.id))}${suffix}-${fp}.md`)
if (await fs.access(out).then(() => true).catch(() => false)) { skipped += 1; return }
await fs.writeFile(out, makeNote(part), 'utf8')
written += 1
}
const tasks = []
for (const cluster of clusters.values()) {
const parts = chunks(cluster.records, 25)
for (let index = 0; index < parts.length; index += 1) {
const part = { ...cluster, records: parts[index], part: index + 1, partCount: parts.length }
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) continue
if (useAtomize) {
try {
const sources = publicSources(part.records.map(r => r.text).join('\n\n'))
// Expand the knowledge first (research), then atomize the EXPANDED material.
let material
if (ENRICH) {
try {
const { enriched, addedSources } = await enrichCluster(part, sources)
if (enriched && enriched.length > 200) {
material = enriched
for (const u of addedSources) if (!sources.some(s => s.url === u)) sources.push({ name: hostOf(u) || 'Source', url: u })
enriched_clusters += 1
}
} catch (err) {
console.error(`[synthesize] enrich failed for cluster ${cluster.id}: ${err.message}; atomizing raw capture`)
}
}
const atoms = await atomizeCluster(part, sources, material)
let wroteAtom = false
for (const atom of atoms) {
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 }
// --deep also runs the network+LLM verify gate; otherwise local structural verdict.
const verdict = DEEP
? await verifyDeep(`${atom.what}\n${atom.why}`, atom.sources)
: verifyLocal(atom.sources)
await fs.writeFile(out, makeAtomNote(part, atom, verdict), 'utf8')
atomized += 1
wroteAtom = true
}
if (wroteAtom) continue // atomized this cluster — skip the template note
console.error(`[synthesize] atomize produced no atoms for cluster ${cluster.id}; using template note`)
} catch (err) {
console.error(`[synthesize] atomize failed for cluster ${cluster.id}: ${err.message}; using template note`)
}
}
const suffix = parts.length > 1 ? `-part-${index + 1}` : ''
// 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 out = path.join(VAULT, '01 Concepts', `synthesis-${slugify(clusterTitle(cluster.id))}${suffix}-${fp}.md`)
if (await fs.access(out).then(() => true).catch(() => false)) {
skipped += 1
continue
}
await fs.writeFile(out, makeNote(part), 'utf8')
written += 1
}
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),
// so the run silently fell back to local templates. Callers can detect this.