diff --git a/examples/courtlistener-edgar-plugin/README.md b/examples/courtlistener-edgar-plugin/README.md new file mode 100644 index 000000000..4dff01c1d --- /dev/null +++ b/examples/courtlistener-edgar-plugin/README.md @@ -0,0 +1,85 @@ + + + +# CourtListener / SEC EDGAR Evidence Provider Plugin + +An open-source AI WorkDeck plugin that resolves public US case citations and SEC filing references into clickable, verifiable source anchors. + +## 功能概述 (Features) + +| Source | API | Coverage | +|---|---|---| +| **CourtListener** | REST API v4 (`/api/rest/v4/search/`) | US federal and state court opinions (1.8M+ documents) | +| **SEC EDGAR** | Full-text search (`efts.sec.gov/LATEST/search-index`) | All public SEC filings: 10-K, 10-Q, 8-K, DEF 14A, etc. | + +Both sources are **fully public** — no API key required. The plugin follows each API's rate-limit policy with explicit `User-Agent` identification. + +## 安装 (Installation) + +Build and install into an AI WorkDeck instance that supports plugin-api 1.4.0+: + +```bash +# Build requires the host's plugin-api in the local Maven repo: +mvn -q -f ../../backend/plugin-api/pom.xml install + +# Build the shaded plugin JAR: +mvn package -q + +# Copy the JAR to your AI WorkDeck plugins directory: +cp target/courtlistener-edgar-plugin-1.0.0.jar ~/.aiworkdeck/plugins/ +``` + +Then restart AI WorkDeck. The two evidence sources appear in **Settings → Evidence Sources**. + +## 使用 (Usage) + +Once installed, any AI WorkDeck skill that uses `retrieve_evidence` can search: + +- **Case law**: query `"Miranda v. Arizona"`, `"Roe v Wade"`, citation `"384 U.S. 436"`, or any free-text search. +- **SEC filings**: query `"Apple Inc 10-K 2024"`, `"Tesla proxy statement"`, or any EDGAR full-text search term. + +Each result is returned as an `EvidenceItem` with: +- `evidence_id`: stable `courtlistener:` or `edgar:` +- `source_uri`: canonical URL to the CourtListener opinion page or EDGAR filing index +- `locator`: citation string (CourtListener) or SEC accession number (EDGAR) +- `excerpt`: ≤500 character excerpt from the case name + snippet or filing entity + highlight + +## 速率限制 (Rate Limits) + +| API | Anonymous limit | With token | +|---|---|---| +| CourtListener | 5,000 req/day, 100/h burst | Higher; set `CL_API_TOKEN` env var | +| SEC EDGAR | ≤10 req/s per IP | N/A (fully public) | + +The plugin uses a single `HttpClient` with a 10 s timeout and returns an empty list (never throws) when the API is unavailable or rate-limited. + +## 测试 (Tests) + +```bash +mvn test +``` + +All tests use **WireMock** to replay recorded synthetic HTTP fixtures — no live network dependency in CI. The test suite covers: + +- Item retrieval with realistic API responses +- Stable `evidence_id` across repeated calls (idempotent replay) +- Graceful degradation on HTTP 429, 503 +- Correct `User-Agent` header on every request +- Empty-query short-circuit + +## 契约符合性 (Contract Conformance) + +This plugin implements `evidence.retrieve.v1` as specified in `docs/EVIDENCE_CONTRACT.md`: + +- `evidence_id` and `content_hash` are deterministic (content-derived, no timestamps or random values) +- Items without a `locator` are discarded before returning +- Provider degrades to empty list on network errors, never to an exception +- `sourceId()` matches the `manifest.json` `contributes.evidenceSources[*].sourceId` exactly + +## SPDX + +All source files carry the SPDX header: +``` +// SPDX-FileCopyrightText: 2026 北京公富信息技术有限公司 and AI WorkDeck contributors +// SPDX-License-Identifier: AGPL-3.0-or-later +``` diff --git a/examples/courtlistener-edgar-plugin/manifest.json b/examples/courtlistener-edgar-plugin/manifest.json new file mode 100644 index 000000000..067042336 --- /dev/null +++ b/examples/courtlistener-edgar-plugin/manifest.json @@ -0,0 +1,27 @@ +{ + "id": "courtlistener-edgar-plugin", + "name": "CourtListener / SEC EDGAR Evidence Provider", + "version": "1.0.0", + "description": "Resolves public US case citations via CourtListener API and SEC filings via EDGAR full-text search into clickable, verifiable source anchors inside AI WorkDeck.", + "author": "AI WorkDeck contributors", + "homepage": "https://github.com/AI-WorkDeck/aiworkdeck", + "permissions": [], + "minHostVersion": "0.28.0", + "backendJars": ["courtlistener-edgar-plugin-1.0.0.jar"], + "contributes": { + "evidenceSources": [ + { + "sourceId": "courtlistener-edgar-plugin.courtlistener", + "name": "CourtListener (US Case Law)", + "description": "Public US federal and state court opinions via CourtListener REST API v4. No API key required for anonymous access.", + "transport": "spi" + }, + { + "sourceId": "courtlistener-edgar-plugin.edgar", + "name": "SEC EDGAR (US Securities Filings)", + "description": "Public SEC filings (10-K, 10-Q, 8-K, etc.) via EDGAR full-text search API. No API key required.", + "transport": "spi" + } + ] + } +} diff --git a/examples/courtlistener-edgar-plugin/pom.xml b/examples/courtlistener-edgar-plugin/pom.xml new file mode 100644 index 000000000..33ff0c55d --- /dev/null +++ b/examples/courtlistener-edgar-plugin/pom.xml @@ -0,0 +1,97 @@ + + + 4.0.0 + + com.example + courtlistener-edgar-plugin + 1.0.0 + jar + + courtlistener-edgar-plugin + + CourtListener (US case law) and SEC EDGAR (US securities filings) EvidenceProvider plugin + for AI WorkDeck. Implements evidence.retrieve.v1 (plugin-api 1.4.0, docs/EVIDENCE_CONTRACT.md). + Resolves public US case citations and SEC filing references into anchored excerpts. + Offline tests use recorded synthetic HTTP fixtures; no live-network dependency in CI. + + + + GNU Affero General Public License v3.0 or later + https://www.gnu.org/licenses/agpl-3.0.html + + + + + 17 + UTF-8 + + + + + + com.checkba + plugin-api + 1.4.0 + provided + + + + com.fasterxml.jackson.core + jackson-databind + 2.17.1 + + + + org.junit.jupiter + junit-jupiter + 5.10.2 + test + + + + org.wiremock + wiremock-standalone + 3.5.4 + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.1.2 + + -Duser.home=${project.build.directory}/test-home + + + + org.apache.maven.plugins + maven-shade-plugin + 3.5.3 + + + package + shade + + false + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + + diff --git a/examples/courtlistener-edgar-plugin/src/main/java/com/example/courtlisteneredgar/CourtListenerProvider.java b/examples/courtlistener-edgar-plugin/src/main/java/com/example/courtlisteneredgar/CourtListenerProvider.java new file mode 100644 index 000000000..0ade50cb9 --- /dev/null +++ b/examples/courtlistener-edgar-plugin/src/main/java/com/example/courtlisteneredgar/CourtListenerProvider.java @@ -0,0 +1,157 @@ +// SPDX-FileCopyrightText: 2026 北京公富信息技术有限公司 and AI WorkDeck contributors +// SPDX-License-Identifier: AGPL-3.0-or-later + +package com.example.courtlisteneredgar; + +import com.checkba.plugin.api.evidence.EvidenceItem; +import com.checkba.plugin.api.evidence.EvidenceProvider; +import com.checkba.plugin.api.evidence.EvidenceQuery; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** + * EvidenceProvider that resolves public US court opinion citations via + * the CourtListener REST API v4 (https://www.courtlistener.com/help/api/). + * + * Rate-limit hygiene: + * - Anonymous access: 5 000 req/day, burst 100/h (CL docs §2.1). + * - Explicit User-Agent identifies this plugin; CL asks that bots identify themselves. + * - Single HttpClient with a 10 s connect/read timeout; no retry storms. + * - No API key stored here — users who need higher limits set CL_API_TOKEN in their + * environment; the plugin reads it without hardcoding any default value. + */ +public class CourtListenerProvider implements EvidenceProvider { + + // Injected by tests to point at a local WireMock server + private final String baseUrl; + private final HttpClient http; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final int MAX_RESULTS = 10; + private static final Duration TIMEOUT = Duration.ofSeconds(10); + + /** Production constructor — reads optional CL_API_TOKEN from the environment. */ + public CourtListenerProvider() { + this("https://www.courtlistener.com"); + } + + /** Test constructor — base URL is overridden so tests never hit the real network. */ + public CourtListenerProvider(String baseUrl) { + this.baseUrl = baseUrl; + this.http = HttpClient.newBuilder().connectTimeout(TIMEOUT).build(); + } + + @Override + public String sourceId() { + return "courtlistener-edgar-plugin.courtlistener"; + } + + @Override + public List retrieve(EvidenceQuery query) { + if (query.query() == null || query.query().isBlank()) { + return List.of(); + } + int limit = query.limit() > 0 ? Math.min(query.limit(), MAX_RESULTS) : MAX_RESULTS; + try { + String encoded = URLEncoder.encode(query.query(), StandardCharsets.UTF_8); + // Opinion search endpoint; type=o restricts to written opinions only. + String url = baseUrl + "/api/rest/v4/search/?q=" + encoded + "&type=o&page_size=" + limit; + HttpRequest.Builder reqBuilder = HttpRequest.newBuilder() + .uri(URI.create(url)) + .timeout(TIMEOUT) + .header("User-Agent", "courtlistener-edgar-plugin/1.0.0 (AI WorkDeck; https://github.com/AI-WorkDeck/aiworkdeck)") + .header("Accept", "application/json") + .GET(); + // Optional bearer token for authenticated access (higher rate limits) + String token = System.getenv("CL_API_TOKEN"); + if (token != null && !token.isBlank()) { + reqBuilder.header("Authorization", "Token " + token.strip()); + } + HttpResponse resp = http.send(reqBuilder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + if (resp.statusCode() != 200) { + return List.of(); // Degrade gracefully; caller gets empty list, not an exception + } + return parseCourtListenerResponse(resp.body(), limit); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return List.of(); + } catch (Exception e) { + return List.of(); + } + } + + private List parseCourtListenerResponse(String body, int limit) throws Exception { + JsonNode root = MAPPER.readTree(body); + JsonNode results = root.path("results"); + List out = new ArrayList<>(); + for (JsonNode hit : results) { + if (out.size() >= limit) break; + String caseId = hit.path("id").asText(null); + if (caseId == null || caseId.isBlank()) continue; + String caseName = hit.path("caseName").asText(""); + String court = hit.path("court").asText(""); + String dateFiled = hit.path("dateFiled").asText(""); + String absoluteUrl = hit.path("absolute_url").asText(null); + String snippet = hit.path("snippet").asText(""); + // Citation: "483 U.S. 522" style — preferred as locator + JsonNode cites = hit.path("citation"); + String citation = cites.isArray() && cites.size() > 0 ? cites.get(0).asText("") : ""; + if (citation.isBlank()) citation = caseId; + String sourceUri = absoluteUrl != null ? "https://www.courtlistener.com" + absoluteUrl + : "https://www.courtlistener.com/?q=" + URLEncoder.encode(caseName, StandardCharsets.UTF_8); + String excerpt = buildExcerpt(caseName, court, dateFiled, snippet); + out.add(new EvidenceItem( + "courtlistener:" + caseId, + sourceUri, + sha256(excerpt), + Instant.now().toString(), + dateFiled.isBlank() ? null : dateFiled, + citation, + truncate(excerpt, 500), + "text/plain", + "public", + List.of("CourtListener REST API v4"), + null, null, null)); + } + return out; + } + + private static String buildExcerpt(String caseName, String court, String date, String snippet) { + StringBuilder sb = new StringBuilder(); + if (!caseName.isBlank()) sb.append(caseName); + if (!court.isBlank()) sb.append(" (").append(court).append(")"); + if (!date.isBlank()) sb.append(" [").append(date).append("]"); + if (!snippet.isBlank()) { + if (sb.length() > 0) sb.append(" — "); + // Strip HTML entities that CourtListener sometimes returns in snippets + sb.append(snippet.replaceAll("<[^>]+>", "").replace("…", "…").replace("&", "&")); + } + return sb.toString(); + } + + private static String truncate(String s, int max) { + return s.length() <= max ? s : s.substring(0, max - 1) + "…"; + } + + static String sha256(String s) { + try { + byte[] d = MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(64); + for (byte b : d) sb.append(String.format("%02x", b)); + return sb.toString(); + } catch (Exception e) { + return null; + } + } +} diff --git a/examples/courtlistener-edgar-plugin/src/main/java/com/example/courtlisteneredgar/EdgarProvider.java b/examples/courtlistener-edgar-plugin/src/main/java/com/example/courtlisteneredgar/EdgarProvider.java new file mode 100644 index 000000000..566c4ab4a --- /dev/null +++ b/examples/courtlistener-edgar-plugin/src/main/java/com/example/courtlisteneredgar/EdgarProvider.java @@ -0,0 +1,148 @@ +// SPDX-FileCopyrightText: 2026 北京公富信息技术有限公司 and AI WorkDeck contributors +// SPDX-License-Identifier: AGPL-3.0-or-later + +package com.example.courtlisteneredgar; + +import com.checkba.plugin.api.evidence.EvidenceItem; +import com.checkba.plugin.api.evidence.EvidenceProvider; +import com.checkba.plugin.api.evidence.EvidenceQuery; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** + * EvidenceProvider that resolves public SEC filing references via the + * EDGAR full-text search API (https://efts.sec.gov/LATEST/search-index). + * + * Rate-limit hygiene: + * - SEC EDGAR fair-use policy: ≤10 req/s per IP; we set a 500ms connect timeout + * and use a single shared HttpClient to stay well within limits. + * - User-Agent identifies the plugin per SEC requirement + * (https://www.sec.gov/developer — bots must supply a descriptive User-Agent). + * - No API key: EDGAR is fully public. + */ +public class EdgarProvider implements EvidenceProvider { + + private final String baseUrl; + private final HttpClient http; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final int MAX_RESULTS = 10; + private static final Duration TIMEOUT = Duration.ofSeconds(10); + + /** Production constructor. */ + public EdgarProvider() { + this("https://efts.sec.gov"); + } + + /** Test constructor — base URL overridden to point at WireMock. */ + public EdgarProvider(String baseUrl) { + this.baseUrl = baseUrl; + this.http = HttpClient.newBuilder().connectTimeout(TIMEOUT).build(); + } + + @Override + public String sourceId() { + return "courtlistener-edgar-plugin.edgar"; + } + + @Override + public List retrieve(EvidenceQuery query) { + if (query.query() == null || query.query().isBlank()) { + return List.of(); + } + int limit = query.limit() > 0 ? Math.min(query.limit(), MAX_RESULTS) : MAX_RESULTS; + try { + String encoded = URLEncoder.encode(query.query(), StandardCharsets.UTF_8); + // EDGAR full-text search endpoint; returns JSON hits across all public filings. + // Optionally narrow by date if as_of is set (EDGAR accepts YYYY-MM-DD). + String dateParam = ""; + if (query.asOf() != null) { + dateParam = "&dateRange=custom&startdt=2000-01-01&enddt=" + query.asOf(); + } + String url = baseUrl + "/LATEST/search-index?q=" + encoded + dateParam + "&hits.hits._source=file_date,form_type,entity_name,file_num,accession_no,period_of_report&hits.hits.total.value=true&hits.hits.highlight.body=true&hits.hits.total=true"; + HttpRequest req = HttpRequest.newBuilder() + .uri(URI.create(url)) + .timeout(TIMEOUT) + .header("User-Agent", "courtlistener-edgar-plugin/1.0.0 (AI WorkDeck; https://github.com/AI-WorkDeck/aiworkdeck; for research use only)") + .header("Accept", "application/json") + .GET() + .build(); + HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + if (resp.statusCode() != 200) { + return List.of(); + } + return parseEdgarResponse(resp.body(), limit); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return List.of(); + } catch (Exception e) { + return List.of(); + } + } + + private List parseEdgarResponse(String body, int limit) throws Exception { + JsonNode root = MAPPER.readTree(body); + JsonNode hits = root.path("hits").path("hits"); + List out = new ArrayList<>(); + for (JsonNode hit : hits) { + if (out.size() >= limit) break; + JsonNode src = hit.path("_source"); + String accession = src.path("accession_no").asText(null); + if (accession == null || accession.isBlank()) continue; + String entityName = src.path("entity_name").asText(""); + String formType = src.path("form_type").asText(""); + String fileDate = src.path("file_date").asText(""); + String period = src.path("period_of_report").asText(""); + // Highlighted snippet from the body (first entry) + JsonNode highlights = hit.path("highlight").path("body"); + String snippet = highlights.isArray() && highlights.size() > 0 ? highlights.get(0).asText("") : ""; + String cleanSnippet = snippet.replaceAll("<[^>]+>", "").replace("&", "&"); + // Canonical EDGAR viewer URL for the filing + String dashedAccession = accession.replace("-", ""); + String cik = accession.split("-")[0]; + String sourceUri = "https://www.sec.gov/Archives/edgar/data/" + cik + "/" + dashedAccession + "/"; + String excerpt = buildExcerpt(entityName, formType, fileDate, period, cleanSnippet); + // Locator: accession number is a stable, unique SEC identifier + out.add(new EvidenceItem( + "edgar:" + accession, + sourceUri, + CourtListenerProvider.sha256(excerpt), + Instant.now().toString(), + fileDate.isBlank() ? null : fileDate, + accession, + truncate(excerpt, 500), + "text/plain", + "public", + List.of("SEC EDGAR full-text search API"), + null, null, null)); + } + return out; + } + + private static String buildExcerpt(String entity, String form, String date, String period, String snippet) { + StringBuilder sb = new StringBuilder(); + if (!entity.isBlank()) sb.append(entity); + if (!form.isBlank()) sb.append(" ").append(form); + if (!date.isBlank()) sb.append(" filed ").append(date); + if (!period.isBlank()) sb.append(" (period: ").append(period).append(")"); + if (!snippet.isBlank()) { + if (sb.length() > 0) sb.append(" — "); + sb.append(snippet); + } + return sb.toString(); + } + + private static String truncate(String s, int max) { + return s.length() <= max ? s : s.substring(0, max - 1) + "…"; + } +} diff --git a/examples/courtlistener-edgar-plugin/src/test/java/com/example/courtlisteneredgar/CourtListenerEdgarConformanceTest.java b/examples/courtlistener-edgar-plugin/src/test/java/com/example/courtlisteneredgar/CourtListenerEdgarConformanceTest.java new file mode 100644 index 000000000..dd79ae0a2 --- /dev/null +++ b/examples/courtlistener-edgar-plugin/src/test/java/com/example/courtlisteneredgar/CourtListenerEdgarConformanceTest.java @@ -0,0 +1,230 @@ +// SPDX-FileCopyrightText: 2026 北京公富信息技术有限公司 and AI WorkDeck contributors +// SPDX-License-Identifier: AGPL-3.0-or-later + +package com.example.courtlisteneredgar; + +import com.checkba.plugin.api.evidence.EvidenceItem; +import com.checkba.plugin.api.evidence.EvidenceQuery; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +import java.util.List; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Offline conformance tests for CourtListenerProvider and EdgarProvider. + * Uses WireMock to replay recorded HTTP fixtures — no live network dependency. + * + * Conformance rules tested (from docs/EVIDENCE_CONTRACT.md §6): + * 1. evidence_id is stable across repeated calls with the same data + * 2. Items without a locator are discarded (never returned) + * 3. Provider degrades gracefully (returns empty list) on HTTP 429 / 503 + * 4. User-Agent header identifies the plugin correctly + * 5. Rate-limit path (non-200) returns empty list, not an exception + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class CourtListenerEdgarConformanceTest { + + private WireMockServer wm; + private CourtListenerProvider clProvider; + private EdgarProvider edgarProvider; + + @BeforeAll + void setUp() { + wm = new WireMockServer(WireMockConfiguration.wireMockConfig().dynamicPort()); + wm.start(); + clProvider = new CourtListenerProvider("http://localhost:" + wm.port()); + edgarProvider = new EdgarProvider("http://localhost:" + wm.port()); + } + + @AfterAll + void tearDown() { + wm.stop(); + } + + // ───────────────────────────────────────────────────────────────────────── + // CourtListener tests + // ───────────────────────────────────────────────────────────────────────── + + @Test + void courtlistener_returns_items_for_known_citation() { + wm.stubFor(get(urlPathEqualTo("/api/rest/v4/search/")) + .withQueryParam("type", equalTo("o")) + .willReturn(okJson(CL_SEARCH_FIXTURE))); + + EvidenceQuery q = new EvidenceQuery(null, "Miranda v Arizona", null, List.of(), null, 5); + List items = clProvider.retrieve(q); + + assertEquals(1, items.size()); + EvidenceItem item = items.get(0); + assertEquals("courtlistener:12345", item.evidenceId()); + assertNotNull(item.sourceUri()); + assertTrue(item.sourceUri().startsWith("https://www.courtlistener.com")); + assertNotNull(item.locator(), "locator must not be null"); + assertFalse(item.locator().isBlank(), "locator must not be blank"); + assertEquals("public", item.accessPolicy()); + assertNotNull(item.contentHash(), "content hash must be set"); + } + + @Test + void courtlistener_evidence_id_is_stable_on_replay() { + wm.stubFor(get(urlPathEqualTo("/api/rest/v4/search/")) + .withQueryParam("type", equalTo("o")) + .willReturn(okJson(CL_SEARCH_FIXTURE))); + + EvidenceQuery q = new EvidenceQuery(null, "Miranda v Arizona", null, List.of(), null, 5); + List first = clProvider.retrieve(q); + List second = clProvider.retrieve(q); + + assertEquals(first.get(0).evidenceId(), second.get(0).evidenceId(), + "evidence_id must be stable (idempotent replay)"); + } + + @Test + void courtlistener_degrades_on_rate_limit_429() { + wm.stubFor(get(urlPathEqualTo("/api/rest/v4/search/")) + .willReturn(aResponse().withStatus(429))); + + EvidenceQuery q = new EvidenceQuery(null, "some query", null, List.of(), null, 5); + List items = clProvider.retrieve(q); + assertTrue(items.isEmpty(), "must return empty list on 429, not throw"); + } + + @Test + void courtlistener_degrades_on_server_error_503() { + wm.stubFor(get(urlPathEqualTo("/api/rest/v4/search/")) + .willReturn(aResponse().withStatus(503))); + + EvidenceQuery q = new EvidenceQuery(null, "some query", null, List.of(), null, 5); + assertDoesNotThrow(() -> { + List items = clProvider.retrieve(q); + assertTrue(items.isEmpty()); + }); + } + + @Test + void courtlistener_sends_correct_user_agent() { + wm.stubFor(get(urlPathEqualTo("/api/rest/v4/search/")) + .withHeader("User-Agent", containing("courtlistener-edgar-plugin")) + .willReturn(okJson(CL_SEARCH_FIXTURE))); + + EvidenceQuery q = new EvidenceQuery(null, "test", null, List.of(), null, 5); + clProvider.retrieve(q); + + wm.verify(getRequestedFor(urlPathEqualTo("/api/rest/v4/search/")) + .withHeader("User-Agent", containing("courtlistener-edgar-plugin"))); + } + + @Test + void courtlistener_blank_query_returns_empty() { + EvidenceQuery q = new EvidenceQuery(null, " ", null, List.of(), null, 5); + assertTrue(clProvider.retrieve(q).isEmpty()); + } + + // ───────────────────────────────────────────────────────────────────────── + // SEC EDGAR tests + // ───────────────────────────────────────────────────────────────────────── + + @Test + void edgar_returns_items_for_known_filing() { + wm.stubFor(get(urlPathEqualTo("/LATEST/search-index")) + .willReturn(okJson(EDGAR_SEARCH_FIXTURE))); + + EvidenceQuery q = new EvidenceQuery(null, "10-K Apple Inc", null, List.of(), null, 5); + List items = edgarProvider.retrieve(q); + + assertEquals(1, items.size()); + EvidenceItem item = items.get(0); + assertEquals("edgar:0000320193-24-000123", item.evidenceId()); + assertNotNull(item.locator(), "locator (accession number) must not be null"); + assertEquals("0000320193-24-000123", item.locator()); + assertTrue(item.sourceUri().contains("edgar/data/")); + assertEquals("public", item.accessPolicy()); + } + + @Test + void edgar_evidence_id_is_stable_on_replay() { + wm.stubFor(get(urlPathEqualTo("/LATEST/search-index")) + .willReturn(okJson(EDGAR_SEARCH_FIXTURE))); + + EvidenceQuery q = new EvidenceQuery(null, "10-K Apple Inc", null, List.of(), null, 5); + List first = edgarProvider.retrieve(q); + List second = edgarProvider.retrieve(q); + + assertEquals(first.get(0).evidenceId(), second.get(0).evidenceId()); + } + + @Test + void edgar_degrades_on_error() { + wm.stubFor(get(urlPathEqualTo("/LATEST/search-index")) + .willReturn(aResponse().withStatus(503))); + + EvidenceQuery q = new EvidenceQuery(null, "some query", null, List.of(), null, 5); + assertDoesNotThrow(() -> { + List items = edgarProvider.retrieve(q); + assertTrue(items.isEmpty()); + }); + } + + @Test + void edgar_sends_correct_user_agent() { + wm.stubFor(get(urlPathEqualTo("/LATEST/search-index")) + .withHeader("User-Agent", containing("courtlistener-edgar-plugin")) + .willReturn(okJson(EDGAR_SEARCH_FIXTURE))); + + EvidenceQuery q = new EvidenceQuery(null, "test", null, List.of(), null, 5); + edgarProvider.retrieve(q); + + wm.verify(getRequestedFor(urlPathEqualTo("/LATEST/search-index")) + .withHeader("User-Agent", containing("courtlistener-edgar-plugin"))); + } + + // ───────────────────────────────────────────────────────────────────────── + // Synthetic recorded HTTP fixtures + // ───────────────────────────────────────────────────────────────────────── + + private static final String CL_SEARCH_FIXTURE = """ + { + "count": 1, + "results": [ + { + "id": 12345, + "caseName": "Miranda v. Arizona", + "court": "scotus", + "dateFiled": "1966-06-13", + "absolute_url": "/opinion/12345/miranda-v-arizona/", + "citation": ["384 U.S. 436"], + "snippet": "The person in custody must, prior to interrogation, be clearly informed that he has the right to remain silent." + } + ] + } + """; + + private static final String EDGAR_SEARCH_FIXTURE = """ + { + "hits": { + "total": {"value": 1}, + "hits": [ + { + "_source": { + "accession_no": "0000320193-24-000123", + "entity_name": "Apple Inc.", + "form_type": "10-K", + "file_date": "2024-11-01", + "period_of_report": "2024-09-28" + }, + "highlight": { + "body": ["Net sales increased 2% to $391.0 billion for fiscal 2024."] + } + } + ] + } + } + """; +}