evidattice 0.5.25__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 (48) hide show
  1. evidattice/__init__.py +11 -0
  2. evidattice/__main__.py +5 -0
  3. evidattice/_artifacts.py +498 -0
  4. evidattice/_capture.py +429 -0
  5. evidattice/_config.py +90 -0
  6. evidattice/_inspect_checks.py +267 -0
  7. evidattice/_inspect_common.py +400 -0
  8. evidattice/_inspect_diagnostics.py +253 -0
  9. evidattice/_inspect_gate.py +259 -0
  10. evidattice/_inspect_navigation.py +477 -0
  11. evidattice/_inspect_query.py +178 -0
  12. evidattice/_inspect_records.py +136 -0
  13. evidattice/_inspect_relations.py +808 -0
  14. evidattice/_inspect_slice.py +302 -0
  15. evidattice/_inspect_text.py +138 -0
  16. evidattice/_logging.py +13 -0
  17. evidattice/_mcp_inspect.py +166 -0
  18. evidattice/_proxy.py +503 -0
  19. evidattice/_recorder.py +741 -0
  20. evidattice/_recording_path.py +26 -0
  21. evidattice/_snapshot.py +197 -0
  22. evidattice/_storage.py +444 -0
  23. evidattice/_types.py +131 -0
  24. evidattice/_values.py +307 -0
  25. evidattice/cli.py +364 -0
  26. evidattice/demo.py +101 -0
  27. evidattice/easy.py +674 -0
  28. evidattice/inspect.py +10 -0
  29. evidattice/integrations/__init__.py +1 -0
  30. evidattice/integrations/_common.py +141 -0
  31. evidattice/integrations/_mcp_capture.py +164 -0
  32. evidattice/integrations/_mcp_native.py +48 -0
  33. evidattice/integrations/_model_capture.py +286 -0
  34. evidattice/integrations/_model_stream.py +300 -0
  35. evidattice/integrations/anyllm_ollama.py +107 -0
  36. evidattice/integrations/mcp_client.py +46 -0
  37. evidattice/integrations/mcp_session.py +64 -0
  38. evidattice/integrations/mcp_session_legacy.py +102 -0
  39. evidattice/integrations/openai_chat.py +75 -0
  40. evidattice/schema.sql +269 -0
  41. evidattice/testing.py +35 -0
  42. evidattice-0.5.25.dist-info/METADATA +280 -0
  43. evidattice-0.5.25.dist-info/RECORD +48 -0
  44. evidattice-0.5.25.dist-info/WHEEL +5 -0
  45. evidattice-0.5.25.dist-info/entry_points.txt +2 -0
  46. evidattice-0.5.25.dist-info/licenses/LICENSE +201 -0
  47. evidattice-0.5.25.dist-info/licenses/NOTICE +7 -0
  48. evidattice-0.5.25.dist-info/top_level.txt +1 -0
evidattice/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """An SDK-independent capture core. Optional integrations live in their own modules."""
2
+ import logging
3
+
4
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
5
+
6
+ from ._recorder import Recorder
7
+ from ._types import RecorderError
8
+ from ._values import MISSING
9
+
10
+ __version__ = "0.5.25"
11
+ __all__ = ["Recorder", "RecorderError", "MISSING"]
evidattice/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Use the same installed JSON CLI through python -m evidattice."""
2
+ from .cli import main
3
+
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,498 @@
1
+ """Retained artifact and ordered-request preparation, without database writes."""
2
+
3
+ import hashlib
4
+ import json
5
+ import uuid
6
+
7
+ from ._config import boolean, fields
8
+ from ._values import (
9
+ MISSING, InvalidInput, MESSAGE_PROJECTION, canonical_bytes, freeze, json_text,
10
+ original_digest, pointer_get, pointer_tokens, text_digest,
11
+ validate_control, validate_pointer,
12
+ )
13
+
14
+
15
+ def _ordered(value, name):
16
+ if type(value) is not list:
17
+ raise InvalidInput(name + " must be an ordered list")
18
+ return value
19
+
20
+
21
+ def _encoded(text):
22
+ try:
23
+ return text.encode("utf-8")
24
+ except UnicodeError as error:
25
+ raise InvalidInput("retained JSON must be valid UTF-8") from error
26
+
27
+
28
+ def _artifact_row(run_id, fields, identity=None):
29
+ """Preserve the reference field order and identity encoding exactly."""
30
+ material = fields if identity is None else [identity, fields]
31
+ prefix = run_id + (":" if identity is None else ":m:")
32
+ artifact_id = prefix + hashlib.sha256(_encoded(json_text(material))).hexdigest()
33
+ return {"artifact_id": artifact_id, **fields}
34
+
35
+
36
+ def _retention(capture, override):
37
+ if override is None:
38
+ return {"policy_id": capture, "retained": MISSING, "redacted": False,
39
+ "truncated": False,
40
+ "omitted_reason": "capture_metadata" if capture == "metadata" else None}
41
+ fields(override, ("policy_id", "retained", "redacted", "truncated", "omitted_reason"),
42
+ ("policy_id",))
43
+ policy = validate_control(override["policy_id"], "retention policy", nonempty=True)
44
+ retained = override.get("retained", MISSING)
45
+ omitted = override.get("omitted_reason")
46
+ if retained is MISSING:
47
+ validate_control(omitted, "omitted reason", nonempty=True)
48
+ elif omitted is not None:
49
+ raise InvalidInput("retained content cannot also have an omission reason")
50
+ return {"policy_id": policy, "retained": retained,
51
+ "redacted": boolean(override.get("redacted", False), "redacted"),
52
+ "truncated": boolean(override.get("truncated", False), "truncated"),
53
+ "omitted_reason": "capture_metadata" if capture == "metadata" else omitted}
54
+
55
+
56
+ def _retained_request(original, policy, message_path, fields):
57
+ """Keep the existing positional request contract for core and policy preflight."""
58
+ retained = policy["retained"]
59
+ if retained is MISSING:
60
+ return original
61
+ for path in (message_path, *fields):
62
+ pointer_get(retained, path)
63
+ originals = pointer_get(original, message_path)
64
+ replacements = pointer_get(retained, message_path)
65
+ if type(replacements) is not list or len(replacements) != len(originals):
66
+ raise InvalidInput("retention must preserve every message array position")
67
+ original_encodings = [canonical_bytes(item) for item in originals]
68
+ original_encoding_set = set(original_encodings)
69
+ for index, replacement in enumerate(replacements):
70
+ encoding = canonical_bytes(replacement)
71
+ if encoding != original_encodings[index] and encoding in original_encoding_set:
72
+ raise InvalidInput("retention cannot reorder original messages")
73
+ return retained
74
+
75
+
76
+ def _retained_text(original, original_text, policy):
77
+ if policy["omitted_reason"] is not None:
78
+ return None
79
+ if original is MISSING:
80
+ return None
81
+ retained = policy["retained"]
82
+ return original_text if retained is MISSING or retained is original else json_text(retained)
83
+
84
+
85
+ def _fields(run_id, original, policy, representation):
86
+ original_text = None if original is MISSING else json_text(original)
87
+ original_data = None if original_text is None else _encoded(original_text)
88
+ observed_bytes = None if original_data is None else len(original_data)
89
+ body = _retained_text(original, original_text, policy)
90
+ data = b"" if body is None else (original_data if body is original_text else _encoded(body))
91
+ return {"run_id": run_id, "media_type": "application/json", "representation": representation,
92
+ "body_text": body,
93
+ "stored_sha256": None if body is None else hashlib.sha256(data).hexdigest(),
94
+ "stored_bytes": len(data), "observed_bytes": observed_bytes,
95
+ "redacted": int(policy["redacted"]), "truncated": int(policy["truncated"]),
96
+ "omitted_reason": (policy["omitted_reason"] or "unexposed") if body is None else None,
97
+ "policy_id": policy["policy_id"]}
98
+
99
+
100
+ def _part_policy(policy, retained):
101
+ return {**policy, "retained": retained}
102
+
103
+
104
+ def _template_copy(value, paths):
105
+ """Copy path containers; borrow other frozen descendants until serialization."""
106
+ template = value.copy()
107
+ for path in paths:
108
+ tokens = pointer_tokens(path)
109
+ parent = template
110
+ for token in tokens[:-1]:
111
+ key = token if type(parent) is dict else int(token)
112
+ parent[key] = parent[key].copy()
113
+ parent = parent[key]
114
+ key = tokens[-1] if type(parent) is dict else int(tokens[-1])
115
+ parent[key] = None
116
+ return template
117
+
118
+
119
+ def _unique_rows(rows):
120
+ return list({row["artifact_id"]: row for row in rows}.values())
121
+
122
+
123
+ def _link_fields(run_id, witness, source, relation, *, target_pointer,
124
+ source_slot=None, source_pointer=None, details=None):
125
+ return {"run_id": run_id, "witness_event_id": witness, "source_event_id": source,
126
+ "target_event_id": witness, "relation": relation, "source_slot": source_slot,
127
+ "source_pointer": source_pointer, "target_slot": "payload",
128
+ "target_pointer": target_pointer, "details_json": json_text(details or {})}
129
+
130
+
131
+ def _link(run_id, witness, source, relation, *, target_pointer,
132
+ source_slot=None, source_pointer=None, details=None):
133
+ values = _link_fields(run_id, witness, source, relation, target_pointer=target_pointer,
134
+ source_slot=source_slot, source_pointer=source_pointer, details=details)
135
+ identity = hashlib.sha256(_encoded(json_text(values))).hexdigest()
136
+ return {"link_id": run_id + ":l:" + identity, **values}
137
+
138
+
139
+ def _binding_link(run_id, event_id, message_id, binding, message_pointer):
140
+ details = {**binding["details"], "binding_format": "message_binding/2",
141
+ "message_artifact_id": message_id, "relative_pointer": binding["pointer"]}
142
+ values = _link_fields(run_id, event_id, binding["decision_event_id"], "answers",
143
+ target_pointer=message_pointer + binding["pointer"], details=details)
144
+ material = json_text([message_id, binding])
145
+ return {"link_id": run_id + ":b:" + hashlib.sha256(_encoded(material)).hexdigest(), **values}
146
+
147
+
148
+ class Artifacts:
149
+ """Prepare immutable-by-ownership SQL row values for the single writer.
150
+
151
+ The caller owns admission and all persistence. No state in this helper
152
+ publishes a binding claim or survives independently of its prepared bundle.
153
+ """
154
+
155
+ def __init__(self, run_id, key, capture, comparisons):
156
+ self.run_id = run_id
157
+ self.key = key
158
+ self.capture = capture
159
+ self.comparisons = comparisons
160
+
161
+ def artifact(self, original, retention=None):
162
+ """Consume original and optional retention frozen by the preparation owner."""
163
+ policy = _retention(self.capture, retention)
164
+ return _artifact_row(self.run_id, _fields(self.run_id, original, policy, "json"))
165
+
166
+ def _artifact(self, original, policy, identity=None, representation="json"):
167
+ return _artifact_row(self.run_id, _fields(self.run_id, original, policy, representation), identity)
168
+
169
+ def _digest(self, value, *, complete, utf8_size):
170
+ return original_digest(value, key=self.key, run_id=self.run_id,
171
+ projection=MESSAGE_PROJECTION, complete=complete,
172
+ enabled=self.comparisons, utf8_size=utf8_size)
173
+
174
+ def _text_digest(self, value, paths, *, complete):
175
+ return text_digest(value, paths, key=self.key, run_id=self.run_id,
176
+ complete=complete, enabled=self.comparisons)
177
+
178
+ def _binding(self, original, binding, complete, lookup):
179
+ fields(binding, ("decision_event_id", "pointer", "result_event_id", "text_paths"),
180
+ ("decision_event_id", "pointer"))
181
+ decision = validate_control(binding["decision_event_id"], "decision event", nonempty=True)
182
+ pointer = validate_pointer(binding["pointer"])
183
+ block = pointer_get(original, pointer)
184
+ result_id = validate_control(binding.get("result_event_id"), "result event", nullable=True,
185
+ nonempty=True)
186
+ details = {"result_event_id": result_id,
187
+ "submitted_text_digest": self._text_digest(
188
+ block, binding.get("text_paths"), complete=complete)}
189
+ unresolved = []
190
+ decision_event = lookup("event", decision)
191
+ if decision_event is None or decision_event.get("kind") != "model.tool_call":
192
+ unresolved.append({"pointer": pointer, "reason": "decision_unavailable"})
193
+ if result_id is not None:
194
+ result = lookup("event", result_id)
195
+ if result is None or result.get("kind") != "mcp.response":
196
+ unresolved.append({"pointer": pointer, "reason": "result_unavailable"})
197
+ return {"decision_event_id": decision, "pointer": pointer, "details": details}, unresolved
198
+
199
+ def _unresolved(self, original, values):
200
+ result = []
201
+ for item in _ordered(values, "unresolved bindings"):
202
+ fields(item, ("pointer", "reason", "provider_ref"), ("pointer", "reason"))
203
+ pointer = validate_pointer(item["pointer"])
204
+ pointer_get(original, pointer)
205
+ reason = validate_control(item["reason"], "unresolved reason", nonempty=True)
206
+ output = {"pointer": pointer, "reason": reason}
207
+ if "provider_ref" in item:
208
+ output["provider_ref"] = validate_control(item["provider_ref"], "provider reference")
209
+ result.append(output)
210
+ return result
211
+
212
+ def _message_annotation(self, original, annotation, complete, lookup):
213
+ if annotation is MISSING:
214
+ return None, [], complete
215
+ fields(annotation, ("bindings", "unresolved", "complete"), ("bindings",))
216
+ message_complete = boolean(annotation.get("complete", True), "message complete")
217
+ complete = complete and message_complete
218
+ unresolved = self._unresolved(original, annotation.get("unresolved", []))
219
+ values = annotation["bindings"]
220
+ if values is None:
221
+ return None, unresolved, complete
222
+ known, pointers = [], set()
223
+ for value in _ordered(values, "bindings"):
224
+ binding, unknown = self._binding(original, value, complete, lookup)
225
+ if binding["pointer"] in pointers:
226
+ raise InvalidInput("one message block must have one decision binding")
227
+ pointers.add(binding["pointer"])
228
+ known.append(binding)
229
+ unresolved.extend(unknown)
230
+ # Match the reference's request-independent canonical declaration order.
231
+ known = [json.loads(text) for text in sorted(
232
+ json.dumps(item, sort_keys=True, separators=(",", ":"), allow_nan=False)
233
+ for item in known)]
234
+ return known, unresolved, complete
235
+
236
+ def _message(self, original, retained, annotation, complete, policy, lookup):
237
+ bindings, unresolved, message_complete = self._message_annotation(
238
+ original, annotation, complete, lookup)
239
+ row_fields = _fields(self.run_id, original, _part_policy(policy, retained), "json")
240
+ token = self._digest(original, complete=message_complete,
241
+ utf8_size=row_fields["observed_bytes"])
242
+ reason = token.get("reason") or ("binding_context_unavailable" if bindings is None else None)
243
+ if unresolved:
244
+ reason = reason or "unresolved_bindings"
245
+ identity = ({"original": token["value"], "bindings": bindings or []}
246
+ if reason is None else {"occurrence": uuid.uuid4().hex})
247
+ artifact = _artifact_row(self.run_id, row_fields, identity)
248
+ return {"row": artifact, "identity": identity, "bindings": bindings or [],
249
+ "unresolved": unresolved, "reason": reason,
250
+ "complete": message_complete}
251
+
252
+ def _request_paths(self, original, facts):
253
+ message_path = facts.get("message_path", "/messages")
254
+ field_paths = _ordered(facts.get("field_paths", []), "field paths")
255
+ catalog_path = facts.get("catalog_path")
256
+ paths = field_paths if message_path is None else [message_path, *field_paths]
257
+ validated = set()
258
+ message_value = None
259
+ for path in paths:
260
+ validate_pointer(path, allow_root=False)
261
+ value = pointer_get(original, path)
262
+ if path in validated:
263
+ raise InvalidInput("extracted request paths cannot overlap")
264
+ validated.add(path)
265
+ if path == message_path:
266
+ message_value = value
267
+ for path in paths:
268
+ ancestor = path.rpartition("/")[0]
269
+ while ancestor:
270
+ if ancestor in validated:
271
+ raise InvalidInput("extracted request paths cannot overlap")
272
+ ancestor = ancestor.rpartition("/")[0]
273
+ if message_path is not None and type(message_value) is not list:
274
+ raise InvalidInput("request messages must be an ordered array")
275
+ if catalog_path is not None:
276
+ validate_pointer(catalog_path, allow_root=False)
277
+ if catalog_path not in field_paths:
278
+ raise InvalidInput("catalog path must be one of the extracted fields")
279
+ return message_path, field_paths, catalog_path
280
+
281
+ def _annotations(self, facts, message_count):
282
+ annotations = facts.get("messages")
283
+ if annotations is None:
284
+ return [MISSING] * message_count
285
+ _ordered(annotations, "message annotations")
286
+ if len(annotations) != message_count:
287
+ raise InvalidInput("annotations must match every ordered message")
288
+ return annotations
289
+
290
+ def _insertions(self, original, facts, event_id, lookup):
291
+ links, diagnostics = [], []
292
+ for insertion in _ordered(facts.get("insertions", []), "insertions"):
293
+ fields(insertion, ("source_event_id", "target_pointer", "content"),
294
+ ("source_event_id", "target_pointer", "content"))
295
+ source = validate_control(insertion["source_event_id"], "insertion source", nonempty=True)
296
+ pointer = validate_pointer(insertion["target_pointer"])
297
+ try:
298
+ destination = pointer_get(original, pointer)
299
+ except InvalidInput:
300
+ diagnostics.append({"pointer": pointer, "reason": "insertion_destination_absent"})
301
+ continue
302
+ if canonical_bytes(destination) != canonical_bytes(insertion["content"]):
303
+ diagnostics.append({"pointer": pointer, "reason": "insertion_destination_mismatch"})
304
+ continue
305
+ known = lookup("event", source)
306
+ if known is None or known.get("kind") != "host.tool_result":
307
+ diagnostics.append({"pointer": pointer, "reason": "insertion_source_unavailable"})
308
+ links.append(_link(self.run_id, event_id, source, "inserted_into",
309
+ source_slot="payload", source_pointer="", target_pointer=pointer))
310
+ return links, diagnostics
311
+
312
+ def _message_parts(self, original, retained, facts, policy, message_path, event_id, lookup):
313
+ messages = pointer_get(original, message_path)
314
+ replacements = pointer_get(retained, message_path)
315
+ annotations = self._annotations(facts, len(messages))
316
+ complete = facts.get("complete", True)
317
+ rows, refs, links, details, identities = [], [], [], {}, {}
318
+ losses = []
319
+ for index, message in enumerate(messages):
320
+ handle = self._message(message, replacements[index], annotations[index], complete, policy, lookup)
321
+ row = handle["row"]
322
+ rows.append(row)
323
+ refs.append(row["artifact_id"])
324
+ identities[row["artifact_id"]] = handle["identity"]
325
+ location = message_path + "/" + str(index)
326
+ links.extend(_binding_link(self.run_id, event_id, row["artifact_id"], binding, location)
327
+ for binding in handle["bindings"])
328
+ if handle["reason"]:
329
+ details.setdefault("message_identity_unavailable", []).append(
330
+ {"message_index": index, "reason": handle["reason"]})
331
+ if handle["unresolved"]:
332
+ details.setdefault("unresolved_answers", []).extend(
333
+ {**item, "pointer": location + item["pointer"]} for item in handle["unresolved"])
334
+ losses.append("unresolved")
335
+ if annotations[index] is MISSING or annotations[index].get("bindings") is None:
336
+ losses.append("unresolved")
337
+ if not handle["complete"]:
338
+ losses.append("partial")
339
+ return rows, refs, links, details, identities, losses
340
+
341
+ def _template_parts(self, original, retained, policy, message_path, field_paths):
342
+ paths = (message_path, *field_paths)
343
+ template = _template_copy(original, paths)
344
+ retained_template = template if retained is original else _template_copy(retained, paths)
345
+ rows, fields = [], []
346
+ for path in field_paths:
347
+ value = pointer_get(original, path)
348
+ replacement = value if retained is original else pointer_get(retained, path)
349
+ row = self._artifact(value, _part_policy(policy, replacement))
350
+ rows.append(row)
351
+ fields.append({"pointer": path, "artifact_id": row["artifact_id"]})
352
+ row = self._artifact(template, _part_policy(policy, retained_template))
353
+ rows.append(row)
354
+ return rows, fields, row["artifact_id"]
355
+
356
+ def _manifest(self, manifest, policy):
357
+ structural = {**policy, "retained": MISSING, "omitted_reason": None,
358
+ "redacted": False, "truncated": False}
359
+ return self._artifact(manifest, structural, representation="request_refs/2")
360
+
361
+ def _direct_fields(self, original, policy, field_paths):
362
+ retained = original if policy["retained"] is MISSING else policy["retained"]
363
+ rows, refs = [], []
364
+ for path in field_paths:
365
+ value, replacement = pointer_get(original, path), pointer_get(retained, path)
366
+ row = self._artifact(value, _part_policy(policy, replacement))
367
+ rows.append(row)
368
+ refs.append({"pointer": path, "artifact_id": row["artifact_id"]})
369
+ return rows, refs
370
+
371
+ def _direct_request(self, original, policy, facts, event_id, lookup, field_paths, catalog_path):
372
+ row = self._artifact(original, policy)
373
+ field_rows, refs = self._direct_fields(original, policy, field_paths)
374
+ catalog = next((item["artifact_id"] for item in refs if item["pointer"] == catalog_path), None)
375
+ links, diagnostics = self._insertions(original, facts, event_id, lookup)
376
+ details = {"request_limitation": "message_array_unavailable"}
377
+ if refs:
378
+ details["direct_field_refs"] = refs
379
+ if diagnostics:
380
+ details["insertion_diagnostics"] = diagnostics
381
+ losses = ["unresolved"]
382
+ if row["body_text"] is None:
383
+ losses.append("body_omitted")
384
+ if not facts.get("complete", True):
385
+ losses.append("partial")
386
+ return {"artifacts": _unique_rows([row, *field_rows]), "payload_ref": row["artifact_id"], "catalog_ref": catalog,
387
+ "links": links, "details": details, "losses": tuple(dict.fromkeys(losses))}
388
+
389
+ def request(self, original, facts, event_id, lookup):
390
+ """Consume payload and facts already frozen by Preparation.observe."""
391
+ policy = _retention(self.capture, facts.get("retention"))
392
+ message_path, field_paths, catalog_path = self._request_paths(original, facts)
393
+ if message_path is None:
394
+ return self._direct_request(original, policy, facts, event_id, lookup, field_paths, catalog_path)
395
+ retained = _retained_request(original, policy, message_path, field_paths)
396
+ rows, refs, links, details, identities, losses = self._message_parts(
397
+ original, retained, facts, policy, message_path, event_id, lookup)
398
+ templates, fields, template_ref = self._template_parts(
399
+ original, retained, policy, message_path, field_paths)
400
+ manifest = {"format": "request_refs/2", "template_ref": template_ref,
401
+ "message_path": message_path, "message_refs": refs, "field_refs": fields}
402
+ manifest_row = self._manifest(manifest, policy)
403
+ rows.extend([*templates, manifest_row])
404
+ insertions, diagnostics = self._insertions(original, facts, event_id, lookup)
405
+ links.extend(insertions)
406
+ if diagnostics:
407
+ details["insertion_diagnostics"] = diagnostics
408
+ losses.append("unresolved")
409
+ if any(row["body_text"] is None for row in rows):
410
+ losses.append("body_omitted")
411
+ catalog = next((item["artifact_id"] for item in fields if item["pointer"] == catalog_path), None)
412
+ return {"artifacts": _unique_rows(rows), "payload_ref": manifest_row["artifact_id"],
413
+ "catalog_ref": catalog, "links": links, "details": details,
414
+ "losses": tuple(dict.fromkeys(losses)),
415
+ "_identities": identities}
416
+
417
+ def omit_artifact(self, row, *, identity=None):
418
+ """Create the retention-distinct omitted row without retaining its body."""
419
+ if row["body_text"] is None:
420
+ return dict(row)
421
+ fields = {key: value for key, value in row.items() if key != "artifact_id"}
422
+ fields.update(body_text=None, stored_sha256=None, stored_bytes=0, omitted_reason="capacity")
423
+ return _artifact_row(self.run_id, fields, identity)
424
+
425
+ def _remap_manifest(self, row, mapping):
426
+ manifest = json.loads(row["body_text"])
427
+ manifest["template_ref"] = mapping.get(manifest["template_ref"], manifest["template_ref"])
428
+ manifest["message_refs"] = [mapping.get(item, item) for item in manifest["message_refs"]]
429
+ manifest["field_refs"] = [{**item, "artifact_id": mapping.get(item["artifact_id"], item["artifact_id"])}
430
+ for item in manifest["field_refs"]]
431
+ policy = {"policy_id": row["policy_id"], "retained": MISSING,
432
+ "redacted": False, "truncated": False, "omitted_reason": None}
433
+ return self._manifest(manifest, policy)
434
+
435
+ def _remap_binding(self, link, mapping):
436
+ if link["relation"] != "answers":
437
+ return dict(link)
438
+ details = json.loads(link["details_json"])
439
+ message_id = mapping.get(details["message_artifact_id"], details["message_artifact_id"])
440
+ relative = details["relative_pointer"]
441
+ stable = {key: value for key, value in details.items()
442
+ if key not in ("message_artifact_id", "relative_pointer", "binding_format")}
443
+ # Reference bind_message consumes canonicalized binding dictionaries.
444
+ binding = json.loads(json.dumps({"decision_event_id": link["source_event_id"],
445
+ "pointer": relative, "details": stable},
446
+ sort_keys=True, separators=(",", ":"), allow_nan=False))
447
+ location = link["target_pointer"][:-len(relative)] if relative else link["target_pointer"]
448
+ return _binding_link(self.run_id, link["witness_event_id"], message_id, binding, location)
449
+
450
+ def omit_prepared(self, prepared, *, include_manifest):
451
+ """Omit optional bodies with reference repair; never shorten membership.
452
+
453
+ If even structural membership cannot be admitted, include_manifest
454
+ replaces it with an explicitly omitted artifact and removes its answer
455
+ candidates. The envelope records that loss instead of asserting a
456
+ complete request or a binding that has no stored membership witness.
457
+ """
458
+ identities = prepared.get("_identities", {})
459
+ mapping, rows, retained_manifests = {}, [], []
460
+ for row in prepared["artifacts"]:
461
+ if row["representation"] == "request_refs/2" and not include_manifest:
462
+ retained_manifests.append(row)
463
+ continue
464
+ omitted = self.omit_artifact(row, identity=identities.get(row["artifact_id"]))
465
+ rows.append(omitted)
466
+ mapping[row["artifact_id"]] = omitted["artifact_id"]
467
+ for row in retained_manifests:
468
+ remapped = self._remap_manifest(row, mapping)
469
+ rows.append(remapped)
470
+ mapping[row["artifact_id"]] = remapped["artifact_id"]
471
+ details = freeze(prepared["details"])
472
+ if "direct_field_refs" in details:
473
+ details["direct_field_refs"] = [
474
+ {**item, "artifact_id": mapping.get(item["artifact_id"], item["artifact_id"])}
475
+ for item in details["direct_field_refs"]]
476
+ if include_manifest:
477
+ details["request_limitation"] = ("manifest_omitted" if any(
478
+ row["representation"] == "request_refs/2" for row in prepared["artifacts"])
479
+ else "direct_request_omitted")
480
+ # These entries describe absent membership. Preserve their counts
481
+ # and explicit omission instead of keeping an unbounded shadow
482
+ # manifest in control metadata.
483
+ for field in ("unresolved_answers", "message_identity_unavailable", "direct_field_refs"):
484
+ if field in details:
485
+ details[field + "_omitted_count"] = len(details.pop(field))
486
+ links = [self._remap_binding(link, mapping) for link in prepared["links"]
487
+ if not include_manifest or link["relation"] != "answers"]
488
+ payload_ref = mapping.get(prepared["payload_ref"], prepared["payload_ref"])
489
+ catalog_ref = mapping.get(prepared["catalog_ref"], prepared["catalog_ref"])
490
+ if include_manifest:
491
+ # Once membership itself is unavailable, orphan placeholders do
492
+ # not contribute evidence. Retain only the envelope's direct
493
+ # references, with an explicit lost-manifest diagnostic above.
494
+ rows = [row for row in rows if row["artifact_id"] in (payload_ref, catalog_ref)]
495
+ losses = (*prepared["losses"], "capacity", "body_omitted", "partial")
496
+ return {"artifacts": _unique_rows(rows), "links": links,
497
+ "payload_ref": payload_ref, "catalog_ref": catalog_ref,
498
+ "details": details, "losses": tuple(dict.fromkeys(losses))}