Overview
The server is Express serving the React app and /api/*. Auth is an httpOnly session cookie, not a Bearer token. Every mutating or tenant-scoped route is org-isolated; cross-tenant reads are treated as incidents.
- JSON request/response unless noted (multipart for evidence upload, raw body for Stripe webhook).
- Always send
credentials: "include"from browsers. - IDs in paths are integers. Forged organizationId in a body is ignored — the server binds the caller’s org.
- Open-source reference: https://github.com/kevin-owens-product/ai-prosecutor.
Base URLs
Production https://www.prosequi.ai
Local http://127.0.0.1:5000 # PORT in .env
Health GET /healthz
Webhook POST /api/billing/webhook
SCIM /scim/v2 # office bearer tokenThere is one hosted environment. Staging was retired in October 2026, and the hosted demo holds synthetic data only.
Authentication
Session name aip.sid. Cookie: httpOnly, SameSite=Lax, Secure when APP_ENV is staging or production, max-age 12 hours. Staging/production use a Postgres session store.
Password login
POST /api/auth/login
Content-Type: application/json
{ "username": "your.username", "password": "your-password" }
# 200 — session set
# 200 + { "mfaRequired": true, "preAuthToken": "…" } when TOTP is enrolled
# 403 { "code": "sso_required" } when the org enforces SSO
# 401 invalid / lockedMFA challenge
POST /api/auth/mfa/challenge
{ "preAuthToken": "…", "code": "123456" } # or a recovery code
POST /api/auth/mfa/setup # start TOTP enrollment (auth)
POST /api/auth/mfa/verify # confirm enrollment
POST /api/auth/mfa/disable
POST /api/auth/mfa/recovery-codes/regenerateSSO (OIDC)
POST /api/auth/sso/start
{ "email": "ada@usao.example.gov" }
# → { "url": "https://login.microsoftonline.com/…" }
GET /api/auth/sso/callback # IdP redirect; sets session
# Super-admin configuration (client secret write-only, encrypted at rest)
GET /api/admin/orgs/:orgId/sso
PUT /api/admin/orgs/:orgId/sso
DELETE /api/admin/orgs/:orgId/ssoSession
GET /api/auth/user # public session user or 401
GET /api/auth/me # requireAuth
POST /api/auth/logout
POST /api/auth/change-passwordmustChangePassword and org-mandated MFA enrollment return 403 with code: "password_change_required" or code: "mfa_enrollment_required" on every other API route until completed.Conventions
- JSON Content-Type for bodies. Default JSON limit 1mb (JSON_LIMIT).
- List routes are org-scoped automatically. Super admins may pass ?organizationId=.
- 404 is used instead of 403 on some cross-tenant fetches so resource existence does not leak.
- Audit logs are append-only and hash-chained per org.
fetch("/api/cases", { credentials: "include" })
fetch("/api/cases", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "United States v. Example", caseNumber: "CR-DEMO-24-001" }),
})Errors and rate limits
| Status | Meaning |
|---|---|
| 400 | Validation (zod), checked before the handler runs. Body { message, code: "invalid_body", issues }. |
| 401 | No session / invalid login. |
| 403 | Role, tenant status, password/MFA gate, or SSO required. |
| 404 | Missing or not visible in this tenant. |
| 409 | Conflict (IAR complete without hashed source evidence; billing portal with no Stripe customer). |
| 423 | Locked (legal hold, retention window, produced in a Bates batch, or expected-source-linked evidence). |
| 429 | Rate limit. |
| 503 | AI off, billing unconfigured, or dependency missing. |
| Limiter | Window |
|---|---|
| /api (production) | 300 / 15 min |
| Auth (login, MFA, SSO, password) | 30 / 15 min |
| AI routes | 20 / min |
| Billing checkout/portal | 20 / 15 min |
| Public leads/support | separate intake limiter |
Tenancy and ACLs
Users belong to one organization. Super admins are platform-scoped. Matter access is owner-org full access or an explicit participant row with full | collaborate | contribute | read_only. Suspended or cancelled tenants cannot log in (super admin excepted).
GET /api/cases/:id/access
GET /api/cases/:id/participants
POST /api/cases/:id/participants
POST /api/cases/:id/participants/accept
DELETE /api/cases/:id/participants/:participantId # revoke partner / withdraw invite
GET /api/ecosystem/network # my agency + partners + shared-matter orgs
GET /api/ecosystem/directory?q= # org_admin agency lookup (min 3 chars)
POST /api/ecosystem/partnerships # org_admin
PUT /api/ecosystem/partnerships/:idMatters API
GET /api/cases
GET /api/cases?shared=true
GET /api/cases?scope=archived
GET /api/cases/pending-invites
GET /api/cases/:id # includes onlineUsers; 410 if archived
POST /api/cases # matter numbers are unique per tenant
PUT /api/cases/:id
DELETE /api/cases/:id # archive (soft) — number stays reserved
POST /api/cases/:id/restore # un-archive
POST /api/cases/bulk/status # status: open|pending|closed|urgent|archived
GET /api/cases/:id/summary # AI
POST /api/cases/:id/analysis
GET /api/cases/:id/filing-package
POST /api/cases/:id/filing-package/attest
GET /api/cases/:id/readiness
GET /api/cases/:id/discovery-export
GET /api/dashboard/statsEvidence API
Uploads are multipart, streamed, never buffered as a whole file in memory. Download is only GET /api/evidence/:id/file.
GET /api/evidence?caseId=
GET /api/evidence/:id # lastIntegrityCheck: { checkedAt, matched, note } | null
GET /api/evidence/:id/file
POST /api/evidence # multipart field "file"
POST /api/evidence/batch # "files", max 50
PUT /api/evidence/:id
DELETE /api/evidence/:id # withdraws; { reason } ≥ 10. 200 the row.
# 423 legal_hold_active | retention_active | produced_in_batch | expected_source_linked
# 400 withdraw_reason_required · 409 already_withdrawn
POST /api/evidence/:id/purge # lead-office attorney, not the withdrawer
# 409 purge_same_approver | not_withdrawn | already_purged
GET /api/evidence?includeWithdrawn=1 # lead office on a matter; ignored for partners
PATCH /api/evidence/:id/discovery
PATCH /api/evidence/:id/hold
PATCH /api/evidence/:id/seal # lead office, canManageEvidenceHold
# { sealed?, sensitivity?, reason? }
# reason ≥ 10 when sealed changes; 400 seal_reason_required
GET /api/evidence/:id/custody
POST /api/evidence/:id/custody # eventType sealed|unsealed → 409 use_seal_control
GET /api/evidence/:id/custody-packet
# read_only; collaborate if sealed
# { generatedAt, disclaimer, sha256, caseId, caseNumber,
# productionId: null, items, productionChecks }
# sha256 is SHA-256 of canonical JSON of the body without sha256
POST /api/evidence/:id/certification-draft
# lead office, attorney role, collaborate
# { rule: "902(14)" | "902(11)" }
# 201 { document, duty } document.status "draft", title starts DRAFT
# duty is undated when the matter has no trial date
# 400 invalid_rule · 403 not lead office or not an attorney
GET /api/productions/:id/custody-packet
# owner office, collaborate. 404 for a partner.
# committed or certified, else 409 production_not_committed
GET /api/evidence/:id/transcript
PUT /api/evidence/:id/transcript
POST /api/evidence/:id/analyze # AI
GET /api/cases/:caseId/notice-duties # lead office, read_only
POST /api/cases/:caseId/notice-duties # lead office, attorney, collaborate
# { catalogId, bradyOrderDate?, dueAt? }
# dueAt is an attorney override (YYYY-MM-DD), not a trial offset
# the trial offset is computed on read and is not stored
# no trial date → displayDueAt null, dueSource "none", never overdue
# 400 brady_order_date_required | unknown_duty | catalog_disabled
POST /api/cases/:caseId/notice-duties/:id/draft
POST /api/cases/:caseId/notice-duties/:id/serve
# { expectedUpdatedAt, servedHow, servedSha256, occurredAt }
# 400 when the SHA-256 is missing. Does not send anything.
POST /api/cases/:caseId/notice-duties/:id/acknowledge
# { expectedUpdatedAt } 409 stale_notice
POST /api/cases/:caseId/notice-duties/:id/close
# attorney. { expectedUpdatedAt, reason } reason ≥ 10
# status closed. Does not cap trial-ready.
# overdue unserved duties (not rule_5f) are hard cap notice_duty_overdue
# due within 14 days stay task notice_duty_open
GET /api/notice-duties/catalog
GET /api/notice-duties/policy
PUT /api/notice-duties/policy # attorney or office admin, caller's office
GET /api/cases/:caseId/motions # lead office, read_only. Partner 403.
POST /api/cases/:caseId/motions # lead office, contribute
# any status proposes unconfirmed (h)(1)(D) and (h)(1)(H)
# Henderson: D through the hearing or the papers;
# H is the next 30 days, ending at disposition if sooner
# optional allPapersIn moves only the start of H
# replyFiled beats replyDue
GET /api/cases/:caseId/motions/:id # suppress includes prep; no drafted response
PATCH /api/cases/:caseId/motions/:id # { expectedUpdatedAt, replyFiled?, allPapersIn?, ... }
# 409 stale_motion
# a date change returns linked exclusions to unconfirmed
POST /api/cases/:caseId/motions/:id/events
POST /api/cases/:caseId/motions/:id/documents
POST /api/cases/:caseId/motions/:id/issues # suppression only; else 400
# confirm exclusions on the existing speedy-trial decision routeField capture sends a phone photo or video through the same POST /api/evidence intake with extra form fields. The custody chain records the phone's hash beside the server's hash. A mismatch keeps the file, tags it hash-mismatch and notifies the office.
GET /api/evidence/field-capture/limits # signed in · the per-file cap, so the page can refuse early
POST /api/evidence # multipart, plus: captureSource, captureId, clientSha256,
# capturedAt, gpsLatitude?, gpsLongitude?, gpsAccuracyM?, queuedOffline?
# captureId is unique per person, so a retry files once.
# A capturedAt more than 10 minutes in the future is refused.Documents, templates, collab
GET /api/documents
POST /api/documents
GET /api/documents/:id
PUT /api/documents/:id
DELETE /api/documents/:id
GET /api/documents/:id/revisions
PUT /api/documents/:id/revisions/:revisionId/restore
POST /api/documents/generate # AI
GET /api/templates
GET /api/templates/:id
POST /api/collab-docs
GET /api/collab-docs/:id
GET /api/cases/:caseId/collab-docs
PUT /api/collab-docs/:id/snapshotDomains
Domain work items are first-class records (intake, grand jury, discovery, …) with an optional caseId. Grand jury responses include secrecy metadata and redaction for uncleared roles.
GET /api/domains
GET /api/domains-catalog
GET /api/domains/:domainId
GET /api/domains/:domainId/items
POST /api/domains/:domainId/items
PUT /api/domain-items/:id
POST /api/domain-items/:id/promote-to-matterJoint Ops
GET /api/joint-ops/catalog
GET /api/action-requests
GET /api/cases/:caseId/action-requests
POST /api/cases/:caseId/action-requests
PUT /api/action-requests/:id
GET /api/cases/:caseId/readiness
GET /api/tasks
POST /api/tasks
PUT /api/tasks/:idStatus transitions are validated server-side. First entry into a working status can mirror an office task (at most one per IAR). When the IAR is linked to expected sources, PUT /api/action-requests/:id with status completed is refused until hashed vault evidence is attached:
| 409 code | Meaning |
|---|---|
| source_evidence_required | Linked sources exist; attach hashed evidence before completing. |
| source_evidence_map_required | More than one source: send sourceEvidenceMap { sourceId, evidenceId }[]. |
| source_hash_required | A linked file has no SHA-256 yet. |
Expected sources
Inventory of digital and paper items that should exist on the file, named before ingest. Owner office records the rows. Partners GET only sources whose IAR is assigned to their org, with the mediation basis stripped. Partner POST is 403. Direct /receive is owner collaborate+; partner receive is IAR complete only. Mediate is attorney-only and notifies Giglio Watch without creating an entry. Clock origin is request time, not insert. Suggest/accept/dismiss is the same pilot gate as Order of Proof (404 when APP_ENV=production).
GET /api/cases/:caseId/expected-sources
POST /api/cases/:caseId/expected-sources
# { kind, label, description?, custodianName?, custodianOrgId?, dueAt?, priority?,
# legalHold?, retentionUntil?, spawnIar?, iarAssignedOrganizationId? }
# legalHold: true needs canManageEvidenceHold — otherwise 403 (not silently dropped)
# spawnIar: true → status requested, requestedAt = now, dueAt defaulted to SLA
PATCH /api/cases/:caseId/expected-sources/:id # label, due, custodian, priority — not status
# { …, expectedUpdatedAt } optimistic lock
POST /api/cases/:caseId/expected-sources/:id/request # { iarId?, dueAt? } expected → requested
POST /api/cases/:caseId/expected-sources/:id/receive # { evidenceId } evidence must be on the matter with sha256
POST /api/cases/:caseId/expected-sources/:id/mediate
# { status: "lost"|"spoliated"|"unobtainable", basis, evidenceId,
# attorneyConfirmed: true, expectedUpdatedAt }
# attorney role · hashed basis memo · not from produced (void-and-reproduce owns that row)
PATCH /api/cases/:caseId/expected-sources/:id/hold # { legalHold, retentionUntil? }
DELETE /api/cases/:caseId/expected-sources/:id # expected or requested, not held, not mediated
# 423 legal_hold_active | source_not_deletable
GET /api/cases/:caseId/expected-sources/:id/events
# Pilot only — 404 when APP_ENV=production. AI rate limiter.
POST /api/cases/:caseId/expected-sources/suggest
POST /api/cases/:caseId/expected-sources/suggestions/:suggestionId/accept
POST /api/cases/:caseId/expected-sources/suggestions/:suggestionId/dismissReadiness GET /api/cases/:id/readiness adds owner-only expectedSources: { open, nextDueAt } (null for partners) and issueHardCaps. Overdue unreceived sources cap trial_ready at strong; they do not block a production commit.
Issue map
Closed catalog of pretrial holes on the matter. Owner payload includes disclaimer, counts, issues, sources, and readiness caps. Partner payload is stripped: { partner: true, assignedSourceCount, assignedOverdueCount } — no bases, no catalog rows, no office-wide caps (not 403: LE needs assigned sources). Resolve is attorney-only, append-only. Completeness checks are tasks until a source of that kind is named; unused inventory does not fail the file. SOL is never a v1 hard cap.
GET /api/pretrial-issues/catalog # { id, class, trigger, ui, severity }[]
GET /api/cases/:caseId/disclosure-gaps # owner; witness rows are role-gated
POST /api/cases/:caseId/disclosure-decisions # objectKind witness is accepted
GET /api/cases/:caseId/issue-map # stale resolution reopens the row
# owner: { disclaimer, counts, issues, sources, readinessCaps }
# partner: { partner: true, assignedSourceCount, assignedOverdueCount }
POST /api/cases/:caseId/issue-map/:catalogId/resolve
# { outcome, basis, attorneyConfirmed: true, expectedFingerprint,
# solDate?, venue?, statute? }
# 403 partner or non-attorney · 404 unknown catalog idFixed disclaimer (never configurable): This map reports recorded gaps and missing sources; it does not certify compliance, preservation, or that every obligation was met.
Review (document review and e-discovery)
Per-matter review set built from the matter's evidence. Cookie session, same conventions as above. Matter routes need matter access: read_only to read, contribute to change anything (the matter check answers 403, 404 or 410 itself). Sealed items the caller may not see are left out of every result. Every write and every export is written to the audit log. When the office requires Rules of Behavior, every matter route and the transcribe route answer 428 { code: "rules_of_behavior_required" } until the caller accepts the current text.
# Processing
POST /api/cases/:caseId/review/process # contribute · 202 { run } · ?wait=1 → 200 { run } when done
# 409 a run is already going for this matter
# a run takes up to maxRunBytes (default 2 GiB); files past it are skipped and the run is "partial"
GET /api/cases/:caseId/review/status # { run, running, engines[], nsrl: { count, loadedAt, loadedBy }, maxRunBytes }
# Documents and search
GET /api/cases/:caseId/review/docs # ?q= &tag= (id or name) &type= &cluster= &thread= &page= &pageSize= (max 200, default 50)
# 200 { ok, query, description, total, page, pageSize, hits[]: { …doc, hitCount, snippets, preview } }
# 400 { message, position, formatted } query could not be parsed; position is 0-based
GET /api/cases/:caseId/review/docs/:key # 404 not in this review set
GET /api/cases/:caseId/review/search-history # own log; office admin: ?userId= or ?all=1 → { userId, entries[] }
GET /api/cases/:caseId/review/search-history.csv
# id, created_at, user_id, case_id, query, query_sha256, result_count · audited
# Tags
GET /api/cases/:caseId/review/tags # { tags[], kinds, scopes }
POST /api/cases/:caseId/review/tags # contribute · { name, kind: responsive|privilege|issue|folder } → 201
# 400 no name · 409 name already used on this matter
POST /api/cases/:caseId/review/tag-apply # contribute · { tagId, docKeys[] (≤ 10,000), scope }
DELETE /api/cases/:caseId/review/tag-apply # same body; removes
# scope: single | duplicate_set | near_duplicates | family | thread
# 200 { docKeys (after expansion), changed } · 400 bad body · 404 tag or documents not found
# Analytics
GET /api/cases/:caseId/review/clusters
GET /api/cases/:caseId/review/concept-search # ?q= (required) &k= (max 100, default 20) → { query, results[] }
GET /api/cases/:caseId/review/expand # ?term= (required) → { term, related[] }
GET /api/cases/:caseId/review/email-graph # threads, senders and recipients → { …graph, messages }
# Technology-assisted review (continuous active learning)
GET /api/cases/:caseId/review/tar # → { projects: [{ id, name, status, settings, createdAt }] }
POST /api/cases/:caseId/review/tar # contribute · { name, settings?: { lambda, iterations, learningRate,
# balanceClasses, targetRecall } } → 201
POST /api/cases/:caseId/review/tar/:id/judgments
# contribute · { judgments: [{ docKey, relevant, purpose: training|validation }] } (≤ 5,000)
# 200 { added, ignored } · 400 none usable · 404 project · 409 project closed
GET /api/cases/:caseId/review/tar/:id/next # ?size= (1–500, default 20) &strategy=relevance|uncertainty|mixed
# { modelStatus, notReadyReason, strategy, batch[]: { docKey, score } }
POST /api/cases/:caseId/review/tar/:id/validation-sample
# contribute · { size? (default 400, max 10,000), seed? } → { sample[], seed, unreviewedCount, drawnAt, drawnBy }
GET /api/cases/:caseId/review/tar/:id/report
# { project, model, reviewed, foundRelevant, population, validation, elusion, recall,
# stopping: { signal: keep_reviewing|consider_stopping, reasons[], metrics }, generatedAt }
# Exports (all audited)
GET /api/cases/:caseId/review/export.dat # ?tag= (id or name, required) &prefix= (A-Z 0-9 _ -, ≤ 12, default REV)
GET /api/cases/:caseId/review/export.opt # same params
GET /api/cases/:caseId/review/export.xml # EDRM XML · 400 no tag · 404 tag not found
GET /api/cases/:caseId/review/exceptions.csv # processing exception report
GET /api/cases/:caseId/review/duplicates.csv # exact and near-duplicate log
# Early case assessment, entities, organization (all under /api/cases/:caseId/review; contribute for writes)
GET /eca POST /eca/hit-report GET /eca/hit-report.csv POST /eca/promote
GET /entities GET /entities/docs GET /entities/cooccurrence # pattern-based extraction, not a trained model
GET /folders POST /folders PATCH /folders/:id
GET /saved-searches POST /saved-searches GET /saved-searches/:id/run DELETE /saved-searches/:id
GET /fields POST /fields GET /fields/values POST /fields/:id/values # custom coding fields; flow into DAT/XML
GET /metrics GET /metrics.csv GET /validation GET /validation.csv GET /filter-report GET /filter-report.csv
GET /workflow-settings PUT /workflow-settings # also GET/PUT /api/admin/review/workflow-settings
# Productions, bulk load, print, viewer (same base path)
GET /productions POST /productions GET /productions/:id GET /productions/:id/package.zip # DATA, NATIVES, TEXT, README; no TIFF
GET /loads POST /loads GET /loads/:id GET /loads/:id/errors.csv # DAT/OPT or EDRM XML; content type application/vnd.prosequi.review-load+json up to 64 MB
POST /print # { tag | docKeys, format: "pdf" | "zip" } with slip sheets
GET /docs/:key/pages GET /docs/:key/native GET /docs/:key/sheet # page viewer, original file, XLSX/CSV grid
# Service levels and page time
GET /api/admin/service-levels[.csv] # office admin
GET /api/platform/service-levels[.csv] # platform admin; also /api/platform/maintenance-windows
POST /api/rum # page-time samples from signed-in pages
# Machine translation (off unless TRANSLATE_ENGINE=libretranslate and LIBRETRANSLATE_URL are set)
POST /api/cases/:caseId/review/docs/:key/translate
# contribute · { to: "en", from? } → 201 { …, mt: true, status: "needs_human_qc" }
# 400 bad language code or no text · 403 { code: "secrecy_material" } sealed or grand jury
# 409 { code: "engine_off", engines } · 502 engine error
GET /api/cases/:caseId/review/translations # ?status=needs_human_qc|approved|corrected
POST /api/cases/:caseId/review/translations/:id/approve
POST /api/cases/:caseId/review/translations/:id/correct # { text } required · 409 already settled
# Speech-to-text (off unless SPEECH_ENGINE=whisper and a local whisper or whisper.cpp binary runs)
POST /api/evidence/:id/transcribe # contribute · { language? } → 201 { transcriptId, engine, machineGenerated: true, segments }
# 403 sealed item the caller may not see, or { code: "secrecy_material" } · 404 · 410 withdrawn or purged
# 409 { code: "engine_off" } · 428 rules_of_behavior_required · 502 engine error
# Office administrators (403 for other roles; no Rules of Behavior gate)
GET /api/admin/review/engines # { engines[]: { name, available, detail }, nsrl }
PUT /api/admin/review/nsrl # raw text body: NSRL CSV (SHA-1, MD5 or SHA-256 column) or hashes,
# one or more per line · { hashes, count, loadedAt, loadedBy } · 503 no storage
GET /api/admin/review/storage-usage # ?month=YYYY-MM → { month, days[]: { date, bytes }, dailyAverageBytes, dailyAverageGb }
GET /api/admin/rules-of-behavior
PUT /api/admin/rules-of-behavior # { text, required: boolean } → { …, sha256 }
# Rules of Behavior (any signed-in user)
GET /api/rules-of-behavior # { text, sha256, required, accepted, updatedAt }
POST /api/rules-of-behavior/accept # { sha256 } of the text read · 404 office has none
# 409 { sha256 } text changed: read it again and accept that hashQuery syntax
The q parameter of /review/docs. Operators are case-insensitive. Binding, tightest first: proximity, NOT, AND (explicit or implied by a space), OR. Limits: 200 terms and 20 levels of nesting. Distance is in word positions; adjacent words are 1 apart.
query := or
or := and { ("OR" | "||") and }
and := not { ["AND" | "&&"] not }
not := ("NOT" | "-") not | prox # "-" only at the start, or after a space or "("
prox := text [ ("w/" N | "pre/" N) text ] # N ≥ 1; w/ either order, pre/ left first; no chaining
| atom
atom := "(" or ")" | text | field
text := word | '"' words '"' # word may hold * (any run) and ? (one character)
field := name ":" (word | '"' words '"') # name: from to subject custodian filetype tag bates
| "date" ("=" | ":" | ">" | ">=" | "<" | "<=") YYYY-MM-DD
# Examples
"wire transfer" AND (invoice OR receipt)
bank w/5 deposit -loan
from:jdoe@example.com date>=2024-01-01 date<2024-07-01
custodian:smith subject:"q3 report" NOT tag:privileged
# Parse error (400), also written to the caller's search log
{ "message": "This opening parenthesis is never closed", "position": 0,
"formatted": "This opening parenthesis is never closed (at character 1)" }npm run sbom writes a CycloneDX software bill of materials. Office data export and destruction are operator scripts, not screens in the app.AI
Default provider is xAI Grok (AI_PROVIDER=xai). AI_MODE=live|mock|off. Live calls require XAI_API_KEY. Anthropic is opt-in via AI_PROVIDER=anthropic.
GET /api/ai/status
POST /api/legal-research
POST /api/charging/recommendations # prosecutor+
GET /api/cases/:id/summary
POST /api/cases/:caseId/analysis
POST /api/evidence/:id/analyze
POST /api/documents/generate
GET /api/agents
GET /api/agents/types
POST /api/agents/:agentId/sessions
POST /api/agents/sessions/:sessionId/messageAI use record
Every AI output shown to a person (case summary, matter analysis, evidence analysis, charging options, document draft, legal research) is written to ai_outputs with the model, mode, input references, token counts and the first draft as generated plus its SHA-256. The AI routes above return its id as aiOutputId. Live Agent Desk runs are joined in when the record is read.
GET /api/cases/:id/ai-ledger # read access on the matter: { caseNumber, entries, features }
GET /api/cases/:id/ai-ledger/disclosure.pdf # tagged PDF packet (audited)
GET /api/cases/:id/ai-ledger/disclosure.csv
GET /api/ai-ledger/:entryId/first-draft # { id, feature, firstDraft, sha256 }
POST /api/ai-ledger/:entryId/review # contribute access on the matter
{ "status": "edited", "note": "Removed the uncited holding." } # accepted | edited | rejected; edited needs a note or finalText
GET /api/ai-ledger/report?days=180 # org admin: outputs by month and feature, reviewed or notAgent Desk
Eight task agents: charging_review, disclosure_review, evidence_review, trial_prep and partner_followup on one matter; intake_triage on the office referral queue; aps_screening and aps_caseload in an APS office. The catalog returns only the agents for the caller's office type and role.
GET /api/agent-desk/catalog
GET /api/agent-desk/settings
PUT /api/agent-desk/settings # org admin: { disabled: [agentKey], nightly?: { enabled, agents: [agentKey] } }
GET /api/agent-desk/nightly # the overnight check: enabled, agents, last night's report
POST /api/agent-desk/nightly/run # org admin: run the overnight check now
POST /api/agent-desk/runs
{ "agentKey": "trial_prep", "caseId": 76 } # caseId only for matter agents
# 200 { id, status, mode: "rules" | "live", trigger: "manual" | "nightly", model, summary, findings, steps, proposals }
# 403 role cannot run it, agent switched off, or another office's matter
# 422 sealed matter
GET /api/agent-desk/runs # recent runs
GET /api/agent-desk/runs/:id # steps, tool calls, findings
GET /api/agent-desk/proposals # waiting for a decision
POST /api/agent-desk/proposals/:id/decision
{ "decision": "approve", "title": "…", "assigneeId": 12 } # title, assignee optional
{ "decision": "reject", "note": "…" } # note required
# 409 someone already decided it
GET /api/agent-desk/flow?days=30 # 7, 30 or 90: proposals from agent to run start to decision to outcome, counts onlyAI_MODE=live and the office allows it; findings it adds must cite records it read, and mode tells you which ran. Approving a proposal opens a task (prosecution) or a notification (APS) and nothing else.Statutes
Dated statute packs load on boot: California (Penal and Vehicle codes, Health and Safety §§ 11000–11999, Welfare and Institutions §§ 200–999 and 15600–15699, from November 2016) and the US Code (Title 18; 21 U.S.C. §§ 801–971; 8 U.S.C. §§ 1321–1330; 26 U.S.C. §§ 7201–7217). Each response carries a verify notice and the source credits; the text is not an official code.
GET /api/statutes/packs # loaded packs, notice, source credits
GET /api/statutes/lookup?cite=PC%20487&on=2025-06-01
# 200 the section as it read on that day, and the changes after it
# 422 unreadable citation or date (YYYY-MM-DD)
GET /api/cases/:caseId/statute-check # each count: text on its offense date and a status
# status: unchanged | changed_since_offense | uncertain | repealed | not_yet_in_force
# | before_record | no_offense_date | not_on_file | no_citation
GET /api/org/statute-changes # office staff: open matters whose charged section changed around the offense dateConflict checks and the public front door
A conflict check runs on its own when a matter is created, edited or reassigned to someone, against that person's declared relationships and the people on matters they handled before. Declarations are visible only to the person who made them.
GET /api/me/conflict-declarations
POST /api/me/conflict-declarations # { name, relationship, dob? }
# relationship: family | household | friend | former_client | business | neighbor | other
DELETE /api/me/conflict-declarations/:id
GET /api/cases/:caseId/conflict-checks
POST /api/cases/:caseId/conflict-checks # run one now; { userId } for someone else is supervisor-only
POST /api/conflict-checks/:id/acknowledge # the assignee, on a flagged check
POST /api/conflict-checks/:id/resolve # a different supervisor
{ "resolution": "screened", "note": "Screened from the matter; reason on file." }
# resolution: no_conflict | screened | recused | reassigned; note at least 10 characters
GET /api/conflict-checks # supervisor queue
GET /api/public/front-door/:office # no sign-in; 404 while the office has it off
GET /api/org/front-door # org admin
PUT /api/org/front-doorLink chart, incident replay and flows
Every picture in Prosequi is drawn by the app itself from records it already holds, with no chart or map library and no outside map tiles. Each route below returns the numbers the picture is drawn from, and the page shows the same numbers as text.
GET /api/link-chart?case=76 # or ?person=<id>; people and matters two steps out
GET /api/link-chart?case=76&expand=person:12,matter:80 # one more step from named points (at most 24)
# 200 { start, nodes[{ id, kind, label, detail, restricted, hop, href, since }], edges[{ from, to, label, kind, since }], truncated, limit, hops }
GET /api/cases/:caseId/incident-replay # recorded places and times, plus field captures with a GPS fix
POST /api/cases/:caseId/incident-points # contribute access
{ "occurredAt": "2026-07-15T19:40:00-07:00", "latitude": 34.05, "longitude": -118.25,
"label": "Camera at the gas station", "kind": "camera", "subject": "Getaway car", "source": "Store DVR" }
# kind: sighting | camera | phone | purchase | vehicle | seizure | arrest | statement | other
DELETE /api/incident-points/:id # the row stays, marked removed
GET /api/forfeiture/office # the office forfeiture page; flow = where the money goes for the same filtered assets
GET /api/agent-desk/flow?days=30 # Agent Desk Flow tab
GET /api/aps/field-map # APS field mapRestricted party and is never followed further, and juvenile, grand jury and confidential matters are never reached from another matter. Incident replay applies matter access and evidence visibility; the speed check flags a leg over 85 mph. An APS case is placed at the centre of its ZIP code, never at an address.Trial modules: common rules
The seven modules below are matter-scoped, lead-office work product. Unless a module says otherwise, every /api/cases/:caseId/… route resolves the caller's access on the matter first, then refuses partner agencies with 403 whatever their access level. None of these routes has a plan (402) limit.
# The examples below reuse a cookie jar from a password login
curl -c cookies.txt -X POST https://<host>/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"your.username","password":"your-password"}'| Status | Meaning in these modules |
|---|---|
| 400 | Invalid :caseId or other path id ("Invalid matter id."), zod validation (strict bodies: unknown fields are refused), or "Nothing to update." |
| 403 | Not on the matter, access level below the module's floor, partner agency on a lead-office module, or an attorney-only action by a non-attorney role. |
| 404 | Row not on this matter; or the route is pilot-only and this is production (see below); or Giglio Watch is off for the office. |
| 409 | Conflict: duplicate row, stale revision/version, or the row changed state since you read it. |
| 410 | The matter is archived. Restore it to continue. |
| 422 | Refused on content: text that mentions grand jury, Rule 6(e), sealed or ex parte material sent to an AI suggest route; a Speedy Trial confirmation blocked by missing findings. |
APP_ENV=production they return 404 (outside development they also need CONTRADICTION_MAP_ENABLED=1). Each module's status route reports whether assist is available. Everything else in these modules works with no AI at all. Sealed and grand jury (Fed. R. Crim. P. 6(e)) sources are never sent to the outside model.Order of Proof
Elements of each charged count, linked to the facts that establish them and to the exhibits that prove each fact. Access: owner office, collaborate or better. Confirming a count's elements and accepting a suggestion need an attorney role (prosecutor, org_admin, super_admin). Facts are the same rows the Contradiction Map uses and can be edited here where the map is off.
GET /api/order-of-proof/status # { enabled, assistEnabled, mode }
GET /api/order-of-proof/catalog # { manual, verifyNotice, entries[] } elements catalog
GET /api/cases/:caseId/order-of-proof # { counts, facts, evidence, map, assist, summary, viewer, … }
POST /api/cases/:caseId/order-of-proof/counts
# { countNumber, catalogKey } or { countNumber, statute, title, elements: string[] }
# 201 { id, countNumber, statute, title } · 409 count number already on matter
PUT /api/cases/:caseId/order-of-proof/counts/:countId # { countNumber?, title? } · 409 duplicate
DELETE /api/cases/:caseId/order-of-proof/counts/:countId # 204
POST /api/cases/:caseId/order-of-proof/counts/:countId/verify
# { confirm: true } · attorney role · 200 { id, verifiedAt }
POST /api/cases/:caseId/order-of-proof/counts/:countId/elements # { text } · 201; clears verification
PUT /api/cases/:caseId/order-of-proof/elements/:elementId # { text?, position? } · text clears verification
DELETE /api/cases/:caseId/order-of-proof/elements/:elementId # 204; clears verification
POST /api/cases/:caseId/order-of-proof/links # { elementId, factId } · 201 · 409 already linked
DELETE /api/cases/:caseId/order-of-proof/links/:linkId
POST /api/cases/:caseId/order-of-proof/sources # { factId, evidenceId, stance: "supports"|"contradicts", note? }
# 201 new, 200 when it updates the existing pair
DELETE /api/cases/:caseId/order-of-proof/sources/:sourceId
POST /api/cases/:caseId/order-of-proof/facts # { text } (min 12 chars) · 201 { id, text, position }
PUT /api/cases/:caseId/order-of-proof/facts/:factId # { text }
DELETE /api/cases/:caseId/order-of-proof/facts/:factId # 204
# Pilot only — 404 when APP_ENV=production. AI rate limiter.
POST /api/cases/:caseId/order-of-proof/suggest # { factId?, countId? } → { run, orderOfProof }
POST /api/cases/:caseId/order-of-proof/suggestions/:suggestionId/accept # {} · attorney role
POST /api/cases/:caseId/order-of-proof/suggestions/:suggestionId/dismiss # {}
# 200 { id, status, linkId } · 409 already decided, element gone, or fact/wording changedSuggestions never become links until an attorney accepts them. Facts that may rest on sealed or grand jury material, or that a full map run has not yet cleared, are held back and never sent.
curl -b cookies.txt -X POST https://<host>/api/cases/116/order-of-proof/counts \
-H "Content-Type: application/json" \
-d '{"countNumber":2,"statute":"18 U.S.C. § 1343","title":"Wire fraud","elements":["The defendant knowingly devised a scheme to defraud."]}'
# 201
{ "id": 14, "countNumber": 2, "statute": "18 U.S.C. § 1343", "title": "Wire fraud" }
# 400 { "message": "Count numbers start at 1." } (countNumber: 0)
# 403 partner agency or not on the matterBench Order Capture
The attorney types what the judge ordered; fixed rules find every date, time and deadline and show the arithmetic. Nothing is written until an attorney confirms. Access: owner office, collaborate or better to open and parse; confirm needs prosecutor, org_admin or super_admin. The order text is shared with partners only when the attorney opts in, and never when it mentions grand jury, sealed or ex parte material.
GET /api/bench-order/status # { assist: { available, mode } }
GET /api/cases/:caseId/bench-order/context?courtEventId=
# { caseNumber, timeZone, today, defaultHearingDate, courtEvent, team, canConfirm, existingEvents, … }
# 400 invalid court event id · 404 court event not on this matter
POST /api/cases/:caseId/bench-order/parse
# { text, hearingDate: "YYYY-MM-DD", choices? } → { hearingDate, today, timeZone, candidates[] }
# Nothing is saved.
GET /api/cases/:caseId/bench-order/captures # last 50 confirmed captures
POST /api/cases/:caseId/bench-order/captures
# { captureKey, text, hearingDate, attest: true, items: [...], courtEventId?, choices?,
# assist?: { id }, shareText? }
# items[].motionId attaches that item only. A motion hearing sets the hearing date,
# an opposition sets response due, a reply sets reply due. Anything else with a
# motionId is 400. A motion that is not on the matter is 404, before anything is written.
# 201 created · 200 { duplicate: true } for a repeated captureKey
# 403 non-attorney role · 400 a continued court date without a keep/move/remove choice
# (items[].replaces: null | { eventId, action: "move"|"remove" })
# Pilot only — 404 when APP_ENV=production. AI rate limiter.
POST /api/cases/:caseId/bench-order/assist # same body as parse
# 422 text mentions grand jury, sealed or ex parte material (never sent)curl -b cookies.txt -X POST https://<host>/api/cases/121/bench-order/parse \
-H "Content-Type: application/json" \
-d '{"text":"Status conference continued to October 14 at 9:30 a.m.","hearingDate":"2026-09-18"}'
# 200
{
"hearingDate": "2026-09-18", "today": "2026-09-18", "timeZone": "America/Los_Angeles",
"candidates": [{
"id": "c1", "kind": "court_event", "hearingType": "status_conference",
"title": "Status conference", "date": "2026-10-14", "time": "09:30", "continuance": true,
"sourceText": "Status conference continued to October 14 at 9:30 a.m",
"basis": ["Stated in the order: \"October 14\" → Wed, Oct 14, 2026.", "…"], …
}]
}Speedy Trial Clock
Federal 18 U.S.C. § 3161 decision aid. Owner office only: read at read_only, write at contribute. Confirming, rejecting or reopening an exclusion needs full access and an attorney role in the matter's own office. Exclusions are created unconfirmed and do not count until an attorney confirms them. Writes on a state or municipal matter return 409 unless the office turned the federal clock on for them.
GET /api/speedy-trial/status # { enabled, aiAssist, mode }
GET /api/speedy-trial/settings # { nonFederalEnabled, canManage }
PUT /api/speedy-trial/settings # org_admin · { nonFederalEnabled: boolean }
GET /api/cases/:caseId/speedy-trial
# { applicable, clock, exclusions, result, badge, permissions, suggestions, today, timeZone, … }
PUT /api/cases/:caseId/speedy-trial/clock
# { arrestDate?, chargingDate?, chargingInstrument?: "indictment"|"information",
# firstAppearanceDate?, counselAppearanceDate?, trialDate?, notes? } → full payload
POST /api/cases/:caseId/speedy-trial/exclusions
# { basis, startDate, endDate?, sourceKind?, sourceRef?, description, findings?,
# findingsDate?, externalRef? } → 201 { id, status: "unconfirmed", payload }
# 409 that bench-order record was already added · 422 matter at the exclusion cap
PUT /api/cases/:caseId/speedy-trial/exclusions/:exclusionId
# partial; changing basis/dates/findings resets a decided exclusion → { id, status, reset, payload }
POST /api/cases/:caseId/speedy-trial/exclusions/:exclusionId/decision
# { decision: "confirm"|"reject"|"reopen", revision, note? }
# 409 { code: "stale_revision" } row changed since you read it · 409 already in that state
# 422 e.g. an (h)(7)(A) exclusion with no recorded findings
DELETE /api/cases/:caseId/speedy-trial/exclusions/:exclusionId
# 204 · a confirmed exclusion needs the attorney gate; full row kept in the audit entry
# Pilot only — 404 when APP_ENV=production. AI rate limiter.
POST /api/cases/:caseId/speedy-trial/suggest-basis
# { text } → { mode, model, basis, confidence, label, note }
# 422 grand jury / Rule 6(e) / sealed text (never sent) · 503 upstream failedcurl -b cookies.txt -X POST https://<host>/api/cases/122/speedy-trial/exclusions/7/decision \
-H "Content-Type: application/json" \
-d '{"decision":"confirm","revision":"3f9a0c12b4e5d678"}'
# 200 { "id": 7, "status": "confirmed", "payload": { … } }
# 409 { "message": "This exclusion changed after you opened it. Review it again before deciding.",
# "code": "stale_revision" }Plea Desk
Formal plea offers, supervisor approval, expiration and a log of how each offer reached defense counsel. No AI anywhere in this module. Owner office only (partners and platform operators get 403): view at contribute, draft and act at full. Approve and reopen need an office approver role or a designated approver, never an author of the offer. Every write is compare-and-set: name the version you reviewed; a stale one gets 409 stale_version. Errors may carry { code, problems[] }.
GET /api/cases/:caseId/plea-offers # { matter, offers, viewer, settings, staff, summary, … }
POST /api/cases/:caseId/plea-offers # { pleadCounts: [{ count, description }], defendant?,
# defenseCounsel?, dismissedCounts?, sentencingStipulations?,
# guidelineNotes?, cooperationRequired?, cooperationTerms?,
# otherConditions?, expiresOn?, expiresTime?, letterBody? } · 201
GET /api/cases/:caseId/plea-offers/:offerId
PUT /api/cases/:caseId/plea-offers/:offerId # draft only · same fields + version · 409 not_draft
POST /api/cases/:caseId/plea-offers/:offerId/submit # { version? }
POST /api/cases/:caseId/plea-offers/:offerId/recall # { version? }
POST /api/cases/:caseId/plea-offers/:offerId/approve # { version, note? } · approver, not an author
POST /api/cases/:caseId/plea-offers/:offerId/return # { note, version? } · approver
POST /api/cases/:caseId/plea-offers/:offerId/extend # { occurredAt, method, counterpart, summary, attested: true,
# conveyedByUserId?, onRecord?, version? }
# 409 letter_deadline_mismatch · 409 offer_expired
POST /api/cases/:caseId/plea-offers/:offerId/accept # { note, attorneyConfirmed: true, version }
# 409 not_extended | offer_expired | reconvey_required
POST /api/cases/:caseId/plea-offers/:offerId/reject # { note, version? }
POST /api/cases/:caseId/plea-offers/:offerId/withdraw # { reason, version? }
POST /api/cases/:caseId/plea-offers/:offerId/reopen # { reason, expiresOn, expiresTime?, letterBody?, version? }
# approver, not an author · 409 not_expired
POST /api/cases/:caseId/plea-offers/:offerId/revise # {} → 201 new draft · 409 not_revisable | open_revision
POST /api/cases/:caseId/plea-offers/:offerId/communications
# { occurredAt, method, counterpart, summary, direction,
# attachLetter?, conveyedByUserId?, onRecord? } · 201
GET /api/cases/:caseId/plea-offers/:offerId/letter # text/plain attachment (audited)
GET /api/cases/:caseId/plea-offers/:offerId/communications/:commId/letter
# the exact letter logged with that communication
GET /api/plea-desk/expiring?days=14 # office view: { expiring, overdue, awaitingApproval, … }
# days 1–90, else 400
GET /api/plea-desk/settings # { approverRoles, approverUserIds, choices, staff, canEdit }
PUT /api/plea-desk/settings # org_admin · { approverRoles[], approverUserIds[] }curl -b cookies.txt -X POST https://<host>/api/cases/121/plea-offers/2/approve \
-H "Content-Type: application/json" \
-d '{"version":4,"note":"Terms match the charging memo."}'
# 200 — the offer detail, status "approved"
# 403 { "message": "…", "code": "own_offer" } you created, edited or submitted it
# 409 { "message": "…", "code": "stale_version" } someone changed it after you read it
# 409 { "message": "…", "code": "offer_expired" }Victim Notice Ledger
A decision aid for 18 U.S.C. § 3771(a)(2) notice duties. No AI: victim contact data and notice text never reach a model. Court-event hooks only open duties; nothing is sent to a victim without a person confirming the send. Access: owner office at contribute+ works the ledger; a victim-advocacy partner on the matter may view it and (at contribute) log attempts; every other partner gets 403. Closing without notice needs full access and an attorney role. Victims classified above the caller's access are listed without identity and cannot be acted on (403).
GET /api/victim-notice/settings # prosecuting office · { settings, defaults, limits, canEdit, holidays, citation }
PUT /api/victim-notice/settings # org_admin · { timeZone, scheduledLeadBusinessDays,
# changeBusinessDays, custodyBusinessDays, dueHour,
# minAttemptsBeforeUnable }
GET /api/victim-notice/queue # office queue: { counts, overdue, dueToday, upcoming, unable, … }
GET /api/cases/:caseId/victim-notice # { victims, duties, summary, authority, settings, … }
PUT /api/cases/:caseId/victim-notice/contacts/:victimId
# { preferredChannels?, mailingAddress?, doNotContact?, doNotContactReason?,
# safeContactNote?, voicemailOk? } · owner office · doNotContact needs a reason
POST /api/cases/:caseId/victim-notice/triggers # { triggerKind, title, eventAt? } → 201 { opened, dutyIds, ledger }
POST /api/cases/:caseId/victim-notice/duties/:dutyId/draft # { subject?, body? }
POST /api/cases/:caseId/victim-notice/duties/:dutyId/send # { confirm: true } — one human click
POST /api/cases/:caseId/victim-notice/duties/:dutyId/delivery # { channel, note, deliveredAt? } off-system delivery
POST /api/cases/:caseId/victim-notice/duties/:dutyId/confirm # { note? }
POST /api/cases/:caseId/victim-notice/duties/:dutyId/attempts # { channel, outcome, note? } · advocacy partner allowed
POST /api/cases/:caseId/victim-notice/duties/:dutyId/unable # { note }
POST /api/cases/:caseId/victim-notice/duties/:dutyId/close # { reason, attestation: true } · attorney, full access
# Each returns the refreshed ledger. 404 duty not on matter · 409 someone else changed the duty,
# the victim left the matter, or the transition is not allowed from the duty's status.curl -b cookies.txt -X POST https://<host>/api/cases/123/victim-notice/duties/5/send \
-H "Content-Type: application/json" -d '{"confirm":true}'
# 200 — the ledger for the matter
# 400 { "message": "Confirm the send: nothing goes to a victim without an explicit confirmation." }
# 409 { "message": "Draft the notice before sending it." }Victims' rights notices and the victim portal
A record of each rights notice owed to each victim, beside the Victim Notice Ledger. The ledger is read, never changed. Staff routes belong to the prosecuting office; office admins edit the notice list and the feed switch. Entries are append-only and audited. Recording a custody change or a post-conviction hearing sends a short alert to victims who opted in. Sealed and grand jury matters and do-not-contact victims get none.
GET /api/rights-notices/types # the office's notices · { types, stages, feed: { enabled, path, scope }, … }
POST /api/rights-notices/types # org_admin · { label, stage, templateText?, active? }
PATCH /api/rights-notices/types/:id # org_admin
GET /api/rights-notices/queue # office-wide: owed or not reachable, oldest first
GET /api/rights-notices/export.csv # whole office, or ?caseId=<id> for one matter · audited
GET /api/cases/:caseId/rights-notices # per-victim record for one matter
POST /api/cases/:caseId/rights-notices/entries # { victimId, typeKey, triggerKey, status, channel?, happenedAt?, note? }
# channel is required when status is "sent"
PUT /api/cases/:caseId/rights-notices/opt-ins/:victimId
# { custodyAlerts, postConvictionAlerts, channel }
POST /api/cases/:caseId/rights-notices/custody-events
# { kind: "custody_status" | "post_conviction_hearing", custodyStatus?, hearingKind?,
# hearingAt?, facility?, effectiveAt?, note? } · alerts opted-in victimsThe inbound custody feed is off by default. An office admin turns it on. It takes an API client access token with the existing partners:write scope; there is no separate scope for the feed. The answer is 202 whether or not the case number matches a matter. Each event waits in a review list, and nothing reaches a victim until a person confirms the event and its matter.
PUT /api/rights-notices/feed # org_admin · turn the inbound feed on or off
POST /api/integrations/custody-feed/events # Bearer token, scope partners:write · rate limited
# { externalId, caseNumber, kind?: "custody_status" | "post_conviction_hearing",
# status?, hearingAt?, hearingKind?, facility?, effectiveAt? }
# 202 { accepted: true } · 400 bad body · 401 no token · 403 feed off for the office
POST /api/rights-notices/feed-events/:id/confirm # staff · { caseId } · or /dismissVictim portal routes use the portal session, not a staff cookie. A person can ask for a new sign-in code; the answer is the same whether or not anyone matches. A code goes by text only when the office has text messaging on and the person has agreed to texts.
POST /api/portal/codes # staff · { caseId, personId } issue a sign-in code
POST /api/portal/code-requests # public, rate limited · same answer for any email or mobile number
POST /api/portal/sessions # public, rate limited · exchange a code for a portal session
GET /api/portal/notices-sent # notice name, day and channel only
PUT /api/portal/statement # save a draft impact statement
POST /api/portal/statement/submit # send it to the office
POST /api/portal/statement/withdraw # until the office marks it received
POST /api/portal/files # multipart · same limits, scan, hash and custody as evidence intakeDefense counsel access
Defense counsel sign in with the email that received discovery and a one-time code. The session is an HttpOnly cookie that lasts two hours. A code request gives the same answer for a known email, an unknown email and an unknown office. Counsel sees only deliveries the signed-in office sent to the verified email; anything else is a 404. Sealed and grand jury matters never appear.
POST /api/defense/code # public, rate limited · { office, email }
POST /api/defense/verify # public, rate limited · { office, email, code } six digits
# 10 minute code · 5 wrong tries lock for 15 minutes
GET /api/defense/session # productions delivered to this email, and its requests
POST /api/defense/session/deliveries/:deliveryId/open # open the delivery page with no second code
POST /api/defense/session/requests # { deliveryId, scope: "production" | "matter", kind, subject, details, name }
# 10 a day per email
POST /api/defense/sign-out
# Staff, owner office only
GET /api/cases/:caseId/discovery-requests
PATCH /api/cases/:caseId/discovery-requests/:id # { assigneeUserId?, dueDate? } YYYY-MM-DD or null
POST /api/cases/:caseId/discovery-requests/:id/respond # { status, responseText?, declineReason?, productionId? }
# responded needs responseText · declined needs declineReason · produced needs a production
# already delivered to that emailWitness page and officers in court
Staff make a witness page link from an issued subpoena. The link and the six-digit code are shown once, and only their hashes are stored. The public routes are rate limited. A wrong code, an unknown link, an expired link and a locked link all get the same 401. After /open, send the returned session in the x-witness-session header.
# Staff
GET /api/cases/:caseId/witness-court # links, confirmations, claims and officer notices on a matter
GET /api/cases/:caseId/officer-conflicts # away days and witness dates that clash with a court date
POST /api/subpoenas/:id/witness-link # → link and code, shown once
POST /api/witness-claims/:id/decide # supervisor · { decision, note? } a denial needs a note
POST /api/officer-notices/:id/acknowledge # record a confirmation by hand
GET /api/witness-court/settings # fee settings
PUT /api/witness-court/settings # supervisor or org_admin · { dailyFee, perMile, claimsOn }
GET /api/officers/court-week # officers due in the next seven days
GET /api/officers/availability
POST /api/officers/availability # { officerName, kind, startDate, endDate, note? }
DELETE /api/officers/availability/:id
# Witness page (public)
POST /api/witness-portal/open # { token, code } → { ok, session, home }
POST /api/witness-portal/home
POST /api/witness-portal/confirm # confirm the subpoena was received
POST /api/witness-portal/status # { onCall, phone? }
POST /api/witness-portal/dates # dates the witness cannot attend
POST /api/witness-portal/claims # { days, roundTripMiles } · the server works out the amount
POST /api/witness-portal/sign-out
POST /api/witness-portal/notice # an officer opens a court date notice
POST /api/witness-portal/notice/acknowledgeCaseload, saved views and bulk actions
Caseload is for supervisors and office admins in a prosecuting office. Restricted matters count toward a load but come back with no number, title or case type. The suggestion only lists people; it never reassigns. Bulk routes run the same permission check on each row as the single-row save and write one audit entry per changed row.
GET /api/caseload/weights # weights by case type, severity and stage
PUT /api/caseload/weights # supervisor or org_admin · audited
GET /api/caseload # people, weighted load, trials in 60 days, overdue items
GET /api/caseload/suggest # ?group=attorney|investigator&caseId=&limit=1..10
# lightest load first; people left out carry a reason
GET /api/saved-views # your views and views shared with the office
POST /api/saved-views # { list, name, shared?, config? } · sharing needs a supervisor or admin
PUT /api/saved-views/:id # only the person who made it
DELETE /api/saved-views/:id
PUT /api/saved-views/default # { list, viewId | null }
GET /api/record-tags # the office's own tags
POST /api/bulk/cases # { action: "reassign" | "tag" | "untag" | "status", ids, assignedToUserId | tag | status }
POST /api/bulk/tasks # the same, plus { action: "due", ids, dueDate | null }
# Rows that fail come back with the reason. A missing row and a row you may not see read the same.Racial Justice Act data and office data
Aggregate counts and rates for supervisors (dept_admin) and office admins. No route lists a matter. Small counts are suppressed. Every report and download is logged. The output is office data: it is not a legal conclusion and it follows no statute's or agency's reporting layout.
GET /api/rja/options # charge codes and groupings the office can pick
GET /api/rja/matter/:caseId/charges # one matter's charges, after a matter-access check
GET /api/rja/report # ?codes=&family=&from=&to=&groupBy=&threshold=
GET /api/rja/report.csv
GET /api/rja/report.pdf # tagged PDF summary
GET /api/org/office-data # org_admin · settings for the public page and the export
PUT /api/org/office-data # org_admin · { publicEnabled, intro, threshold, columnMap }
GET /api/org/office-data/case-level.csv # org_admin · ?from=&to= · one row per matter, restricted matters left out
GET /api/public/office-data/:office # public, rate limited · 404 when the page is off or the office is unknown
GET /api/public/office-data/:office/data.csvStatus, feedback and usage
The status endpoint is public and carries no tenant data. Uptime is measured by the service itself, not by an outside monitor. Feedback and usage need a signed-in user. Usage is a page-view count by area; reports show only distinct people and views.
GET /api/public/status # public, rate limited, cached 30 s · app, database, email, file storage,
# 90-day uptime, incidents
POST /api/product-feedback # { message, rating?: 1..5, route? } · rate limited
POST /api/usage/view # the workspace's own page-view beacon
GET /api/admin/usage # org_admin · the office's own counts
GET /api/mail/readiness # signed-in staff · whether outbound email is switched onGiglio Watch
A restricted office list of law-enforcement witnesses with potential impeachment information (JM 9-5.100). Off by default; only an org_admin enables it, recording the policy reference and the office's policy id. Visible only to lead-office prosecutor, dept_admin, admin, org_admin and designated reviewers; partner agencies (including the officer's own agency), courts, advocates, investigators, analysts and platform operators get a 403 that says nothing more. When the office has it off, list routes return 404 { enabled: false }. Two-person rule: an entry is active only after a different org_admin or designated reviewer approves it. Every view and mutation is audited with ids only. No AI.
GET /api/giglio/status # always 200; all-false flags for anyone who may not view
PUT /api/giglio/settings # org_admin · { enabled: true, policyReference, officePolicyId, acknowledged: true }
# | { enabled: false, reason }
GET /api/giglio/reviewers # org_admin
POST /api/giglio/reviewers # org_admin · { userId } (active office member)
DELETE /api/giglio/reviewers/:userId
GET /api/giglio/officers
POST /api/giglio/officers # { fullName, agency, agencyAliases?, badgeNumber?, aliases?,
# entry: { category, description, source, sourceDate } } · 409 already listed
GET /api/giglio/officers/:officerId # view is audited
POST /api/giglio/officers/:officerId/entries # { category, description, source, sourceDate } → pending
POST /api/giglio/entries/:entryId/approve # { note? } · approver, not the enterer
POST /api/giglio/entries/:entryId/reject # { reason } · approver, not the enterer
POST /api/giglio/entries/:entryId/retire # { reason }
POST /api/giglio/entries/:entryId/withdraw # { reason } · the enterer, while pending
# 403 two-person rule · 409 already decided / decided a moment ago
GET /api/giglio/queue # pending entries + candidate matches
POST /api/giglio/matches/decide # { officerId, caseId, sourceKind, sourceId, decision, note? }
GET /api/cases/:caseId/giglio/summary # { caseId, reviewRequired, possibleMatches, reviewed }
GET /api/cases/:caseId/giglio # { items, rejectedMatches, permissions, legalBasis, disclaimer, … }
POST /api/cases/:caseId/giglio/reviews # { officerId, fingerprint, outcome, note, attorneyConfirmed: true }
# attorney role with full access · 409 record changedcurl -b cookies.txt https://<host>/api/cases/124/giglio/summary
# 200 { "caseId": 124, "reviewRequired": 1, "possibleMatches": 0, "reviewed": 0 }
# 403 { "message": "Giglio Watch is not available to you." } partner agency, investigator, …
# 404 { "message": "Giglio Watch is off for this office.", "enabled": false }Contradiction Map (pilot only)
/status returns 404 when APP_ENV=production. Outside development it also needs CONTRADICTION_MAP_ENABLED=1.For each (fact, passage) pair the map records whether the passage supports the fact, contradicts it, or says nothing; every cell cites a passage that exists verbatim in a transcript. Owner office, collaborate or better. Sealed and grand jury sources are shown as “Held back” and never sent to the model.
GET /api/contradiction-map/status # { enabled, mode } — 200 in every environment
GET /api/cases/:caseId/contradiction-map # { enabled, mode, model, threshold, facts, sources, cells, summary, disclaimer }
POST /api/cases/:caseId/contradiction-map/facts # { text } → 201 { id, text, position }
PUT /api/cases/:caseId/contradiction-map/facts/:factId # { text?, position? }
DELETE /api/cases/:caseId/contradiction-map/facts/:factId # 204
POST /api/cases/:caseId/contradiction-map/run # { evidenceId? } · AI rate limiter → { run, map }curl -b cookies.txt -X POST https://<host>/api/cases/116/contradiction-map/run \
-H "Content-Type: application/json" -d '{}'
# 200 { "run": { "calls": 3, "judged": 12, … }, "map": { "facts": […], "cells": […], … } }
# 404 { "message": "…" } APP_ENV=productionBilling
Checkout is server-created Stripe Sessions for pro and team only. Enterprise has no Price ID. The webhook path is registered with a raw body parser and signature verification — do not JSON-parse it.
GET /api/billing/config # public; publishable key + plan catalog
POST /api/billing/checkout # { "plan": "pro" | "team" } → { "url" }
POST /api/billing/portal # → { "url" }
GET /api/org/subscription
POST /api/billing/webhook # Stripe-Signature required
# Events: checkout.session.completed, invoice.paid,
# invoice.payment_failed, customer.subscription.*Production webhook URL: https://www.prosequi.ai/api/billing/webhook. See also in-repo docs/STRIPE_BILLING.md.
Realtime
WebSocket upgrades authenticate with the same session cookie. Presence rooms are org- and matter-scoped. Collab is Yjs over /collab/*.
WS /presence
WS /collab/*Admin surfaces
Organization admin
GET /api/org/stats
GET /api/org/users
POST /api/org/users
PUT /api/org/users/:id
DELETE /api/org/users/:id
POST /api/org/users/:id/reset-password
POST /api/org/users/:id/reset-mfa
GET /api/org/audit-logs
GET /api/org/subscriptionPlatform admin
GET /api/admin/platform/operations
GET /api/admin/organizations
POST /api/admin/organizations
GET /api/admin/users
GET /api/admin/audit-logs
GET /api/admin/audit/verify
GET /api/admin/audit/export # NDJSON
GET /api/admin/business-opsOffice security and SCIM
Approved networks
GET /api/admin/orgs/:orgId/network-access
PUT /api/admin/orgs/:orgId/network-access
{ "enabled": true, "ranges": ["203.0.113.0/24", "2001:db8::/32"] }
# 400 when the list leaves out the caller's own address
# Requests from outside the list: 403 { code: "ip_not_allowed" }, auditedElevated access alerts
GET /api/org/elevated-access-alerts
PUT /api/org/elevated-access-alerts/settings
POST /api/org/elevated-access-alerts/acknowledge # with a noteSealing and expungement compliance
GET /api/org/sealing-compliance
GET /api/org/sealing-compliance/:id/history
POST /api/org/sealing-compliance/:id/apply
POST /api/org/sealing-compliance/:id/unseal # office admin, stated authoritySCIM 2.0 Users
An office admin issues one SCIM bearer token on the Security panel. It is shown once and stored as a hash, and it reaches only that office. The provider can read people, change name, email or role (up to office admin) and deactivate them; a deactivation or role change runs the same audited access revocation as the admin screen. People are still created in Prosequi, so POST /scim/v2/Users returns 501.
POST /api/admin/orgs/:orgId/scim/token # office admin; token shown once
DELETE /api/admin/orgs/:orgId/scim
GET /scim/v2/ServiceProviderConfig
GET /scim/v2/Users
GET /scim/v2/Users/:id
PATCH /scim/v2/Users/:id
PUT /scim/v2/Users/:id
DELETE /scim/v2/Users/:id # deactivate
Authorization: Bearer <office SCIM token>Adult Protective Services
APS offices use /api/aps/* with the same session cookie. Every route sits in one table (server/aps/routes.ts) with the module switch and the ability it needs, so a route answers only when the office has that module on and the caller's APS role has the ability.
GET /api/aps/reports # reports waiting to be screened
POST /api/aps/reports # take a report
POST /api/aps/reports/:id/screen # or /screen-out, /rating
GET /api/aps/caseload
GET /api/aps/cases/:id
POST /api/aps/cases/:id/contacts # notes, photos, cross-reports, closure
GET /api/aps/queue # supervisor
POST /api/aps/reassign
GET /api/aps/reports/registry # inventory reports
POST /api/aps/report-runs
GET /api/aps/settings # office settings; the client reads them against the federal rule (shared/aps/rule-1324.ts)
GET /api/aps/field-map # open cases by ZIP code with the worst clock, and open work by worker
POST /api/aps/public/:slug/reports # public web report form
POST /api/aps/v1/referrals # partner referrals, X-APS-Key headerPartner API (preview)
A machine API for partner systems is built behind an office's API clients: OAuth 2.0 client credentials at /oauth/token, short-lived tokens, scopes such as cases:read and evidence:write, and an OpenAPI document at /api/v1/openapi.json. It is a preview: the issuer is a demo host and it is not offered for production integrations yet. Ask through the contact form if you want to build against it.
MCP server (preview)
The same API clients can reach a read-only Model Context Protocol server, so an office's own AI assistant can look things up in Prosequi without a custom integration. It speaks JSON-RPC 2.0 over Streamable HTTP (JSON responses, no server-sent events) and uses the client's bearer token from /oauth/token.
POST /api/v1/mcp
Authorization: Bearer <client-credentials token>
Content-Type: application/json
{ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }| Tool | Scope |
|---|---|
| list_cases, get_case | cases:read |
| list_evidence, get_evidence, list_custody_events | evidence:read |
| list_discovery_items, list_disclosure_decisions | discovery:read |
| list_productions | productions:read |
| get_report (discovery-compliance, workload, speedy-trial) | reports:read |
tools/list shows only the tools the token's scopes allow. Every call goes through the same checks as /api/v1: the client's case allow-list, its rate limit and the API audit log. Sealed, grand jury and juvenile matters are never returned. There are no write tools. Like the Partner API, it is a preview and not offered for production integrations yet.
Health and ops
GET /healthz
{
"status": "ok",
"service": "prosequi",
"env": "production",
"appEnv": "production" | "staging" | "development",
"seed": "ok" | "skipped" | "failed",
"ai": {
"mode": "live" | "mock" | "off",
"provider": "xai" | "anthropic",
"model": "grok-4.5",
"models": { "deep": "grok-4.5", "standard": "grok-4.5", "fast": "grok-4.5" },
"fallbacks": false,
"live": true,
"keyConfigured": true,
"misconfigured": false
},
"billing": { "configured": true, "livemode": true }
}Health never returns secrets. ai.keyConfigured is a boolean for the selected provider only. billing.livemode is inferred from the secret key prefix, not the key itself.
GET /readyz answers 503 while an instance is draining or a check is failing, so a load balancer can take it out of rotation.
- Logs: in production every log line is one JSON object with time, level, msg and the requestId of the request it ran in. Request lines carry the route, status and user and office ids; no bodies, query strings, headers, names or matter content.
- Metrics: GET /metrics returns Prometheus text (requests and latency per route template and status class, memory and uptime). It is off unless the operator sets METRICS_TOKEN, and then needs Authorization: Bearer <token>.
- Alerts: more than 5% 5xx answers over at least 20 API requests in five minutes, or /readyz failing twice in a row, logs one line at level alert and emails OPS_ALERT_EMAIL when that is set and mail delivers. Each kind fires at most once per 30 minutes and says when it clears.
- AI calls: people's names on the matters in a request leave as Person 1, Person 2 and so on and come back as real names only for the reader. SSNs, their birth dates, emails and phone numbers are masked and not restored.
Local development
git clone https://github.com/kevin-owens-product/ai-prosecutor
cp .env.example .env
# DATABASE_URL, SESSION_SECRET, APP_ENCRYPTION_KEY
# XAI_API_KEY + AI_PROVIDER=xai + AI_MODE=live # or AI_MODE=mock
npm install
npm run db:migrate # versioned migrations; db:push only on a scratch database
npm run dev # http://localhost:5000
npm test
npm run check
npm run e2e
npm run e2e:multi-roleNode 20. Seeded demo users are listed in the README. SEED_DB=true is blocked when APP_ENV=production unless ALLOW_PROD_SEED=1.
stripe listen --forward-to localhost:5000/api/billing/webhook and put the CLI whsec_ in STRIPE_WEBHOOK_SECRET. There is no mock Stripe.