caelum0x ab05bb4dc6 feat: Mixture-of-Agents verifier with real composition across all engines
Replace the flat "run 17 adapters in parallel and sum" design with a
collaborative, layered blackboard MoA where the backend engines compose:
agents declare produces/consumes typed artifacts, a scheduler topologically
orders them into layers, and each layer commits its artifacts to a shared
blackboard before the next runs — so downstream agents genuinely build on
upstream findings.

Composition core (lib/moa):
- types.ts: MoaAgent contract (produces/consumes/gate/run(ctx,bb)) + typed
  artifact taxonomy (source_labels, effect_sizes, quality, relevance,
  contested, entities, mechanisms, design_priors, sufficiency, debate,
  research_brief)
- blackboard.ts: typed single-producer-per-kind shared memory
- scheduler.ts: dependency-DAG layering; parallel within a layer, artifacts
  committed between layers
- router.ts + planner.ts: deterministic gate + advisory Claude planner
  (boosts never revive a 0 gate)
- aggregate.ts: deterministic vote mix -> verdict + trust (no LLM; the moat)
- synthesize.ts: grounded Claude narrative (explains, never decides)
- 21 composing agents under lib/moa/agents/*

Real composition edges proven live: MiniCheck produces source_labels ->
MultiVerS aggregates them + Valsci produces contested -> STORM debates;
quant-extractor produces effect_sizes -> PyMARE pools them; paper-qa quality
+ Loki relevance feed MiniCheck. Sample (EMPA-REG vs DECLARE) yields a
calibrated "supported, trust 73/100" with an honest heterogeneity caveat.

New production engines from vendored research repos (MVP -> production),
wired as Layer-3 deliberation agents with papertrail_*.py + PAPERTRAIL.md:
- autoreview (eimenhmdt/autoresearcher): citation-grounded literature review
- autogather (lucereal/AutoResearcher): query-gen + coverage-gap analysis
- autoloop (karpathy/autoresearch pattern): bounded evidence-refinement loop

Platform robustness: callClaudeForJson now tolerates prose-wrapped JSON
(balanced-value extraction) with one stricter retry — fixes model
editorializing that previously broke MiniCheck and any strict-JSON engine.

API /api/moa/orchestrate + console page /console/orchestrator visualizing the
layered DAG, artifact provenance, and per-agent produce/consume.
2026-07-11 05:07:08 +03:00

98 lines
3.4 KiB
TypeScript

import { NextRequest } from "next/server";
import { z } from "zod";
import { ok, fail } from "@/lib/api/response";
import { checkRateLimit } from "@/lib/rateLimit";
import { logEvent } from "@/lib/logger";
import { orchestrate } from "@/lib/moa/orchestrate";
// Public POST endpoint for the MIXTURE-OF-AGENTS verifier. Given { claim, sources[], options? }
// it routes the claim through all 17 backend engines as gated experts, mixes their
// contributions into one deterministic verdict + trust score, and (optionally) writes a
// grounded narrative. Claude touches only the advisory routing planner and the explanatory
// narrative — never the numeric verdict/scoring mix (the moat).
//
// Never logs claim or source text — ids/counts/verdict only.
export const runtime = "nodejs";
export const maxDuration = 60;
const SourceSchema = z.object({
id: z.string().min(1, "each source needs a non-empty id."),
text: z.string().min(1, "each source needs non-empty text.").max(20000),
title: z.string().max(500).optional(),
url: z.string().max(1000).optional(),
journal: z.string().max(300).optional(),
year: z.number().int().min(1800).max(2100).optional(),
citations: z.number().int().min(0).optional(),
isPreprint: z.boolean().optional(),
isOpenAccess: z.boolean().optional(),
retracted: z.boolean().optional(),
doi: z.string().max(200).optional(),
label: z.enum(["SUPPORTS", "REFUTES", "NEI"]).optional(),
labelConfidence: z.number().min(0).max(1).optional(),
});
const OrchestrateRequestSchema = z.object({
claim: z.string().trim().min(3, "claim must be at least 3 characters.").max(2000),
sources: z
.array(SourceSchema)
.min(1, "provide at least one source.")
.max(40, "too many sources — send at most 40."),
options: z
.object({
llm: z.boolean().optional(),
maxExperts: z.number().int().min(1).max(20).optional(),
})
.optional(),
});
export async function POST(req: NextRequest) {
const start = Date.now();
const ip = req.headers.get("x-forwarded-for") ?? "unknown";
const rate = checkRateLimit(ip);
if (!rate.allowed) {
logEvent("moa.orchestrate.rate_limited", { ip });
return fail("Rate limit reached. Please try again shortly.", 429);
}
let raw: unknown;
try {
raw = await req.json();
} catch {
return fail("Request body must be valid JSON.", 400);
}
const parsed = OrchestrateRequestSchema.safeParse(raw);
if (!parsed.success) {
const issue = parsed.error.issues[0];
const where = issue?.path.length ? `${issue.path.join(".")}: ` : "";
return fail(
`Invalid request — ${where}${issue?.message ?? "provide a claim plus sources[{id, text}]."}`,
400
);
}
try {
const { claim, sources, options } = parsed.data;
const result = await orchestrate({ claim, sources, options });
logEvent("moa.orchestrate.success", {
latencyMs: Date.now() - start,
sourceCount: sources.length,
selected: result.agents.length,
verdict: result.aggregate.verdict,
trust: result.aggregate.trust,
usedClaude: result.usedClaude,
});
return ok(result);
} catch (err) {
logEvent("moa.orchestrate.error", { latencyMs: Date.now() - start, error: String(err) });
console.error("[/api/moa/orchestrate] failed:", err);
return fail(
"Something went wrong while running the mixture of agents. This has been logged — please check your inputs and try again.",
500
);
}
}