W3.6: chat request_investigation tool + /jobs/[id] case-file viewer
Some checks failed
CI / Web — typecheck + lint + build (push) Failing after 44s
CI / Scripts — Python smoke (push) Failing after 3s
CI / Web — npm audit (push) Failing after 43s
CI / Retrieval — golden set (Recall@5 + MRR) (push) Failing after 7s

Closes the loop between the chat UI and the Investigation Bureau runtime.

Chat tool (web/lib/chat/tools.ts):
  - request_investigation { kind, question, doc_id?, chunks?, claim? }
    INSERTs a row in public.investigation_jobs and returns
    { job_id, kind, status, eta_seconds, status_url, detective }.
  - kind=hypothesis_tournament → Holmes (1 question → 2-3 rival hypotheses)
  - kind=evidence_chain → Locard (1 doc → grade-A/B/C evidence with chain
    of custody, default top-5 anomaly chunks)
  - Plumbed user.email through ToolHandlerContext so triggered_by audits
    the requesting user.

Public job viewer:
  - GET /api/jobs/[id] joins investigation_jobs → public.evidence +
    public.hypotheses for the IDs surfaced in outputs[]. Returns one
    payload the page can render without n+1 round-trips. Strips
    triggered_by from the response (it carries the user's email).
  - app/jobs/[id]/page.tsx server-renders the case-file shell:
    detective lore header (Holmes blue or Locard green), question chip,
    scope chip with link back to the document.
  - components/job-status-poller.tsx client island that polls every 3 s
    while non-terminal, then once on terminal to hydrate evidence +
    hypotheses. Renders:
      · Phase tracker (queued → running → complete | failed)
      · Hypothesis cards w/ prior + posterior bars + Δ delta indicator
        + Tetlock band badge (high/medium/low/speculation)
      · Argument-for / argument-against with [[wiki-link]] auto-linking
        to /d/<doc>/p<NNN>#<cNNNN>
      · Evidence cards w/ Grade A/B/C badge + verbatim blockquote +
        bbox crop preview via /api/crop + custody-steps disclosure
      · Empty/in-flight panel ("os detetives estão lendo o corpus")
      · Failure panel surfacing error + partial outputs

Inline chat-bubble card (components/chat-bubble.tsx):
  - ToolTrace.richRender recognises request_investigation results and
    renders a detective banner with status + ETA + link to /jobs/[id]
    (target=_blank). Error case renders a red strip with the message.

UX flow now: user asks Sherlock a question → request_investigation
queues the job → chat card shows "🔎 Holmes · hypothesis_tournament ·
ETA ~60s" → user clicks → /jobs/<id> live-updates → 60 s later, 2-3
rival hypotheses + their arguments + chunk citations are rendered with
Bayesian update visible.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Luiz Gustavo 2026-05-23 21:26:18 -03:00
parent 4d4c02a8e1
commit b76e81e4b3
6 changed files with 868 additions and 0 deletions

View file

@ -0,0 +1,140 @@
/**
* GET /api/jobs/[id] public read of an investigation_jobs row.
*
* Hydrates the outputs[] payload by joining to public.evidence / public.hypotheses
* so the /jobs/[id] page can render evidence cards + hypothesis cards without
* n+1 round-trips.
*
* No auth required (read-only): anyone with a job_id can see status. This
* matches the chat tool's UX: the chat reveals the URL, the user opens it,
* the page renders. No PII is exposed beyond what the user already typed
* (triggered_by carries their email we strip it).
*/
import { NextResponse } from "next/server";
import { pgQuery } from "@/lib/retrieval/db";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
interface JobRow {
job_id: string;
kind: string;
payload: Record<string, unknown> | null;
status: string;
worker_id: string | null;
started_at: string | null;
finished_at: string | null;
outputs: unknown;
error: string | null;
created_at: string;
}
interface EvidenceRow {
evidence_id: string;
grade: string | null;
source_page_id: string;
doc_id: string | null;
page: number | null;
chunk_id: string | null;
verbatim_excerpt: string | null;
custody_steps: unknown;
bbox: unknown;
confidence_band: string | null;
related_hypotheses: unknown;
}
interface HypothesisRow {
hypothesis_id: string;
question: string | null;
position: string | null;
argument_for: string | null;
argument_against: string | null;
prior: number | null;
posterior: number | null;
confidence_band: string | null;
status: string | null;
evidence_refs: unknown;
}
function durationMs(started: string | null, finished: string | null, created: string): number | null {
const a = started ? new Date(started).getTime() : null;
const b = finished ? new Date(finished).getTime() : null;
if (a !== null && b !== null) return b - a;
if (a !== null) return Date.now() - a;
return Date.now() - new Date(created).getTime();
}
export async function GET(
_request: Request,
ctx: { params: Promise<{ id: string }> },
) {
const { id } = await ctx.params;
if (!/^[0-9a-f-]{36}$/i.test(id)) {
return NextResponse.json({ error: "bad_job_id" }, { status: 400 });
}
try {
const rows = await pgQuery<JobRow>(
`SELECT job_id, kind, payload, status, worker_id, started_at, finished_at,
outputs, error, created_at
FROM public.investigation_jobs WHERE job_id = $1`,
[id],
);
const job = rows[0];
if (!job) return NextResponse.json({ error: "not_found" }, { status: 404 });
// Collect IDs surfaced in outputs[] for hydration.
const evidenceIds: string[] = [];
const hypothesisIds: string[] = [];
if (Array.isArray(job.outputs)) {
for (const o of job.outputs as Array<Record<string, unknown>>) {
if (typeof o.evidence_id === "string") evidenceIds.push(o.evidence_id);
if (typeof o.hypothesis_id === "string") hypothesisIds.push(o.hypothesis_id);
}
}
const [evidence, hypotheses] = await Promise.all([
evidenceIds.length > 0
? pgQuery<EvidenceRow>(
`SELECT e.evidence_id, e.grade, e.source_page_id,
split_part(e.source_page_id, '/p', 1) AS doc_id,
NULLIF(split_part(e.source_page_id, '/p', 2), '')::int AS page,
c.chunk_id, e.verbatim_excerpt, e.custody_steps, e.bbox,
e.confidence_band, e.related_hypotheses
FROM public.evidence e
LEFT JOIN public.chunks c ON c.chunk_pk = e.source_chunk_pk
WHERE e.evidence_id = ANY($1::text[])
ORDER BY e.evidence_id`,
[evidenceIds],
)
: Promise.resolve([] as EvidenceRow[]),
hypothesisIds.length > 0
? pgQuery<HypothesisRow>(
`SELECT hypothesis_id, question, position, argument_for, argument_against,
prior, posterior, confidence_band, status, evidence_refs
FROM public.hypotheses
WHERE hypothesis_id = ANY($1::text[])
ORDER BY hypothesis_id`,
[hypothesisIds],
)
: Promise.resolve([] as HypothesisRow[]),
]);
return NextResponse.json({
job_id: job.job_id,
kind: job.kind,
payload: job.payload,
status: job.status,
worker_id: job.worker_id,
started_at: job.started_at,
finished_at: job.finished_at,
created_at: job.created_at,
duration_ms: durationMs(job.started_at, job.finished_at, job.created_at),
error: job.error,
outputs: Array.isArray(job.outputs) ? job.outputs : [],
evidence,
hypotheses,
});
} catch (e) {
return NextResponse.json({ error: "db_unavailable", message: (e as Error).message }, { status: 503 });
}
}

View file

@ -217,6 +217,7 @@ export async function POST(request: Request, ctx: { params: Promise<{ id: string
doc_id: session.context_doc_id,
page_id: session.context_page_id,
lang: (await getLocale()) === "en" ? "en" : "pt",
user_email: user.email ?? null,
},
});

122
web/app/jobs/[id]/page.tsx Normal file
View file

@ -0,0 +1,122 @@
/**
* /jobs/[id] Investigation Bureau case file viewer.
*
* Server-rendered shell with the first snapshot fetched directly from
* pg (one round-trip). A client island then polls /api/jobs/[id] every 3s
* while the job is non-terminal (queued | running).
*
* Detectives:
* - hypothesis_tournament Sherlock Holmes
* - evidence_chain Edmond Locard
*
* Renders:
* - Phase tracker (queued claimed running complete | failed)
* - Hypothesis cards w/ prior+posterior bars + Tetlock confidence_band badge
* - Evidence cards w/ grade A/B/C badge + verbatim_excerpt + bbox crop link
*/
import { notFound } from "next/navigation";
import Link from "next/link";
import { pgQuery } from "@/lib/retrieval/db";
import { AuthBar } from "@/components/auth-bar";
import { JobStatusPoller } from "@/components/job-status-poller";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
interface InitialJob {
job_id: string;
kind: string;
payload: Record<string, unknown> | null;
status: string;
worker_id: string | null;
started_at: string | null;
finished_at: string | null;
outputs: unknown;
error: string | null;
created_at: string;
}
export default async function JobPage({
params,
}: { params: Promise<{ id: string }> }) {
const { id } = await params;
if (!/^[0-9a-f-]{36}$/i.test(id)) notFound();
const rows = await pgQuery<InitialJob>(
`SELECT job_id, kind, payload, status, worker_id, started_at, finished_at,
outputs, error, created_at
FROM public.investigation_jobs WHERE job_id = $1`,
[id],
).catch(() => [] as InitialJob[]);
const job = rows[0];
if (!job) notFound();
const isHolmes = job.kind === "hypothesis_tournament";
const detectiveName = isHolmes ? "Sherlock Holmes" : "Edmond Locard";
const detectiveSlug = isHolmes ? "holmes" : "locard";
const detectiveTone = isHolmes ? "text-[#7fdbff]" : "text-[#06d6a0]";
const detectiveBg = isHolmes ? "from-[rgba(127,219,255,0.08)]" : "from-[rgba(6,214,160,0.08)]";
const question = (job.payload as Record<string, unknown>)?.question as string | undefined;
const docId = (job.payload as Record<string, unknown>)?.doc_id as string | undefined;
return (
<div className="min-h-screen bg-[#0a0e1a] text-[#e7ecf3]">
<AuthBar />
<div className="mx-auto max-w-5xl px-4 py-8 pt-16">
<div className="text-[11px] text-[#5a6678] font-mono mb-2">
<Link href="/" className="hover:text-[#7fdbff]">disclosure.top</Link>
<span className="mx-1">/</span>
<span>investigation</span>
<span className="mx-1">/</span>
<span className="text-[#7fdbff]">{job.job_id.slice(0, 8)}</span>
</div>
<div className={`rounded-lg border border-[rgba(127,219,255,0.18)] bg-gradient-to-br ${detectiveBg} to-transparent p-5`}>
<div className="flex items-baseline justify-between gap-4 flex-wrap">
<div>
<h1 className={`text-2xl font-mono font-bold ${detectiveTone}`}>
{detectiveName}
</h1>
<p className="text-[12px] text-[#9aa6b8] mt-1 font-mono">
{isHolmes
? "Hypothesis tournament · rival hypotheses with Bayesian update"
: "Evidence chain · verbatim quotes with chain of custody (Locard)"}
</p>
</div>
<span className={`px-2 py-0.5 rounded text-[10px] font-mono uppercase border ${detectiveTone} border-current`}>
{detectiveSlug}
</span>
</div>
{question && (
<div className="mt-4 p-3 bg-[#060a13] rounded border border-[rgba(127,219,255,0.1)]">
<div className="text-[10px] text-[#5a6678] font-mono uppercase mb-1">Question</div>
<div className="text-[14px] text-[#e7ecf3] leading-snug">{question}</div>
</div>
)}
{docId && (
<div className="mt-2 text-[11px] font-mono text-[#9aa6b8]">
Scope: <Link href={`/d/${docId}`} className="text-[#7fdbff] hover:underline">{docId}</Link>
</div>
)}
</div>
<JobStatusPoller
jobId={job.job_id}
initialJob={{
job_id: job.job_id,
kind: job.kind,
payload: job.payload,
status: job.status,
worker_id: job.worker_id,
started_at: job.started_at,
finished_at: job.finished_at,
created_at: job.created_at,
outputs: Array.isArray(job.outputs) ? job.outputs : [],
error: job.error,
}}
/>
</div>
</div>
);
}

View file

@ -671,6 +671,45 @@ function ToolTrace({ t }: { t: ToolBlock }) {
// Rich render for retrieval tools — show citation cards inline
const richRender = (() => {
if (!t.result || typeof t.result !== "object") return null;
// request_investigation: render a detective status card with a link to /jobs/[id]
if (t.name === "request_investigation") {
const r = t.result as {
job_id?: string; kind?: string; status?: string; status_url?: string;
eta_seconds?: number; detective?: string; error?: string;
};
if (r.error || !r.job_id) {
return (
<div className="mt-1 ml-3 p-2 rounded border border-[#ff3344]/40 bg-[rgba(255,51,68,0.06)] text-[11px] font-mono text-[#ff6ec7]">
investigation_unavailable: {r.error || "unknown"}
</div>
);
}
const isHolmes = r.kind === "hypothesis_tournament";
const tone = isHolmes ? "text-[#7fdbff] border-[#7fdbff]" : "text-[#06d6a0] border-[#06d6a0]";
return (
<div className={`mt-1 ml-3 p-3 rounded border ${tone} bg-[#060a13]`}>
<div className="flex items-baseline justify-between mb-1">
<div className={`font-mono text-[11px] font-bold ${isHolmes ? "text-[#7fdbff]" : "text-[#06d6a0]"}`}>
🔎 {isHolmes ? "Holmes" : "Locard"} · {r.kind}
</div>
<span className="text-[10px] text-[#5a6678] font-mono uppercase">{r.status}</span>
</div>
<div className="text-[10px] text-[#9aa6b8] font-mono">
job <span className="text-[#e7ecf3]">{r.job_id.slice(0, 8)}</span>
{r.eta_seconds ? <span className="ml-2">· ETA ~{r.eta_seconds}s</span> : null}
</div>
{r.status_url && (
<Link
href={r.status_url}
target="_blank"
className={`mt-2 inline-flex items-center gap-1 text-[11px] font-mono ${isHolmes ? "text-[#7fdbff]" : "text-[#06d6a0]"} hover:underline`}
>
acompanhar a investigação <ArrowUpRight size={11} />
</Link>
)}
</div>
);
}
const r = t.result as { hits?: ChunkHit[]; anomalies?: ChunkHit[]; chunks?: ChunkHit[] };
const items = r.hits ?? r.anomalies ?? r.chunks ?? null;
if (!items || items.length === 0) return null;

View file

@ -0,0 +1,453 @@
"use client";
/**
* JobStatusPoller client island for /jobs/[id].
*
* Polls /api/jobs/[id] every 3s while job.status is non-terminal. Renders:
* - Phase tracker bar (queued claimed running complete | failed)
* - Hypothesis cards (prior/posterior bars + Tetlock confidence_band)
* - Evidence cards (grade A/B/C + verbatim excerpt + bbox preview)
* - Error panel when status='failed'
*/
import { useEffect, useState } from "react";
import Link from "next/link";
interface JobPayloadOutput {
evidence_id?: string;
hypothesis_id?: string;
case_file?: string;
chunk_id?: string;
error?: string;
skipped?: boolean;
reason?: string;
kind?: string;
}
interface InitialJob {
job_id: string;
kind: string;
payload: Record<string, unknown> | null;
status: string;
worker_id: string | null;
started_at: string | null;
finished_at: string | null;
outputs: JobPayloadOutput[];
error: string | null;
created_at: string;
}
interface EvidenceItem {
evidence_id: string;
grade: string | null;
source_page_id: string;
doc_id: string | null;
page: number | null;
chunk_id: string | null;
verbatim_excerpt: string | null;
custody_steps: Array<Record<string, unknown>> | null;
bbox: { x: number; y: number; w: number; h: number } | null;
confidence_band: string | null;
}
interface HypothesisItem {
hypothesis_id: string;
question: string | null;
position: string | null;
argument_for: string | null;
argument_against: string | null;
prior: number | string | null;
posterior: number | string | null;
confidence_band: string | null;
status: string | null;
}
interface FetchedJob extends InitialJob {
evidence: EvidenceItem[];
hypotheses: HypothesisItem[];
duration_ms: number | null;
}
const BAND_COLOR: Record<string, string> = {
high: "text-[#06d6a0] border-[#06d6a0]",
medium: "text-[#3fde6a] border-[#3fde6a]",
low: "text-[#ffa500] border-[#ffa500]",
speculation: "text-[#ff6ec7] border-[#ff6ec7]",
};
const GRADE_COLOR: Record<string, string> = {
A: "text-[#06d6a0] border-[#06d6a0]",
B: "text-[#3fde6a] border-[#3fde6a]",
C: "text-[#ffa500] border-[#ffa500]",
};
const STATUS_LABEL: Record<string, string> = {
queued: "Aguardando worker",
running: "Investigação em curso",
complete: "Concluído",
failed: "Falhou",
};
const PHASES = ["queued", "running", "complete"] as const;
function isTerminal(status: string): boolean {
return status === "complete" || status === "failed";
}
function asNumber(n: number | string | null): number | null {
if (n === null || n === undefined) return null;
const v = typeof n === "string" ? parseFloat(n) : n;
return Number.isFinite(v) ? v : null;
}
function formatDuration(ms: number | null): string {
if (!ms || ms < 0) return "—";
if (ms < 1000) return `${ms} ms`;
if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;
return `${Math.floor(ms / 60_000)} min ${Math.floor((ms % 60_000) / 1000)} s`;
}
export function JobStatusPoller(props: { jobId: string; initialJob: InitialJob }) {
const [job, setJob] = useState<FetchedJob>({
...props.initialJob,
evidence: [],
hypotheses: [],
duration_ms: null,
});
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
async function tick() {
try {
const r = await fetch(`/api/jobs/${props.jobId}`, { cache: "no-store" });
if (!r.ok) {
if (!cancelled) setError(`HTTP ${r.status}`);
} else {
const data = (await r.json()) as FetchedJob;
if (!cancelled) {
setJob(data);
setError(null);
}
}
} catch (e) {
if (!cancelled) setError((e as Error).message);
}
if (!cancelled) {
const next = isTerminal(job.status) ? null : setTimeout(tick, 3000);
timer = next;
}
}
if (!isTerminal(job.status)) {
timer = setTimeout(tick, 1500);
} else {
// Even when terminal, do a single hydrate to fetch evidence/hypotheses
tick();
}
return () => {
cancelled = true;
if (timer) clearTimeout(timer);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.jobId, job.status]);
const currentPhaseIdx = (() => {
if (job.status === "complete") return 2;
if (job.status === "failed") return -1;
if (job.status === "running") return 1;
return 0;
})();
return (
<div className="mt-6 space-y-4">
{/* Phase tracker */}
<div className="rounded-lg border border-[rgba(127,219,255,0.18)] bg-[#0d1220] p-4">
<div className="flex items-center justify-between mb-3">
<div className="text-[11px] font-mono text-[#5a6678] uppercase">Status</div>
<div className="text-[11px] font-mono text-[#9aa6b8]">
{STATUS_LABEL[job.status] ?? job.status}
{job.duration_ms !== null && (
<span className="ml-2 text-[#5a6678]">· {formatDuration(job.duration_ms)}</span>
)}
</div>
</div>
<div className="flex items-center gap-2">
{PHASES.map((phase, i) => {
const done = i <= currentPhaseIdx && job.status !== "failed";
const active = i === currentPhaseIdx && !isTerminal(job.status);
return (
<div key={phase} className="flex-1 flex items-center gap-2">
<div
className={`flex-1 h-1.5 rounded-full ${
job.status === "failed" ? "bg-[#ff3344]/40" :
done ? "bg-[#06d6a0]" :
active ? "bg-gradient-to-r from-[#06d6a0] to-[#0d1220] animate-pulse" :
"bg-[rgba(127,219,255,0.15)]"
}`}
/>
{i < PHASES.length - 1 && <span className="text-[#5a6678]"></span>}
</div>
);
})}
</div>
<div className="flex justify-between mt-2 text-[10px] font-mono text-[#5a6678]">
{PHASES.map((p) => <span key={p}>{p}</span>)}
</div>
{job.worker_id && (
<div className="mt-3 text-[10px] font-mono text-[#5a6678]">
worker: <span className="text-[#9aa6b8]">{job.worker_id}</span>
</div>
)}
{error && (
<div className="mt-3 text-[10px] font-mono text-[#ff6ec7]">
polling error: {error}
</div>
)}
</div>
{/* Failure panel */}
{job.status === "failed" && (
<div className="rounded-lg border border-[#ff3344]/40 bg-[rgba(255,51,68,0.06)] p-4">
<div className="text-[11px] font-mono uppercase text-[#ff3344] mb-2">Job failed</div>
<pre className="text-[12px] text-[#e7ecf3] whitespace-pre-wrap font-mono leading-snug">
{job.error || "(no error message)"}
</pre>
{job.outputs.length > 0 && (
<details className="mt-3">
<summary className="text-[10px] font-mono text-[#5a6678] cursor-pointer hover:text-[#9aa6b8]">
{job.outputs.length} partial output(s)
</summary>
<pre className="mt-2 text-[10px] text-[#8896aa] overflow-x-auto max-h-48 font-mono">
{JSON.stringify(job.outputs, null, 2)}
</pre>
</details>
)}
</div>
)}
{/* Hypothesis cards */}
{job.hypotheses.length > 0 && (
<div className="space-y-3">
<div className="text-[12px] font-mono text-[#7fdbff] uppercase tracking-wider">
Hipóteses rivais ({job.hypotheses.length})
</div>
{job.hypotheses.map((h) => <HypothesisCard key={h.hypothesis_id} h={h} />)}
</div>
)}
{/* Evidence cards */}
{job.evidence.length > 0 && (
<div className="space-y-3">
<div className="text-[12px] font-mono text-[#06d6a0] uppercase tracking-wider">
Cadeia de evidência ({job.evidence.length})
</div>
{job.evidence.map((e) => <EvidenceCard key={e.evidence_id} e={e} />)}
</div>
)}
{/* Empty / in-flight state */}
{!isTerminal(job.status) && job.hypotheses.length === 0 && job.evidence.length === 0 && (
<div className="rounded-lg border border-dashed border-[rgba(127,219,255,0.15)] bg-[#0d1220] p-6 text-center">
<div className="text-[12px] font-mono text-[#9aa6b8] animate-pulse">
🔎 Os detetives estão lendo o corpus
</div>
<div className="text-[10px] font-mono text-[#5a6678] mt-2">
Holmes constrói hipóteses rivais com priors + posteriors em ~60 s.<br />
Locard documenta evidências verbatim com cadeia de custódia em ~30 s por chunk.
</div>
</div>
)}
{/* Outputs raw */}
{job.outputs.length > 0 && job.status === "complete" && (
<details className="mt-2">
<summary className="text-[10px] font-mono text-[#5a6678] cursor-pointer hover:text-[#9aa6b8]">
Raw audit outputs ({job.outputs.length})
</summary>
<pre className="mt-2 p-3 bg-[#060a13] border border-[rgba(127,219,255,0.1)] rounded text-[10px] text-[#8896aa] overflow-x-auto max-h-64 font-mono">
{JSON.stringify(job.outputs, null, 2)}
</pre>
</details>
)}
</div>
);
}
function HypothesisCard({ h }: { h: HypothesisItem }) {
const prior = asNumber(h.prior);
const posterior = asNumber(h.posterior);
const delta = prior !== null && posterior !== null ? posterior - prior : null;
const bandTone = (h.confidence_band && BAND_COLOR[h.confidence_band]) || "text-[#9aa6b8] border-[#9aa6b8]";
return (
<div className="rounded-lg border border-[rgba(127,219,255,0.18)] bg-[#0d1220] p-4">
<div className="flex items-baseline justify-between gap-3 mb-2">
<div className="text-[10px] font-mono text-[#5a6678] uppercase">
{h.hypothesis_id}
</div>
{h.confidence_band && (
<span className={`px-2 py-0.5 rounded text-[10px] font-mono uppercase border ${bandTone}`}>
{h.confidence_band}
</span>
)}
</div>
<div className="text-[14px] text-[#e7ecf3] leading-snug font-medium mb-3">
{h.position}
</div>
{(prior !== null || posterior !== null) && (
<div className="grid grid-cols-2 gap-3 mb-3 text-[11px] font-mono">
<ProbabilityBar label="prior" value={prior} color="#5a6678" />
<ProbabilityBar label="posterior" value={posterior} color="#7fdbff" />
</div>
)}
{delta !== null && (
<div className="text-[10px] font-mono text-[#5a6678] mb-2">
Δ {delta >= 0 ? "+" : ""}{delta.toFixed(3)} ·{" "}
{delta > 0.05 ? <span className="text-[#06d6a0]">evidência reforçou</span> :
delta < -0.05 ? <span className="text-[#ff6ec7]">evidência reduziu</span> :
<span className="text-[#9aa6b8]">evidência ambígua</span>}
</div>
)}
{h.argument_for && (
<div className="mt-3">
<div className="text-[10px] font-mono text-[#06d6a0] uppercase mb-1">Argumento a favor</div>
<ArgumentBody text={h.argument_for} />
</div>
)}
{h.argument_against && (
<div className="mt-3">
<div className="text-[10px] font-mono text-[#ff6ec7] uppercase mb-1">Argumento contra</div>
<ArgumentBody text={h.argument_against} />
</div>
)}
</div>
);
}
function EvidenceCard({ e }: { e: EvidenceItem }) {
const gradeTone = (e.grade && GRADE_COLOR[e.grade]) || "text-[#9aa6b8] border-[#9aa6b8]";
const bandTone = (e.confidence_band && BAND_COLOR[e.confidence_band]) || "text-[#9aa6b8] border-[#9aa6b8]";
const stepsCount = Array.isArray(e.custody_steps) ? e.custody_steps.length : 0;
const cropUrl = e.doc_id && e.page && e.bbox && e.bbox.w > 0 && e.bbox.h > 0
? `/api/crop?doc=${encodeURIComponent(e.doc_id)}&page=${e.page}&x=${e.bbox.x}&y=${e.bbox.y}&w=${e.bbox.w}&h=${e.bbox.h}&w_px=480`
: null;
return (
<div className="rounded-lg border border-[rgba(6,214,160,0.18)] bg-[#0d1220] p-4">
<div className="flex items-baseline justify-between gap-3 mb-2">
<div className="text-[10px] font-mono text-[#5a6678] uppercase">{e.evidence_id}</div>
<div className="flex items-center gap-2">
{e.grade && (
<span className={`px-2 py-0.5 rounded text-[10px] font-mono uppercase border ${gradeTone}`}>
Grade {e.grade}
</span>
)}
{e.confidence_band && (
<span className={`px-2 py-0.5 rounded text-[10px] font-mono uppercase border ${bandTone}`}>
{e.confidence_band}
</span>
)}
</div>
</div>
{e.verbatim_excerpt && (
<blockquote className="text-[13px] text-[#e7ecf3] leading-snug italic border-l-2 border-[#06d6a0] pl-3 my-2">
{e.verbatim_excerpt}
</blockquote>
)}
{cropUrl && (
// eslint-disable-next-line @next/next/no-img-element
<img
src={cropUrl}
alt={`${e.doc_id} p${e.page}`}
className="mt-2 rounded border border-[rgba(127,219,255,0.1)] max-h-48 w-auto"
/>
)}
<div className="mt-3 flex flex-wrap items-center gap-2 text-[10px] font-mono text-[#5a6678]">
{e.doc_id && e.page && (
<Link
href={`/d/${e.doc_id}/p${String(e.page).padStart(3, "0")}${e.chunk_id ? `#${e.chunk_id}` : ""}`}
className="text-[#7fdbff] hover:underline"
>
{e.doc_id}/p{String(e.page).padStart(3, "0")}{e.chunk_id ? `#${e.chunk_id}` : ""}
</Link>
)}
<span>·</span>
<span>{stepsCount} custody step{stepsCount === 1 ? "" : "s"}</span>
</div>
{stepsCount > 0 && (
<details className="mt-2">
<summary className="text-[10px] font-mono text-[#5a6678] cursor-pointer hover:text-[#9aa6b8]">
Cadeia de custódia
</summary>
<ol className="mt-2 ml-4 list-decimal text-[11px] text-[#9aa6b8] space-y-1">
{(e.custody_steps as Array<Record<string, unknown>>).map((s, i) => (
<li key={i}>
<span className="text-[#7fdbff]">{String(s.actor ?? "?")}</span>
{s.action ? `${String(s.action)}` : ""}
{s.timestamp ? ` (${String(s.timestamp)})` : ""}
</li>
))}
</ol>
</details>
)}
</div>
);
}
function ProbabilityBar({ label, value, color }: { label: string; value: number | null; color: string }) {
const pct = value !== null ? Math.round(value * 100) : 0;
return (
<div>
<div className="flex items-center justify-between mb-1">
<span className="text-[#5a6678]">{label}</span>
<span className="text-[#e7ecf3]">{value !== null ? value.toFixed(3) : "—"}</span>
</div>
<div className="h-1.5 bg-[rgba(127,219,255,0.08)] rounded-full overflow-hidden">
<div className="h-full rounded-full" style={{ width: `${pct}%`, background: color }} />
</div>
</div>
);
}
// Linkify [[doc-id/pNNN#cNNNN]] wiki-links in argument prose into <a> tags.
function ArgumentBody({ text }: { text: string }) {
const parts: Array<{ kind: "text" | "link"; raw: string; href?: string; label?: string }> = [];
const re = /\[\[([^\]|]+?)(?:\|([^\]]+))?\]\]/g;
let lastIdx = 0;
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
if (m.index > lastIdx) parts.push({ kind: "text", raw: text.slice(lastIdx, m.index) });
const target = m[1];
const label = m[2] ?? m[1];
let href: string | undefined;
// doc-id/pNNN#cNNNN
const chunkMatch = target.match(/^([a-z0-9][a-z0-9-]*)\/p(\d{3})#(c\d{4})$/);
const pageMatch = target.match(/^([a-z0-9][a-z0-9-]*)\/p(\d{3})$/);
if (chunkMatch) href = `/d/${chunkMatch[1]}/p${chunkMatch[2]}#${chunkMatch[3]}`;
else if (pageMatch) href = `/d/${pageMatch[1]}/p${pageMatch[2]}`;
parts.push({ kind: "link", raw: m[0], href, label });
lastIdx = m.index + m[0].length;
}
if (lastIdx < text.length) parts.push({ kind: "text", raw: text.slice(lastIdx) });
return (
<div className="text-[12px] text-[#cbd2dd] leading-relaxed">
{parts.map((p, i) =>
p.kind === "text" ? <span key={i}>{p.raw}</span> :
p.href ? <Link key={i} href={p.href} className="text-[#7fdbff] hover:underline">{p.label}</Link> :
<span key={i} className="text-[#5a6678]">{p.label}</span>
)}
</div>
);
}

View file

@ -43,6 +43,7 @@ import {
findPaths,
getCoMentionChunks,
} from "../retrieval/graph";
import { pgQuery } from "../retrieval/db";
export interface ToolDefinition {
type: "function";
@ -59,6 +60,9 @@ export interface ToolHandlerContext {
page_id?: string | null;
/** UI language preference (pt | en). */
lang?: "pt" | "en";
/** Authenticated user's email populated by /api/sessions/[id]/messages so
* tools that audit (e.g. request_investigation) can label `triggered_by`. */
user_email?: string | null;
/** Optional sink for inline AG-UI artifacts (citations, crops, entity cards).
* When provided, tools may push typed artifacts that the UI renders inline
* alongside the tool block. Safe to leave undefined for non-streaming callers. */
@ -347,6 +351,58 @@ const analyze_image_region_tool: ToolDefinition = {
},
};
const request_investigation_tool: ToolDefinition = {
type: "function",
function: {
name: "request_investigation",
description:
"Queue a deeper investigation by the 8-detective Investigation Bureau. " +
"Use ONLY when the user asks for analysis that requires structured reasoning " +
"across multiple chunks — e.g. 'build rival hypotheses about X', " +
"'audit this doc for contradictions', 'trace the chain of custody for claim Y'. " +
"Do NOT use for plain lookups; hybrid_search is faster. " +
"kinds: hypothesis_tournament (Holmes — 2-3 rival hypotheses with priors/posteriors) | " +
"evidence_chain (Locard — verbatim evidence with chain_of_custody on N chunks of one doc). " +
"Returns { job_id, kind, status_url, eta_seconds }. The UI renders a status card " +
"with a link to /jobs/<job_id>; the worker takes ~30-120 seconds.",
parameters: {
type: "object",
properties: {
kind: {
type: "string",
enum: ["hypothesis_tournament", "evidence_chain"],
description: "Detective task kind.",
},
question: {
type: "string",
description:
"For hypothesis_tournament: the investigative question (one sentence, declarative). " +
"Required for hypothesis_tournament; ignored for evidence_chain.",
},
doc_id: {
type: "string",
description:
"Optional scope. For hypothesis_tournament: narrows the corpus shortlist. " +
"For evidence_chain: REQUIRED — the doc Locard scans.",
},
chunks: {
type: "array",
items: { type: "string" },
description:
"Optional for evidence_chain: list of chunk_ids to inspect. Defaults to the " +
"top 5 anomaly-flagged chunks in the doc.",
},
claim: {
type: "string",
description:
"Optional for evidence_chain: a specific claim Locard should look for support of.",
},
},
required: ["kind"],
},
},
};
const navigate_to_tool: ToolDefinition = {
type: "function",
function: {
@ -379,6 +435,7 @@ export const TOOL_DEFINITIONS: ToolDefinition[] = [
read_entity_tool,
search_corpus_tool,
analyze_image_region_tool,
request_investigation_tool,
navigate_to_tool,
];
@ -716,6 +773,61 @@ async function handleCoMentionChunks(args: Record<string, unknown>): Promise<unk
}
}
async function handleRequestInvestigation(
args: Record<string, unknown>,
ctx: ToolHandlerContext,
): Promise<unknown> {
const kind = String(args.kind ?? "").trim();
if (kind !== "hypothesis_tournament" && kind !== "evidence_chain") {
return { error: "bad_kind", message: "kind must be hypothesis_tournament or evidence_chain" };
}
const docArg = typeof args.doc_id === "string" && args.doc_id.trim()
? args.doc_id.trim() : ctx.doc_id || null;
const lang = pickLang(ctx);
const payload: Record<string, unknown> = {};
if (kind === "hypothesis_tournament") {
const question = String(args.question ?? "").trim();
if (!question) return { error: "question_required", message: "hypothesis_tournament needs a question" };
payload.question = question;
payload.lang = lang;
if (docArg) payload.doc_id = docArg;
} else {
if (!docArg) return { error: "doc_id_required", message: "evidence_chain needs a doc_id" };
payload.doc_id = docArg;
if (Array.isArray(args.chunks)) {
payload.chunks = (args.chunks as unknown[]).filter((c): c is string => typeof c === "string");
}
if (typeof args.claim === "string" && args.claim.trim()) payload.claim = args.claim.trim();
}
const triggered_by = ctx.user_email ? `user:${ctx.user_email}` : "user:anonymous";
// Investigation Bureau expected duration: Holmes ~60s, Locard ~30s × n_chunks.
const eta = kind === "hypothesis_tournament" ? 60 : 30 * 5;
try {
const rows = await pgQuery<{ job_id: string; created_at: string }>(
`INSERT INTO public.investigation_jobs (kind, payload, triggered_by, status)
VALUES ($1, $2::jsonb, $3, 'queued')
RETURNING job_id, created_at`,
[kind, JSON.stringify(payload), triggered_by],
);
const row = rows[0];
if (!row) return { error: "insert_failed" };
return {
job_id: row.job_id,
kind,
status: "queued",
eta_seconds: eta,
status_url: `/jobs/${row.job_id}`,
payload_summary: payload,
detective: kind === "hypothesis_tournament" ? "holmes" : "locard",
};
} catch (e) {
return { error: "db_unavailable", message: (e as Error).message };
}
}
async function handleNavigate(args: Record<string, unknown>): Promise<unknown> {
const target = String(args.target ?? "").trim();
const label = String(args.label ?? "").slice(0, 40);
@ -767,5 +879,6 @@ export const TOOL_HANDLERS: Record<string, ToolHandler> = {
read_entity: handleReadEntity,
search_corpus: handleSearch,
analyze_image_region: handleAnalyzeImageRegion,
request_investigation: handleRequestInvestigation,
navigate_to: handleNavigate,
};