Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions examples/courtlistener-edgar-plugin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<!-- SPDX-FileCopyrightText: 2026 北京公富信息技术有限公司 and AI WorkDeck contributors -->
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->

# 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:<id>` or `edgar:<accession_no>`
- `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
```
27 changes: 27 additions & 0 deletions examples/courtlistener-edgar-plugin/manifest.json
Original file line number Diff line number Diff line change
@@ -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"
}
]
}
}
97 changes: 97 additions & 0 deletions examples/courtlistener-edgar-plugin/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>courtlistener-edgar-plugin</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>

<name>courtlistener-edgar-plugin</name>
<description>
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.
</description>
<licenses>
<license>
<name>GNU Affero General Public License v3.0 or later</name>
<url>https://www.gnu.org/licenses/agpl-3.0.html</url>
</license>
</licenses>

<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<!-- Public SPI: provided at runtime by the host -->
<dependency>
<groupId>com.checkba</groupId>
<artifactId>plugin-api</artifactId>
<version>1.4.0</version>
<scope>provided</scope>
</dependency>
<!-- JSON parsing: minimal, no external network required in production -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
</dependency>
<!-- Tests -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
<!-- WireMock for recording/replaying HTTP fixtures in tests -->
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>3.5.4</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<argLine>-Duser.home=${project.build.directory}/test-home</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.3</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>shade</goal></goals>
<configuration>
<shadedArtifactAttached>false</shadedArtifactAttached>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -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<EvidenceItem> 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<String> 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<EvidenceItem> parseCourtListenerResponse(String body, int limit) throws Exception {
JsonNode root = MAPPER.readTree(body);
JsonNode results = root.path("results");
List<EvidenceItem> 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("&hellip;", "…").replace("&amp;", "&"));
}
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;
}
}
}
Loading