tarel 0.0.1__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 (63) hide show
  1. tarel/__init__.py +5 -0
  2. tarel/__main__.py +3 -0
  3. tarel/annotations/__init__.py +1 -0
  4. tarel/annotations/apply.py +102 -0
  5. tarel/annotations/contracts.py +179 -0
  6. tarel/annotations/review.py +377 -0
  7. tarel/annotations/runner.py +234 -0
  8. tarel/annotations/states.py +40 -0
  9. tarel/annotations/tasks.py +270 -0
  10. tarel/application.py +1015 -0
  11. tarel/cli.py +1689 -0
  12. tarel/connectors/__init__.py +1 -0
  13. tarel/connectors/authoring.py +179 -0
  14. tarel/connectors/contracts.py +389 -0
  15. tarel/connectors/host.py +90 -0
  16. tarel/connectors/sqlite/__init__.py +1 -0
  17. tarel/connectors/sqlite/connector.py +361 -0
  18. tarel/connectors/sqlite/manifest.toml +12 -0
  19. tarel/connectors/sqlite/references/authoring.md +13 -0
  20. tarel/connectors/sqlite/references/dialect.md +7 -0
  21. tarel/connectors/sqlserver/__init__.py +1 -0
  22. tarel/connectors/sqlserver/connector.py +744 -0
  23. tarel/connectors/sqlserver/manifest.toml +12 -0
  24. tarel/connectors/sqlserver/references/authoring.md +30 -0
  25. tarel/connectors/sqlserver/references/dialect.md +20 -0
  26. tarel/context.py +654 -0
  27. tarel/context_output.py +284 -0
  28. tarel/context_packets.py +352 -0
  29. tarel/demo.py +367 -0
  30. tarel/graph/__init__.py +1 -0
  31. tarel/graph/build.py +155 -0
  32. tarel/graph/change_store.py +88 -0
  33. tarel/graph/changes.py +339 -0
  34. tarel/graph/contracts.py +270 -0
  35. tarel/graph/refresh.py +422 -0
  36. tarel/graph/revision.py +18 -0
  37. tarel/graph/store.py +81 -0
  38. tarel/providers/__init__.py +1 -0
  39. tarel/providers/config.py +160 -0
  40. tarel/providers/contracts.py +55 -0
  41. tarel/providers/host.py +13 -0
  42. tarel/providers/openrouter.py +101 -0
  43. tarel/py.typed +1 -0
  44. tarel/relationships/__init__.py +1 -0
  45. tarel/relationships/core.py +439 -0
  46. tarel/retrieval/__init__.py +5 -0
  47. tarel/retrieval/bm25.py +111 -0
  48. tarel/retrieval/contracts.py +78 -0
  49. tarel/retrieval/documents.py +173 -0
  50. tarel/retrieval/index.py +409 -0
  51. tarel/retrieval/local.py +252 -0
  52. tarel/search.py +321 -0
  53. tarel/workspaces/__init__.py +21 -0
  54. tarel/workspaces/contracts.py +346 -0
  55. tarel/workspaces/core.py +318 -0
  56. tarel/workspaces/impact.py +68 -0
  57. tarel/workspaces/store.py +98 -0
  58. tarel-0.0.1.dist-info/METADATA +597 -0
  59. tarel-0.0.1.dist-info/RECORD +63 -0
  60. tarel-0.0.1.dist-info/WHEEL +4 -0
  61. tarel-0.0.1.dist-info/entry_points.txt +2 -0
  62. tarel-0.0.1.dist-info/licenses/LICENSE +18 -0
  63. tarel-0.0.1.dist-info/licenses/THIRD_PARTY_NOTICES.md +26 -0
tarel/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """TAREL: topology, annotation, retrieval, evidence, and lineage."""
2
+
3
+ __version__ = "0.0.1"
4
+
5
+ __all__ = ["__version__"]
tarel/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from tarel.cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1 @@
1
+ """Provider-neutral annotation tasks, proposals, and execution."""
@@ -0,0 +1,102 @@
1
+ """Validate and apply annotation proposals as graph drafts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+
7
+ from tarel.annotations.contracts import AnnotationFailure, AnnotationProposalEnvelope
8
+ from tarel.annotations.review import has_human_review
9
+ from tarel.annotations.tasks import annotation_task_for_target
10
+ from tarel.graph.contracts import AnnotationProvenance, GraphAnnotation, GraphDocument, GraphNode
11
+
12
+
13
+ def apply_annotation_proposal(
14
+ graph: GraphDocument,
15
+ envelope: AnnotationProposalEnvelope,
16
+ *,
17
+ source: str,
18
+ provider: str | None = None,
19
+ model: str | None = None,
20
+ ) -> GraphDocument:
21
+ task = annotation_task_for_target(graph, envelope.target_id)
22
+ if envelope.task_id != task.id:
23
+ raise AnnotationFailure(
24
+ "stale_proposal",
25
+ "Annotation proposal does not match the current graph object.",
26
+ )
27
+ proposal = envelope.annotation
28
+ field_proposals = {item.name: item for item in proposal.fields}
29
+ object_fields = {
30
+ node.label
31
+ for node in graph.nodes
32
+ if node.type == "field" and node.metadata.get("object_id") == envelope.target_id
33
+ }
34
+ if set(field_proposals) != object_fields:
35
+ raise AnnotationFailure(
36
+ "invalid_proposal",
37
+ "Proposal must annotate every supplied field exactly once.",
38
+ )
39
+
40
+ reviewed_nodes = [
41
+ node
42
+ for node in graph.nodes
43
+ if (
44
+ node.id == envelope.target_id
45
+ or (node.type == "field" and node.metadata.get("object_id") == envelope.target_id)
46
+ )
47
+ and (has_human_review(node) or (node.annotation and node.annotation.state == "validated"))
48
+ ]
49
+ if reviewed_nodes:
50
+ raise AnnotationFailure(
51
+ "reviewed_annotation",
52
+ "A new proposal cannot overwrite human-reviewed annotations: "
53
+ + ", ".join(node.label for node in reviewed_nodes),
54
+ )
55
+
56
+ provenance = AnnotationProvenance(source=source, provider=provider, model=model)
57
+ updated_nodes: list[GraphNode] = []
58
+ for node in graph.nodes:
59
+ if node.id == envelope.target_id:
60
+ metadata = dict(node.metadata)
61
+ metadata["grain"] = proposal.grain
62
+ updated_nodes.append(
63
+ replace(
64
+ node,
65
+ metadata=metadata,
66
+ annotation=GraphAnnotation(
67
+ description=proposal.description,
68
+ role=proposal.role,
69
+ synonyms=proposal.synonyms,
70
+ warnings=proposal.warnings,
71
+ confidence=proposal.confidence,
72
+ confidence_reason=proposal.confidence_reason,
73
+ evidence=proposal.evidence,
74
+ provenance=provenance,
75
+ ),
76
+ )
77
+ )
78
+ continue
79
+ field_proposal = field_proposals.get(node.label)
80
+ if node.type == "field" and node.metadata.get("object_id") == envelope.target_id:
81
+ assert field_proposal is not None
82
+ metadata = dict(node.metadata)
83
+ metadata["semantic_type"] = field_proposal.semantic_type
84
+ updated_nodes.append(
85
+ replace(
86
+ node,
87
+ metadata=metadata,
88
+ annotation=GraphAnnotation(
89
+ description=field_proposal.description,
90
+ role=field_proposal.role,
91
+ synonyms=field_proposal.synonyms,
92
+ warnings=field_proposal.warnings,
93
+ confidence=field_proposal.confidence,
94
+ confidence_reason=field_proposal.confidence_reason,
95
+ evidence=field_proposal.evidence,
96
+ provenance=provenance,
97
+ ),
98
+ )
99
+ )
100
+ continue
101
+ updated_nodes.append(node)
102
+ return replace(graph, nodes=tuple(updated_nodes))
@@ -0,0 +1,179 @@
1
+ """Annotation task and proposal contracts shared by agents and API providers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from tarel.graph.contracts import AnnotationEvidence
9
+ from tarel.providers.contracts import StructuredRequest
10
+
11
+
12
+ class AnnotationFailure(RuntimeError):
13
+ def __init__(self, code: str, message: str) -> None:
14
+ super().__init__(message)
15
+ self.code = code
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class AnnotationTask:
20
+ id: str
21
+ graph_name: str
22
+ target_id: str
23
+ target_label: str
24
+ request: StructuredRequest
25
+ protected_values: tuple[str, ...] = field(default=(), repr=False)
26
+
27
+ def to_dict(self) -> dict[str, object]:
28
+ return {
29
+ "graph_name": self.graph_name,
30
+ "id": self.id,
31
+ "messages": [message.to_dict() for message in self.request.messages],
32
+ "response_schema": self.request.schema,
33
+ "schema_name": self.request.schema_name,
34
+ "target_id": self.target_id,
35
+ "target_label": self.target_label,
36
+ "submission_template": {
37
+ "annotation": "<response matching response_schema>",
38
+ "target_id": self.target_id,
39
+ "task_id": self.id,
40
+ },
41
+ }
42
+
43
+
44
+ @dataclass(frozen=True, slots=True)
45
+ class FieldAnnotationProposal:
46
+ name: str
47
+ description: str
48
+ role: str | None
49
+ semantic_type: str | None
50
+ synonyms: tuple[str, ...]
51
+ warnings: tuple[str, ...]
52
+ confidence: float
53
+ confidence_reason: str
54
+ evidence: tuple[AnnotationEvidence, ...]
55
+
56
+
57
+ @dataclass(frozen=True, slots=True)
58
+ class ObjectAnnotationProposal:
59
+ description: str
60
+ role: str | None
61
+ grain: str | None
62
+ synonyms: tuple[str, ...]
63
+ warnings: tuple[str, ...]
64
+ confidence: float
65
+ confidence_reason: str
66
+ evidence: tuple[AnnotationEvidence, ...]
67
+ fields: tuple[FieldAnnotationProposal, ...]
68
+
69
+ @classmethod
70
+ def from_dict(cls, data: dict[str, Any]) -> ObjectAnnotationProposal:
71
+ fields = data.get("fields")
72
+ if not isinstance(fields, list):
73
+ raise AnnotationFailure("invalid_proposal", "Proposal fields must be an array.")
74
+ return cls(
75
+ description=_required_string(data, "description"),
76
+ role=_optional_string(data.get("role")),
77
+ grain=_optional_string(data.get("grain")),
78
+ synonyms=_strings(data.get("synonyms"), "synonyms"),
79
+ warnings=_strings(data.get("warnings"), "warnings"),
80
+ confidence=_confidence(data.get("confidence")),
81
+ confidence_reason=_required_string(data, "confidence_reason"),
82
+ evidence=_evidence(data.get("evidence")),
83
+ fields=tuple(_field(item) for item in fields),
84
+ )
85
+
86
+
87
+ @dataclass(frozen=True, slots=True)
88
+ class AnnotationProposalEnvelope:
89
+ task_id: str
90
+ target_id: str
91
+ annotation: ObjectAnnotationProposal
92
+
93
+ @classmethod
94
+ def from_dict(cls, data: dict[str, Any]) -> AnnotationProposalEnvelope:
95
+ annotation = data.get("annotation")
96
+ if not isinstance(annotation, dict):
97
+ raise AnnotationFailure("invalid_proposal", "Proposal requires an annotation object.")
98
+ return cls(
99
+ task_id=_required_string(data, "task_id"),
100
+ target_id=_required_string(data, "target_id"),
101
+ annotation=ObjectAnnotationProposal.from_dict(annotation),
102
+ )
103
+
104
+
105
+ @dataclass(frozen=True, slots=True)
106
+ class AnnotationRunResult:
107
+ planned: int
108
+ annotated: int
109
+ failed: int
110
+
111
+ def to_dict(self) -> dict[str, int]:
112
+ return {"annotated": self.annotated, "failed": self.failed, "planned": self.planned}
113
+
114
+
115
+ def _field(value: Any) -> FieldAnnotationProposal:
116
+ if not isinstance(value, dict):
117
+ raise AnnotationFailure("invalid_proposal", "Every field proposal must be an object.")
118
+ return FieldAnnotationProposal(
119
+ name=_required_string(value, "name"),
120
+ description=_required_string(value, "description"),
121
+ role=_optional_string(value.get("role")),
122
+ semantic_type=_optional_string(value.get("semantic_type")),
123
+ synonyms=_strings(value.get("synonyms"), "field synonyms"),
124
+ warnings=_strings(value.get("warnings"), "field warnings"),
125
+ confidence=_confidence(value.get("confidence")),
126
+ confidence_reason=_required_string(value, "confidence_reason"),
127
+ evidence=_evidence(value.get("evidence")),
128
+ )
129
+
130
+
131
+ def _evidence(value: Any) -> tuple[AnnotationEvidence, ...]:
132
+ if not isinstance(value, list) or not value:
133
+ raise AnnotationFailure("invalid_proposal", "Proposal evidence must be a non-empty array.")
134
+ result: list[AnnotationEvidence] = []
135
+ for item in value:
136
+ if not isinstance(item, dict):
137
+ raise AnnotationFailure("invalid_proposal", "Every evidence item must be an object.")
138
+ result.append(
139
+ AnnotationEvidence(
140
+ source=_required_string(item, "source"),
141
+ reference=_required_string(item, "reference"),
142
+ value=_optional_string(item.get("value")),
143
+ reason=_optional_string(item.get("reason")),
144
+ )
145
+ )
146
+ return tuple(result)
147
+
148
+
149
+ def _required_string(data: dict[str, Any], key: str) -> str:
150
+ value = data.get(key)
151
+ if not isinstance(value, str) or not value.strip():
152
+ raise AnnotationFailure("invalid_proposal", f"Proposal field must be a string: {key}")
153
+ return value.strip()
154
+
155
+
156
+ def _optional_string(value: Any) -> str | None:
157
+ if value is None:
158
+ return None
159
+ if not isinstance(value, str):
160
+ raise AnnotationFailure("invalid_proposal", "Optional proposal field must be a string.")
161
+ return value.strip() or None
162
+
163
+
164
+ def _strings(value: Any, label: str) -> tuple[str, ...]:
165
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
166
+ raise AnnotationFailure(
167
+ "invalid_proposal",
168
+ f"Proposal {label} must be an array of strings.",
169
+ )
170
+ return tuple(item.strip() for item in value if item.strip())
171
+
172
+
173
+ def _confidence(value: Any) -> float:
174
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
175
+ raise AnnotationFailure("invalid_proposal", "Proposal confidence must be a number.")
176
+ result = float(value)
177
+ if not 0.0 <= result <= 1.0:
178
+ raise AnnotationFailure("invalid_proposal", "Proposal confidence must be between 0 and 1.")
179
+ return result
@@ -0,0 +1,377 @@
1
+ """Human review operations over persisted graph annotations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, replace
6
+ from typing import Any
7
+
8
+ from tarel.annotations.contracts import AnnotationFailure
9
+ from tarel.graph.contracts import (
10
+ ANNOTATION_STATES,
11
+ AnnotationProvenance,
12
+ GraphAnnotation,
13
+ GraphDocument,
14
+ GraphFailure,
15
+ GraphNode,
16
+ )
17
+
18
+ _REVIEW_KEY = "annotation_review"
19
+ _EDITABLE_KEYS = frozenset(
20
+ {"description", "grain", "role", "semantic_type", "synonyms", "warnings"}
21
+ )
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class AnnotationReviewRecord:
26
+ reference: str
27
+ node: GraphNode
28
+
29
+ def to_dict(self) -> dict[str, object]:
30
+ annotation = self.node.annotation
31
+ return {
32
+ "annotation": annotation.to_dict() if annotation else None,
33
+ "grain": _optional_metadata_string(self.node, "grain"),
34
+ "node_id": self.node.id,
35
+ "node_type": self.node.type,
36
+ "reference": self.reference,
37
+ "review": _review_metadata(self.node),
38
+ "semantic_type": _optional_metadata_string(self.node, "semantic_type"),
39
+ }
40
+
41
+
42
+ def annotation_review_record(
43
+ graph: GraphDocument,
44
+ reference: str,
45
+ ) -> AnnotationReviewRecord:
46
+ node, resolved_reference = resolve_annotation_target(graph, reference)
47
+ return AnnotationReviewRecord(reference=resolved_reference, node=node)
48
+
49
+
50
+ def list_annotation_reviews(
51
+ graph: GraphDocument,
52
+ *,
53
+ states: frozenset[str] | None = None,
54
+ ) -> tuple[AnnotationReviewRecord, ...]:
55
+ selected_states = ANNOTATION_STATES if states is None else states
56
+ _validate_states(selected_states)
57
+ object_by_id = {
58
+ node.id: node for node in graph.nodes if node.type in {"table", "view"}
59
+ }
60
+ records: list[AnnotationReviewRecord] = []
61
+ for node in graph.nodes:
62
+ if node.annotation is None or node.annotation.state not in selected_states:
63
+ continue
64
+ if node.type in {"table", "view"}:
65
+ reference = node.label
66
+ elif node.type == "field":
67
+ parent = object_by_id.get(str(node.metadata.get("object_id") or ""))
68
+ if parent is None:
69
+ raise AnnotationFailure(
70
+ "invalid_annotation_target",
71
+ f"Annotated field has no parent object: {node.id}",
72
+ )
73
+ reference = f"{parent.label}.{node.label}"
74
+ else:
75
+ continue
76
+ records.append(AnnotationReviewRecord(reference=reference, node=node))
77
+ return tuple(sorted(records, key=lambda item: (item.reference.casefold(), item.node.id)))
78
+
79
+
80
+ def edit_annotation(
81
+ graph: GraphDocument,
82
+ reference: str,
83
+ patch: dict[str, Any],
84
+ *,
85
+ reason: str,
86
+ ) -> tuple[GraphDocument, AnnotationReviewRecord]:
87
+ node, resolved_reference = resolve_annotation_target(graph, reference)
88
+ annotation = _require_annotation(node)
89
+ clean_reason = _review_reason(reason)
90
+ unknown = set(patch) - _EDITABLE_KEYS
91
+ if unknown:
92
+ raise AnnotationFailure(
93
+ "invalid_annotation_patch",
94
+ f"Unsupported annotation edit fields: {', '.join(sorted(unknown))}",
95
+ )
96
+ if not patch:
97
+ raise AnnotationFailure("invalid_annotation_patch", "Annotation edit cannot be empty.")
98
+ if node.type == "field" and "grain" in patch:
99
+ raise AnnotationFailure(
100
+ "invalid_annotation_patch",
101
+ "grain can only be edited on a table or view annotation.",
102
+ )
103
+ if node.type in {"table", "view"} and "semantic_type" in patch:
104
+ raise AnnotationFailure(
105
+ "invalid_annotation_patch",
106
+ "semantic_type can only be edited on a field annotation.",
107
+ )
108
+
109
+ description = (
110
+ _required_patch_string(patch["description"], "description")
111
+ if "description" in patch
112
+ else annotation.description
113
+ )
114
+ role = _optional_patch_string(patch["role"], "role") if "role" in patch else annotation.role
115
+ synonyms = (
116
+ _patch_strings(patch["synonyms"], "synonyms")
117
+ if "synonyms" in patch
118
+ else annotation.synonyms
119
+ )
120
+ warnings = (
121
+ _patch_strings(patch["warnings"], "warnings")
122
+ if "warnings" in patch
123
+ else annotation.warnings
124
+ )
125
+ metadata = _metadata_with_review(node, action="edit", reason=clean_reason)
126
+ if "grain" in patch:
127
+ metadata["grain"] = _optional_patch_string(patch["grain"], "grain")
128
+ if "semantic_type" in patch:
129
+ metadata["semantic_type"] = _optional_patch_string(
130
+ patch["semantic_type"], "semantic_type"
131
+ )
132
+ updated_node = replace(
133
+ node,
134
+ metadata=metadata,
135
+ annotation=replace(
136
+ annotation,
137
+ description=description,
138
+ role=role,
139
+ synonyms=synonyms,
140
+ warnings=warnings,
141
+ confidence=None,
142
+ confidence_reason=None,
143
+ evidence=(),
144
+ provenance=AnnotationProvenance(source="human"),
145
+ state="draft",
146
+ ),
147
+ )
148
+ updated_graph = _replace_node(graph, updated_node)
149
+ return updated_graph, AnnotationReviewRecord(resolved_reference, updated_node)
150
+
151
+
152
+ def decide_annotation(
153
+ graph: GraphDocument,
154
+ reference: str,
155
+ *,
156
+ state: str,
157
+ reason: str,
158
+ ) -> tuple[GraphDocument, AnnotationReviewRecord]:
159
+ if state not in {"deferred", "rejected", "validated"}:
160
+ raise AnnotationFailure("invalid_annotation_state", f"Unsupported review state: {state}")
161
+ node, resolved_reference = resolve_annotation_target(graph, reference)
162
+ annotation = _require_annotation(node)
163
+ clean_reason = _review_reason(reason)
164
+ action = {"deferred": "defer", "rejected": "reject", "validated": "validate"}[state]
165
+ updated_node = replace(
166
+ node,
167
+ metadata=_metadata_with_review(node, action=action, reason=clean_reason),
168
+ annotation=replace(annotation, state=state),
169
+ )
170
+ updated_graph = _replace_node(graph, updated_node)
171
+ return updated_graph, AnnotationReviewRecord(resolved_reference, updated_node)
172
+
173
+
174
+ def decide_annotation_scope(
175
+ graph: GraphDocument,
176
+ reference: str,
177
+ *,
178
+ state: str,
179
+ reason: str,
180
+ include_fields: bool,
181
+ ) -> tuple[GraphDocument, tuple[AnnotationReviewRecord, ...]]:
182
+ updated, root = decide_annotation(graph, reference, state=state, reason=reason)
183
+ if not include_fields:
184
+ return updated, (root,)
185
+ if root.node.type not in {"table", "view"}:
186
+ raise AnnotationFailure(
187
+ "invalid_annotation_scope",
188
+ "--include-fields requires a table or view target.",
189
+ )
190
+ fields = sorted(
191
+ (
192
+ node
193
+ for node in updated.nodes
194
+ if node.type == "field" and node.metadata.get("object_id") == root.node.id
195
+ ),
196
+ key=lambda node: (int(node.metadata.get("position") or 9999), node.id),
197
+ )
198
+ records = [root]
199
+ for field in fields:
200
+ updated, record = decide_annotation(
201
+ updated,
202
+ field.id,
203
+ state=state,
204
+ reason=reason,
205
+ )
206
+ records.append(record)
207
+ return updated, tuple(records)
208
+
209
+
210
+ def resolve_annotation_target(
211
+ graph: GraphDocument,
212
+ reference: str,
213
+ ) -> tuple[GraphNode, str]:
214
+ normalized = reference.strip().casefold()
215
+ object_by_id = {
216
+ node.id: node for node in graph.nodes if node.type in {"table", "view"}
217
+ }
218
+ matches: list[tuple[GraphNode, str]] = []
219
+ for node in graph.nodes:
220
+ if node.type in {"table", "view"}:
221
+ candidates = {node.id.casefold(), node.label.casefold()}
222
+ name = node.metadata.get("name")
223
+ if isinstance(name, str):
224
+ candidates.add(name.casefold())
225
+ if normalized in candidates:
226
+ matches.append((node, node.label))
227
+ elif node.type == "field":
228
+ parent = object_by_id.get(str(node.metadata.get("object_id") or ""))
229
+ if parent is None:
230
+ continue
231
+ full_reference = f"{parent.label}.{node.label}"
232
+ if normalized in {node.id.casefold(), full_reference.casefold()}:
233
+ matches.append((node, full_reference))
234
+ if len(matches) != 1:
235
+ code = "annotation_target_not_found" if not matches else "ambiguous_annotation_target"
236
+ raise AnnotationFailure(code, f"Could not resolve one annotation target: {reference}")
237
+ return matches[0]
238
+
239
+
240
+ def has_human_review(node: GraphNode) -> bool:
241
+ return _REVIEW_KEY in node.metadata
242
+
243
+
244
+ def _metadata_with_review(node: GraphNode, *, action: str, reason: str) -> dict[str, object]:
245
+ metadata = dict(node.metadata)
246
+ metadata.pop("change_review", None)
247
+ existing = _review_metadata(node)
248
+ if existing is None:
249
+ annotation = _require_annotation(node)
250
+ original = {
251
+ "annotation": annotation.to_dict(),
252
+ "grain": _optional_metadata_string(node, "grain"),
253
+ "semantic_type": _optional_metadata_string(node, "semantic_type"),
254
+ }
255
+ events: list[object] = []
256
+ else:
257
+ original = existing["original"]
258
+ events = list(existing["events"])
259
+ events.append({"action": action, "reason": reason, "source": "human"})
260
+ metadata[_REVIEW_KEY] = {"events": events, "original": original}
261
+ return metadata
262
+
263
+
264
+ def _review_metadata(node: GraphNode) -> dict[str, object] | None:
265
+ value = node.metadata.get(_REVIEW_KEY)
266
+ if value is None:
267
+ return None
268
+ if not isinstance(value, dict):
269
+ raise AnnotationFailure("invalid_annotation_review", "Annotation review must be an object.")
270
+ original = value.get("original")
271
+ events = value.get("events")
272
+ if not isinstance(original, dict) or not isinstance(events, list):
273
+ raise AnnotationFailure(
274
+ "invalid_annotation_review",
275
+ "Annotation review requires original and events values.",
276
+ )
277
+ original_annotation = original.get("annotation")
278
+ if not isinstance(original_annotation, dict):
279
+ raise AnnotationFailure(
280
+ "invalid_annotation_review",
281
+ "Annotation review requires the original annotation proposal.",
282
+ )
283
+ try:
284
+ GraphAnnotation.from_dict(original_annotation)
285
+ except GraphFailure as exc:
286
+ raise AnnotationFailure(
287
+ "invalid_annotation_review",
288
+ "Annotation review contains an invalid original proposal.",
289
+ ) from exc
290
+ for key in ("grain", "semantic_type"):
291
+ if original.get(key) is not None and not isinstance(original.get(key), str):
292
+ raise AnnotationFailure(
293
+ "invalid_annotation_review",
294
+ f"Annotation review {key} must be a string or null.",
295
+ )
296
+ for event in events:
297
+ if (
298
+ not isinstance(event, dict)
299
+ or event.get("action") not in {"defer", "edit", "reject", "validate"}
300
+ or event.get("source") != "human"
301
+ or not isinstance(event.get("reason"), str)
302
+ or not str(event["reason"]).strip()
303
+ ):
304
+ raise AnnotationFailure(
305
+ "invalid_annotation_review",
306
+ "Annotation review contains an invalid event.",
307
+ )
308
+ return value
309
+
310
+
311
+ def _replace_node(graph: GraphDocument, updated: GraphNode) -> GraphDocument:
312
+ return replace(
313
+ graph,
314
+ nodes=tuple(updated if node.id == updated.id else node for node in graph.nodes),
315
+ )
316
+
317
+
318
+ def _require_annotation(node: GraphNode) -> GraphAnnotation:
319
+ if node.annotation is None:
320
+ raise AnnotationFailure(
321
+ "annotation_not_found",
322
+ f"Target does not have an annotation proposal: {node.label}",
323
+ )
324
+ return node.annotation
325
+
326
+
327
+ def _review_reason(value: str) -> str:
328
+ clean = value.strip()
329
+ if not clean:
330
+ raise AnnotationFailure(
331
+ "missing_annotation_review_reason",
332
+ "An annotation review requires a non-empty reason.",
333
+ )
334
+ return clean
335
+
336
+
337
+ def _required_patch_string(value: Any, label: str) -> str:
338
+ if not isinstance(value, str) or not value.strip():
339
+ raise AnnotationFailure(
340
+ "invalid_annotation_patch",
341
+ f"{label} must be a non-empty string.",
342
+ )
343
+ return value.strip()
344
+
345
+
346
+ def _optional_patch_string(value: Any, label: str) -> str | None:
347
+ if value is None:
348
+ return None
349
+ if not isinstance(value, str):
350
+ raise AnnotationFailure(
351
+ "invalid_annotation_patch",
352
+ f"{label} must be a string or null.",
353
+ )
354
+ return value.strip() or None
355
+
356
+
357
+ def _patch_strings(value: Any, label: str) -> tuple[str, ...]:
358
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
359
+ raise AnnotationFailure(
360
+ "invalid_annotation_patch",
361
+ f"{label} must be an array of strings.",
362
+ )
363
+ return tuple(item.strip() for item in value if item.strip())
364
+
365
+
366
+ def _optional_metadata_string(node: GraphNode, key: str) -> str | None:
367
+ value = node.metadata.get(key)
368
+ return value if isinstance(value, str) and value else None
369
+
370
+
371
+ def _validate_states(states: frozenset[str]) -> None:
372
+ unknown = states - ANNOTATION_STATES
373
+ if unknown:
374
+ raise AnnotationFailure(
375
+ "invalid_annotation_state",
376
+ f"Unsupported annotation states: {', '.join(sorted(unknown))}",
377
+ )