disclosure-bureau/web/app/jobs/[id]/page.tsx
Luiz Gustavo b76e81e4b3
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
W3.6: chat request_investigation tool + /jobs/[id] case-file viewer
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>
2026-05-23 21:26:18 -03:00

122 lines
4.6 KiB
TypeScript

/**
* /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>
);
}