disclosure-bureau/web/components/job-status-poller.tsx

535 lines
19 KiB
TypeScript
Raw Normal View History

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-24 00:26:18 +00:00
"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;
}
W3.7: Dupin contradiction-scan detective + UI integration Adds the third AI detective in the Investigation Bureau runtime: C. Auguste Dupin, who scans a corpus shortlist for pairs (or small groups) of chunks that cannot both be true under any ordinary reading. Runtime: - prompts/dupin.md — discipline (no contradiction without ≥2 distinct chunk_ids; reject same-vocabulary near-misses; FEW high-confidence over MANY weak ones; emit `NO_CONTRADICTIONS` when corpus is silent) - src/detectives/dupin.ts — hybridSearch with k=18 (more chunks than Holmes because contradictions emerge from comparing dispersed claims), strict JSON-array parsing, AT MOST 3 contradictions per call - src/tools/write_contradiction.ts — validates topic + ≥2 positions drawn from ≥2 distinct chunks, resolves chunk_pk via DB lookup (rejects positions citing unknown chunks), INSERTs into public.contradictions + writes case/contradictions/R-NNNN.md - orchestrator: new `contradiction_scan` kind dispatching to runDupin; payload { topic, doc_id?, lang?, context_chunks? } Chat + UI: - request_investigation gains kind=contradiction_scan + topic arg; triggered detective auto-resolves to dupin - chat-bubble inline card renders dupin in orange (#ff8a4d) to distinguish from holmes (cyan) and locard (green) - /jobs/[id] page swaps title + subtitle + tone per detective; "Question" label becomes "Topic" for contradiction_scan - /api/jobs/[id] hydrates public.contradictions when outputs[] surfaces contradiction_ids - job-status-poller renders ContradictionCard: topic + N positions (verbatim statements quoted, stance label optional, link to source chunk) + optional notes panel, with resolution_status badge (open/resolved/irreconcilable) R-NNNN shares the contradiction_id_seq slot with relation per CLAUDE.md naming — same conceptual class (a connection between two pieces of evidence in tension). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 00:34:04 +00:00
interface ContradictionPositionItem {
doc_id: string;
chunk_id: string;
page: number;
statement: string;
stance?: string | null;
}
interface ContradictionItem {
contradiction_id: string;
topic: string;
chunks: ContradictionPositionItem[];
resolution_status: string | null;
notes: string | null;
detected_by: string | null;
}
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-24 00:26:18 +00:00
interface FetchedJob extends InitialJob {
evidence: EvidenceItem[];
hypotheses: HypothesisItem[];
W3.7: Dupin contradiction-scan detective + UI integration Adds the third AI detective in the Investigation Bureau runtime: C. Auguste Dupin, who scans a corpus shortlist for pairs (or small groups) of chunks that cannot both be true under any ordinary reading. Runtime: - prompts/dupin.md — discipline (no contradiction without ≥2 distinct chunk_ids; reject same-vocabulary near-misses; FEW high-confidence over MANY weak ones; emit `NO_CONTRADICTIONS` when corpus is silent) - src/detectives/dupin.ts — hybridSearch with k=18 (more chunks than Holmes because contradictions emerge from comparing dispersed claims), strict JSON-array parsing, AT MOST 3 contradictions per call - src/tools/write_contradiction.ts — validates topic + ≥2 positions drawn from ≥2 distinct chunks, resolves chunk_pk via DB lookup (rejects positions citing unknown chunks), INSERTs into public.contradictions + writes case/contradictions/R-NNNN.md - orchestrator: new `contradiction_scan` kind dispatching to runDupin; payload { topic, doc_id?, lang?, context_chunks? } Chat + UI: - request_investigation gains kind=contradiction_scan + topic arg; triggered detective auto-resolves to dupin - chat-bubble inline card renders dupin in orange (#ff8a4d) to distinguish from holmes (cyan) and locard (green) - /jobs/[id] page swaps title + subtitle + tone per detective; "Question" label becomes "Topic" for contradiction_scan - /api/jobs/[id] hydrates public.contradictions when outputs[] surfaces contradiction_ids - job-status-poller renders ContradictionCard: topic + N positions (verbatim statements quoted, stance label optional, link to source chunk) + optional notes panel, with resolution_status badge (open/resolved/irreconcilable) R-NNNN shares the contradiction_id_seq slot with relation per CLAUDE.md naming — same conceptual class (a connection between two pieces of evidence in tension). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 00:34:04 +00:00
contradictions: ContradictionItem[];
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-24 00:26:18 +00:00
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: [],
W3.7: Dupin contradiction-scan detective + UI integration Adds the third AI detective in the Investigation Bureau runtime: C. Auguste Dupin, who scans a corpus shortlist for pairs (or small groups) of chunks that cannot both be true under any ordinary reading. Runtime: - prompts/dupin.md — discipline (no contradiction without ≥2 distinct chunk_ids; reject same-vocabulary near-misses; FEW high-confidence over MANY weak ones; emit `NO_CONTRADICTIONS` when corpus is silent) - src/detectives/dupin.ts — hybridSearch with k=18 (more chunks than Holmes because contradictions emerge from comparing dispersed claims), strict JSON-array parsing, AT MOST 3 contradictions per call - src/tools/write_contradiction.ts — validates topic + ≥2 positions drawn from ≥2 distinct chunks, resolves chunk_pk via DB lookup (rejects positions citing unknown chunks), INSERTs into public.contradictions + writes case/contradictions/R-NNNN.md - orchestrator: new `contradiction_scan` kind dispatching to runDupin; payload { topic, doc_id?, lang?, context_chunks? } Chat + UI: - request_investigation gains kind=contradiction_scan + topic arg; triggered detective auto-resolves to dupin - chat-bubble inline card renders dupin in orange (#ff8a4d) to distinguish from holmes (cyan) and locard (green) - /jobs/[id] page swaps title + subtitle + tone per detective; "Question" label becomes "Topic" for contradiction_scan - /api/jobs/[id] hydrates public.contradictions when outputs[] surfaces contradiction_ids - job-status-poller renders ContradictionCard: topic + N positions (verbatim statements quoted, stance label optional, link to source chunk) + optional notes panel, with resolution_status badge (open/resolved/irreconcilable) R-NNNN shares the contradiction_id_seq slot with relation per CLAUDE.md naming — same conceptual class (a connection between two pieces of evidence in tension). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 00:34:04 +00:00
contradictions: [],
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-24 00:26:18 +00:00
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>
)}
W3.7: Dupin contradiction-scan detective + UI integration Adds the third AI detective in the Investigation Bureau runtime: C. Auguste Dupin, who scans a corpus shortlist for pairs (or small groups) of chunks that cannot both be true under any ordinary reading. Runtime: - prompts/dupin.md — discipline (no contradiction without ≥2 distinct chunk_ids; reject same-vocabulary near-misses; FEW high-confidence over MANY weak ones; emit `NO_CONTRADICTIONS` when corpus is silent) - src/detectives/dupin.ts — hybridSearch with k=18 (more chunks than Holmes because contradictions emerge from comparing dispersed claims), strict JSON-array parsing, AT MOST 3 contradictions per call - src/tools/write_contradiction.ts — validates topic + ≥2 positions drawn from ≥2 distinct chunks, resolves chunk_pk via DB lookup (rejects positions citing unknown chunks), INSERTs into public.contradictions + writes case/contradictions/R-NNNN.md - orchestrator: new `contradiction_scan` kind dispatching to runDupin; payload { topic, doc_id?, lang?, context_chunks? } Chat + UI: - request_investigation gains kind=contradiction_scan + topic arg; triggered detective auto-resolves to dupin - chat-bubble inline card renders dupin in orange (#ff8a4d) to distinguish from holmes (cyan) and locard (green) - /jobs/[id] page swaps title + subtitle + tone per detective; "Question" label becomes "Topic" for contradiction_scan - /api/jobs/[id] hydrates public.contradictions when outputs[] surfaces contradiction_ids - job-status-poller renders ContradictionCard: topic + N positions (verbatim statements quoted, stance label optional, link to source chunk) + optional notes panel, with resolution_status badge (open/resolved/irreconcilable) R-NNNN shares the contradiction_id_seq slot with relation per CLAUDE.md naming — same conceptual class (a connection between two pieces of evidence in tension). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 00:34:04 +00:00
{/* Contradiction cards */}
{job.contradictions.length > 0 && (
<div className="space-y-3">
<div className="text-[12px] font-mono text-[#ff8a4d] uppercase tracking-wider">
Contradições detectadas ({job.contradictions.length})
</div>
{job.contradictions.map((c) => <ContradictionCard key={c.contradiction_id} c={c} />)}
</div>
)}
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-24 00:26:18 +00:00
{/* 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 */}
W3.7: Dupin contradiction-scan detective + UI integration Adds the third AI detective in the Investigation Bureau runtime: C. Auguste Dupin, who scans a corpus shortlist for pairs (or small groups) of chunks that cannot both be true under any ordinary reading. Runtime: - prompts/dupin.md — discipline (no contradiction without ≥2 distinct chunk_ids; reject same-vocabulary near-misses; FEW high-confidence over MANY weak ones; emit `NO_CONTRADICTIONS` when corpus is silent) - src/detectives/dupin.ts — hybridSearch with k=18 (more chunks than Holmes because contradictions emerge from comparing dispersed claims), strict JSON-array parsing, AT MOST 3 contradictions per call - src/tools/write_contradiction.ts — validates topic + ≥2 positions drawn from ≥2 distinct chunks, resolves chunk_pk via DB lookup (rejects positions citing unknown chunks), INSERTs into public.contradictions + writes case/contradictions/R-NNNN.md - orchestrator: new `contradiction_scan` kind dispatching to runDupin; payload { topic, doc_id?, lang?, context_chunks? } Chat + UI: - request_investigation gains kind=contradiction_scan + topic arg; triggered detective auto-resolves to dupin - chat-bubble inline card renders dupin in orange (#ff8a4d) to distinguish from holmes (cyan) and locard (green) - /jobs/[id] page swaps title + subtitle + tone per detective; "Question" label becomes "Topic" for contradiction_scan - /api/jobs/[id] hydrates public.contradictions when outputs[] surfaces contradiction_ids - job-status-poller renders ContradictionCard: topic + N positions (verbatim statements quoted, stance label optional, link to source chunk) + optional notes panel, with resolution_status badge (open/resolved/irreconcilable) R-NNNN shares the contradiction_id_seq slot with relation per CLAUDE.md naming — same conceptual class (a connection between two pieces of evidence in tension). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 00:34:04 +00:00
{!isTerminal(job.status) && job.hypotheses.length === 0 && job.evidence.length === 0 && job.contradictions.length === 0 && (
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-24 00:26:18 +00:00
<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 />
W3.7: Dupin contradiction-scan detective + UI integration Adds the third AI detective in the Investigation Bureau runtime: C. Auguste Dupin, who scans a corpus shortlist for pairs (or small groups) of chunks that cannot both be true under any ordinary reading. Runtime: - prompts/dupin.md — discipline (no contradiction without ≥2 distinct chunk_ids; reject same-vocabulary near-misses; FEW high-confidence over MANY weak ones; emit `NO_CONTRADICTIONS` when corpus is silent) - src/detectives/dupin.ts — hybridSearch with k=18 (more chunks than Holmes because contradictions emerge from comparing dispersed claims), strict JSON-array parsing, AT MOST 3 contradictions per call - src/tools/write_contradiction.ts — validates topic + ≥2 positions drawn from ≥2 distinct chunks, resolves chunk_pk via DB lookup (rejects positions citing unknown chunks), INSERTs into public.contradictions + writes case/contradictions/R-NNNN.md - orchestrator: new `contradiction_scan` kind dispatching to runDupin; payload { topic, doc_id?, lang?, context_chunks? } Chat + UI: - request_investigation gains kind=contradiction_scan + topic arg; triggered detective auto-resolves to dupin - chat-bubble inline card renders dupin in orange (#ff8a4d) to distinguish from holmes (cyan) and locard (green) - /jobs/[id] page swaps title + subtitle + tone per detective; "Question" label becomes "Topic" for contradiction_scan - /api/jobs/[id] hydrates public.contradictions when outputs[] surfaces contradiction_ids - job-status-poller renders ContradictionCard: topic + N positions (verbatim statements quoted, stance label optional, link to source chunk) + optional notes panel, with resolution_status badge (open/resolved/irreconcilable) R-NNNN shares the contradiction_id_seq slot with relation per CLAUDE.md naming — same conceptual class (a connection between two pieces of evidence in tension). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 00:34:04 +00:00
Dupin localiza pares de chunks em tensão irreconciliável em ~60 s.<br />
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-24 00:26:18 +00:00
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>
);
}
W3.7: Dupin contradiction-scan detective + UI integration Adds the third AI detective in the Investigation Bureau runtime: C. Auguste Dupin, who scans a corpus shortlist for pairs (or small groups) of chunks that cannot both be true under any ordinary reading. Runtime: - prompts/dupin.md — discipline (no contradiction without ≥2 distinct chunk_ids; reject same-vocabulary near-misses; FEW high-confidence over MANY weak ones; emit `NO_CONTRADICTIONS` when corpus is silent) - src/detectives/dupin.ts — hybridSearch with k=18 (more chunks than Holmes because contradictions emerge from comparing dispersed claims), strict JSON-array parsing, AT MOST 3 contradictions per call - src/tools/write_contradiction.ts — validates topic + ≥2 positions drawn from ≥2 distinct chunks, resolves chunk_pk via DB lookup (rejects positions citing unknown chunks), INSERTs into public.contradictions + writes case/contradictions/R-NNNN.md - orchestrator: new `contradiction_scan` kind dispatching to runDupin; payload { topic, doc_id?, lang?, context_chunks? } Chat + UI: - request_investigation gains kind=contradiction_scan + topic arg; triggered detective auto-resolves to dupin - chat-bubble inline card renders dupin in orange (#ff8a4d) to distinguish from holmes (cyan) and locard (green) - /jobs/[id] page swaps title + subtitle + tone per detective; "Question" label becomes "Topic" for contradiction_scan - /api/jobs/[id] hydrates public.contradictions when outputs[] surfaces contradiction_ids - job-status-poller renders ContradictionCard: topic + N positions (verbatim statements quoted, stance label optional, link to source chunk) + optional notes panel, with resolution_status badge (open/resolved/irreconcilable) R-NNNN shares the contradiction_id_seq slot with relation per CLAUDE.md naming — same conceptual class (a connection between two pieces of evidence in tension). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 00:34:04 +00:00
function ContradictionCard({ c }: { c: ContradictionItem }) {
const statusTone =
c.resolution_status === "resolved" ? "text-[#06d6a0] border-[#06d6a0]" :
c.resolution_status === "irreconcilable" ? "text-[#ff3344] border-[#ff3344]" :
"text-[#ff8a4d] border-[#ff8a4d]";
return (
<div className="rounded-lg border border-[rgba(255,138,77,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">{c.contradiction_id}</div>
{c.resolution_status && (
<span className={`px-2 py-0.5 rounded text-[10px] font-mono uppercase border ${statusTone}`}>
{c.resolution_status}
</span>
)}
</div>
<div className="text-[14px] text-[#e7ecf3] leading-snug font-medium mb-3">
{c.topic}
</div>
<div className="space-y-2">
{c.chunks.map((p, i) => {
const pageStr = String(p.page).padStart(3, "0");
return (
<div key={i} className="p-2 bg-[#060a13] rounded border border-[rgba(255,138,77,0.1)]">
<div className="text-[10px] font-mono text-[#5a6678] uppercase mb-1">
Position {i + 1}{p.stance ? `${p.stance}` : ""}
</div>
<blockquote className="text-[12px] text-[#e7ecf3] italic border-l-2 border-[#ff8a4d] pl-2 mb-2">
{p.statement}
</blockquote>
<Link
href={`/d/${p.doc_id}/p${pageStr}#${p.chunk_id}`}
className="text-[10px] font-mono text-[#7fdbff] hover:underline"
>
{p.doc_id}/p{pageStr}#{p.chunk_id}
</Link>
</div>
);
})}
</div>
{c.notes && (
<div className="mt-3 p-2 bg-[#060a13] rounded border border-[rgba(255,138,77,0.08)]">
<div className="text-[10px] font-mono text-[#5a6678] uppercase mb-1">Notes</div>
<div className="text-[12px] text-[#cbd2dd] leading-relaxed">{c.notes}</div>
</div>
)}
</div>
);
}
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-24 00:26:18 +00:00
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>
);
}