@claude-flow/plugin-legal-contracts 3.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,391 @@
1
+ # @claude-flow/plugin-legal-contracts
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@claude-flow/plugin-legal-contracts.svg)](https://www.npmjs.com/package/@claude-flow/plugin-legal-contracts)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@claude-flow/plugin-legal-contracts.svg)](https://www.npmjs.com/package/@claude-flow/plugin-legal-contracts)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ A comprehensive legal contract analysis plugin combining hyperbolic embeddings for legal ontology navigation with fast vector search for clause similarity. The plugin enables automated clause extraction, risk scoring, obligation tracking, and regulatory compliance checking while maintaining attorney-client privilege through on-device processing.
8
+
9
+ ## Features
10
+
11
+ - **Clause Extraction**: Extract and classify clauses from contracts (indemnification, liability, termination, etc.)
12
+ - **Risk Assessment**: Identify and score contractual risks by category and severity
13
+ - **Contract Comparison**: Compare contracts with detailed diff and semantic alignment
14
+ - **Obligation Tracking**: Extract obligations, deadlines, and dependencies using DAG analysis
15
+ - **Playbook Matching**: Compare contract clauses against negotiation playbook positions
16
+
17
+ ## Installation
18
+
19
+ ### npm
20
+
21
+ ```bash
22
+ npm install @claude-flow/plugin-legal-contracts
23
+ ```
24
+
25
+ ### CLI
26
+
27
+ ```bash
28
+ npx claude-flow plugins install --name @claude-flow/plugin-legal-contracts
29
+ ```
30
+
31
+ ## Quick Start
32
+
33
+ ```typescript
34
+ import { LegalContractsPlugin } from '@claude-flow/plugin-legal-contracts';
35
+
36
+ // Initialize the plugin
37
+ const legal = new LegalContractsPlugin({
38
+ indexPath: './data/clause-index',
39
+ playbookPath: './data/playbooks',
40
+ privilegeProtection: true
41
+ });
42
+
43
+ // Extract clauses from a contract
44
+ const clauses = await legal.clauseExtract({
45
+ document: contractText,
46
+ clauseTypes: ['indemnification', 'limitation_of_liability', 'termination'],
47
+ jurisdiction: 'US',
48
+ includePositions: true
49
+ });
50
+
51
+ // Assess contract risks
52
+ const risks = await legal.riskAssess({
53
+ document: contractText,
54
+ partyRole: 'buyer',
55
+ riskCategories: ['financial', 'legal', 'operational'],
56
+ threshold: 'medium'
57
+ });
58
+
59
+ // Compare two contracts
60
+ const comparison = await legal.contractCompare({
61
+ baseDocument: standardContract,
62
+ compareDocument: vendorContract,
63
+ comparisonMode: 'full',
64
+ generateRedline: true
65
+ });
66
+ ```
67
+
68
+ ## MCP Tools
69
+
70
+ ### 1. `legal/clause-extract`
71
+
72
+ Extract and classify clauses from legal documents.
73
+
74
+ ```typescript
75
+ const result = await mcp.invoke('legal/clause-extract', {
76
+ document: contractText,
77
+ clauseTypes: [
78
+ 'indemnification',
79
+ 'limitation_of_liability',
80
+ 'termination',
81
+ 'confidentiality',
82
+ 'ip_assignment',
83
+ 'governing_law'
84
+ ],
85
+ jurisdiction: 'US',
86
+ includePositions: true
87
+ });
88
+
89
+ // Returns:
90
+ // {
91
+ // clauses: [
92
+ // {
93
+ // type: 'indemnification',
94
+ // text: 'Vendor shall indemnify and hold harmless...',
95
+ // position: { start: 4523, end: 5012 },
96
+ // confidence: 0.94,
97
+ // subType: 'mutual'
98
+ // },
99
+ // ...
100
+ // ]
101
+ // }
102
+ ```
103
+
104
+ ### 2. `legal/risk-assess`
105
+
106
+ Identify and score contractual risks.
107
+
108
+ ```typescript
109
+ const result = await mcp.invoke('legal/risk-assess', {
110
+ document: contractText,
111
+ partyRole: 'licensee',
112
+ riskCategories: ['financial', 'legal', 'compliance'],
113
+ industryContext: 'software',
114
+ threshold: 'medium'
115
+ });
116
+
117
+ // Returns:
118
+ // {
119
+ // overallRiskScore: 0.72,
120
+ // risks: [
121
+ // {
122
+ // category: 'financial',
123
+ // severity: 'high',
124
+ // description: 'Uncapped indemnification obligation',
125
+ // clause: 'Section 8.2',
126
+ // recommendation: 'Negotiate liability cap'
127
+ // },
128
+ // ...
129
+ // ]
130
+ // }
131
+ ```
132
+
133
+ ### 3. `legal/contract-compare`
134
+
135
+ Compare two contracts with semantic alignment.
136
+
137
+ ```typescript
138
+ const result = await mcp.invoke('legal/contract-compare', {
139
+ baseDocument: masterServiceAgreement,
140
+ compareDocument: vendorRedlinedVersion,
141
+ comparisonMode: 'full',
142
+ highlightChanges: true,
143
+ generateRedline: true
144
+ });
145
+
146
+ // Returns:
147
+ // {
148
+ // differences: [
149
+ // {
150
+ // section: 'Limitation of Liability',
151
+ // baseText: 'not exceed $1,000,000',
152
+ // compareText: 'not exceed $500,000',
153
+ // changeType: 'modification',
154
+ // significance: 'high',
155
+ // recommendation: 'Reject - reduces protection by 50%'
156
+ // },
157
+ // ...
158
+ // ],
159
+ // redlineDocument: '...'
160
+ // }
161
+ ```
162
+
163
+ ### 4. `legal/obligation-track`
164
+
165
+ Extract and track obligations, deadlines, and conditions.
166
+
167
+ ```typescript
168
+ const result = await mcp.invoke('legal/obligation-track', {
169
+ document: contractText,
170
+ party: 'Vendor',
171
+ timeframe: 'P90D', // Next 90 days
172
+ obligationTypes: ['payment', 'delivery', 'notification'],
173
+ includeDependencies: true
174
+ });
175
+
176
+ // Returns:
177
+ // {
178
+ // obligations: [
179
+ // {
180
+ // id: 'OBL-001',
181
+ // type: 'delivery',
182
+ // description: 'Deliver initial software release',
183
+ // deadline: '2024-03-15',
184
+ // dependsOn: [],
185
+ // triggers: ['OBL-002']
186
+ // },
187
+ // {
188
+ // id: 'OBL-002',
189
+ // type: 'payment',
190
+ // description: 'Payment due upon delivery acceptance',
191
+ // deadline: 'NET-30 from OBL-001',
192
+ // dependsOn: ['OBL-001'],
193
+ // amount: 50000
194
+ // }
195
+ // ]
196
+ // }
197
+ ```
198
+
199
+ ### 5. `legal/playbook-match`
200
+
201
+ Match clauses against standard playbook positions.
202
+
203
+ ```typescript
204
+ const result = await mcp.invoke('legal/playbook-match', {
205
+ document: vendorContract,
206
+ playbook: 'enterprise-saas-v2',
207
+ strictness: 'moderate',
208
+ suggestAlternatives: true,
209
+ prioritizeClauses: ['indemnification', 'limitation_of_liability']
210
+ });
211
+
212
+ // Returns:
213
+ // {
214
+ // matchResults: [
215
+ // {
216
+ // clause: 'Indemnification',
217
+ // playbookPosition: 'Mutual indemnification with IP carve-out',
218
+ // documentPosition: 'One-way vendor indemnification only',
219
+ // deviation: 'major',
220
+ // negotiationTip: 'Request mutual indemnification',
221
+ // fallbackPosition: 'Accept one-way with enhanced IP coverage'
222
+ // },
223
+ // ...
224
+ // ]
225
+ // }
226
+ ```
227
+
228
+ ## Configuration Options
229
+
230
+ ```typescript
231
+ interface LegalContractsConfig {
232
+ // Data paths
233
+ indexPath: string; // Path to clause index storage
234
+ playbookPath: string; // Path to playbook definitions
235
+
236
+ // Privacy
237
+ privilegeProtection: boolean; // Zero-knowledge processing (default: true)
238
+ auditLogPath: string; // Path for ethics-compliant audit logs
239
+
240
+ // Performance
241
+ maxMemoryMB: number; // WASM memory limit (default: 2048)
242
+ maxCpuTimeSeconds: number; // Operation timeout (default: 120)
243
+
244
+ // Matter isolation
245
+ matterIsolation: boolean; // Per-matter WASM instances (default: true)
246
+
247
+ // Access control
248
+ roleBasedAccess: boolean; // Enable RBAC (default: true)
249
+ ethicalWalls: boolean; // Enable conflict checking (default: true)
250
+ }
251
+ ```
252
+
253
+ ## Security Considerations
254
+
255
+ ### Attorney-Client Privilege Protection
256
+
257
+ This plugin is designed to maintain attorney-client privilege:
258
+
259
+ | Requirement | Implementation |
260
+ |-------------|----------------|
261
+ | **Privilege Preservation** | Zero-knowledge processing - no document content transmitted |
262
+ | **Work Product Protection** | Analysis results encrypted, attorney-eyes-only by default |
263
+ | **Document Isolation** | Each matter processed in isolated WASM instance |
264
+ | **Chain of Custody** | Cryptographic proof of document handling |
265
+ | **Conflict Detection** | Prevent cross-matter data leakage |
266
+
267
+ ### Matter Isolation
268
+
269
+ Each legal matter gets its own isolated WASM instance:
270
+ - Separate memory regions per matter
271
+ - No cross-matter data access possible
272
+ - Independent audit trails per matter
273
+ - Automatic cleanup on matter close
274
+
275
+ ### Role-Based Access Control
276
+
277
+ ```typescript
278
+ const roles = {
279
+ PARTNER: ['clause-extract', 'risk-assess', 'contract-compare', 'obligation-track', 'playbook-match'],
280
+ ASSOCIATE: ['clause-extract', 'risk-assess', 'contract-compare', 'obligation-track'],
281
+ PARALEGAL: ['clause-extract', 'obligation-track'],
282
+ CONTRACT_MANAGER: ['obligation-track', 'playbook-match'],
283
+ CLIENT: [] // No direct tool access - results only via attorney
284
+ };
285
+ ```
286
+
287
+ ### Ethical Walls
288
+
289
+ ```typescript
290
+ interface EthicalWall {
291
+ matterId: string;
292
+ blockedUsers: string[]; // Users who cannot access this matter
293
+ reason: string; // Encrypted conflict reason
294
+ createdBy: string; // Partner who created wall
295
+ createdAt: string;
296
+ }
297
+ ```
298
+
299
+ ### Audit Logging
300
+
301
+ All tool invocations are logged with:
302
+ - Timestamp (ISO 8601)
303
+ - User ID and role at time of access
304
+ - Matter ID
305
+ - Document hash (not content)
306
+ - Operation type
307
+
308
+ Logs are encrypted at rest, accessible only to ethics/compliance, and retained per jurisdiction requirements (typically 7+ years).
309
+
310
+ ### Input Validation
311
+
312
+ All inputs are validated using Zod schemas:
313
+ - Maximum document size: 10MB
314
+ - Maximum clause types per request: 20
315
+ - Path traversal prevention on file inputs
316
+ - Malicious content detection (macros, scripts)
317
+ - Character encoding validation (UTF-8 required)
318
+ - Playbook identifiers: alphanumeric with hyphens, max 64 characters
319
+
320
+ ### WASM Security Constraints
321
+
322
+ | Constraint | Value | Rationale |
323
+ |------------|-------|-----------|
324
+ | Memory Limit | 2GB max | Handle large contract documents |
325
+ | CPU Time Limit | 120 seconds | Allow complex multi-document comparison |
326
+ | No Network Access | Enforced | Preserve attorney-client privilege |
327
+ | No File System Access | Sandboxed paths only | Prevent unauthorized document access |
328
+ | Per-Matter Isolation | Enforced | Prevent cross-matter data leakage |
329
+
330
+ ### Rate Limiting
331
+
332
+ ```typescript
333
+ const rateLimits = {
334
+ 'legal/clause-extract': { requestsPerMinute: 30, maxConcurrent: 3 },
335
+ 'legal/risk-assess': { requestsPerMinute: 20, maxConcurrent: 2 },
336
+ 'legal/contract-compare': { requestsPerMinute: 10, maxConcurrent: 1 },
337
+ 'legal/obligation-track': { requestsPerMinute: 30, maxConcurrent: 3 },
338
+ 'legal/playbook-match': { requestsPerMinute: 30, maxConcurrent: 3 }
339
+ };
340
+ ```
341
+
342
+ ## Performance
343
+
344
+ | Metric | Target |
345
+ |--------|--------|
346
+ | Clause extraction | <2s for 50-page contract |
347
+ | Risk assessment | <5s full analysis |
348
+ | Contract comparison | <10s for two 100-page contracts |
349
+ | Obligation extraction | <3s per contract |
350
+ | Playbook matching | <1s per clause |
351
+
352
+ ## Dependencies
353
+
354
+ - `micro-hnsw-wasm`: Fast semantic search for clause similarity and precedent matching
355
+ - `ruvector-hyperbolic-hnsw-wasm`: Legal taxonomy navigation (contract types, clause hierarchies)
356
+ - `ruvector-attention-wasm`: Cross-attention for contract comparison (redline analysis)
357
+ - `ruvector-dag-wasm`: Contract dependency graphs (obligations, conditions, timelines)
358
+ - `pdf-parse`: PDF document parsing
359
+ - `mammoth`: DOCX document parsing
360
+
361
+ ## Related Plugins
362
+
363
+ | Plugin | Description | Use Case |
364
+ |--------|-------------|----------|
365
+ | [@claude-flow/plugin-financial-risk](../financial-risk) | Financial risk analysis | Financial contract risk assessment |
366
+ | [@claude-flow/plugin-healthcare-clinical](../healthcare-clinical) | Clinical decision support | Healthcare BAA and compliance agreements |
367
+ | [@claude-flow/plugin-code-intelligence](../code-intelligence) | Code analysis | Software licensing and IP contracts |
368
+
369
+ ## License
370
+
371
+ MIT License
372
+
373
+ Copyright (c) 2026 Claude Flow
374
+
375
+ Permission is hereby granted, free of charge, to any person obtaining a copy
376
+ of this software and associated documentation files (the "Software"), to deal
377
+ in the Software without restriction, including without limitation the rights
378
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
379
+ copies of the Software, and to permit persons to whom the Software is
380
+ furnished to do so, subject to the following conditions:
381
+
382
+ The above copyright notice and this permission notice shall be included in all
383
+ copies or substantial portions of the Software.
384
+
385
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
386
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
387
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
388
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
389
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
390
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
391
+ SOFTWARE.
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Flash Attention Bridge for Legal Contract Analysis
3
+ *
4
+ * Provides cross-attention computation for clause alignment and similarity
5
+ * using ruvector-attention-wasm for high-performance attention operations.
6
+ *
7
+ * Features:
8
+ * - Cross-attention for contract comparison
9
+ * - Clause alignment between documents
10
+ * - Semantic similarity scoring
11
+ * - Memory-efficient attention patterns
12
+ *
13
+ * Based on ADR-034: Legal Contract Analysis Plugin
14
+ *
15
+ * @module v3/plugins/legal-contracts/bridges/attention-bridge
16
+ */
17
+ import type { IAttentionBridge, ExtractedClause, ClauseAlignment } from '../types.js';
18
+ /**
19
+ * Flash Attention Bridge Implementation
20
+ */
21
+ export declare class AttentionBridge implements IAttentionBridge {
22
+ private wasmModule;
23
+ private initialized;
24
+ private readonly embeddingDim;
25
+ constructor(embeddingDim?: number);
26
+ /**
27
+ * Initialize the WASM module
28
+ */
29
+ initialize(): Promise<void>;
30
+ /**
31
+ * Check if initialized
32
+ */
33
+ isInitialized(): boolean;
34
+ /**
35
+ * Compute cross-attention between clause embeddings
36
+ */
37
+ computeCrossAttention(queryEmbeddings: Float32Array[], keyEmbeddings: Float32Array[], mask?: boolean[][]): Promise<Float32Array[][]>;
38
+ /**
39
+ * Align clauses between two documents using attention
40
+ */
41
+ alignClauses(baseClauses: ExtractedClause[], compareClauses: ExtractedClause[]): Promise<ClauseAlignment[]>;
42
+ /**
43
+ * Find most relevant clauses for a given query
44
+ */
45
+ findRelevantClauses(query: string | Float32Array, clauses: ExtractedClause[], topK: number): Promise<Array<{
46
+ clause: ExtractedClause;
47
+ score: number;
48
+ }>>;
49
+ /**
50
+ * Load WASM module dynamically
51
+ */
52
+ private loadWasmModule;
53
+ /**
54
+ * Flatten array of embeddings into single Float32Array
55
+ */
56
+ private flattenEmbeddings;
57
+ /**
58
+ * Compute attention scores in pure JavaScript (fallback)
59
+ */
60
+ private computeAttentionScoresJS;
61
+ /**
62
+ * Compute softmax over array
63
+ */
64
+ private softmax;
65
+ /**
66
+ * Get embeddings from clauses or compute them
67
+ */
68
+ private getOrComputeEmbeddings;
69
+ /**
70
+ * Embed text to vector (placeholder - would use embedding model)
71
+ */
72
+ private embedText;
73
+ /**
74
+ * Compute differences between two clauses
75
+ */
76
+ private computeDifferences;
77
+ }
78
+ /**
79
+ * Create and export default bridge instance
80
+ */
81
+ export declare function createAttentionBridge(embeddingDim?: number): IAttentionBridge;
82
+ export default AttentionBridge;
83
+ //# sourceMappingURL=attention-bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attention-bridge.d.ts","sourceRoot":"","sources":["../../src/bridges/attention-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,eAAe,EAChB,MAAM,aAAa,CAAC;AA2CrB;;GAEG;AACH,qBAAa,eAAgB,YAAW,gBAAgB;IACtD,OAAO,CAAC,UAAU,CAAoC;IACtD,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;gBAE1B,YAAY,SAAM;IAI9B;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAiBjC;;OAEG;IACH,aAAa,IAAI,OAAO;IAIxB;;OAEG;IACG,qBAAqB,CACzB,eAAe,EAAE,YAAY,EAAE,EAC/B,aAAa,EAAE,YAAY,EAAE,EAC7B,IAAI,CAAC,EAAE,OAAO,EAAE,EAAE,GACjB,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC;IAqE5B;;OAEG;IACG,YAAY,CAChB,WAAW,EAAE,eAAe,EAAE,EAC9B,cAAc,EAAE,eAAe,EAAE,GAChC,OAAO,CAAC,eAAe,EAAE,CAAC;IA0E7B;;OAEG;IACG,mBAAmB,CACvB,KAAK,EAAE,MAAM,GAAG,YAAY,EAC5B,OAAO,EAAE,eAAe,EAAE,EAC1B,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,KAAK,CAAC;QAAE,MAAM,EAAE,eAAe,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAyC7D;;OAEG;YACW,cAAc;IAM5B;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAWzB;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAyBhC;;OAEG;IACH,OAAO,CAAC,OAAO;IAmBf;;OAEG;YACW,sBAAsB;IAgBpC;;OAEG;YACW,SAAS;IA4BvB;;OAEG;IACH,OAAO,CAAC,kBAAkB;CAsC3B;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,YAAY,SAAM,GAAG,gBAAgB,CAE1E;AAED,eAAe,eAAe,CAAC"}