margin-fine-print 0.1.0__tar.gz

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.
@@ -0,0 +1,86 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ /lib/
14
+ /lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ share/python-wheels/
20
+ *.egg-info/
21
+ .installed.cfg
22
+ *.egg
23
+
24
+ # Virtual environments
25
+ .venv/
26
+ venv/
27
+ ENV/
28
+ env/
29
+
30
+ # uv
31
+ .uv/
32
+
33
+ # Environment variables & secrets
34
+ .env
35
+ .env.local
36
+ .env.*.local
37
+ *.key
38
+ *.pem
39
+
40
+ # Testing & Coverage
41
+ .pytest_cache/
42
+ .coverage
43
+ .coverage.*
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+
51
+ # Type checking & linting
52
+ .mypy_cache/
53
+ .ruff_cache/
54
+ .dmypy.json
55
+ dmypy.json
56
+
57
+ # IDEs & Editors
58
+ .vscode/
59
+ .idea/
60
+ *.swp
61
+ *.swo
62
+ *~
63
+
64
+ # Operating System
65
+ .DS_Store
66
+ Thumbs.db
67
+ ehthumbs.db
68
+ desktop.ini
69
+
70
+ # Output / Reports
71
+ report.json
72
+ report.md
73
+ temp/
74
+ tmp/
75
+
76
+ # Private planning notes (kept locally, not published)
77
+ PLAN.md
78
+ # notes for Claude Code and Antigravity sessions; marker files stay out of the public repo
79
+ CLAUDE.md
80
+ GEMINI.md
81
+
82
+ # the web UI bundled into margin-api at release time (scripts/build_release.py)
83
+ packages/api/src/margin_api/ui/
84
+
85
+ # local agent plugins and state
86
+ .agents/
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ All notable changes to this agent are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.1.0] - 2026-12-03
8
+
9
+ ### Added
10
+ - Initial experimental release of the Fine Print document reviewer (`fine-print`).
11
+ - Local ingestion for `.pdf` (via `pypdf`), `.docx` (safe stdlib XML/zip), `.txt`, `.md`, and
12
+ `.html` files with section and page/paragraph tracking.
13
+ - Deterministic extraction of money amounts, dates, notice periods, durations, percentages, and
14
+ governing law.
15
+ - Human-in-the-loop checkpoint (`ctx.ask`) to confirm document type (`employment`, `lease`,
16
+ `freelance`, `nda`, `saas`, `general`), user perspective, and priorities.
17
+ - 27 deterministic clause rules covering flagged risks and checked protections, plus
18
+ context-aware missing-protection checks and a prioritized pre-signing question checklist.
19
+ - Optional PII-redacted LLM plain-English notes with prompt-injection boundaries, citation and
20
+ number validation, and clean fallback to built-in templates.
21
+ - Printable HTML review, copy-pasteable Markdown question checklist, and formula-safe terms CSV
22
+ exports (`output_dir`).
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 margin contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.5
2
+ Name: margin-fine-print
3
+ Version: 0.1.0
4
+ Summary: Reads a contract, lease, offer, or policy and puts plain-English notes in the margin.
5
+ Project-URL: Homepage, https://github.com/Waddah0-0/margin
6
+ Project-URL: Source, https://github.com/Waddah0-0/margin/tree/main/agents/fine_print
7
+ Project-URL: Issues, https://github.com/Waddah0-0/margin/issues
8
+ Project-URL: Changelog, https://github.com/Waddah0-0/margin/blob/main/agents/fine_print/CHANGELOG.md
9
+ Author: Waddah Ali
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,contracts,documents,docx,fine-print,pdf,privacy
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: End Users/Desktop
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: margin-core<0.2,>=0.1.3
23
+ Requires-Dist: pypdf>=5.0.0
24
+ Description-Content-Type: text/markdown
25
+
26
+ # Fine Print
27
+
28
+ Reads a contract, lease, offer, or policy and puts plain-English notes in the margin.
29
+
30
+ > **Status: experimental.** Runs locally on PDF, Word (`.docx`), Markdown, plain text, and HTML
31
+ > documents, with a local model or with no model at all. Plain-English reading aid, not legal
32
+ > advice.
33
+
34
+ ## What it does
35
+
36
+ Drop a lease, job offer, freelance agreement, NDA, vendor contract, or privacy policy and Fine
37
+ Print reads it locally on your computer. It pulls out every dollar figure, date, notice period,
38
+ duration, and governing law, asks which side you are on, flags one-sided or risky clauses in red
39
+ beside the exact quote, marks standard protections in blue, lists important protections missing
40
+ from the text, and builds a ready-to-send checklist of questions to ask before signing.
41
+
42
+ ## How it works
43
+
44
+ 1. Reads the local file (`.pdf`, `.docx`, `.txt`, `.md`, `.html`, `.htm`) and splits it into
45
+ numbered, section-aware paragraphs with page and paragraph locations (`p. 2, ¶14`).
46
+ 2. Deterministically extracts money amounts, dates, notice windows, durations, percentages, and
47
+ governing law without calling a model.
48
+ 3. Detects the document type (`employment`, `lease`, `freelance`, `nda`, `saas`, or `general`)
49
+ and pauses once via `ctx.ask` so you can confirm the document type, which side you are on,
50
+ and what matters most to you.
51
+ 4. Runs deterministic clause rules for both flagged risks (auto-renewal, unilateral changes,
52
+ broad IP assignment, IP before payment, non-compete, uncapped indemnity, arbitration,
53
+ early-exit penalties, bonus clawbacks, AI data training, unlimited revisions, etc.) and
54
+ checked protections (IP carveouts, liability caps, notice & cure windows, payment timelines,
55
+ NDA carveouts, deposit return deadlines, data deletion rights). Every quote is verified
56
+ verbatim against the source paragraph.
57
+ 5. Checks for common protective clauses missing for your document type and perspective.
58
+ 6. Optionally asks your configured local or hosted model (with emails, phone numbers, SSNs, and
59
+ long account numbers redacted by default) to rewrite the top notes in tailored plain English.
60
+ A validator rejects unknown note IDs, invented dollar figures or durations, and legal
61
+ verdicts, falling back cleanly to built-in templates when needed or when no model is running.
62
+ 7. When `output_dir` is set, writes a printable HTML review (`<stem>.review.html`), a
63
+ copy-pasteable Markdown question checklist (`<stem>.checklist.md`), and a formula-safe CSV of
64
+ extracted terms (`<stem>.terms.csv`).
65
+
66
+ ## Input
67
+
68
+ | Field | Default | Meaning |
69
+ |---|---|---|
70
+ | `document` | required | Local path to a `.pdf`, `.docx`, `.txt`, `.md`, `.html`, or `.htm` file. The primary input. |
71
+ | `use_llm` | `true` | Use a model for tailored plain-English notes. Works without one using built-in explanations. |
72
+ | `focus` | `"all"` | Show both flagged risks and checked protections (`"all"`), or only flagged risks (`"risks_only"`). |
73
+ | `redact_personal_info` | `true` | Mask emails, phone numbers, SSNs, and long account-like numbers before sending excerpts to a model. |
74
+ | `max_clauses_for_llm` | `16` | Maximum number of flagged clauses sent to the model (`0` to `50`). |
75
+ | `output_dir` | empty | Folder for exported HTML, Markdown checklist, and terms CSV. Filled automatically in the web UI. |
76
+ | `answers` | `{}` | Preset answers for the confirmation checkpoint (`doc_type`, `side`, `priorities`). |
77
+ | `assume_defaults` | `false` | Skip interactive questions and record the auto-detected defaults as unconfirmed. |
78
+
79
+ ## Output
80
+
81
+ `data` holds a `FinePrintOutput` with:
82
+
83
+ - `document`: filename, format, page/word/paragraph counts, reading time, confirmed `doc_type`,
84
+ `party_side`, `priorities`, and detected `parties`.
85
+ - `caveat`: plain-language notice that the review is a reading aid, not legal advice.
86
+ - `summary_headline`, `risk_counts` (`high`, `medium`, `low`, `checked`), and `writer_mode`
87
+ (`model` or `template`).
88
+ - `clauses`: numbered paragraphs from the document with section headers and page locations.
89
+ - `notes`: quote-anchored `MarginNote` entries with severity, tone (`red` or `blue`), verbatim
90
+ quote, plain-English explanation, why it matters for your side, and suggested question.
91
+ - `key_terms`: extracted dollar amounts, dates, notice periods, durations, percentages, and
92
+ governing law with exact locations.
93
+ - `missing_protections`: standard protections expected for your document type and side that were
94
+ absent from the text.
95
+ - `checklist`: prioritized questions to ask before signing.
96
+ - `files`: exported report paths when `output_dir` is set.
97
+
98
+ `findings` contains every margin note and missing protection with verbatim quotes and locations
99
+ as evidence.
100
+
101
+ ## Limits
102
+
103
+ - Not legal advice. Always consult a qualified attorney for high-stakes or complex agreements.
104
+ - Scanned image PDFs without a text layer cannot be read without OCR first; password-protected
105
+ PDFs must be unlocked before running.
106
+ - Rule-based extraction catches common contract patterns, but unusual phrasing, cross-referenced
107
+ addenda, or external URLs referenced in the text can be missed.
108
+ - Large files are bounded to 50 MB, 200 PDF pages, and 1,500 paragraphs; truncated runs report
109
+ `partial` status with a warning.
110
+ - Document text is untrusted input. Excerpts sent to a model are wrapped in random delimiters
111
+ and validated so the model cannot invent dollar amounts, durations, or fake citations.
112
+
113
+ ## Usage
114
+
115
+ ```bash
116
+ pip install margin-cli margin-fine-print
117
+ margin run fine-print lease.pdf
118
+ margin run fine-print offer.docx --set assume_defaults=true --set use_llm=false
119
+ margin run fine-print terms.txt --set output_dir=out --format markdown
120
+ ```
121
+
122
+ ```python
123
+ import asyncio
124
+
125
+ from fine_print import FinePrintAgent
126
+
127
+
128
+ async def main() -> None:
129
+ result = await FinePrintAgent().execute(
130
+ {"document": "contract.pdf", "assume_defaults": True, "use_llm": False}
131
+ )
132
+ print(result.summary)
133
+
134
+
135
+ asyncio.run(main())
136
+ ```
137
+
138
+ ## Development
139
+
140
+ This agent lives in the [margin](https://github.com/Waddah0-0/margin) monorepo, in
141
+ [`agents/fine_print`](https://github.com/Waddah0-0/margin/tree/main/agents/fine_print). If you
142
+ are reading this in its mirror repository, that copy is read-only: open issues and pull requests
143
+ in the main repository.
144
+
145
+ Run its tests with `uv run python -m pytest agents/fine_print`.
@@ -0,0 +1,120 @@
1
+ # Fine Print
2
+
3
+ Reads a contract, lease, offer, or policy and puts plain-English notes in the margin.
4
+
5
+ > **Status: experimental.** Runs locally on PDF, Word (`.docx`), Markdown, plain text, and HTML
6
+ > documents, with a local model or with no model at all. Plain-English reading aid, not legal
7
+ > advice.
8
+
9
+ ## What it does
10
+
11
+ Drop a lease, job offer, freelance agreement, NDA, vendor contract, or privacy policy and Fine
12
+ Print reads it locally on your computer. It pulls out every dollar figure, date, notice period,
13
+ duration, and governing law, asks which side you are on, flags one-sided or risky clauses in red
14
+ beside the exact quote, marks standard protections in blue, lists important protections missing
15
+ from the text, and builds a ready-to-send checklist of questions to ask before signing.
16
+
17
+ ## How it works
18
+
19
+ 1. Reads the local file (`.pdf`, `.docx`, `.txt`, `.md`, `.html`, `.htm`) and splits it into
20
+ numbered, section-aware paragraphs with page and paragraph locations (`p. 2, ¶14`).
21
+ 2. Deterministically extracts money amounts, dates, notice windows, durations, percentages, and
22
+ governing law without calling a model.
23
+ 3. Detects the document type (`employment`, `lease`, `freelance`, `nda`, `saas`, or `general`)
24
+ and pauses once via `ctx.ask` so you can confirm the document type, which side you are on,
25
+ and what matters most to you.
26
+ 4. Runs deterministic clause rules for both flagged risks (auto-renewal, unilateral changes,
27
+ broad IP assignment, IP before payment, non-compete, uncapped indemnity, arbitration,
28
+ early-exit penalties, bonus clawbacks, AI data training, unlimited revisions, etc.) and
29
+ checked protections (IP carveouts, liability caps, notice & cure windows, payment timelines,
30
+ NDA carveouts, deposit return deadlines, data deletion rights). Every quote is verified
31
+ verbatim against the source paragraph.
32
+ 5. Checks for common protective clauses missing for your document type and perspective.
33
+ 6. Optionally asks your configured local or hosted model (with emails, phone numbers, SSNs, and
34
+ long account numbers redacted by default) to rewrite the top notes in tailored plain English.
35
+ A validator rejects unknown note IDs, invented dollar figures or durations, and legal
36
+ verdicts, falling back cleanly to built-in templates when needed or when no model is running.
37
+ 7. When `output_dir` is set, writes a printable HTML review (`<stem>.review.html`), a
38
+ copy-pasteable Markdown question checklist (`<stem>.checklist.md`), and a formula-safe CSV of
39
+ extracted terms (`<stem>.terms.csv`).
40
+
41
+ ## Input
42
+
43
+ | Field | Default | Meaning |
44
+ |---|---|---|
45
+ | `document` | required | Local path to a `.pdf`, `.docx`, `.txt`, `.md`, `.html`, or `.htm` file. The primary input. |
46
+ | `use_llm` | `true` | Use a model for tailored plain-English notes. Works without one using built-in explanations. |
47
+ | `focus` | `"all"` | Show both flagged risks and checked protections (`"all"`), or only flagged risks (`"risks_only"`). |
48
+ | `redact_personal_info` | `true` | Mask emails, phone numbers, SSNs, and long account-like numbers before sending excerpts to a model. |
49
+ | `max_clauses_for_llm` | `16` | Maximum number of flagged clauses sent to the model (`0` to `50`). |
50
+ | `output_dir` | empty | Folder for exported HTML, Markdown checklist, and terms CSV. Filled automatically in the web UI. |
51
+ | `answers` | `{}` | Preset answers for the confirmation checkpoint (`doc_type`, `side`, `priorities`). |
52
+ | `assume_defaults` | `false` | Skip interactive questions and record the auto-detected defaults as unconfirmed. |
53
+
54
+ ## Output
55
+
56
+ `data` holds a `FinePrintOutput` with:
57
+
58
+ - `document`: filename, format, page/word/paragraph counts, reading time, confirmed `doc_type`,
59
+ `party_side`, `priorities`, and detected `parties`.
60
+ - `caveat`: plain-language notice that the review is a reading aid, not legal advice.
61
+ - `summary_headline`, `risk_counts` (`high`, `medium`, `low`, `checked`), and `writer_mode`
62
+ (`model` or `template`).
63
+ - `clauses`: numbered paragraphs from the document with section headers and page locations.
64
+ - `notes`: quote-anchored `MarginNote` entries with severity, tone (`red` or `blue`), verbatim
65
+ quote, plain-English explanation, why it matters for your side, and suggested question.
66
+ - `key_terms`: extracted dollar amounts, dates, notice periods, durations, percentages, and
67
+ governing law with exact locations.
68
+ - `missing_protections`: standard protections expected for your document type and side that were
69
+ absent from the text.
70
+ - `checklist`: prioritized questions to ask before signing.
71
+ - `files`: exported report paths when `output_dir` is set.
72
+
73
+ `findings` contains every margin note and missing protection with verbatim quotes and locations
74
+ as evidence.
75
+
76
+ ## Limits
77
+
78
+ - Not legal advice. Always consult a qualified attorney for high-stakes or complex agreements.
79
+ - Scanned image PDFs without a text layer cannot be read without OCR first; password-protected
80
+ PDFs must be unlocked before running.
81
+ - Rule-based extraction catches common contract patterns, but unusual phrasing, cross-referenced
82
+ addenda, or external URLs referenced in the text can be missed.
83
+ - Large files are bounded to 50 MB, 200 PDF pages, and 1,500 paragraphs; truncated runs report
84
+ `partial` status with a warning.
85
+ - Document text is untrusted input. Excerpts sent to a model are wrapped in random delimiters
86
+ and validated so the model cannot invent dollar amounts, durations, or fake citations.
87
+
88
+ ## Usage
89
+
90
+ ```bash
91
+ pip install margin-cli margin-fine-print
92
+ margin run fine-print lease.pdf
93
+ margin run fine-print offer.docx --set assume_defaults=true --set use_llm=false
94
+ margin run fine-print terms.txt --set output_dir=out --format markdown
95
+ ```
96
+
97
+ ```python
98
+ import asyncio
99
+
100
+ from fine_print import FinePrintAgent
101
+
102
+
103
+ async def main() -> None:
104
+ result = await FinePrintAgent().execute(
105
+ {"document": "contract.pdf", "assume_defaults": True, "use_llm": False}
106
+ )
107
+ print(result.summary)
108
+
109
+
110
+ asyncio.run(main())
111
+ ```
112
+
113
+ ## Development
114
+
115
+ This agent lives in the [margin](https://github.com/Waddah0-0/margin) monorepo, in
116
+ [`agents/fine_print`](https://github.com/Waddah0-0/margin/tree/main/agents/fine_print). If you
117
+ are reading this in its mirror repository, that copy is read-only: open issues and pull requests
118
+ in the main repository.
119
+
120
+ Run its tests with `uv run python -m pytest agents/fine_print`.
@@ -0,0 +1,45 @@
1
+ [project]
2
+ name = "margin-fine-print"
3
+ version = "0.1.0"
4
+ description = "Reads a contract, lease, offer, or policy and puts plain-English notes in the margin."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Waddah Ali" }]
10
+ keywords = ["contracts", "documents", "fine-print", "privacy", "pdf", "docx", "agents"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: End Users/Desktop",
14
+ "Intended Audience :: Developers",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Typing :: Typed",
20
+ ]
21
+ dependencies = [
22
+ "margin-core>=0.1.3,<0.2",
23
+ "pypdf>=5.0.0",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/Waddah0-0/margin"
28
+ Source = "https://github.com/Waddah0-0/margin/tree/main/agents/fine_print"
29
+ Issues = "https://github.com/Waddah0-0/margin/issues"
30
+ Changelog = "https://github.com/Waddah0-0/margin/blob/main/agents/fine_print/CHANGELOG.md"
31
+
32
+ [project.entry-points."margin.agents"]
33
+ fine-print = "fine_print.agent:FinePrintAgent"
34
+
35
+ [tool.margin]
36
+ id = "fine-print"
37
+ stage = "experimental"
38
+ mirror = "Waddah0-0/margin-fine-print"
39
+
40
+ [build-system]
41
+ requires = ["hatchling"]
42
+ build-backend = "hatchling.build"
43
+
44
+ [tool.hatch.build.targets.wheel]
45
+ packages = ["src/fine_print"]
@@ -0,0 +1,30 @@
1
+ """Fine Print."""
2
+
3
+ from fine_print.agent import FinePrintAgent
4
+ from fine_print.models import (
5
+ ACCEPTED,
6
+ Clause,
7
+ DocumentMeta,
8
+ FinePrintInput,
9
+ FinePrintOutput,
10
+ KeyTerm,
11
+ MarginNote,
12
+ MissingProtection,
13
+ NegotiationItem,
14
+ )
15
+
16
+ __version__ = "0.1.0"
17
+
18
+ __all__ = [
19
+ "ACCEPTED",
20
+ "Clause",
21
+ "DocumentMeta",
22
+ "FinePrintAgent",
23
+ "FinePrintInput",
24
+ "FinePrintOutput",
25
+ "KeyTerm",
26
+ "MarginNote",
27
+ "MissingProtection",
28
+ "NegotiationItem",
29
+ "__version__",
30
+ ]
@@ -0,0 +1,192 @@
1
+ """Fine Print: reads contracts, leases, offers, and policies with notes in the margin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from margin_core import AgentResult, BaseAgent, Evidence, Finding, RunContext
6
+
7
+ from fine_print.models import FinePrintInput, FinePrintOutput
8
+
9
+ _SEVERITY_SCORE: dict[str, float] = {
10
+ "high": 1.0,
11
+ "medium": 0.6,
12
+ "low": 0.3,
13
+ "ok": 0.0,
14
+ }
15
+
16
+
17
+ class FinePrintAgent(BaseAgent):
18
+ id = "fine-print"
19
+ name = "Fine Print"
20
+ description = (
21
+ "Reads a contract, lease, offer, or policy and puts plain-English notes in the margin."
22
+ )
23
+ version = "0.1.0"
24
+ InputModel = FinePrintInput
25
+ OutputModel = FinePrintOutput
26
+ primary_input = "document"
27
+ uses_llm = True
28
+ requires_git = False
29
+
30
+ async def run(self, input: FinePrintInput, ctx: RunContext) -> AgentResult:
31
+ import asyncio
32
+ import math
33
+
34
+ from fine_print.exports import write_reports
35
+ from fine_print.extract import detect_doc_type, extract_key_terms, extract_parties
36
+ from fine_print.ingest import ingest_document
37
+ from fine_print.models import DocumentMeta
38
+ from fine_print.questions import confirm_review_context
39
+ from fine_print.rules import (
40
+ CAVEAT_TEXT,
41
+ analyze_clauses,
42
+ build_checklist,
43
+ build_template_headline,
44
+ find_missing_protections,
45
+ )
46
+ from fine_print.write import enrich_with_model
47
+
48
+ ctx.report_progress("ingest", "Reading document", 0.1)
49
+ doc = await asyncio.to_thread(ingest_document, input.document)
50
+
51
+ for warning in doc.warnings:
52
+ ctx.warn(warning)
53
+ ctx.check_cancelled()
54
+
55
+ ctx.report_progress("extract", "Extracting dates, amounts, and clauses", 0.25)
56
+ detected_type, indicators = detect_doc_type(doc.clauses)
57
+ parties = extract_parties(doc.clauses)
58
+ key_terms = extract_key_terms(doc.clauses)
59
+
60
+ review_ctx = await confirm_review_context(
61
+ detected_type,
62
+ indicators,
63
+ ctx,
64
+ preset=input.answers,
65
+ assume_defaults=input.assume_defaults,
66
+ )
67
+ ctx.check_cancelled()
68
+
69
+ meta = DocumentMeta(
70
+ filename=doc.filename,
71
+ file_format=doc.file_format,
72
+ pages=doc.pages,
73
+ word_count=doc.word_count,
74
+ paragraph_count=len(doc.clauses),
75
+ char_count=doc.char_count,
76
+ reading_minutes=max(1, math.ceil(doc.word_count / 220)),
77
+ detected_type=detected_type,
78
+ doc_type=review_ctx.doc_type,
79
+ party_side=review_ctx.party_side,
80
+ party_side_label=review_ctx.party_side_label,
81
+ priorities=review_ctx.priorities,
82
+ parties=parties,
83
+ )
84
+
85
+ ctx.report_progress("analyze", "Checking clauses and missing protections", 0.5)
86
+ notes = analyze_clauses(
87
+ doc.clauses,
88
+ doc_type=review_ctx.doc_type,
89
+ party_side=review_ctx.party_side,
90
+ priorities=review_ctx.priorities,
91
+ focus=input.focus,
92
+ )
93
+ missing = find_missing_protections(
94
+ review_ctx.doc_type,
95
+ review_ctx.party_side,
96
+ doc.clauses,
97
+ notes,
98
+ )
99
+ template_headline = build_template_headline(meta, notes, missing)
100
+ ctx.check_cancelled()
101
+
102
+ if input.use_llm and ctx.llm is not None and notes and input.max_clauses_for_llm > 0:
103
+ ctx.report_progress("write", "Writing plain-English notes with model", 0.7)
104
+ headline, notes, used_model = await enrich_with_model(
105
+ meta,
106
+ doc.clauses,
107
+ notes,
108
+ template_headline,
109
+ ctx,
110
+ use_llm=input.use_llm,
111
+ redact=input.redact_personal_info,
112
+ max_clauses=input.max_clauses_for_llm,
113
+ )
114
+ ctx.check_cancelled()
115
+
116
+ checklist = build_checklist(notes, missing)
117
+ risk_counts = {
118
+ "high": sum(1 for n in notes if n.severity == "high"),
119
+ "medium": sum(1 for n in notes if n.severity == "medium"),
120
+ "low": sum(1 for n in notes if n.severity == "low"),
121
+ "checked": sum(1 for n in notes if n.severity == "ok"),
122
+ }
123
+
124
+ output = FinePrintOutput(
125
+ document=meta,
126
+ caveat=CAVEAT_TEXT,
127
+ summary_headline=headline,
128
+ risk_counts=risk_counts,
129
+ clauses=doc.clauses,
130
+ notes=notes,
131
+ key_terms=key_terms,
132
+ missing_protections=missing,
133
+ checklist=checklist,
134
+ writer_mode="model" if used_model else "template",
135
+ )
136
+
137
+ if input.output_dir:
138
+ ctx.report_progress("export", f"Writing review files to {input.output_dir}", 0.92)
139
+ output.files = await asyncio.to_thread(write_reports, input.output_dir, output)
140
+
141
+ findings = _build_findings(output)
142
+ ctx.report_progress("done", "Finished", 1.0)
143
+ return self.make_result(
144
+ summary=headline,
145
+ output=output,
146
+ findings=findings,
147
+ status="partial" if doc.warnings else "ok",
148
+ )
149
+
150
+
151
+ def _build_findings(output: FinePrintOutput) -> list[Finding]:
152
+ findings: list[Finding] = []
153
+ for note in output.notes:
154
+ ev = [
155
+ Evidence(
156
+ kind="quote",
157
+ location=f"{note.clause_id} ({note.location})",
158
+ detail=f'"{note.quote}"',
159
+ )
160
+ ]
161
+ if note.suggested_question:
162
+ ev.append(
163
+ Evidence(
164
+ kind="question",
165
+ location=note.location,
166
+ detail=f"Ask before signing: {note.suggested_question}",
167
+ )
168
+ )
169
+ findings.append(
170
+ Finding(
171
+ title=f"{note.title} ({note.margin_tag})",
172
+ severity_or_score=_SEVERITY_SCORE.get(note.severity, 0.3),
173
+ summary=f"{note.explanation} {note.why_it_matters}",
174
+ evidence=ev,
175
+ )
176
+ )
177
+ for miss in output.missing_protections:
178
+ findings.append(
179
+ Finding(
180
+ title=f"Not mentioned: {miss.title}",
181
+ severity_or_score=0.5,
182
+ summary=miss.detail,
183
+ evidence=[
184
+ Evidence(
185
+ kind="question",
186
+ location="document",
187
+ detail=f"Ask before signing: {miss.suggested_question}",
188
+ )
189
+ ],
190
+ )
191
+ )
192
+ return findings