probative 0.1.0__py3-none-any.whl
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.
- probative/__init__.py +14 -0
- probative/agents/__init__.py +1 -0
- probative/cli.py +167 -0
- probative/config.py +76 -0
- probative/core/__init__.py +1 -0
- probative/core/candidates.py +165 -0
- probative/core/critic.py +113 -0
- probative/core/evidence.py +158 -0
- probative/critics/__init__.py +26 -0
- probative/critics/base.py +66 -0
- probative/critics/constraint_critic.py +434 -0
- probative/critics/dependency_critic.py +132 -0
- probative/critics/evidence_auditor.py +127 -0
- probative/critics/invest.py +62 -0
- probative/critics/llm_judge.py +530 -0
- probative/critics/red_team.py +127 -0
- probative/critics/rubric.py +46 -0
- probative/critics/rubrics/constraint_critic/rubric.yaml +42 -0
- probative/critics/rubrics/dependency_critic/rubric.yaml +31 -0
- probative/critics/rubrics/evidence_auditor/rubric.yaml +74 -0
- probative/critics/rubrics/invest/rubric.yaml +67 -0
- probative/critics/rubrics/red_team/rubric.yaml +119 -0
- probative/critics/rubrics/segment_skeptic/rubric.yaml +47 -0
- probative/critics/rubrics/space_warden/rubric.yaml +24 -0
- probative/critics/runner.py +34 -0
- probative/critics/scoring.py +50 -0
- probative/critics/segment_skeptic.py +125 -0
- probative/critics/space_warden.py +57 -0
- probative/critics/testing.py +46 -0
- probative/critique/__init__.py +65 -0
- probative/critique/pipeline.py +374 -0
- probative/critique/report.py +230 -0
- probative/critique/roster.py +103 -0
- probative/critique/scoring.py +94 -0
- probative/critique/sources.py +198 -0
- probative/critique/verify.py +141 -0
- probative/exporters/__init__.py +1 -0
- probative/extract/__init__.py +33 -0
- probative/extract/chunking.py +47 -0
- probative/extract/pipeline.py +182 -0
- probative/extract/prompts.py +183 -0
- probative/extract/resolve.py +85 -0
- probative/extract/scoring.py +156 -0
- probative/formulas/__init__.py +1 -0
- probative/graph_runtime/__init__.py +1 -0
- probative/ingest/__init__.py +144 -0
- probative/ingest/_extracted.py +18 -0
- probative/ingest/_html.py +27 -0
- probative/ingest/_lines.py +41 -0
- probative/ingest/_tracker_text.py +71 -0
- probative/ingest/_wiki.py +30 -0
- probative/ingest/ado_csv.py +74 -0
- probative/ingest/confluence.py +91 -0
- probative/ingest/confluence_word.py +128 -0
- probative/ingest/csv_.py +50 -0
- probative/ingest/docx_.py +66 -0
- probative/ingest/jira_csv.py +76 -0
- probative/ingest/jira_html.py +116 -0
- probative/ingest/jira_xml.py +94 -0
- probative/ingest/markdown.py +70 -0
- probative/ingest/pdf.py +76 -0
- probative/ingest/text.py +20 -0
- probative/ingest/tracker.py +158 -0
- probative/ingest/xlsx.py +61 -0
- probative/interfaces/__init__.py +1 -0
- probative/interfaces/doctor.py +189 -0
- probative/interfaces/mcp_server.py +487 -0
- probative/llm/__init__.py +21 -0
- probative/llm/factory.py +85 -0
- probative/llm/fake.py +47 -0
- probative/llm/litellm_provider.py +86 -0
- probative/llm/provider.py +34 -0
- probative/llm/structured.py +38 -0
- probative/llm/types.py +51 -0
- probative/render/__init__.py +1 -0
- probative/render/_view.py +125 -0
- probative/render/design.py +63 -0
- probative/render/html.py +256 -0
- probative/render/markdown.py +122 -0
- probative-0.1.0.dist-info/METADATA +143 -0
- probative-0.1.0.dist-info/RECORD +84 -0
- probative-0.1.0.dist-info/WHEEL +4 -0
- probative-0.1.0.dist-info/entry_points.txt +2 -0
- probative-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""The shape every critique renderer reads (PROBATIVE_PHASE_SPECS.md PB9).
|
|
2
|
+
|
|
3
|
+
`CritiqueReport` is a projection (I5): every string in it is a fixed label, a
|
|
4
|
+
rubric string carried by a `Finding`, or bytes of the source document. Every
|
|
5
|
+
number in it is a pure function of findings and candidate counts (I4), and
|
|
6
|
+
`probative.critique.verify` recomputes them. A finding that cannot name a quote
|
|
7
|
+
in a source is not a blank cell, it is a `ReportIntegrityError` (I1).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
from enum import StrEnum
|
|
14
|
+
|
|
15
|
+
from pydantic import BaseModel, ConfigDict
|
|
16
|
+
|
|
17
|
+
from probative.core.critic import Finding, Severity
|
|
18
|
+
from probative.core.evidence import Locator, Source, SourceFormat
|
|
19
|
+
|
|
20
|
+
SCHEMA_VERSION = "1"
|
|
21
|
+
CONTEXT_CHARS = 240
|
|
22
|
+
SMALL_SAMPLE = 5 # fewer candidates than this is labelled "small sample"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ReportIntegrityError(Exception):
|
|
26
|
+
"""The report would say something the sources or the arithmetic do not support."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class DimensionStatus(StrEnum):
|
|
30
|
+
ASSESSED = "assessed"
|
|
31
|
+
NOT_APPLICABLE = "not_applicable"
|
|
32
|
+
INCOMPLETE = "incomplete"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _Frozen(BaseModel):
|
|
36
|
+
model_config = ConfigDict(frozen=True)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class SeverityCounts(_Frozen):
|
|
40
|
+
block: int = 0
|
|
41
|
+
warn: int = 0
|
|
42
|
+
note: int = 0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def locator_label(locator: Locator) -> str:
|
|
46
|
+
"""A deterministic human label for a locator, from the fields it has."""
|
|
47
|
+
if locator.sheet is not None and locator.cell is not None:
|
|
48
|
+
return f"{locator.sheet}!{locator.cell}"
|
|
49
|
+
parts: list[str] = []
|
|
50
|
+
if locator.issue_key:
|
|
51
|
+
parts.append(locator.issue_key)
|
|
52
|
+
if locator.field:
|
|
53
|
+
parts.append(locator.field)
|
|
54
|
+
if locator.page is not None:
|
|
55
|
+
parts.append(f"p.{locator.page}")
|
|
56
|
+
if locator.line is not None:
|
|
57
|
+
parts.append(f"line {locator.line}")
|
|
58
|
+
if locator.heading_path:
|
|
59
|
+
parts.append(" > ".join(locator.heading_path))
|
|
60
|
+
return " · ".join(parts) if parts else "location unknown"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ReportFinding(_Frozen):
|
|
64
|
+
critic_id: str
|
|
65
|
+
check_id: str
|
|
66
|
+
check_headline: str # the rubric's own first sentence for the check
|
|
67
|
+
severity: Severity
|
|
68
|
+
invariant: str | None
|
|
69
|
+
message: str
|
|
70
|
+
detail: str # what `message` says beyond its `check: “quote” — headline` prefix
|
|
71
|
+
remedy: str
|
|
72
|
+
target_id: str
|
|
73
|
+
source_id: str
|
|
74
|
+
quote: str
|
|
75
|
+
start: int
|
|
76
|
+
end: int
|
|
77
|
+
locator: Locator
|
|
78
|
+
locator_label: str
|
|
79
|
+
context_before: str
|
|
80
|
+
context_after: str
|
|
81
|
+
context_clipped_before: bool
|
|
82
|
+
context_clipped_after: bool
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _clip_before(text: str, start: int) -> tuple[str, bool]:
|
|
86
|
+
lo = max(0, start - CONTEXT_CHARS)
|
|
87
|
+
chunk = text[lo:start]
|
|
88
|
+
if lo == 0:
|
|
89
|
+
return chunk, False
|
|
90
|
+
if not text[lo - 1].isspace() and not chunk[:1].isspace():
|
|
91
|
+
cut = next((i for i, ch in enumerate(chunk) if ch.isspace()), None)
|
|
92
|
+
chunk = "" if cut is None else chunk[cut:].lstrip(" ")
|
|
93
|
+
return chunk, True
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _clip_after(text: str, end: int) -> tuple[str, bool]:
|
|
97
|
+
hi = min(len(text), end + CONTEXT_CHARS)
|
|
98
|
+
chunk = text[end:hi]
|
|
99
|
+
if hi == len(text):
|
|
100
|
+
return chunk, False
|
|
101
|
+
if not text[hi].isspace() and not chunk[-1:].isspace():
|
|
102
|
+
cut = next((i for i in range(len(chunk) - 1, -1, -1) if chunk[i].isspace()), None)
|
|
103
|
+
chunk = "" if cut is None else chunk[:cut].rstrip(" ")
|
|
104
|
+
return chunk, True
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def report_finding(
|
|
108
|
+
finding: Finding, source: Source, *, headline: str | None = None
|
|
109
|
+
) -> ReportFinding:
|
|
110
|
+
"""Build a report row, or raise: no evidence, no target, a span from another
|
|
111
|
+
source or a quote that is not the source's own bytes is never rendered (I1)."""
|
|
112
|
+
where = f"{finding.critic_id}/{finding.check_id}"
|
|
113
|
+
if finding.evidence is None:
|
|
114
|
+
raise ReportIntegrityError(f"{where}: finding has no evidence span")
|
|
115
|
+
if finding.target_id is None:
|
|
116
|
+
raise ReportIntegrityError(f"{where}: finding has no target candidate")
|
|
117
|
+
ev = finding.evidence
|
|
118
|
+
if ev.source_id != source.id:
|
|
119
|
+
raise ReportIntegrityError(
|
|
120
|
+
f"{where}: evidence belongs to source {ev.source_id!r}, not {source.id!r}"
|
|
121
|
+
)
|
|
122
|
+
if (
|
|
123
|
+
not (0 <= ev.start < ev.end <= len(source.text))
|
|
124
|
+
or source.text[ev.start : ev.end] != ev.text
|
|
125
|
+
):
|
|
126
|
+
raise ReportIntegrityError(
|
|
127
|
+
f"{where}: quote does not match the source bytes at ({ev.start}, {ev.end})"
|
|
128
|
+
)
|
|
129
|
+
before, clipped_before = _clip_before(source.text, ev.start)
|
|
130
|
+
after, clipped_after = _clip_after(source.text, ev.end)
|
|
131
|
+
head = headline or finding.check_id
|
|
132
|
+
prefix = f"{finding.check_id}: “{ev.text}” — {head}"
|
|
133
|
+
detail = (
|
|
134
|
+
finding.message[len(prefix) :].strip()
|
|
135
|
+
if finding.message.startswith(prefix)
|
|
136
|
+
else (finding.message)
|
|
137
|
+
)
|
|
138
|
+
return ReportFinding(
|
|
139
|
+
critic_id=finding.critic_id,
|
|
140
|
+
check_id=finding.check_id,
|
|
141
|
+
check_headline=head,
|
|
142
|
+
detail=detail,
|
|
143
|
+
severity=finding.severity,
|
|
144
|
+
invariant=finding.invariant,
|
|
145
|
+
message=finding.message,
|
|
146
|
+
remedy=finding.remedy,
|
|
147
|
+
target_id=finding.target_id,
|
|
148
|
+
source_id=source.id,
|
|
149
|
+
quote=ev.text,
|
|
150
|
+
start=ev.start,
|
|
151
|
+
end=ev.end,
|
|
152
|
+
locator=ev.locator,
|
|
153
|
+
locator_label=locator_label(ev.locator),
|
|
154
|
+
context_before=before,
|
|
155
|
+
context_after=after,
|
|
156
|
+
context_clipped_before=clipped_before,
|
|
157
|
+
context_clipped_after=clipped_after,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class DimensionResult(_Frozen):
|
|
162
|
+
critic_id: str
|
|
163
|
+
label: str
|
|
164
|
+
invariant: str | None
|
|
165
|
+
status: DimensionStatus
|
|
166
|
+
checked: int
|
|
167
|
+
flagged: int
|
|
168
|
+
clean_rate: float | None
|
|
169
|
+
floor_score: float | None
|
|
170
|
+
blocked: bool
|
|
171
|
+
counts: SeverityCounts
|
|
172
|
+
unjudged: int = 0
|
|
173
|
+
unextracted: int = 0 # extraction passes feeding this critic that failed
|
|
174
|
+
cannot_tell: int = 0 # judgements the model declined; counted as clean, so shown
|
|
175
|
+
findings: list[ReportFinding]
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def clean(self) -> int:
|
|
179
|
+
return self.checked - self.flagged
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def small_sample(self) -> bool:
|
|
183
|
+
return self.status is DimensionStatus.ASSESSED and self.checked < SMALL_SAMPLE
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class DocumentSummary(_Frozen):
|
|
187
|
+
source_id: str
|
|
188
|
+
file_name: str
|
|
189
|
+
format: SourceFormat
|
|
190
|
+
format_choice: str # "detected" | "forced"
|
|
191
|
+
sha256: str
|
|
192
|
+
chars: int
|
|
193
|
+
pages: int | None
|
|
194
|
+
tier: str # recorded, never rendered: a default, not a judgement
|
|
195
|
+
kind: str
|
|
196
|
+
candidates: dict[str, int]
|
|
197
|
+
rejected: dict[str, int]
|
|
198
|
+
counts: SeverityCounts
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class SkippedFile(_Frozen):
|
|
202
|
+
path: str
|
|
203
|
+
reason: str
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class RunStats(_Frozen):
|
|
207
|
+
calls: int
|
|
208
|
+
input_tokens: int
|
|
209
|
+
output_tokens: int
|
|
210
|
+
wall_seconds: float
|
|
211
|
+
jobs: int
|
|
212
|
+
reply: str = "full" # how the critics were asked to reply: "full" or "flagged"
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class CritiqueReport(_Frozen):
|
|
216
|
+
schema_version: str = SCHEMA_VERSION
|
|
217
|
+
generated_at: datetime
|
|
218
|
+
tool_version: str
|
|
219
|
+
model: str
|
|
220
|
+
is_reference_model: bool
|
|
221
|
+
subject: str # the file or folder name the run was pointed at
|
|
222
|
+
documents: list[DocumentSummary]
|
|
223
|
+
dimensions: list[DimensionResult]
|
|
224
|
+
totals: SeverityCounts
|
|
225
|
+
skipped: list[SkippedFile]
|
|
226
|
+
run: RunStats
|
|
227
|
+
|
|
228
|
+
@property
|
|
229
|
+
def incomplete(self) -> bool:
|
|
230
|
+
return any(d.status is DimensionStatus.INCOMPLETE for d in self.dimensions)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""The critics `probative critique` runs, as one named constant.
|
|
2
|
+
|
|
3
|
+
One entry per critic, one report dimension per entry (no invented grouping).
|
|
4
|
+
Keeping the roster as data is what lets PB39 make onboarding-mode exclusion a
|
|
5
|
+
configuration (OI22, I9) rather than a prompt request; nothing here enforces
|
|
6
|
+
that yet, because there is no mode.
|
|
7
|
+
|
|
8
|
+
`subjects` is what a dimension counts as "checked". `feeds` is what the critic
|
|
9
|
+
is sent, which for `ConstraintCritic` includes stories it traces to. Only
|
|
10
|
+
critics that judge each candidate independently are `shardable`: sharding at
|
|
11
|
+
`batch_size` boundaries sends the same prompts an unsharded run would, so the
|
|
12
|
+
recordings do not move.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
|
|
20
|
+
from probative.core.candidates import CandidateKind
|
|
21
|
+
from probative.critics.base import Critic
|
|
22
|
+
from probative.critics.constraint_critic import ConstraintCritic
|
|
23
|
+
from probative.critics.dependency_critic import DependencyCritic
|
|
24
|
+
from probative.critics.evidence_auditor import EvidenceAuditor
|
|
25
|
+
from probative.critics.invest import INVESTCritic
|
|
26
|
+
from probative.critics.llm_judge import Reply
|
|
27
|
+
from probative.critics.red_team import RedTeam
|
|
28
|
+
from probative.critics.segment_skeptic import SegmentSkeptic
|
|
29
|
+
from probative.critics.space_warden import SpaceWarden
|
|
30
|
+
from probative.llm import Provider
|
|
31
|
+
|
|
32
|
+
Factory = Callable[[Provider, str, int, Reply], Critic]
|
|
33
|
+
K = CandidateKind
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class RosterEntry:
|
|
38
|
+
rubric_id: str
|
|
39
|
+
label: str
|
|
40
|
+
subjects: tuple[CandidateKind, ...]
|
|
41
|
+
feeds: tuple[CandidateKind, ...]
|
|
42
|
+
shardable: bool
|
|
43
|
+
make: Factory
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
ROSTER: tuple[RosterEntry, ...] = (
|
|
47
|
+
RosterEntry(
|
|
48
|
+
"evidence_auditor",
|
|
49
|
+
"Evidence",
|
|
50
|
+
(K.CLAIM,),
|
|
51
|
+
(K.CLAIM,),
|
|
52
|
+
True,
|
|
53
|
+
lambda p, m, b, r: EvidenceAuditor.from_builtin_rubric(p, model=m, batch_size=b, reply=r),
|
|
54
|
+
),
|
|
55
|
+
RosterEntry(
|
|
56
|
+
"space_warden",
|
|
57
|
+
"Problem framing",
|
|
58
|
+
(K.NEED,),
|
|
59
|
+
(K.NEED,),
|
|
60
|
+
True,
|
|
61
|
+
lambda p, m, b, r: SpaceWarden.from_builtin_rubric(p, model=m, batch_size=b, reply=r),
|
|
62
|
+
),
|
|
63
|
+
RosterEntry(
|
|
64
|
+
"segment_skeptic",
|
|
65
|
+
"Segments",
|
|
66
|
+
(K.SEGMENT,),
|
|
67
|
+
(K.SEGMENT,),
|
|
68
|
+
True,
|
|
69
|
+
lambda p, m, b, r: SegmentSkeptic.from_builtin_rubric(p, model=m, batch_size=b, reply=r),
|
|
70
|
+
),
|
|
71
|
+
RosterEntry(
|
|
72
|
+
"invest",
|
|
73
|
+
"Story quality",
|
|
74
|
+
(K.STORY,),
|
|
75
|
+
(K.STORY,),
|
|
76
|
+
True,
|
|
77
|
+
lambda p, m, b, r: INVESTCritic.from_builtin_rubric(p, model=m, batch_size=b, reply=r),
|
|
78
|
+
),
|
|
79
|
+
RosterEntry(
|
|
80
|
+
"dependency_critic",
|
|
81
|
+
"Dependencies",
|
|
82
|
+
(K.DEPENDENCY,),
|
|
83
|
+
(K.DEPENDENCY,),
|
|
84
|
+
True,
|
|
85
|
+
lambda p, m, b, r: DependencyCritic.from_builtin_rubric(p, model=m, batch_size=b, reply=r),
|
|
86
|
+
),
|
|
87
|
+
RosterEntry(
|
|
88
|
+
"constraint_critic",
|
|
89
|
+
"Constraints",
|
|
90
|
+
(K.CONSTRAINT,),
|
|
91
|
+
(K.CONSTRAINT, K.STORY),
|
|
92
|
+
False,
|
|
93
|
+
lambda p, m, b, r: ConstraintCritic.from_builtin_rubric(p, model=m, batch_size=b),
|
|
94
|
+
),
|
|
95
|
+
RosterEntry(
|
|
96
|
+
"red_team",
|
|
97
|
+
"Stress test: least sure about",
|
|
98
|
+
(K.CLAIM, K.FORECAST),
|
|
99
|
+
(K.CLAIM, K.FORECAST),
|
|
100
|
+
True,
|
|
101
|
+
lambda p, m, b, r: RedTeam.from_builtin_rubric(p, model=m, batch_size=b, reply=r),
|
|
102
|
+
),
|
|
103
|
+
)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Deterministic report numbers (OI18, resolved in PB9; I4).
|
|
2
|
+
|
|
3
|
+
PB3's `score_dimension` is a veto-shaped floor and does not depend on how many
|
|
4
|
+
candidates were checked, so it cannot say how conforming a document is. The
|
|
5
|
+
report therefore carries a rate beside it: of the candidates a critic examined,
|
|
6
|
+
how many drew no block or warn finding. Notes do not flag. Several findings on
|
|
7
|
+
one candidate flag it once.
|
|
8
|
+
|
|
9
|
+
A dimension that examined nothing is `not_applicable`, never a clean 10.
|
|
10
|
+
A dimension with a candidate that could not be judged is `incomplete` and has
|
|
11
|
+
no rate: a rate over the part that was judged would read as a verdict.
|
|
12
|
+
|
|
13
|
+
Formula ids are recorded here until PB11's registry exists.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from collections.abc import Sequence
|
|
19
|
+
from typing import Final
|
|
20
|
+
|
|
21
|
+
from probative.core.critic import Finding, Rubric, Severity
|
|
22
|
+
from probative.critics.scoring import score_dimension
|
|
23
|
+
from probative.critique.report import (
|
|
24
|
+
DimensionResult,
|
|
25
|
+
DimensionStatus,
|
|
26
|
+
ReportFinding,
|
|
27
|
+
SeverityCounts,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
FORMULA_CLEAN_RATE: Final = "critique.clean_rate"
|
|
31
|
+
FORMULA_FLAGGED: Final = "critique.flagged"
|
|
32
|
+
|
|
33
|
+
_FLAGGING = (Severity.BLOCK, Severity.WARN)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def flagged_candidates(findings: Sequence[Finding | ReportFinding]) -> int:
|
|
37
|
+
"""Distinct candidates with at least one block or warn finding."""
|
|
38
|
+
return len({f.target_id for f in findings if f.severity in _FLAGGING})
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def severity_counts(findings: Sequence[Finding | ReportFinding]) -> SeverityCounts:
|
|
42
|
+
return SeverityCounts(
|
|
43
|
+
block=sum(1 for f in findings if f.severity is Severity.BLOCK),
|
|
44
|
+
warn=sum(1 for f in findings if f.severity is Severity.WARN),
|
|
45
|
+
note=sum(1 for f in findings if f.severity is Severity.NOTE),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def clean_rate(checked: int, flagged: int) -> float | None:
|
|
50
|
+
if checked < 0 or flagged < 0 or flagged > checked:
|
|
51
|
+
raise ValueError(f"impossible counts: checked={checked}, flagged={flagged}")
|
|
52
|
+
if checked == 0:
|
|
53
|
+
return None
|
|
54
|
+
return (checked - flagged) / checked
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def assess_dimension(
|
|
58
|
+
rubric: Rubric,
|
|
59
|
+
label: str,
|
|
60
|
+
*,
|
|
61
|
+
checked: int,
|
|
62
|
+
findings: Sequence[Finding],
|
|
63
|
+
rendered: Sequence[ReportFinding],
|
|
64
|
+
unjudged: int,
|
|
65
|
+
unextracted: int = 0,
|
|
66
|
+
cannot_tell: int = 0,
|
|
67
|
+
) -> DimensionResult:
|
|
68
|
+
if len(findings) != len(rendered):
|
|
69
|
+
raise ValueError("findings and rendered findings must align one to one")
|
|
70
|
+
counts = severity_counts(findings)
|
|
71
|
+
flagged = flagged_candidates(findings)
|
|
72
|
+
if unjudged > 0 or unextracted > 0:
|
|
73
|
+
status = DimensionStatus.INCOMPLETE
|
|
74
|
+
elif checked == 0:
|
|
75
|
+
status = DimensionStatus.NOT_APPLICABLE
|
|
76
|
+
else:
|
|
77
|
+
status = DimensionStatus.ASSESSED
|
|
78
|
+
assessed = status is DimensionStatus.ASSESSED
|
|
79
|
+
return DimensionResult(
|
|
80
|
+
critic_id=rubric.id,
|
|
81
|
+
label=label,
|
|
82
|
+
invariant=rubric.invariant,
|
|
83
|
+
status=status,
|
|
84
|
+
checked=checked,
|
|
85
|
+
flagged=flagged,
|
|
86
|
+
clean_rate=clean_rate(checked, flagged) if assessed else None,
|
|
87
|
+
floor_score=score_dimension(rubric, findings).score if assessed else None,
|
|
88
|
+
blocked=counts.block > 0,
|
|
89
|
+
counts=counts,
|
|
90
|
+
unjudged=unjudged,
|
|
91
|
+
unextracted=unextracted,
|
|
92
|
+
cannot_tell=cannot_tell,
|
|
93
|
+
findings=list(rendered),
|
|
94
|
+
)
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Find, route and load the documents a critique is pointed at.
|
|
2
|
+
|
|
3
|
+
PB2 deliberately does not sniff tracker or Confluence formats: the caller states
|
|
4
|
+
the format. `probative critique` has no setup (I6), so this module states it on
|
|
5
|
+
the caller's behalf from signatures that are unambiguous (a Jira CSV has an
|
|
6
|
+
`Issue key` column, an ADO CSV a `Work Item Type` column, Jira HTML a
|
|
7
|
+
`issuetable`, a Confluence Word export an MHTML header), records that it did so
|
|
8
|
+
(`format_choice`), and lets `--as` override it. Once a signature matches, the
|
|
9
|
+
format is committed to: a malformed Jira CSV is a skipped file with a reason,
|
|
10
|
+
never a quiet fallback to plain CSV.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import csv
|
|
16
|
+
import io
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from probative.core.evidence import (
|
|
21
|
+
EvidenceKind,
|
|
22
|
+
EvidenceSpan,
|
|
23
|
+
IngestError,
|
|
24
|
+
Locator,
|
|
25
|
+
Source,
|
|
26
|
+
SourceFormat,
|
|
27
|
+
Tier,
|
|
28
|
+
)
|
|
29
|
+
from probative.critique.report import SkippedFile
|
|
30
|
+
from probative.ingest import ingest, reextract
|
|
31
|
+
from probative.ingest.confluence import ingest_confluence, reextract_confluence
|
|
32
|
+
from probative.ingest.tracker import ingest_tracker, reextract_tracker
|
|
33
|
+
|
|
34
|
+
DEFAULT_MAX_FILES = 25
|
|
35
|
+
|
|
36
|
+
_TRACKER = {
|
|
37
|
+
SourceFormat.JIRA_CSV,
|
|
38
|
+
SourceFormat.JIRA_HTML,
|
|
39
|
+
SourceFormat.JIRA_XML,
|
|
40
|
+
SourceFormat.ADO_CSV,
|
|
41
|
+
}
|
|
42
|
+
_FORCIBLE = _TRACKER | {SourceFormat.CONFLUENCE_WORD}
|
|
43
|
+
_PLAIN = {
|
|
44
|
+
".pdf": SourceFormat.PDF,
|
|
45
|
+
".docx": SourceFormat.DOCX,
|
|
46
|
+
".xlsx": SourceFormat.XLSX,
|
|
47
|
+
".md": SourceFormat.MARKDOWN,
|
|
48
|
+
".markdown": SourceFormat.MARKDOWN,
|
|
49
|
+
".txt": SourceFormat.TEXT,
|
|
50
|
+
}
|
|
51
|
+
_HEAD_BYTES = 8192
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class LoadedSource:
|
|
56
|
+
source: Source
|
|
57
|
+
format_choice: str # "detected" | "forced"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class LoadResult:
|
|
62
|
+
loaded: list[LoadedSource] = field(default_factory=list)
|
|
63
|
+
skipped: list[SkippedFile] = field(default_factory=list)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _head(path: Path) -> str:
|
|
67
|
+
with path.open("rb") as handle:
|
|
68
|
+
return handle.read(_HEAD_BYTES).decode("utf-8-sig", errors="replace")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _csv_header(path: Path) -> list[str]:
|
|
72
|
+
first = _head(path).splitlines()[:1]
|
|
73
|
+
if not first:
|
|
74
|
+
return []
|
|
75
|
+
rows = list(csv.reader(io.StringIO(first[0])))
|
|
76
|
+
return [cell.strip() for cell in rows[0]] if rows else []
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def sniff_format(path: Path) -> SourceFormat | None:
|
|
80
|
+
"""The format a file will be read as, or `None` when this tool cannot read it."""
|
|
81
|
+
suffix = path.suffix.lower()
|
|
82
|
+
if suffix == ".csv":
|
|
83
|
+
header = _csv_header(path)
|
|
84
|
+
if "Issue key" in header:
|
|
85
|
+
return SourceFormat.JIRA_CSV
|
|
86
|
+
if "Work Item Type" in header:
|
|
87
|
+
return SourceFormat.ADO_CSV
|
|
88
|
+
return SourceFormat.CSV
|
|
89
|
+
if suffix in {".html", ".htm"}:
|
|
90
|
+
return SourceFormat.JIRA_HTML if "issuetable" in _head(path) else None
|
|
91
|
+
if suffix == ".xml":
|
|
92
|
+
return SourceFormat.JIRA_XML
|
|
93
|
+
if suffix == ".doc":
|
|
94
|
+
head = _head(path)
|
|
95
|
+
mhtml = "MIME-Version" in head and "multipart/related" in head
|
|
96
|
+
return SourceFormat.CONFLUENCE_WORD if mhtml else None
|
|
97
|
+
return _PLAIN.get(suffix)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def load_source(
|
|
101
|
+
path: Path, *, tier: Tier, kind: EvidenceKind, forced: SourceFormat | None
|
|
102
|
+
) -> LoadedSource:
|
|
103
|
+
"""Ingest one file. Raises an `IngestError` subclass when it cannot be read."""
|
|
104
|
+
if forced is not None:
|
|
105
|
+
if forced not in _FORCIBLE:
|
|
106
|
+
raise ValueError(
|
|
107
|
+
f"--as accepts {', '.join(sorted(f.value for f in _FORCIBLE))}; "
|
|
108
|
+
f"{forced.value} is chosen by file extension"
|
|
109
|
+
)
|
|
110
|
+
return LoadedSource(_ingest(path, forced, tier, kind), "forced")
|
|
111
|
+
fmt = sniff_format(path)
|
|
112
|
+
if fmt is None:
|
|
113
|
+
# let PB1 raise its own typed error (unsupported extension, etc.)
|
|
114
|
+
return LoadedSource(ingest(path, tier=tier, kind=kind), "detected")
|
|
115
|
+
return LoadedSource(_ingest(path, fmt, tier, kind), "detected")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _ingest(path: Path, fmt: SourceFormat, tier: Tier, kind: EvidenceKind) -> Source:
|
|
119
|
+
if fmt in _TRACKER:
|
|
120
|
+
return ingest_tracker(path, format=fmt, tier=tier, kind=kind)
|
|
121
|
+
if fmt is SourceFormat.CONFLUENCE_WORD:
|
|
122
|
+
return ingest_confluence(path, format=fmt, tier=tier, kind=kind)
|
|
123
|
+
return ingest(path, tier=tier, kind=kind)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def reextract_whole(source: Source) -> str:
|
|
127
|
+
"""Re-run the source's own extractor over the whole text, via the official
|
|
128
|
+
re-extraction API for its format (CLAUDE.md: re-extract and compare)."""
|
|
129
|
+
whole = EvidenceSpan(
|
|
130
|
+
source_id=source.id, start=0, end=len(source.text), text=source.text, locator=Locator()
|
|
131
|
+
)
|
|
132
|
+
if source.format in _TRACKER:
|
|
133
|
+
return reextract_tracker(source, whole)
|
|
134
|
+
if source.format is SourceFormat.CONFLUENCE_WORD:
|
|
135
|
+
return reextract_confluence(source, whole)
|
|
136
|
+
return reextract(source, whole)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _reason(error: Exception) -> str:
|
|
140
|
+
name = type(error).__name__
|
|
141
|
+
return f"{name.replace('Error', '')}: {error}" if name != "Exception" else str(error)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _unsupported_reason(path: Path) -> str:
|
|
145
|
+
return f"Unsupported format: {path.suffix or 'no extension'} is not a document this tool reads"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def discover_and_load(
|
|
149
|
+
root: Path,
|
|
150
|
+
*,
|
|
151
|
+
tier: Tier,
|
|
152
|
+
kind: EvidenceKind,
|
|
153
|
+
forced: SourceFormat | None = None,
|
|
154
|
+
max_files: int = DEFAULT_MAX_FILES,
|
|
155
|
+
) -> LoadResult:
|
|
156
|
+
if not root.exists():
|
|
157
|
+
raise FileNotFoundError(root)
|
|
158
|
+
if forced is not None and root.is_dir():
|
|
159
|
+
raise ValueError("--as applies to a single file, not a folder")
|
|
160
|
+
if root.is_dir():
|
|
161
|
+
files = sorted(
|
|
162
|
+
(
|
|
163
|
+
p
|
|
164
|
+
for p in root.rglob("*")
|
|
165
|
+
if p.is_file()
|
|
166
|
+
and not any(part.startswith(".") for part in p.relative_to(root).parts)
|
|
167
|
+
),
|
|
168
|
+
key=lambda p: p.relative_to(root).as_posix(),
|
|
169
|
+
)
|
|
170
|
+
else:
|
|
171
|
+
files = [root]
|
|
172
|
+
result = LoadResult()
|
|
173
|
+
seen: dict[str, Path] = {}
|
|
174
|
+
for path in files:
|
|
175
|
+
try:
|
|
176
|
+
loaded = load_source(path, tier=tier, kind=kind, forced=forced)
|
|
177
|
+
except IngestError as error:
|
|
178
|
+
reason = (
|
|
179
|
+
_unsupported_reason(path)
|
|
180
|
+
if type(error).__name__ == "UnsupportedFormatError"
|
|
181
|
+
else _reason(error)
|
|
182
|
+
)
|
|
183
|
+
result.skipped.append(SkippedFile(path=str(path), reason=reason))
|
|
184
|
+
continue
|
|
185
|
+
digest = loaded.source.sha256
|
|
186
|
+
if digest in seen:
|
|
187
|
+
result.skipped.append(
|
|
188
|
+
SkippedFile(path=str(path), reason=f"duplicate of {seen[digest].name} (same bytes)")
|
|
189
|
+
)
|
|
190
|
+
continue
|
|
191
|
+
if len(result.loaded) >= max_files:
|
|
192
|
+
result.skipped.append(
|
|
193
|
+
SkippedFile(path=str(path), reason=f"over the --max-files cap of {max_files}")
|
|
194
|
+
)
|
|
195
|
+
continue
|
|
196
|
+
seen[digest] = path
|
|
197
|
+
result.loaded.append(loaded)
|
|
198
|
+
return result
|