disclosure-bureau/web/app/jobs/[id]/page.tsx
Luiz Gustavo dd75a67964
Some checks failed
CI / Web — typecheck + lint + build (push) Failing after 45s
CI / Scripts — Python smoke (push) Failing after 5s
CI / Web — npm audit (push) Failing after 40s
CI / Retrieval — golden set (Recall@5 + MRR) (push) Failing after 3s
W3.8: Investigation Bureau complete — Poirot, Taleb, Tetlock, Case-Writer
Brings the bureau from 4 → 8 detectives. All eight run as Bun + claude-CLI
subprocesses against the same Supabase + investigation_jobs LISTEN/NOTIFY
queue, sharing search.ts hybridSearch and writer-side validators that
gate writes against schema + FK.

New detectives:

  Poirot (witness_analysis)
    - prompts/poirot.md — credibility / access / bias / corroboration /
      verdict; uses entity_mentions JOIN chunks to pull 12 chunks per
      person; resolves corroboration_refs chunk_ids defensively (accepts
      bare cNNNN even when the model emits pNNN/cNNNN).
    - INSERT into public.witnesses with W-NNNN naming.
    - Tone: purple (#9b5de5).

  Taleb (outlier_scan)
    - prompts/taleb.md — "surprise is relative to a model"; at most 3
      outliers; each requires explicit dominant_model + why_surprising +
      what_it_implies; fan-out into public.gaps with scope.kind="outlier".
    - Same unscoped-fallback as Dupin (Pass 1 with doc_id, Pass 2 widens
      to corpus if hits < 3).
    - Tone: yellow (#ffd23f).

  Tetlock (calibrate_hypothesis)
    - prompts/tetlock.md — honest Bayesian update; emits new_posterior +
      Δ + recommended_action ∈ {keep, downgrade, upgrade, supersede}.
    - write_calibration UPDATEs public.hypotheses + APPENDS a
      "## Calibration history" section to the H-NNNN.md case file
      (calibration is append-only — each datapoint matters). Posterior
      band auto-corrected to match Tetlock thresholds.
    - NO_NEW_EVIDENCE sentinel handled; pure 'keep' with |Δ|<0.005 only
      touches updated_at + reviewed_by.
    - Tone: teal (#26d4cc).

  Case-Writer (case_report)
    - prompts/case-writer.md — Dr. Watson assembles all artefacts
      (E-NNNN, H-NNNN, R-NNNN, W-NNNN, G-NNNN) into a five-act narrative.
      ILIKE filter on topic; doc_id optional scope.
    - Larger budget cap (≥ $0.50) + longer timeout for prose generation.
    - Writes case/reports/<slug>.md with frontmatter (topic + counts);
      no DB table for v0.
    - New page /c/[slug] renders the report via MarkdownBody + stat chips.
    - Tone: gold (#e0c080).

Hardening across the bureau:
  - Sentinel parsing now accepts backticked AND prose-trailing forms
    (Holmes NO_HYPOTHESES, Dupin NO_CONTRADICTIONS, Schneier
    INSUFFICIENT_HYPOTHESIS, Poirot INSUFFICIENT_TESTIMONY, Taleb
    NO_OUTLIERS, Tetlock NO_NEW_EVIDENCE, Case-Writer
    INSUFFICIENT_ARTEFACTS). Avoids the failure mode where the model
    refuses honestly but the runtime treated it as a parse error
    (observed live with Poirot+Hoover identifying the DIRECTOR
    false-positive disambiguation issue in entity_mentions).

Chat tool extensions (web/lib/chat/tools.ts):
  - request_investigation now accepts 7 kinds. Each routes to its
    detective with appropriate validation (hypothesis_id regex,
    person_id kebab-case, topic non-empty, doc_id for evidence_chain).
  - ETA per kind: Holmes/Dupin 60s, Poirot 45s, Schneier/Tetlock 30s,
    Taleb 50s, Case-Writer 180s (longer prose), Locard 30×n_chunks.

UI integration:
  - chat-bubble inline card paints each detective in its tone color.
  - /jobs/[id] page header swaps name/subtitle/tone per detective;
    question label adapts ("Topic" / "Hypothesis under attack" /
    "Witness under analysis" / "Topic to outlier-scan" / "Hypothesis
    under recalibration" / "Case to assemble").
  - job-status-poller renders: case-report link card (gold), outlier
    cards (yellow), witness cards (purple) — alongside existing
    hypothesis, evidence, contradiction cards.
  - /api/jobs/[id] hydrates witnesses (JOIN entities for canonical_name)
    + gaps (with scope JSONB).
  - /c/[slug] page reads /data/ufo/case/reports/<slug>.md and renders
    with MarkdownBody, frontmatter parsed for stat chips.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 22:11:39 -03:00

166 lines
7.2 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 detective = job.kind === "hypothesis_tournament" ? "holmes"
: job.kind === "contradiction_scan" ? "dupin"
: job.kind === "red_team_review" ? "schneier"
: job.kind === "witness_analysis" ? "poirot"
: job.kind === "outlier_scan" ? "taleb"
: job.kind === "calibrate_hypothesis" ? "tetlock"
: job.kind === "case_report" ? "case-writer"
: "locard";
const detectiveName =
detective === "holmes" ? "Sherlock Holmes" :
detective === "dupin" ? "C. Auguste Dupin" :
detective === "schneier" ? "Bruce Schneier" :
detective === "poirot" ? "Hercule Poirot" :
detective === "taleb" ? "Nassim Taleb" :
detective === "tetlock" ? "Philip Tetlock" :
detective === "case-writer" ? "Dr. Watson (Case-Writer)" :
"Edmond Locard";
const detectiveSubtitle =
detective === "holmes" ? "Hypothesis tournament · rival hypotheses with Bayesian update" :
detective === "dupin" ? "Contradiction scan · pairs of chunks in irreconcilable tension" :
detective === "schneier" ? "Red-team review · hidden assumptions, failure modes, alt explanations" :
detective === "poirot" ? "Witness analysis · credibility / access / bias / corroboration" :
detective === "taleb" ? "Outlier scan · chunks that violate the dominant model" :
detective === "tetlock" ? "Calibration · honest Bayesian update with action recommendation" :
detective === "case-writer" ? "Case narrative · five-act Watson assembly of all bureau artefacts" :
"Evidence chain · verbatim quotes with chain of custody (Locard)";
const detectiveTone =
detective === "holmes" ? "text-[#7fdbff]" :
detective === "dupin" ? "text-[#ff8a4d]" :
detective === "schneier" ? "text-[#ff3344]" :
detective === "poirot" ? "text-[#9b5de5]" :
detective === "taleb" ? "text-[#ffd23f]" :
detective === "tetlock" ? "text-[#26d4cc]" :
detective === "case-writer" ? "text-[#e0c080]" :
"text-[#06d6a0]";
const detectiveBg =
detective === "holmes" ? "from-[rgba(127,219,255,0.08)]" :
detective === "dupin" ? "from-[rgba(255,138,77,0.08)]" :
detective === "schneier" ? "from-[rgba(255,51,68,0.08)]" :
detective === "poirot" ? "from-[rgba(155,93,229,0.08)]" :
detective === "taleb" ? "from-[rgba(255,210,63,0.08)]" :
detective === "tetlock" ? "from-[rgba(38,212,204,0.08)]" :
detective === "case-writer" ? "from-[rgba(224,192,128,0.08)]" :
"from-[rgba(6,214,160,0.08)]";
const payload = (job.payload ?? {}) as Record<string, unknown>;
const question = (payload.question ?? payload.topic ?? payload.hypothesis_id ?? payload.person_id) as string | undefined;
const questionLabel =
job.kind === "contradiction_scan" ? "Topic" :
job.kind === "red_team_review" ? "Hypothesis under attack" :
job.kind === "witness_analysis" ? "Witness under analysis" :
job.kind === "outlier_scan" ? "Topic to outlier-scan" :
job.kind === "calibrate_hypothesis" ? "Hypothesis under recalibration" :
job.kind === "case_report" ? "Case to assemble" :
"Question";
const docId = payload.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">{detectiveSubtitle}</p>
</div>
<span className={`px-2 py-0.5 rounded text-[10px] font-mono uppercase border ${detectiveTone} border-current`}>
{detective}
</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">{questionLabel}</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>
);
}