parsefabric 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 (51) hide show
  1. parsefabric/__init__.py +79 -0
  2. parsefabric/_json.py +247 -0
  3. parsefabric/_summary_review.py +315 -0
  4. parsefabric/aggregation/__init__.py +30 -0
  5. parsefabric/aggregation/base.py +265 -0
  6. parsefabric/aggregation/codec.py +77 -0
  7. parsefabric/aggregation/evidence.py +667 -0
  8. parsefabric/aggregation/routing.py +161 -0
  9. parsefabric/aggregation/statistical.py +153 -0
  10. parsefabric/builtins/__init__.py +22 -0
  11. parsefabric/builtins/application_log.py +121 -0
  12. parsefabric/builtins/cli_output.py +159 -0
  13. parsefabric/builtins/code_detection.py +228 -0
  14. parsefabric/builtins/json_parser.py +140 -0
  15. parsefabric/builtins/mixed_content.py +655 -0
  16. parsefabric/builtins/python_traceback.py +120 -0
  17. parsefabric/builtins/timestamped_log.py +135 -0
  18. parsefabric/capabilities.py +109 -0
  19. parsefabric/compression.py +118 -0
  20. parsefabric/engine.py +462 -0
  21. parsefabric/errors.py +150 -0
  22. parsefabric/execution/__init__.py +15 -0
  23. parsefabric/execution/_executor.py +102 -0
  24. parsefabric/execution/async_backend.py +69 -0
  25. parsefabric/execution/base.py +143 -0
  26. parsefabric/execution/process_backend.py +41 -0
  27. parsefabric/execution/thread_backend.py +36 -0
  28. parsefabric/models.py +506 -0
  29. parsefabric/observability.py +252 -0
  30. parsefabric/parser/__init__.py +10 -0
  31. parsefabric/parser/_text.py +34 -0
  32. parsefabric/parser/async_parser.py +53 -0
  33. parsefabric/parser/base.py +205 -0
  34. parsefabric/parser/deterministic.py +219 -0
  35. parsefabric/parser/semantic.py +15 -0
  36. parsefabric/partitioning.py +172 -0
  37. parsefabric/patterns/__init__.py +19 -0
  38. parsefabric/patterns/base.py +98 -0
  39. parsefabric/patterns/exact.py +61 -0
  40. parsefabric/patterns/match.py +22 -0
  41. parsefabric/patterns/predicate.py +62 -0
  42. parsefabric/patterns/regex.py +78 -0
  43. parsefabric/patterns/structured.py +59 -0
  44. parsefabric/py.typed +0 -0
  45. parsefabric/registry.py +174 -0
  46. parsefabric/serialization.py +67 -0
  47. parsefabric/summarization.py +563 -0
  48. parsefabric-0.1.0.dist-info/METADATA +208 -0
  49. parsefabric-0.1.0.dist-info/RECORD +51 -0
  50. parsefabric-0.1.0.dist-info/WHEEL +4 -0
  51. parsefabric-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,79 @@
1
+ """ParseFabric: composable parsers with traceable, losslessly aggregated evidence.
2
+
3
+ The package root exports the engine, the result models, the parser
4
+ contracts, aggregation types and errors. Built-in parsers live in
5
+ `parsefabric.builtins`, patterns in `parsefabric.patterns`,
6
+ execution backends in `parsefabric.execution` and lifecycle sinks in
7
+ `parsefabric.observability`.
8
+ """
9
+
10
+ from parsefabric._json import MAX_JSON_DEPTH
11
+ from parsefabric.aggregation import (
12
+ Aggregate,
13
+ Aggregator,
14
+ EvidenceAggregate,
15
+ EvidenceAggregator,
16
+ EvidenceEntry,
17
+ EvidenceGroup,
18
+ RoutingAggregator,
19
+ )
20
+ from parsefabric.capabilities import ParserCapabilities
21
+ from parsefabric.compression import CompressionMetrics, measure_compression
22
+ from parsefabric.engine import ParseEngine
23
+ from parsefabric.errors import (
24
+ CapabilityError,
25
+ ConfigurationError,
26
+ DuplicateParserError,
27
+ IntegrityError,
28
+ ParseError,
29
+ ParseFabricError,
30
+ ParseIssue,
31
+ RegistryError,
32
+ SerializationError,
33
+ SummaryValidationError,
34
+ )
35
+ from parsefabric.models import (
36
+ Evidence,
37
+ ParseContext,
38
+ ParsedEvent,
39
+ ParseResult,
40
+ PatternStatistic,
41
+ )
42
+ from parsefabric.parser import AsyncParser, DeterministicParser, Parser, SemanticParser
43
+
44
+ __version__ = "0.1.0"
45
+
46
+ __all__ = [
47
+ "MAX_JSON_DEPTH",
48
+ "Aggregate",
49
+ "Aggregator",
50
+ "AsyncParser",
51
+ "CapabilityError",
52
+ "CompressionMetrics",
53
+ "ConfigurationError",
54
+ "DeterministicParser",
55
+ "DuplicateParserError",
56
+ "Evidence",
57
+ "EvidenceAggregate",
58
+ "EvidenceAggregator",
59
+ "EvidenceEntry",
60
+ "EvidenceGroup",
61
+ "IntegrityError",
62
+ "ParseContext",
63
+ "ParseEngine",
64
+ "ParseError",
65
+ "ParseFabricError",
66
+ "ParseIssue",
67
+ "ParseResult",
68
+ "ParsedEvent",
69
+ "Parser",
70
+ "ParserCapabilities",
71
+ "PatternStatistic",
72
+ "RegistryError",
73
+ "RoutingAggregator",
74
+ "SemanticParser",
75
+ "SerializationError",
76
+ "SummaryValidationError",
77
+ "__version__",
78
+ "measure_compression",
79
+ ]
parsefabric/_json.py ADDED
@@ -0,0 +1,247 @@
1
+ """Strict JSON helpers shared by ParseFabric's models and wire formats."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from collections import Counter
8
+ from typing import Any, cast
9
+
10
+ type JSONScalar = str | int | float | bool | None
11
+ type JSONValue = JSONScalar | list[JSONValue] | dict[str, JSONValue]
12
+
13
+ MAX_JSON_DEPTH = 256
14
+ """Deepest nesting of lists and objects accepted in a JSON value."""
15
+
16
+ STRUCTURE_DEPTH = MAX_JSON_DEPTH + 16
17
+ """Nesting allowed for package documents that embed JSON values."""
18
+
19
+ _INVALID = (
20
+ "must be JSON-compatible: strings, finite numbers, booleans, null, "
21
+ "lists, and objects with string keys"
22
+ )
23
+ _ENCODER = json.JSONEncoder(ensure_ascii=False, allow_nan=False, separators=(",", ":"))
24
+ _SORTED_ENCODER = json.JSONEncoder(
25
+ ensure_ascii=False, allow_nan=False, separators=(",", ":"), sort_keys=True
26
+ )
27
+ # Validated model values are trees, so these encoders skip cycle checks.
28
+ _CANONICAL_ENCODER = json.JSONEncoder(
29
+ ensure_ascii=False,
30
+ allow_nan=False,
31
+ separators=(",", ":"),
32
+ sort_keys=True,
33
+ check_circular=False,
34
+ )
35
+ _VALIDATED_ENCODER = json.JSONEncoder(
36
+ ensure_ascii=False, allow_nan=False, separators=(",", ":"), check_circular=False
37
+ )
38
+
39
+
40
+ def check_text(value: str, what: str) -> str:
41
+ """Return ``value`` if it is valid Unicode text (no lone surrogates).
42
+
43
+ Args:
44
+ value: Text to check.
45
+ what: Description used in the error message.
46
+
47
+ Returns:
48
+ The unchanged text.
49
+
50
+ Raises:
51
+ ValueError: If the text cannot be encoded as UTF-8.
52
+ """
53
+ if not value.isascii():
54
+ try:
55
+ value.encode("utf-8")
56
+ except UnicodeEncodeError as error:
57
+ raise ValueError(f"{what} must be valid Unicode text") from error
58
+ return value
59
+
60
+
61
+ def _is_scalar(value: object, what: str) -> bool:
62
+ """Validate a JSON scalar; return ``False`` for lists and objects."""
63
+ if value is None or isinstance(value, (bool, int)):
64
+ return True
65
+ if isinstance(value, str):
66
+ check_text(value, what)
67
+ return True
68
+ if isinstance(value, float):
69
+ if not math.isfinite(value):
70
+ raise ValueError(f"{what} must not contain non-finite numbers")
71
+ return True
72
+ if isinstance(value, (list, dict)):
73
+ return False
74
+ raise ValueError(f"{what} {_INVALID}")
75
+
76
+
77
+ def copy_json(
78
+ value: object, what: str = "JSON value", *, max_depth: int = MAX_JSON_DEPTH
79
+ ) -> Any:
80
+ """Validate a JSON-compatible value and return an independent deep copy.
81
+
82
+ Lists and objects are copied so that callers cannot mutate a validated
83
+ value through a reference they still hold. Nesting is limited to
84
+ ``max_depth`` levels, which also rejects self-referencing containers.
85
+
86
+ Args:
87
+ value: Candidate JSON value.
88
+ what: Description used in error messages.
89
+ max_depth: Deepest accepted nesting of lists and objects.
90
+
91
+ Returns:
92
+ A deep copy containing only JSON-compatible values.
93
+
94
+ Raises:
95
+ ValueError: If the value is not JSON-compatible.
96
+ """
97
+ if type(value) is dict:
98
+ flat = _copy_flat_object(value, what)
99
+ if flat is not None:
100
+ return flat
101
+ elif _is_scalar(value, what):
102
+ return value
103
+ root: list[Any] | dict[str, Any] = [] if isinstance(value, list) else {}
104
+ stack: list[tuple[object, list[Any] | dict[str, Any], int]] = [(value, root, 1)]
105
+ while stack:
106
+ source, target, depth = stack.pop()
107
+ if depth > max_depth:
108
+ raise ValueError(f"{what} nests deeper than {max_depth} levels")
109
+ # Every target was created with the same container type as its source.
110
+ if isinstance(target, list):
111
+ for item in cast("list[Any]", source):
112
+ target.append(_copy_child(item, what, stack, depth))
113
+ else:
114
+ for key, item in cast("dict[Any, Any]", source).items():
115
+ if not isinstance(key, str):
116
+ raise ValueError(f"{what} object keys must be strings")
117
+ check_text(key, what)
118
+ target[key] = _copy_child(item, what, stack, depth)
119
+ return root
120
+
121
+
122
+ def _copy_child(
123
+ item: object,
124
+ what: str,
125
+ stack: list[tuple[object, list[Any] | dict[str, Any], int]],
126
+ depth: int,
127
+ ) -> Any:
128
+ """Return a scalar, or an empty container scheduled to receive its copy."""
129
+ if _is_scalar(item, what):
130
+ return item
131
+ child: list[Any] | dict[str, Any] = [] if isinstance(item, list) else {}
132
+ stack.append((item, child, depth + 1))
133
+ return child
134
+
135
+
136
+ def _copy_flat_object(value: dict[Any, Any], what: str) -> dict[str, Any] | None:
137
+ """Copy an object of exact scalar types; ``None`` defers to the general path."""
138
+ result: dict[str, Any] = {}
139
+ for key, item in value.items():
140
+ if type(key) is not str:
141
+ return None
142
+ if not key.isascii():
143
+ check_text(key, what)
144
+ if type(item) is str:
145
+ if not item.isascii():
146
+ check_text(item, what)
147
+ elif not (item is None or type(item) is int or type(item) is bool):
148
+ return None
149
+ result[key] = item
150
+ return result
151
+
152
+
153
+ def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
154
+ result = dict(pairs)
155
+ if len(result) != len(pairs):
156
+ counts = Counter(key for key, _ in pairs)
157
+ duplicates = sorted(key for key, count in counts.items() if count > 1)
158
+ raise ValueError(f"duplicate JSON object key {duplicates[0]!r}")
159
+ return result
160
+
161
+
162
+ def _reject_constant(name: str) -> object:
163
+ raise ValueError(f"{name} is not a JSON number")
164
+
165
+
166
+ def loads(payload: str | bytes | bytearray) -> Any:
167
+ """Decode one strict RFC 8259 JSON document.
168
+
169
+ Bytes must be UTF-8. Duplicate object keys, ``NaN``/``Infinity`` and
170
+ nesting too deep for the decoder are rejected.
171
+
172
+ Args:
173
+ payload: JSON text or UTF-8 bytes.
174
+
175
+ Returns:
176
+ The decoded value.
177
+
178
+ Raises:
179
+ TypeError: If ``payload`` is not text or bytes.
180
+ ValueError: If the payload is not strict JSON.
181
+ """
182
+ if isinstance(payload, (bytes, bytearray)):
183
+ text = bytes(payload).decode("utf-8")
184
+ elif isinstance(payload, str):
185
+ text = payload
186
+ else:
187
+ raise TypeError("JSON payload must be str or bytes")
188
+ try:
189
+ return json.loads(
190
+ text, object_pairs_hook=_unique_object, parse_constant=_reject_constant
191
+ )
192
+ except RecursionError as error:
193
+ raise ValueError("JSON document nests too deeply") from error
194
+
195
+
196
+ def dumps(value: object, *, indent: int | None = None, sort_keys: bool = False) -> str:
197
+ """Encode a JSON-compatible value as compact UTF-8-safe JSON text."""
198
+ if indent is None:
199
+ return (_SORTED_ENCODER if sort_keys else _ENCODER).encode(value)
200
+ return json.dumps(
201
+ value, ensure_ascii=False, allow_nan=False, indent=indent, sort_keys=sort_keys
202
+ )
203
+
204
+
205
+ def canonical_dumps(value: object) -> str:
206
+ """Encode a validated value as canonical JSON: compact with sorted keys."""
207
+ return _CANONICAL_ENCODER.encode(value)
208
+
209
+
210
+ def dumps_validated(value: object) -> str:
211
+ """Encode an already-validated, acyclic value as compact JSON."""
212
+ return _VALIDATED_ENCODER.encode(value)
213
+
214
+
215
+ def require_object(
216
+ value: object,
217
+ what: str,
218
+ required: frozenset[str],
219
+ optional: frozenset[str] = frozenset(),
220
+ ) -> dict[str, Any]:
221
+ """Return ``value`` if it is a JSON object with exactly the allowed keys.
222
+
223
+ Args:
224
+ value: Decoded JSON value.
225
+ what: Description used in error messages.
226
+ required: Keys that must be present.
227
+ optional: Keys that may be present.
228
+
229
+ Returns:
230
+ The object.
231
+
232
+ Raises:
233
+ ValueError: If ``value`` is not an object, lacks a required key, or
234
+ contains an unknown key.
235
+ """
236
+ if not isinstance(value, dict):
237
+ raise ValueError(f"{what} must be a JSON object")
238
+ keys = value.keys()
239
+ if keys == required:
240
+ return value
241
+ missing = required - keys
242
+ if missing:
243
+ raise ValueError(f"{what} is missing {', '.join(sorted(missing))}")
244
+ unknown = keys - required - optional
245
+ if unknown:
246
+ raise ValueError(f"{what} has unknown fields {', '.join(sorted(unknown))}")
247
+ return value
@@ -0,0 +1,315 @@
1
+ """Structured summary claims and deterministic evidence checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from dataclasses import dataclass
8
+
9
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
10
+
11
+ from parsefabric.aggregation.evidence import EvidenceAggregate
12
+
13
+
14
+ class Claim(BaseModel):
15
+ model_config = ConfigDict(extra="forbid", strict=True)
16
+
17
+ text: str = Field(min_length=1)
18
+ evidence_ids: list[str] = Field(min_length=1)
19
+ context_ids: list[str] = Field(default_factory=list)
20
+ occurrences: int = Field(ge=1)
21
+
22
+
23
+ class Claims(BaseModel):
24
+ model_config = ConfigDict(extra="forbid", strict=True)
25
+
26
+ claims: list[Claim]
27
+
28
+
29
+ class Critique(BaseModel):
30
+ model_config = ConfigDict(extra="forbid", strict=True)
31
+
32
+ issues: list[str]
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Fact:
37
+ id: str
38
+ source_id: str | None
39
+ event_type: str
40
+ severity: str | None
41
+ message: object
42
+ occurrences: int
43
+ positions: tuple[int | None, ...]
44
+ timestamps: tuple[tuple[int | None, str], ...]
45
+ timestamps_known: bool
46
+
47
+ def to_dict(self) -> dict[str, object]:
48
+ return {
49
+ "id": self.id,
50
+ "source_id": self.source_id,
51
+ "event_type": self.event_type,
52
+ "severity": self.severity,
53
+ "message": self.message,
54
+ "occurrences": self.occurrences,
55
+ "positions": self.positions,
56
+ "timestamps": self.timestamps,
57
+ "timestamps_known": self.timestamps_known,
58
+ }
59
+
60
+
61
+ def facts_for(aggregates: tuple[EvidenceAggregate, ...]) -> tuple[Fact, ...]:
62
+ """Merge disjoint runs of an identical finding without re-counting text."""
63
+ grouped: dict[str, list[Fact]] = {}
64
+ for aggregate in aggregates:
65
+ for group in aggregate.groups:
66
+ for entry in group.evidence:
67
+ key = json.dumps(
68
+ [
69
+ aggregate.source_id,
70
+ aggregate.parser_name,
71
+ aggregate.parser_version,
72
+ aggregate.event_type,
73
+ group.pattern,
74
+ group.severity,
75
+ entry.message,
76
+ ],
77
+ sort_keys=True,
78
+ )
79
+ grouped.setdefault(key, []).append(
80
+ Fact(
81
+ "",
82
+ aggregate.source_id,
83
+ aggregate.event_type,
84
+ group.severity,
85
+ entry.message,
86
+ entry.occurrences,
87
+ entry.positions,
88
+ tuple(
89
+ (event.evidence.line_number, event.timestamp.isoformat())
90
+ for event in entry.events
91
+ if event.timestamp is not None
92
+ ),
93
+ bool(entry.events),
94
+ )
95
+ )
96
+ facts: list[Fact] = []
97
+ for index, runs in enumerate(grouped.values()):
98
+ first = runs[0]
99
+ positions = tuple(
100
+ sorted(
101
+ (position for run in runs for position in run.positions),
102
+ key=lambda position: position if position is not None else float("inf"),
103
+ )
104
+ )
105
+ facts.append(
106
+ Fact(
107
+ f"e{index}",
108
+ first.source_id,
109
+ first.event_type,
110
+ first.severity,
111
+ first.message,
112
+ sum(run.occurrences for run in runs),
113
+ positions,
114
+ tuple(
115
+ sorted(
116
+ (timestamp for run in runs for timestamp in run.timestamps),
117
+ key=lambda item: (
118
+ item[0] if item[0] is not None else float("inf"),
119
+ item[1],
120
+ ),
121
+ )
122
+ ),
123
+ all(run.timestamps_known for run in runs),
124
+ )
125
+ )
126
+ return tuple(facts)
127
+
128
+
129
+ _CLOCK = re.compile(r"\b\d{1,2}:\d{2}(?::\d{2})?\b")
130
+ _CITATION = re.compile(r"\[(?:L?\d|lines?\b)", re.IGNORECASE)
131
+ _TIME_ASSERTION = re.compile(r"\b(?:untimestamped|timestamped)\b", re.IGNORECASE)
132
+ _NUMBER = re.compile(r"(?<!\w)[+-]?\d+(?:\.\d+)?(?!\w)")
133
+
134
+
135
+ def check_claims(text: str, facts: tuple[Fact, ...]) -> tuple[Claims, list[str]]:
136
+ """Check drafted claims against the facts deterministically.
137
+
138
+ Returns the parsed claims (empty when the draft is not valid JSON for the
139
+ schema) and the issues that must be repaired before critique.
140
+ """
141
+ try:
142
+ claims = Claims.model_validate_json(text)
143
+ except ValidationError:
144
+ return Claims(claims=[]), [
145
+ "Return valid JSON matching the supplied Claims schema."
146
+ ]
147
+ by_id = {fact.id: fact for fact in facts}
148
+ used: set[str] = set()
149
+ issues: list[str] = []
150
+ for number, claim in enumerate(claims.claims, 1):
151
+ ids = set(claim.evidence_ids)
152
+ context_ids = set(claim.context_ids)
153
+ if len(ids) != len(claim.evidence_ids):
154
+ issues.append(f"Claim {number}: duplicate evidence IDs.")
155
+ if not ids <= by_id.keys():
156
+ issues.append(f"Claim {number}: unknown evidence IDs.")
157
+ continue
158
+ if not context_ids <= by_id.keys():
159
+ issues.append(f"Claim {number}: unknown context IDs.")
160
+ continue
161
+ if len(context_ids) != len(claim.context_ids) or ids & context_ids:
162
+ issues.append(f"Claim {number}: duplicate context references.")
163
+ if ids & used:
164
+ issues.append(f"Claim {number}: evidence counted in more than one claim.")
165
+ used.update(ids)
166
+ selected = [by_id[id_] for id_ in claim.evidence_ids]
167
+ support = [*selected, *(by_id[id_] for id_ in claim.context_ids)]
168
+ if any(fact.event_type == "fence" for fact in support):
169
+ issues.append(f"Claim {number}: fence delimiters cannot support claims.")
170
+ if claim.occurrences != sum(fact.occurrences for fact in selected):
171
+ issues.append(f"Claim {number}: occurrences do not match cited evidence.")
172
+ if not claim.text.strip():
173
+ issues.append(f"Claim {number}: text must not be blank.")
174
+ if (
175
+ _CLOCK.search(claim.text)
176
+ or _CITATION.search(claim.text)
177
+ or _TIME_ASSERTION.search(claim.text)
178
+ ):
179
+ issues.append(
180
+ f"Claim {number}: timestamps and citations belong to the renderer, "
181
+ "not claim text."
182
+ )
183
+ supplied_numbers = {
184
+ value
185
+ for fact in support
186
+ for value in _NUMBER.findall(json.dumps(fact.message))
187
+ }
188
+ if set(_NUMBER.findall(claim.text)) - supplied_numbers:
189
+ issues.append(
190
+ f"Claim {number}: numeric values are absent from cited evidence."
191
+ )
192
+ required = {
193
+ fact.id
194
+ for fact in facts
195
+ if (fact.severity or "").upper()
196
+ in {"ERROR", "WARN", "WARNING", "CRITICAL", "FATAL"}
197
+ and fact.event_type != "fence"
198
+ }
199
+ if required - used:
200
+ issues.append("Include every error/warning finding with its exact total.")
201
+ return claims, issues
202
+
203
+
204
+ def render_claims(
205
+ documents: list[tuple[Claims, tuple[Fact, ...]]],
206
+ ) -> str:
207
+ """Render checked counts and exact positions without another model call."""
208
+ rows: list[tuple[str, int, str]] = []
209
+ occurrences: list[tuple[str, int, int, str]] = []
210
+ for document, facts in documents:
211
+ by_id = {fact.id: fact for fact in facts}
212
+ selected_ids = {id_ for claim in document.claims for id_ in claim.evidence_ids}
213
+ complete = [
214
+ *document.claims,
215
+ *(
216
+ Claim(
217
+ text="Source record.",
218
+ evidence_ids=[fact.id],
219
+ occurrences=fact.occurrences,
220
+ )
221
+ for fact in facts
222
+ if fact.id not in selected_ids and fact.event_type != "fence"
223
+ ),
224
+ ]
225
+ for claim in complete:
226
+ selected = [by_id[id_] for id_ in claim.evidence_ids]
227
+ context = [by_id[id_] for id_ in claim.context_ids]
228
+ citations: list[str] = []
229
+ timestamps: list[str] = []
230
+ for fact in selected:
231
+ message = json.dumps(fact.message, ensure_ascii=False, allow_nan=False)
232
+ timestamps_by_position: dict[int | None, list[str]] = {}
233
+ for position, timestamp in fact.timestamps:
234
+ timestamps_by_position.setdefault(position, []).append(timestamp)
235
+ positions = ", ".join(
236
+ str(position) if position is not None else "unknown"
237
+ for position in fact.positions
238
+ )
239
+ source = json.dumps(fact.source_id, ensure_ascii=False)
240
+ citations.append(f"source {source}, lines {positions}")
241
+ timestamps.extend(
242
+ f"line {position}: {value}" for position, value in fact.timestamps
243
+ )
244
+ for position in fact.positions:
245
+ if position is None:
246
+ continue
247
+ occurrence = (
248
+ f"- [source {source}, line {position}] Recorded evidence: "
249
+ f"{message}."
250
+ )
251
+ recorded = timestamps_by_position.get(position, [])
252
+ if recorded:
253
+ occurrence += (
254
+ " Recorded timestamps: " + "; ".join(recorded) + "."
255
+ )
256
+ occurrences.append(
257
+ (fact.source_id or "", position, len(rows), occurrence)
258
+ )
259
+ count_label = (
260
+ ("occurrence" if claim.occurrences == 1 else "occurrences")
261
+ if len(selected) == 1
262
+ else "supporting records"
263
+ )
264
+ row = (
265
+ f"- {claim.text.strip()} **{claim.occurrences} "
266
+ f"{count_label} total** "
267
+ f"[{'; '.join(citations)}]."
268
+ )
269
+ messages = [
270
+ json.dumps(fact.message, ensure_ascii=False, allow_nan=False)
271
+ for fact in selected
272
+ ]
273
+ row += " Recorded evidence: " + "; ".join(messages) + "."
274
+ if context:
275
+ context_messages = [
276
+ f"source {json.dumps(fact.source_id, ensure_ascii=False)}, lines "
277
+ + ", ".join(
278
+ str(position) if position is not None else "unknown"
279
+ for position in fact.positions
280
+ )
281
+ + ": "
282
+ + json.dumps(fact.message, ensure_ascii=False, allow_nan=False)
283
+ for fact in context
284
+ ]
285
+ row += (
286
+ " Context evidence (not additional occurrences): "
287
+ + "; ".join(context_messages)
288
+ + "."
289
+ )
290
+ if timestamps:
291
+ row += " Recorded timestamps: " + "; ".join(timestamps) + "."
292
+ first = min(
293
+ (
294
+ position
295
+ for fact in selected
296
+ for position in fact.positions
297
+ if position is not None
298
+ ),
299
+ default=0,
300
+ )
301
+ rows.append((selected[0].source_id or "", first, row))
302
+ text = "\n".join(row for _, _, row in sorted(rows, key=lambda row: row[:2]))
303
+ ordered = sorted(occurrences, key=lambda item: item[:2])
304
+ visited: set[int] = set()
305
+ previous: int | None = None
306
+ interleaved = False
307
+ for _, _, owner, _ in ordered:
308
+ if owner != previous and owner in visited:
309
+ interleaved = True
310
+ visited.add(owner)
311
+ previous = owner
312
+ if interleaved:
313
+ text += "\n\n### Source-order occurrence timeline\n"
314
+ text += "\n".join(row for _, _, _, row in ordered)
315
+ return text
@@ -0,0 +1,30 @@
1
+ """Package-managed aggregation: lossless grouped evidence and lossy statistics."""
2
+
3
+ from parsefabric.aggregation.base import Aggregate, Aggregator, CountAggregate
4
+ from parsefabric.aggregation.codec import FORMAT
5
+ from parsefabric.aggregation.evidence import (
6
+ EvidenceAggregate,
7
+ EvidenceAggregator,
8
+ EvidenceEntry,
9
+ EvidenceGroup,
10
+ canonical_event,
11
+ default_event_message,
12
+ )
13
+ from parsefabric.aggregation.routing import RoutingAggregator
14
+ from parsefabric.aggregation.statistical import EventAccumulator, EventAggregator
15
+
16
+ __all__ = [
17
+ "FORMAT",
18
+ "Aggregate",
19
+ "Aggregator",
20
+ "CountAggregate",
21
+ "EventAccumulator",
22
+ "EventAggregator",
23
+ "EvidenceAggregate",
24
+ "EvidenceAggregator",
25
+ "EvidenceEntry",
26
+ "EvidenceGroup",
27
+ "RoutingAggregator",
28
+ "canonical_event",
29
+ "default_event_message",
30
+ ]