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.
Files changed (84) hide show
  1. probative/__init__.py +14 -0
  2. probative/agents/__init__.py +1 -0
  3. probative/cli.py +167 -0
  4. probative/config.py +76 -0
  5. probative/core/__init__.py +1 -0
  6. probative/core/candidates.py +165 -0
  7. probative/core/critic.py +113 -0
  8. probative/core/evidence.py +158 -0
  9. probative/critics/__init__.py +26 -0
  10. probative/critics/base.py +66 -0
  11. probative/critics/constraint_critic.py +434 -0
  12. probative/critics/dependency_critic.py +132 -0
  13. probative/critics/evidence_auditor.py +127 -0
  14. probative/critics/invest.py +62 -0
  15. probative/critics/llm_judge.py +530 -0
  16. probative/critics/red_team.py +127 -0
  17. probative/critics/rubric.py +46 -0
  18. probative/critics/rubrics/constraint_critic/rubric.yaml +42 -0
  19. probative/critics/rubrics/dependency_critic/rubric.yaml +31 -0
  20. probative/critics/rubrics/evidence_auditor/rubric.yaml +74 -0
  21. probative/critics/rubrics/invest/rubric.yaml +67 -0
  22. probative/critics/rubrics/red_team/rubric.yaml +119 -0
  23. probative/critics/rubrics/segment_skeptic/rubric.yaml +47 -0
  24. probative/critics/rubrics/space_warden/rubric.yaml +24 -0
  25. probative/critics/runner.py +34 -0
  26. probative/critics/scoring.py +50 -0
  27. probative/critics/segment_skeptic.py +125 -0
  28. probative/critics/space_warden.py +57 -0
  29. probative/critics/testing.py +46 -0
  30. probative/critique/__init__.py +65 -0
  31. probative/critique/pipeline.py +374 -0
  32. probative/critique/report.py +230 -0
  33. probative/critique/roster.py +103 -0
  34. probative/critique/scoring.py +94 -0
  35. probative/critique/sources.py +198 -0
  36. probative/critique/verify.py +141 -0
  37. probative/exporters/__init__.py +1 -0
  38. probative/extract/__init__.py +33 -0
  39. probative/extract/chunking.py +47 -0
  40. probative/extract/pipeline.py +182 -0
  41. probative/extract/prompts.py +183 -0
  42. probative/extract/resolve.py +85 -0
  43. probative/extract/scoring.py +156 -0
  44. probative/formulas/__init__.py +1 -0
  45. probative/graph_runtime/__init__.py +1 -0
  46. probative/ingest/__init__.py +144 -0
  47. probative/ingest/_extracted.py +18 -0
  48. probative/ingest/_html.py +27 -0
  49. probative/ingest/_lines.py +41 -0
  50. probative/ingest/_tracker_text.py +71 -0
  51. probative/ingest/_wiki.py +30 -0
  52. probative/ingest/ado_csv.py +74 -0
  53. probative/ingest/confluence.py +91 -0
  54. probative/ingest/confluence_word.py +128 -0
  55. probative/ingest/csv_.py +50 -0
  56. probative/ingest/docx_.py +66 -0
  57. probative/ingest/jira_csv.py +76 -0
  58. probative/ingest/jira_html.py +116 -0
  59. probative/ingest/jira_xml.py +94 -0
  60. probative/ingest/markdown.py +70 -0
  61. probative/ingest/pdf.py +76 -0
  62. probative/ingest/text.py +20 -0
  63. probative/ingest/tracker.py +158 -0
  64. probative/ingest/xlsx.py +61 -0
  65. probative/interfaces/__init__.py +1 -0
  66. probative/interfaces/doctor.py +189 -0
  67. probative/interfaces/mcp_server.py +487 -0
  68. probative/llm/__init__.py +21 -0
  69. probative/llm/factory.py +85 -0
  70. probative/llm/fake.py +47 -0
  71. probative/llm/litellm_provider.py +86 -0
  72. probative/llm/provider.py +34 -0
  73. probative/llm/structured.py +38 -0
  74. probative/llm/types.py +51 -0
  75. probative/render/__init__.py +1 -0
  76. probative/render/_view.py +125 -0
  77. probative/render/design.py +63 -0
  78. probative/render/html.py +256 -0
  79. probative/render/markdown.py +122 -0
  80. probative-0.1.0.dist-info/METADATA +143 -0
  81. probative-0.1.0.dist-info/RECORD +84 -0
  82. probative-0.1.0.dist-info/WHEEL +4 -0
  83. probative-0.1.0.dist-info/entry_points.txt +2 -0
  84. probative-0.1.0.dist-info/licenses/LICENSE +201 -0
probative/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """Probative — evidence-grounded product discovery.
2
+
3
+ Every claim in every artifact either traces to a source it came from or is
4
+ labelled a hypothesis with a test attached. See ``docs/DESIGN.md``.
5
+ """
6
+
7
+ from importlib.metadata import PackageNotFoundError, version
8
+
9
+ try:
10
+ __version__ = version("probative")
11
+ except PackageNotFoundError: # pragma: no cover — running from a bare checkout
12
+ __version__ = "0.0.0+unknown"
13
+
14
+ __all__ = ["__version__"]
@@ -0,0 +1 @@
1
+ """Agents propose patches; they never mutate the graph (S1)."""
probative/cli.py ADDED
@@ -0,0 +1,167 @@
1
+ """Probative's command-line entry point.
2
+
3
+ `--version`, `--help` and `critique` (PB9). Every later phase adds a
4
+ subcommand here (`onboard`, `ingest`, `run`, ...) — this module stays the thin
5
+ interface over `probative.critique` / `probative.core` /
6
+ `probative.graph_runtime`, never a place logic accumulates.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+ from typing import Annotated
13
+
14
+ import typer
15
+
16
+ import probative.critique as critique_api
17
+ from probative import __version__
18
+ from probative.config import MissingCredentialsError, Settings
19
+ from probative.core.evidence import EvidenceKind, SourceFormat, Tier
20
+ from probative.critique.pipeline import (
21
+ DEFAULT_CRITIC_BATCH,
22
+ DEFAULT_JOBS,
23
+ DEFAULT_WINDOW_CHARS,
24
+ CritiqueOptions,
25
+ )
26
+ from probative.critique.report import ReportIntegrityError
27
+ from probative.critique.sources import DEFAULT_MAX_FILES
28
+ from probative.llm.factory import make_provider
29
+ from probative.render.html import render_html
30
+ from probative.render.markdown import render_markdown, render_summary
31
+
32
+ app = typer.Typer(
33
+ name="probative",
34
+ help="Evidence-grounded product discovery. Every claim cites its source "
35
+ "or is labelled a hypothesis with a test attached.",
36
+ no_args_is_help=True,
37
+ )
38
+
39
+
40
+ def _version_callback(value: bool) -> None:
41
+ if value:
42
+ typer.echo(f"probative {__version__}")
43
+ raise typer.Exit()
44
+
45
+
46
+ @app.callback()
47
+ def main(
48
+ version: bool = typer.Option(
49
+ False,
50
+ "--version",
51
+ callback=_version_callback,
52
+ is_eager=True,
53
+ help="Show the installed version and exit.",
54
+ ),
55
+ ) -> None:
56
+ """Probative."""
57
+
58
+
59
+ _FORMATS = ("md", "html")
60
+ EXIT_INCOMPLETE = 3
61
+ EXIT_FAILED = 2
62
+
63
+ # Shared with the MCP server; the alias keeps the name tests patch.
64
+ _make_provider = make_provider
65
+
66
+
67
+ def _fail(message: str) -> typer.Exit:
68
+ typer.echo(f"error: {message}", err=True)
69
+ return typer.Exit(EXIT_FAILED)
70
+
71
+
72
+ @app.command()
73
+ def critique(
74
+ path: Annotated[Path, typer.Argument(help="A document, an export, or a folder of them.")],
75
+ out: Annotated[Path, typer.Option(help="Where to write the reports.")] = Path("."),
76
+ format: Annotated[str, typer.Option(help="Comma-separated: md, html.")] = "md,html",
77
+ model: Annotated[str | None, typer.Option(help="Model id; default from settings.")] = None,
78
+ jobs: Annotated[int, typer.Option(min=1, help="Concurrent model calls.")] = DEFAULT_JOBS,
79
+ batch_size: Annotated[
80
+ int,
81
+ typer.Option(min=1, help="Candidates per critic call (calibrated at 5; critique uses 2)."),
82
+ ] = DEFAULT_CRITIC_BATCH,
83
+ window_chars: Annotated[
84
+ int, typer.Option(min=1, help="Characters of document per extraction call.")
85
+ ] = DEFAULT_WINDOW_CHARS,
86
+ tier: Annotated[Tier, typer.Option(help="Recorded, never rendered.")] = Tier.T4,
87
+ kind: Annotated[EvidenceKind, typer.Option(help="Recorded, never rendered.")] = (
88
+ EvidenceKind.DOCUMENTARY
89
+ ),
90
+ as_: Annotated[
91
+ str | None,
92
+ typer.Option("--as", help="Force a tracker or Confluence format instead of detecting it."),
93
+ ] = None,
94
+ max_files: Annotated[int, typer.Option(min=1, help="Folder cap.")] = DEFAULT_MAX_FILES,
95
+ ) -> None:
96
+ """Score a document: quoted findings per dimension, as Markdown and one HTML file."""
97
+ chosen = [part.strip() for part in format.split(",") if part.strip()]
98
+ if not chosen or any(part not in _FORMATS for part in chosen):
99
+ raise _fail(f"--format takes {', '.join(_FORMATS)}; got {format!r}")
100
+ forced: SourceFormat | None = None
101
+ if as_ is not None:
102
+ try:
103
+ forced = SourceFormat(as_)
104
+ except ValueError:
105
+ raise _fail(f"--as {as_!r} is not a known format") from None
106
+ model_id = model or Settings().model
107
+ try:
108
+ provider = _make_provider(model_id)
109
+ run = critique_api.critique(
110
+ path,
111
+ provider,
112
+ CritiqueOptions(
113
+ model=model_id, jobs=jobs, batch_size=batch_size, window_chars=window_chars
114
+ ),
115
+ tier=tier,
116
+ kind=kind,
117
+ forced=forced,
118
+ max_files=max_files,
119
+ )
120
+ except (
121
+ FileNotFoundError,
122
+ critique_api.NoReadableInputError,
123
+ MissingCredentialsError,
124
+ ReportIntegrityError,
125
+ ValueError,
126
+ ) as error:
127
+ raise _fail(str(error)) from error
128
+ except Exception as error: # a provider outage, a bug: say what, exit 2
129
+ raise _fail(f"{type(error).__name__}: {error}") from error
130
+
131
+ report = run.report
132
+ stem = path.resolve().stem if path.is_file() else path.resolve().name
133
+ # render everything before writing anything: a failure leaves no partial output
134
+ rendered: list[tuple[Path, str]] = []
135
+ try:
136
+ if "md" in chosen:
137
+ rendered.append((out / f"{stem}.critique.md", render_markdown(report)))
138
+ if "html" in chosen:
139
+ rendered.append((out / f"{stem}.critique.html", render_html(report)))
140
+ out.mkdir(parents=True, exist_ok=True)
141
+ for target, text in rendered:
142
+ target.write_text(text, encoding="utf-8")
143
+ except Exception as error:
144
+ raise _fail(f"{type(error).__name__}: {error}") from error
145
+ written = [target for target, _ in rendered]
146
+ typer.echo(render_summary(report))
147
+ for target in written:
148
+ typer.echo(f"Full report → {target}")
149
+ if report.incomplete:
150
+ raise typer.Exit(EXIT_INCOMPLETE)
151
+
152
+
153
+ @app.command()
154
+ def mcp() -> None:
155
+ """Serve `critique` to an MCP client over stdio (needs `pip install 'probative[mcp]'`)."""
156
+ try:
157
+ from probative.interfaces.mcp_server import serve
158
+ except ModuleNotFoundError as error:
159
+ if error.name is None or not error.name.startswith("mcp"):
160
+ raise
161
+ typer.echo("error: the MCP server needs the extra: pip install 'probative[mcp]'", err=True)
162
+ raise typer.Exit(EXIT_FAILED) from error
163
+ serve()
164
+
165
+
166
+ if __name__ == "__main__": # pragma: no cover
167
+ app()
probative/config.py ADDED
@@ -0,0 +1,76 @@
1
+ """Configuration: environment variables, with `.env` for local development.
2
+
3
+ `.env` is gitignored; `.env.example` documents the keys. Loading configuration
4
+ must never crash on an empty environment — a missing credential is reported as
5
+ a typed error at the point it is needed, not as a startup failure. This is
6
+ what lets the default test suite run with zero LLM credentials present (S3).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Final
12
+
13
+ from pydantic import SecretStr
14
+ from pydantic_settings import BaseSettings, SettingsConfigDict
15
+
16
+ # OI2 (resolved in PB5): the model every *published* eval number is measured on,
17
+ # so catch rate and false-positive rate are comparable across releases. A module
18
+ # constant, deliberately not a `Settings` field: an env var or a change to the
19
+ # `Settings.model` default must not silently move a published number. Per-provider
20
+ # variance against this reference is reported by PB32.
21
+ REFERENCE_MODEL: Final = "anthropic/claude-sonnet-5"
22
+
23
+
24
+ class MissingCredentialsError(Exception):
25
+ """Raised when a provider is used but no credential for it is configured.
26
+
27
+ Not raised at settings-load time — only when something actually needs
28
+ the credential. Loading `Settings()` with no environment variables set
29
+ must always succeed.
30
+ """
31
+
32
+ def __init__(self, provider: str) -> None:
33
+ self.provider = provider
34
+ super().__init__(
35
+ f"No credentials configured for provider {provider!r}. "
36
+ f"Set the corresponding *_API_KEY environment variable "
37
+ f"(see .env.example)."
38
+ )
39
+
40
+
41
+ class Settings(BaseSettings):
42
+ """Process configuration, loaded from the environment and `.env`.
43
+
44
+ Every field is optional at load time. A run that needs a provider it has
45
+ no key for fails loudly and specifically via `credential_for`, not via an
46
+ attribute access on `None`.
47
+ """
48
+
49
+ model_config = SettingsConfigDict(
50
+ env_file=".env",
51
+ env_file_encoding="utf-8",
52
+ extra="ignore",
53
+ )
54
+
55
+ anthropic_api_key: SecretStr | None = None
56
+ openai_api_key: SecretStr | None = None
57
+ gemini_api_key: SecretStr | None = None
58
+
59
+ # The default model for the provider adapter (`probative.llm`).
60
+ model: str = "anthropic/claude-sonnet-5"
61
+
62
+ def credential_for(self, provider: str) -> SecretStr:
63
+ """Return the configured credential for `provider`.
64
+
65
+ Raises `MissingCredentialsError` if it is not set — the only place
66
+ an unconfigured provider becomes an error.
67
+ """
68
+ credentials: dict[str, SecretStr | None] = {
69
+ "anthropic": self.anthropic_api_key,
70
+ "openai": self.openai_api_key,
71
+ "gemini": self.gemini_api_key,
72
+ }
73
+ value = credentials.get(provider)
74
+ if value is None:
75
+ raise MissingCredentialsError(provider)
76
+ return value
@@ -0,0 +1 @@
1
+ """Graph schema, validators and the invariants (I1-I9). mypy strict."""
@@ -0,0 +1,165 @@
1
+ """Typed extraction candidates (PROBATIVE_PHASE_SPECS.md, PB4).
2
+
3
+ A candidate is *not* a graph node (PB10) and *not* a claim of truth: it is a
4
+ statement a document makes, located by an `EvidenceSpan`. Nothing here can
5
+ carry a number a model might have authored (I4) — the only integers
6
+ reachable from a candidate are the span's character offsets.
7
+
8
+ Tier and evidence kind are deliberately absent: they live on `Source` and are
9
+ reached through `evidence.source_id` (single source of record, CLAUDE.md).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ from enum import StrEnum
16
+ from typing import Annotated, Literal
17
+
18
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
19
+
20
+ from probative.core.evidence import EvidenceSpan
21
+ from probative.llm.types import TokenUsage
22
+
23
+
24
+ class CandidateKind(StrEnum):
25
+ CLAIM = "claim"
26
+ NEED = "need"
27
+ STORY = "story"
28
+ CONSTRAINT = "constraint"
29
+ DEPENDENCY = "dependency"
30
+ SEGMENT = "segment"
31
+ FORECAST = "forecast"
32
+
33
+
34
+ def candidate_id(kind: CandidateKind, span: EvidenceSpan) -> str:
35
+ """The id is derived from what the candidate *is*, never authored."""
36
+ digest = hashlib.sha256(f"{span.source_id}:{span.start}:{span.end}".encode()).hexdigest()
37
+ return f"cand_{kind.value}_{digest[:12]}"
38
+
39
+
40
+ class _CandidateBase(BaseModel):
41
+ model_config = ConfigDict(frozen=True)
42
+
43
+ id: str
44
+ evidence: EvidenceSpan
45
+
46
+ @property
47
+ def text(self) -> str:
48
+ return self.evidence.text
49
+
50
+ @model_validator(mode="after")
51
+ def _span_is_coherent(self) -> _CandidateBase:
52
+ ev = self.evidence
53
+ if not (0 <= ev.start < ev.end) or len(ev.text) != ev.end - ev.start:
54
+ raise ValueError(
55
+ f"span ({ev.start}, {ev.end}) is not coherent with text of length {len(ev.text)}"
56
+ )
57
+ return self
58
+
59
+ @model_validator(mode="after")
60
+ def _id_is_derived(self) -> _CandidateBase:
61
+ kind = getattr(self, "kind", None)
62
+ if isinstance(kind, CandidateKind) and self.id != candidate_id(kind, self.evidence):
63
+ raise ValueError(f"id {self.id!r} is not the derived id for this kind and span")
64
+ return self
65
+
66
+
67
+ class ClaimCandidate(_CandidateBase):
68
+ kind: Literal[CandidateKind.CLAIM] = CandidateKind.CLAIM
69
+
70
+
71
+ class NeedCandidate(_CandidateBase):
72
+ kind: Literal[CandidateKind.NEED] = CandidateKind.NEED
73
+
74
+
75
+ class StoryCandidate(_CandidateBase):
76
+ kind: Literal[CandidateKind.STORY] = CandidateKind.STORY
77
+
78
+
79
+ class ConstraintCandidate(_CandidateBase):
80
+ kind: Literal[CandidateKind.CONSTRAINT] = CandidateKind.CONSTRAINT
81
+
82
+
83
+ class DependencyCandidate(_CandidateBase):
84
+ kind: Literal[CandidateKind.DEPENDENCY] = CandidateKind.DEPENDENCY
85
+
86
+
87
+ class SegmentCandidate(_CandidateBase):
88
+ """A statement that names or defines the group of customers the document
89
+ says the product is for, in the document's own words (PB6-p2). It makes no
90
+ claim that the group is a real segment; `SegmentSkeptic` asks that."""
91
+
92
+ kind: Literal[CandidateKind.SEGMENT] = CandidateKind.SEGMENT
93
+
94
+
95
+ class ForecastCandidate(_CandidateBase):
96
+ """A statement in which the document predicts what will happen to customers,
97
+ the market or competitors as a result of something, in its own words (PB8).
98
+ It makes no claim that the prediction is sound; `RedTeam` asks that."""
99
+
100
+ kind: Literal[CandidateKind.FORECAST] = CandidateKind.FORECAST
101
+
102
+
103
+ Candidate = Annotated[
104
+ ClaimCandidate
105
+ | NeedCandidate
106
+ | StoryCandidate
107
+ | ConstraintCandidate
108
+ | DependencyCandidate
109
+ | SegmentCandidate
110
+ | ForecastCandidate,
111
+ Field(discriminator="kind"),
112
+ ]
113
+
114
+
115
+ class RejectReason(StrEnum):
116
+ NOT_FOUND = "not_found"
117
+ EMPTY = "empty"
118
+ TOO_LONG = "too_long"
119
+ DUPLICATE = "duplicate"
120
+
121
+
122
+ class RejectedQuote(BaseModel):
123
+ """A quote the model proposed that could not become a candidate."""
124
+
125
+ kind: CandidateKind
126
+ quote: str
127
+ reason: RejectReason
128
+
129
+
130
+ class ExtractionResult(BaseModel):
131
+ source_id: str
132
+ claims: list[ClaimCandidate] = Field(default_factory=list)
133
+ needs: list[NeedCandidate] = Field(default_factory=list)
134
+ stories: list[StoryCandidate] = Field(default_factory=list)
135
+ constraints: list[ConstraintCandidate] = Field(default_factory=list)
136
+ dependencies: list[DependencyCandidate] = Field(default_factory=list)
137
+ segments: list[SegmentCandidate] = Field(default_factory=list)
138
+ forecasts: list[ForecastCandidate] = Field(default_factory=list)
139
+ rejected: list[RejectedQuote] = Field(default_factory=list)
140
+ usage: TokenUsage = Field(default_factory=lambda: TokenUsage(input_tokens=0, output_tokens=0))
141
+
142
+ def candidates(self) -> list[Candidate]:
143
+ """Every candidate, in document order."""
144
+ flat: list[Candidate] = [
145
+ *self.claims,
146
+ *self.needs,
147
+ *self.stories,
148
+ *self.constraints,
149
+ *self.dependencies,
150
+ *self.segments,
151
+ *self.forecasts,
152
+ ]
153
+ return sorted(flat, key=lambda c: (c.evidence.start, c.evidence.end, c.kind.value))
154
+
155
+
156
+ class ExtractionFailedError(Exception):
157
+ """A model kept returning output that does not match the requested
158
+ schema, after the one repair retry."""
159
+
160
+ def __init__(self, source_id: str, pass_name: str) -> None:
161
+ self.source_id = source_id
162
+ self.pass_name = pass_name
163
+ super().__init__(
164
+ f"{source_id}: pass {pass_name!r} returned malformed output after a repair retry"
165
+ )
@@ -0,0 +1,113 @@
1
+ """Critic framework types (docs/DESIGN.md §9.1, §13; PROBATIVE_PHASE_SPECS.md
2
+ PB3): the rubric shape a critic is configured from (S2), and what a critic
3
+ returns.
4
+
5
+ A `Critic` is not an `Agent` (S1): it never proposes a patch and never
6
+ touches the graph. It only returns `Finding`s, which the runtime's critic
7
+ fan-out (PB12) attaches to a patch under review.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from enum import StrEnum
13
+ from pathlib import Path
14
+
15
+ from pydantic import BaseModel, Field
16
+
17
+ from probative.core.evidence import EvidenceSpan
18
+
19
+
20
+ class Severity(StrEnum):
21
+ """How much authority a Finding carries (docs/DESIGN.md §9.1)."""
22
+
23
+ BLOCK = "block"
24
+ WARN = "warn"
25
+ NOTE = "note"
26
+
27
+
28
+ class RubricCheck(BaseModel):
29
+ """One named check within a rubric (S2).
30
+
31
+ `severity` is optional (added in PB5): unset, the check inherits the
32
+ rubric's severity; set, it overrides it, so a rubric can say "block on
33
+ this check, warn on the rest" as data rather than in critic code.
34
+ """
35
+
36
+ id: str = Field(min_length=1)
37
+ description: str = Field(min_length=1)
38
+ examples_bad: list[str] = Field(default_factory=list)
39
+ examples_good: list[str] = Field(default_factory=list)
40
+ remedy: str = Field(min_length=1)
41
+ severity: Severity | None = None
42
+ # Optional (PB8): the rubric's own sentence for what would have to be true for the
43
+ # statement to hold, with a literal `{quote}` placeholder. Rubric data, not model
44
+ # output (I4/I5); never shown to the model.
45
+ must_be_true: str | None = None
46
+
47
+
48
+ class Rubric(BaseModel):
49
+ """A critic's configuration, loaded from YAML (S2).
50
+
51
+ `clean_fixtures`/`defect_fixtures` are globs relative to the rubric
52
+ file's own directory, resolved by `probative.critics.rubric`.
53
+ """
54
+
55
+ id: str = Field(min_length=1)
56
+ severity: Severity
57
+ invariant: str | None = None
58
+ applies_to: list[str] = Field(default_factory=list)
59
+ checks: list[RubricCheck] = Field(min_length=1)
60
+ clean_fixtures: str = Field(min_length=1)
61
+ defect_fixtures: str = Field(min_length=1)
62
+
63
+
64
+ class Finding(BaseModel):
65
+ """What a critic emits for one violation of one of its rubric's checks."""
66
+
67
+ critic_id: str
68
+ check_id: str
69
+ severity: Severity
70
+ invariant: str | None
71
+ message: str
72
+ remedy: str
73
+ target_id: str | None = None
74
+ evidence: EvidenceSpan | None = None
75
+
76
+
77
+ class DimensionScore(BaseModel):
78
+ """One rubric's aggregate result over a batch of Findings
79
+ (`probative.critics.scoring.score_dimension`)."""
80
+
81
+ critic_id: str
82
+ invariant: str | None
83
+ blocked: bool
84
+ score: float
85
+ findings: list[Finding]
86
+
87
+
88
+ class RubricError(Exception):
89
+ """Base for rubric-loading failures. Always names the offending file."""
90
+
91
+ def __init__(self, path: Path, message: str) -> None:
92
+ self.path = path
93
+ super().__init__(f"{path}: {message}")
94
+
95
+
96
+ class RubricNotFoundError(RubricError):
97
+ """The rubric file does not exist."""
98
+
99
+
100
+ class MalformedRubricError(RubricError):
101
+ """The rubric file is not valid YAML, is not a mapping at the top
102
+ level, or fails `Rubric`'s schema."""
103
+
104
+
105
+ class UnknownCheckError(ValueError):
106
+ """A critic referenced a `check_id` its own rubric does not declare —
107
+ an authoring bug, not a rubric-loading failure, so it names the critic
108
+ and check rather than a file path."""
109
+
110
+ def __init__(self, critic_id: str, check_id: str) -> None:
111
+ self.critic_id = critic_id
112
+ self.check_id = check_id
113
+ super().__init__(f"{critic_id}: no check {check_id!r} declared in its rubric")
@@ -0,0 +1,158 @@
1
+ """Evidence-model types (docs/DESIGN.md §5.1): tier, kind, Source and
2
+ EvidenceSpan.
3
+
4
+ These are the shapes PB10's graph is built on top of, not the graph itself —
5
+ PB1 has no persistence layer. `Source.id`/`sha256` are pure functions of a
6
+ file's bytes, which is what makes ingestion idempotent (see `probative.ingest`).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import datetime
12
+ from enum import StrEnum
13
+ from pathlib import Path
14
+
15
+ from pydantic import BaseModel
16
+
17
+
18
+ class Tier(StrEnum):
19
+ """How direct a piece of evidence is (docs/DESIGN.md §5.1)."""
20
+
21
+ T1 = "T1"
22
+ T2 = "T2"
23
+ T3 = "T3"
24
+ T4 = "T4"
25
+ T5 = "T5"
26
+
27
+
28
+ class EvidenceKind(StrEnum):
29
+ """What sort of thing a piece of evidence is (docs/DESIGN.md §5.1)."""
30
+
31
+ CUSTOMER = "customer"
32
+ OPERATIONAL = "operational"
33
+ DOCUMENTARY = "documentary"
34
+ SYSTEM = "system"
35
+ DELIVERY = "delivery"
36
+ MARKET = "market"
37
+
38
+
39
+ class SourceFormat(StrEnum):
40
+ PDF = "pdf"
41
+ DOCX = "docx"
42
+ XLSX = "xlsx"
43
+ CSV = "csv"
44
+ MARKDOWN = "markdown"
45
+ TEXT = "text"
46
+ JIRA_CSV = "jira_csv"
47
+ JIRA_HTML = "jira_html"
48
+ JIRA_XML = "jira_xml"
49
+ ADO_CSV = "ado_csv"
50
+ CONFLUENCE_WORD = "confluence_word"
51
+
52
+
53
+ class Locator(BaseModel):
54
+ """A human-meaningful place within a Source.
55
+
56
+ Every field is optional; a given format populates only the ones that
57
+ apply to it (page/line for PDF, sheet/cell for XLSX, heading_path for
58
+ Markdown and DOCX, issue_key/field for the PB2 tracker formats).
59
+ """
60
+
61
+ page: int | None = None
62
+ line: int | None = None
63
+ sheet: str | None = None
64
+ cell: str | None = None
65
+ heading_path: list[str] | None = None
66
+ issue_key: str | None = None
67
+ field: str | None = None
68
+
69
+
70
+ class LocatorRegion(BaseModel):
71
+ """One contiguous, non-overlapping slice of `Source.text`.
72
+
73
+ A Source's regions are sorted by `start` and cover `[0, len(text))`
74
+ with no gaps — `probative.ingest.spans` depends on this invariant.
75
+ """
76
+
77
+ start: int
78
+ end: int
79
+ locator: Locator
80
+
81
+
82
+ class Source(BaseModel):
83
+ """A raw ingested artifact: its bytes, declared tier and kind, and the
84
+ normalised text projection every EvidenceSpan's offsets point into."""
85
+
86
+ id: str
87
+ path: Path
88
+ sha256: str
89
+ format: SourceFormat
90
+ tier: Tier
91
+ kind: EvidenceKind
92
+ ingested_at: datetime
93
+ extractor: str
94
+ extractor_version: str
95
+ text: str
96
+ locator_regions: list[LocatorRegion]
97
+
98
+
99
+ class EvidenceSpan(BaseModel):
100
+ """A located extract — the atom of provenance (I1).
101
+
102
+ Deliberately carries no `source_path`/`format`/`extractor_version`:
103
+ those belong to `Source` alone (single source of record per field).
104
+ """
105
+
106
+ source_id: str
107
+ start: int
108
+ end: int
109
+ text: str
110
+ locator: Locator
111
+
112
+
113
+ class IngestError(Exception):
114
+ """Base for all ingestion failures. Always names the offending file."""
115
+
116
+ def __init__(self, path: Path, message: str) -> None:
117
+ self.path = path
118
+ super().__init__(f"{path}: {message}")
119
+
120
+
121
+ class UnsupportedFormatError(IngestError):
122
+ """The file's extension is not one PB1 recognises."""
123
+
124
+
125
+ class EmptySourceError(IngestError):
126
+ """The file is zero bytes, or (XLSX) every sheet is empty."""
127
+
128
+
129
+ class EncryptedSourceError(IngestError):
130
+ """The file is password-protected and no password was supplied."""
131
+
132
+
133
+ class CorruptSourceError(IngestError):
134
+ """The file cannot be parsed as its declared format."""
135
+
136
+
137
+ class NoTextLayerError(IngestError):
138
+ """A PDF has at least one page with no extractable text (OCR refusal)."""
139
+
140
+
141
+ class MalformedCSVError(IngestError):
142
+ """A CSV row's column count does not match the header's."""
143
+
144
+
145
+ class SpanOutOfRangeError(IngestError):
146
+ """`spans()` was given a range outside the source's text, or start >= end."""
147
+
148
+
149
+ class StaleNormalizationError(IngestError):
150
+ """`reextract()` found that re-ingesting now would use a different
151
+ normalisation version than the one the span's offsets were recorded
152
+ against — those offsets are not guaranteed valid any more."""
153
+
154
+
155
+ class UnrecognisedTrackerFormatError(IngestError):
156
+ """A tracker export (PB2) is missing a column/field its declared
157
+ `SourceFormat` requires — the file does not match the format it was
158
+ told to be ingested as."""