Spec: Analysis Studio¶
- ID: 007-analysis-studio
- Status: shipped
- Owner: @copilot
- Created: 2026-04-29
- Roadmap Epic: User request 2026-04-29 — "build the analysis studio"
- Constitution Compliance: confirmed against docs/constitution.md §§1–11.
1. Problem & Motivation¶
The home page advertises the Analysis Studio at /analysis, but the route 404s. The /api/analysis endpoint exists as a thin stub that runs LegalAnalyst + PrecedentHunter sequentially, returns mock data, and synthesises a fake id/timestamp. There is:
- no input validation (empty
textis accepted; no max length), - no parallelism (analyst + hunter run serially),
- no HITL flag despite the constitution mandating one for high-stakes outputs (constitution §1, §11),
- no
trace_idexposed to the UI so audit drill-down is impossible, - no UI at all.
This blocks the "multi-agent legal analysis with traces, IRAC briefs, and precedents" pillar advertised on the home page.
2. Goals¶
- G1: Harden
POST /api/analysiswith input validation, parallel agent execution, returnedtrace_ids, and a confidence-driven HITL flag. - G2: Ship
/analysispage with a textarea, jurisdiction selector, sample loader, IRAC card, precedents list, agent trace, and HITL banner. - G3: Every analysis run lands a
provenance.log_agent_callevent per agent and a singleanalysis_runevent tying bothtrace_ids together. - G4: Reuse the existing
AgentTraceandprovenanceinfra — no new dependencies.
3. Non-Goals¶
- NG1: Real GraphRAG / LLM integration. The
LegalAnalystandPrecedentHunterkeep their mock outputs (closing those TODOs is tracked separately as BL-20260430-03 and BL-20260430-04). - NG2: Authn/z (same posture as specs 003, 006).
- NG3: Streaming responses (SSE / WebSocket). Single JSON response is sufficient for MVP.
- NG4: Persisting full request text — only hashed in audit log (privacy-preserving, matches existing provenance behaviour).
4. User Stories¶
- As a lawyer, I want to paste a fact pattern and get an IRAC brief with cited precedents in one click so I can iterate on a memo without context-switching.
- As a reviewer, I want every analysis to expose a
trace_idso I can find the run on the Agent Ops dashboard. - As a maintainer, I want low-confidence analyses to surface a HITL banner so we never silently ship hallucinated legal advice.
5. Functional Requirements¶
- FR-1:
POST /api/analysisbody validates with Pydantic:text(1 ≤ len ≤ 20_000),jurisdiction(optional, ≤ 64 chars),case_id(optional, ≤ 200 chars). - FR-2:
LegalAnalyst.run(...)andPrecedentHunter.run(...)are invoked in parallel viaasyncio.gatherand the wall-clock latency is measured. - FR-3: Both crew classes return their
trace_idin the response. The route generates a top-levelanalysis_id(an-+ 12 hex chars) and overallconfidence= mean of the two agent confidences. - FR-4: Response model
AnalysisResponse:{ "id": str, "timestamp": iso8601, "latency_ms": int, "confidence": float, "requires_human_review": bool, # true when confidence < 0.7 "irac": IRACOutput, "precedents": PrecedentList, "agent_trace": [ {"agent": "LegalAnalyst", "trace_id": str, "latency_ms": float, "confidence": float}, {"agent": "PrecedentHunter","trace_id": str, "latency_ms": float, "confidence": float} ] } - FR-5: After both agents return, the route records an
analysis_runevent viaprovenance.log_agent_call(agent_name="AnalysisStudio", sources merged from both agents). - FR-6:
LegalAnalyst.runandPrecedentHunter.runare updated to also return their generatedtrace_idso the route can surface it without re-hashing — exposed asIRACOutput.trace_idandPrecedentList.trace_id(Optional[str], default None for back-compat). - FR-7: Frontend
app/analysis/page.tsxserver shell + newcomponents/AnalysisStudio.tsxclient component: - Textarea + jurisdiction
<select>(US, US-CA, US-NY, EU, Other). - "Load sample" button populates a canned negligence fact pattern.
- Submit → spinner → results: IRAC card (Issue / Rule / Application / Conclusion), Precedents list with relevance bars,
AgentTracecomponent reused from spec 003. - Amber HITL banner when
requires_human_review: true. trace_idandanalysis_idshown in a footer chip with copy affordance.- FR-8:
lib/api.tsgains a typedrunAnalysis(input)client returning the fullAnalysisResponse.
6. Non-Functional Requirements¶
- NFR-PERF-1: With mock agents, end-to-end p95 < 200 ms (parallel
asyncio.gatherkeeps wall-clock close tomax(latency), not sum). - NFR-AUDIT-1: Three audit events per request —
LegalAnalyst,PrecedentHunter,AnalysisStudio(the umbrella). Verified by readingaudit_store.tail. - NFR-HITL-1: Every response sets
requires_human_reviewpurely as a function ofconfidence(< 0.7 → true). Documented in the OpenAPI schema via Pydantic field description. - NFR-SEC-1: Pydantic validation rejects empty / over-long input
(FR-1). The raw
textis never re-emitted in audit events — only itshash()per the existingprovenance.log_agent_callcontract. - NFR-COVERAGE-1: Backend coverage stays ≥ 75% repo-wide; new code ≥ 85%. Frontend coverage stays ≥ 70%.
7. Data Model Impact¶
- No Neo4j schema change.
IRACOutputandPrecedentListgain optionaltrace_id: str | Nonefield for FR-6.
8. API Surface¶
POST /api/analysis
request: AnalysisRequest { text, jurisdiction?, case_id? }
response: AnalysisResponse (see FR-4)
9. Agent / Crew Impact¶
LegalAnalyst.runandPrecedentHunter.runupdated to returntrace_idon their structured output (FR-6). No prompt / behavioural change. Mock outputs retained (NG1).- New "AnalysisStudio" umbrella entry in audit log (FR-5) — not a registered crew, just a provenance label.
10. Acceptance Criteria¶
- AC-1:
POST /api/analysiswith{"text": "..."}returns HTTP 200 with all FR-4 fields populated andlen(agent_trace) == 2(verifies FR-1, FR-2, FR-3, FR-4). - AC-2:
POST /api/analysiswith{"text": ""}returns HTTP 422 (verifies FR-1). - AC-3: After one successful run,
audit_store.tail(10)contains exactly three events whoseagent∈ {LegalAnalyst, PrecedentHunter, AnalysisStudio} (verifies FR-5, NFR-AUDIT-1). - AC-4: When both agents return
confidence ≥ 0.7,requires_human_review == false. When monkeypatched so one agent returnsconfidence = 0.4, the response setsrequires_human_review == true(verifies FR-3, NFR-HITL-1). - AC-5: Wall-clock latency of a request where each mocked agent sleeps 50 ms is < 90 ms (verifies FR-2 parallelism — serial would be ≥ 100 ms).
- AC-6: Frontend
/analysisrenders the IRAC card, the precedents list, and the agent trace from MSW-mocked API; clicking "Load sample" populates the textarea; the HITL banner appears when the mock returnsrequires_human_review: true(verifies FR-7).
11. LegalBench Impact¶
- Tasks affected: none (mock agents).
- Expected delta: 0 pp. Real reasoning lands when BL-20260430-03 and -04 are implemented; this spec ships the rails.
12. Risks & Open Questions¶
- R-1: Returning two
trace_ids plus an umbrella one could confuse the audit drill-down (BL-20260429-14). Mitigation: the umbrella event carrieschild_trace_ids: [..]so the relationship is explicit. - R-2: A 20 KB textarea could OOM under load. Mitigation: hard cap in Pydantic; document the limit in the UI.
13. Out of Scope / Follow-ups¶
- Streaming agent output (SSE).
- Saving / sharing analyses.
- Real LegalAnalyst + PrecedentHunter (BL-20260430-03/04).
- Drill-down view (BL-20260429-14).