domdrift 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.
domdrift/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """Public snapshot inference, checking and comparison API."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .contract import check_contract, infer_contract, infer_html_contract, infer_json_contract
6
+ from .differ import diff_snapshots
7
+ from .dom import Element, SelectorSyntaxError, parse_html, query_selector_all
8
+ from .redact import redact_attrs, redact_text
9
+ from .report import CheckResult, format_repair_bundle
10
+ from .softblock import SoftBlockReport, detect_soft_block
11
+
12
+ __all__ = [
13
+ "CheckResult", "Element", "SelectorSyntaxError", "SoftBlockReport", "__version__",
14
+ "check_contract", "detect_soft_block", "diff_snapshots", "format_repair_bundle",
15
+ "infer_contract", "infer_html_contract", "infer_json_contract", "parse_html",
16
+ "query_selector_all", "redact_attrs", "redact_text",
17
+ ]
domdrift/cli.py ADDED
@@ -0,0 +1,107 @@
1
+ """Unix command-line entry point."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+ from tempfile import NamedTemporaryFile
9
+
10
+ from . import __version__, check_contract, diff_snapshots, format_repair_bundle, infer_contract
11
+ from .jsonpaths import parse_json
12
+ from .redact import redact_text
13
+ from .report import validate_budget
14
+ from .source import load_source
15
+
16
+
17
+ class Parser(argparse.ArgumentParser):
18
+ def error(self, message):
19
+ self.exit(1, f"{self.prog}: {redact_text(message)}\n")
20
+
21
+
22
+ def _parser():
23
+ parser = Parser(prog="domdrift", description="Check HTML and JSON snapshot contracts.")
24
+ parser.add_argument("--version", action="version", version=f"domdrift {__version__}")
25
+ sub = parser.add_subparsers(dest="command", required=True)
26
+ init = sub.add_parser("init", help="Infer a contract from a known-good response.")
27
+ check = sub.add_parser("check", help="Check a response against a saved contract.")
28
+ diff = sub.add_parser("diff", help="Compare two snapshots without saving a contract.")
29
+ sub.add_parser("mcp", help="Serve MCP tools on stdin/stdout.")
30
+ for cmd in (init, check, diff):
31
+ cmd.add_argument("--allow-private-net", action="store_true",
32
+ help="Allow HTTP connections to non-public addresses.")
33
+ for cmd in (init, check):
34
+ cmd.add_argument("source", nargs="?", default="-", help="File, HTTP(S) URL or - for stdin.")
35
+ init.add_argument("-o", "--output", metavar="FILE")
36
+ init.add_argument("--select", action="append", default=[], metavar="NAME=EXPR")
37
+ init.add_argument("--auto-landmarks", action="store_true",
38
+ help="Include inferred HTML landmarks alongside explicit rules.")
39
+ init.add_argument("--format", choices=("auto", "html", "json"), default="auto")
40
+ check.add_argument("-c", "--contract", required=True, metavar="FILE")
41
+ check.add_argument("-q", "--quiet", action="store_true")
42
+ check.add_argument("--no-soft-block", action="store_true")
43
+ diff.add_argument("old_source")
44
+ diff.add_argument("new_source")
45
+ diff.add_argument("--doc-format", choices=("auto", "html", "json"), default="auto")
46
+ for cmd in (check, diff):
47
+ cmd.add_argument("--max-bytes", type=int, default=2048)
48
+ cmd.add_argument("--format", choices=("json", "text"), default="text")
49
+ return parser
50
+
51
+
52
+ def _write_contract(text, path):
53
+ if not path or path == "-":
54
+ sys.stdout.write(text)
55
+ return
56
+ with NamedTemporaryFile(dir=Path(path).parent, delete=False) as tmp:
57
+ try:
58
+ tmp.write(text.encode())
59
+ tmp.close()
60
+ os.replace(tmp.name, path)
61
+ finally:
62
+ Path(tmp.name).unlink(missing_ok=True)
63
+
64
+
65
+ def main(argv=None) -> int:
66
+ args = _parser().parse_args(argv)
67
+ try:
68
+ if args.command == "mcp":
69
+ from .mcp_server import serve
70
+ return serve()
71
+ if args.command == "init":
72
+ selects = {}
73
+ for pair in args.select:
74
+ name, sep, expr = pair.partition("=")
75
+ if not sep or not name.strip() or not expr.strip() or name in selects:
76
+ raise ValueError("Use --select NAME=EXPR with a unique name")
77
+ selects[name] = expr
78
+ contract = infer_contract(load_source(args.source, args.allow_private_net),
79
+ args.format, selects, auto_landmarks=args.auto_landmarks)
80
+ _write_contract(json.dumps(contract, indent=2) + "\n", args.output)
81
+ return 0
82
+ validate_budget(args.max_bytes)
83
+ if args.command == "check":
84
+ contract = parse_json(Path(args.contract).read_text(encoding="utf-8-sig"))
85
+ result = check_contract(contract, load_source(args.source, args.allow_private_net),
86
+ no_soft_block=args.no_soft_block)
87
+ if args.quiet or not result.exit_code:
88
+ return result.exit_code
89
+ report = format_repair_bundle(result, args.max_bytes, args.format)
90
+ else:
91
+ if args.old_source == args.new_source == "-":
92
+ raise ValueError("Only one snapshot may read stdin")
93
+ result = diff_snapshots(load_source(args.old_source, args.allow_private_net),
94
+ load_source(args.new_source, args.allow_private_net),
95
+ fmt=args.doc_format, max_bytes=args.max_bytes, output_format=args.format)
96
+ report = result.report
97
+ if report:
98
+ data = report.encode()
99
+ sys.stdout.buffer.write(data + (b"\n" if len(data) < args.max_bytes else b""))
100
+ return result.exit_code
101
+ except (ValueError, OSError, RecursionError, OverflowError) as exc:
102
+ print(f"domdrift: {redact_text(str(exc))}", file=sys.stderr)
103
+ return 1
104
+
105
+
106
+ if __name__ == "__main__":
107
+ sys.exit(main())
domdrift/contract.py ADDED
@@ -0,0 +1,359 @@
1
+ """Infer, validate and diagnose version 1 snapshot contracts."""
2
+
3
+ import re
4
+ from collections import defaultdict
5
+
6
+ from . import jsonpaths
7
+ from .dom import (
8
+ INVISIBLE,
9
+ VOID,
10
+ Element,
11
+ compile_selector,
12
+ evaluate,
13
+ parse_html,
14
+ query_selector_all,
15
+ related,
16
+ )
17
+ from .redact import redact_attrs, redact_text
18
+ from .report import CheckResult, format_repair_bundle, safe_record
19
+ from .softblock import detect_soft_block
20
+
21
+ __all__ = ["CheckResult", "check_contract", "format_repair_bundle", "infer_contract",
22
+ "infer_html_contract", "infer_json_contract"]
23
+
24
+ _IDENT = re.compile(r"[a-zA-Z_][\w-]{0,63}\Z")
25
+ _STRUCTURAL = {"main", "section", "ul", "ol", "table", "article", "div", "form", "body"} | VOID | INVISIBLE
26
+
27
+
28
+ def _stable(value):
29
+ return (_IDENT.fullmatch(value) and not value.startswith(("css-", "sc-", "jsx-"))
30
+ and redact_text(value) == value)
31
+
32
+
33
+ def labels(node: Element):
34
+ """Only stable structural attributes may enter generated contracts or evidence."""
35
+ tag = node.tag
36
+ if not _stable(tag):
37
+ return []
38
+ attrs = redact_attrs(tag, {k: v for k, v in node.attrs.items() if k != "class"})
39
+ names = []
40
+ for key in ("data-testid", "itemprop", "data-role", "data-test"):
41
+ value = attrs.get(key, "")
42
+ if _stable(value):
43
+ names.append(f'[{key}="{value}"]')
44
+ classes = node.attrs.get("class", "")
45
+ names.extend("." + c for c in sorted(redact_text(classes, len(classes)).split()) if _stable(c))
46
+ if _stable(attrs.get("id", "")):
47
+ names.append("#" + attrs["id"])
48
+ names.extend(f"[{k}]" for k, v in attrs.items() if k.startswith("data-")
49
+ and _stable(k) and v != "[REDACTED]")
50
+ if tag == "a" and "href" in attrs:
51
+ names.append("a[href]")
52
+ return list(dict.fromkeys([*names, tag]))
53
+
54
+
55
+ def _auto_selectors(root):
56
+ selected = {}
57
+ for tag in ("h1", "main", "table", "article"):
58
+ if len(query_selector_all(root, tag)) == 1:
59
+ selected[tag] = tag
60
+ groups = {}
61
+ for parent in (root, *root.descendants(visible=True)):
62
+ if len(parent.children) < 3:
63
+ continue
64
+ buckets = defaultdict(list)
65
+ for child in parent.children:
66
+ if child.tag in INVISIBLE:
67
+ continue
68
+ for label in labels(child):
69
+ if label != child.tag or child.tag in {"li", "article", "tr"}:
70
+ buckets[(child.tag, label)].append(child)
71
+ for (tag, label), siblings in buckets.items():
72
+ if len(siblings) >= 3:
73
+ selector = tag + label if label.startswith((".", "[")) else label
74
+ groups.setdefault(selector, siblings)
75
+ used = set()
76
+ for selector, siblings in sorted(groups.items(), key=lambda kv: -len(kv[1])):
77
+ if siblings[0] in used:
78
+ continue
79
+ used.add(siblings[0])
80
+ selected[selector] = selector
81
+ fields = {}
82
+ for child in siblings[0].descendants(visible=True):
83
+ names = labels(child)
84
+ if not names:
85
+ continue
86
+ label = names[0]
87
+ if child.tag in {"h1", "h2", "h3", "h4"}:
88
+ fields[label] = 1
89
+ elif child.tag == "a" and "href" in child.attrs:
90
+ fields["a[href]"] = 2
91
+ else:
92
+ field = next((name for name in names if re.search(r"price|meta|itemprop|data-testid",
93
+ name, re.I)), None)
94
+ if field:
95
+ fields[field] = 0
96
+ for name in sorted(fields, key=fields.get)[:3]:
97
+ expr = selector + " " + name
98
+ selected[expr] = expr
99
+ if len(used) == 2:
100
+ break
101
+ if not selected:
102
+ nodes = list(root.descendants(visible=True))
103
+ fallback = next((n for n in nodes if n.tag not in {"html", "head", "body", "title", "meta", "link"}), None)
104
+ if fallback and (names := labels(fallback)):
105
+ selected[names[0]] = names[0]
106
+ return selected
107
+
108
+
109
+ def _selects(selects):
110
+ if selects is None:
111
+ return {}
112
+ if not isinstance(selects, dict) or not all(
113
+ isinstance(k, str) and k.strip() and isinstance(v, str) and v.strip()
114
+ for k, v in selects.items()
115
+ ):
116
+ raise ValueError("selects must map rule names to non-empty expressions")
117
+ return selects
118
+
119
+
120
+ def _presence_attr(selector):
121
+ # An inferred attribute must apply to the target of every selector group.
122
+ attrs = [{test[1] for test in chain[-1].tests if test[0] == "attr" and test[2] is None}
123
+ for chain in compile_selector(selector)]
124
+ return min(set.intersection(*attrs), default=None)
125
+
126
+
127
+ def infer_html_contract(raw_html: str, selects=None, *, auto_landmarks=False) -> dict:
128
+ root = parse_html(raw_html)
129
+ explicit = _selects(selects)
130
+ expressions = _auto_selectors(root) if auto_landmarks or not explicit else {}
131
+ expressions.update(explicit)
132
+ rules = []
133
+ for name, selector in expressions.items():
134
+ nodes = query_selector_all(root, selector)
135
+ count = len(nodes)
136
+ if not count:
137
+ raise ValueError(f"Baseline selector matched nothing: {redact_text(selector)}")
138
+ required_attr = _presence_attr(selector)
139
+ ratio = 0.0
140
+ if not required_attr and any(n.tag not in _STRUCTURAL or any(t.strip() for t in n.text_chunks)
141
+ for n in nodes):
142
+ ratio = min(0.8, sum(bool(n.text_content()) for n in nodes) / count)
143
+ rules.append({"name": name, "selector": selector,
144
+ "min_count": max(1, int(count * 0.6)) if count >= 3 else count,
145
+ "min_non_empty_ratio": ratio, "required_attr": required_attr})
146
+ return {"version": 1, "format": "html", "detect_soft_block": True, "rules": rules}
147
+
148
+
149
+ def infer_json_contract(raw_json: str, selects=None) -> dict:
150
+ doc = jsonpaths.parse_json(raw_json)
151
+ selects = _selects(selects)
152
+ if selects:
153
+ rules = [jsonpaths.make_rule(name, path, jsonpaths.locate(doc, path), doc)
154
+ for name, path in selects.items()]
155
+ else:
156
+ rules = [jsonpaths.make_rule(path, path, values, doc)
157
+ for path, values in jsonpaths.schema(doc, required_only=True)]
158
+ return {"version": 1, "format": "json", "rules": rules}
159
+
160
+
161
+ def infer_contract(raw: str, fmt: str = "auto", selects=None, *, auto_landmarks=False):
162
+ if fmt == "auto":
163
+ fmt = "html" if raw.lstrip().startswith("<") else "json"
164
+ if fmt == "html":
165
+ return infer_html_contract(raw, selects, auto_landmarks=auto_landmarks)
166
+ if fmt == "json":
167
+ return infer_json_contract(raw, selects)
168
+ raise ValueError("Document format must be auto, html or json")
169
+
170
+
171
+ def validate_contract(contract):
172
+ if not isinstance(contract, dict) or type(contract.get("version")) is not int or contract["version"] != 1:
173
+ raise ValueError("Expected contract version 1")
174
+ fmt = contract.get("format")
175
+ if fmt not in ("html", "json") or not isinstance(contract.get("rules"), list):
176
+ raise ValueError("Expected format html or json and a rules array")
177
+ if type(contract.get("detect_soft_block", True)) is not bool:
178
+ raise ValueError("detect_soft_block must be boolean")
179
+ for rule in contract["rules"]:
180
+ if not isinstance(rule, dict) or not isinstance(rule.get("name"), str) or not rule["name"].strip():
181
+ raise ValueError("Each rule needs a non-empty name")
182
+ for key in ("min_non_empty_ratio", "min_presence_ratio"):
183
+ ratio = rule.get(key, 0)
184
+ if type(ratio) not in (int, float) or not 0 <= ratio <= 1:
185
+ raise ValueError(f"{key} must be between 0 and 1")
186
+ for key in ("min_count", "min_items", "max_count"):
187
+ count = rule.get(key, 0)
188
+ if key == "max_count" and count is None:
189
+ continue
190
+ if type(count) is not int or count < 0:
191
+ raise ValueError(f"{key} must be a non-negative integer")
192
+ if fmt == "html":
193
+ if not isinstance(rule.get("selector"), str):
194
+ raise ValueError("HTML rule needs a selector")
195
+ compile_selector(rule["selector"])
196
+ if rule.get("max_count") is not None and rule["max_count"] < rule.get("min_count", 1):
197
+ raise ValueError("max_count is below min_count")
198
+ for key in ("required_attr", "pattern"):
199
+ if rule.get(key) is not None and not isinstance(rule[key], str):
200
+ raise ValueError(f"{key} must be a string")
201
+ if rule.get("pattern") is not None:
202
+ try:
203
+ re.compile(rule["pattern"])
204
+ except re.error as exc:
205
+ raise ValueError("Invalid rule pattern") from exc
206
+ else:
207
+ if not isinstance(rule.get("path"), str):
208
+ raise ValueError("JSON rule needs a path")
209
+ jsonpaths.parts(rule["path"])
210
+ types = rule.get("type")
211
+ if isinstance(types, str):
212
+ types = [types]
213
+ if not isinstance(types, list) or not all(isinstance(t, str) and t in jsonpaths.TYPES for t in types):
214
+ raise ValueError("JSON rule needs a valid expected type")
215
+ if type(rule.get("allow_null", False)) is not bool:
216
+ raise ValueError("allow_null must be boolean")
217
+
218
+
219
+ def _join(prefix, relation, label):
220
+ if not prefix:
221
+ return label
222
+ return prefix + (" " if relation == " " else f" {relation} ") + label
223
+
224
+
225
+ def _skeleton(root):
226
+ lines = []
227
+
228
+ def visit(node, depth, count):
229
+ names = labels(node)
230
+ label = names[0] if names else "element"
231
+ if label != node.tag and label.startswith((".", "#", "[")):
232
+ label = node.tag + label
233
+ if node.tag != "#document":
234
+ lines.append(" " * depth + f"<{label}>" + (f" x{count}" if count > 1 else ""))
235
+ if depth >= 4 or len(lines) >= 24:
236
+ return
237
+ groups = {}
238
+ for child in node.children:
239
+ if child.tag in INVISIBLE:
240
+ continue
241
+ key = (child.tag, tuple(labels(child)[:1]))
242
+ if key not in groups:
243
+ groups[key] = [child, 0]
244
+ groups[key][1] += 1
245
+ for child, repeats in groups.values():
246
+ if len(lines) >= 24:
247
+ break
248
+ visit(child, depth + 1, repeats)
249
+ visit(root, 0, 1)
250
+ return lines
251
+
252
+
253
+ def _nearby_labels(nodes, relation):
254
+ matches = defaultdict(list)
255
+ seen = set()
256
+ for parent in nodes:
257
+ for child in related(parent, relation):
258
+ if child in seen or child.tag in INVISIBLE:
259
+ continue
260
+ seen.add(child)
261
+ for label in labels(child):
262
+ matches[label].append(child)
263
+ return matches
264
+
265
+
266
+ def _replacements(scope, chain, prefix, target):
267
+ choices = [(0, prefix, scope)]
268
+ for step in chain:
269
+ choices_next = []
270
+ for score, path, nodes in choices:
271
+ direct = {}
272
+ relations = (">", " ") if step.relation == ">" else (step.relation,)
273
+ for relation in relations:
274
+ options = _nearby_labels(nodes, relation)
275
+ for label, matches in options.items():
276
+ n = len(matches)
277
+ if relation != step.relation and direct.get(label) == n:
278
+ continue
279
+ rank = 3 * jsonpaths.similarity(step.source, label)
280
+ rank += min(n, target) / max(n, target)
281
+ rank += 0.2 * bool(matches[0].text_content()) + 0.1 * ("href" in matches[0].attrs)
282
+ rank -= 0.3 * (relation != step.relation)
283
+ choices_next.append((score + rank, _join(path, relation, label), matches))
284
+ if relation == ">":
285
+ direct = {label: len(matches) for label, matches in options.items()}
286
+ if not choices_next:
287
+ return []
288
+ choices = sorted(choices_next, key=lambda c: (-c[0], c[1]))[:3]
289
+ return [{"selector": path, "count": len(nodes)} for _, path, nodes in choices if path != prefix]
290
+
291
+
292
+ def _html_evidence(root, rule, result):
293
+ for chain in compile_selector(rule["selector"]):
294
+ lo, hi = 0, len(chain)
295
+ while lo < hi:
296
+ mid = (lo + hi + 1) // 2
297
+ if evaluate([root], chain[:mid]):
298
+ lo = mid
299
+ else:
300
+ hi = mid - 1
301
+ scope = evaluate([root], chain[:lo])
302
+ prefix = ""
303
+ for step in chain[:lo]:
304
+ prefix = _join(prefix, step.relation, step.source)
305
+ result.survivors.append(safe_record({"selector": prefix or "(document)", "count": len(scope),
306
+ "broken": chain[lo].source if lo < len(chain) else ""}))
307
+ if lo < len(chain):
308
+ for choice in _replacements(scope, chain[lo:], prefix, max(1, rule.get("min_count", 1))):
309
+ result.candidates.append(safe_record(choice))
310
+ result.skeleton.extend(_skeleton(scope[0]))
311
+
312
+
313
+ def _html_problems(nodes, rule):
314
+ count = len(nodes)
315
+ minimum = rule.get("min_count", 1)
316
+ if count < minimum:
317
+ yield f"matched {count}, need >= {minimum}"
318
+ if rule.get("max_count") is not None and count > rule["max_count"]:
319
+ yield f"matched {count}, need <= {rule['max_count']}"
320
+ if not nodes:
321
+ return
322
+ key = rule.get("required_attr")
323
+ if key and any(key.lower() not in n.attrs for n in nodes):
324
+ yield f"missing attribute {key}"
325
+ values = [n.attrs.get(key.lower(), "") if key else n.text_content() for n in nodes]
326
+ default = 0 if key or _presence_attr(rule["selector"]) or all(n.tag in _STRUCTURAL for n in nodes) else 0.8
327
+ if sum(bool(v.strip()) for v in values) / count < rule.get("min_non_empty_ratio", default):
328
+ yield "non-empty ratio too low"
329
+ if rule.get("pattern") is not None and any(not re.search(rule["pattern"], v) for v in values):
330
+ yield "pattern mismatch"
331
+
332
+
333
+ def check_contract(contract: dict, raw: str, *, no_soft_block: bool = False) -> CheckResult:
334
+ validate_contract(contract)
335
+ html = contract["format"] == "html"
336
+ root = parse_html(raw) if html or raw.lstrip().startswith("<") else None
337
+ if (root and not no_soft_block and contract.get("detect_soft_block", True)
338
+ and (block := detect_soft_block(raw, root))):
339
+ return CheckResult.blocked(block)
340
+ doc = None if html else jsonpaths.parse_json(raw)
341
+ result = CheckResult()
342
+ for rule in contract["rules"]:
343
+ if html:
344
+ expr = rule["selector"]
345
+ problems = list(_html_problems(query_selector_all(root, expr), rule))
346
+ else:
347
+ expr = rule["path"]
348
+ problems = jsonpaths.failures(doc, rule)
349
+ for reason in problems:
350
+ result.violation(rule=rule["name"], **{"selector" if html else "path": expr}, reason=reason)
351
+ if problems:
352
+ if html:
353
+ _html_evidence(root, rule, result)
354
+ else:
355
+ survivor, choices, lines = jsonpaths.diagnose(doc, rule)
356
+ result.survivors.append(safe_record(survivor))
357
+ result.candidates.extend(map(safe_record, choices))
358
+ result.skeleton.extend(lines)
359
+ return result
domdrift/differ.py ADDED
@@ -0,0 +1,74 @@
1
+ """Compare contracts and inventories while ignoring changes to scalar values."""
2
+
3
+ from collections import Counter
4
+
5
+ from . import jsonpaths
6
+ from .contract import check_contract, infer_contract, labels
7
+ from .dom import parse_html
8
+ from .report import CheckResult, format_repair_bundle, safe_record, validate_budget
9
+ from .softblock import detect_soft_block
10
+
11
+
12
+ def _inventory(raw, fmt):
13
+ counts = Counter()
14
+ types = {}
15
+ edges = Counter()
16
+ if fmt == "json":
17
+ for path, values in jsonpaths.schema(jsonpaths.parse_json(raw)):
18
+ counts[path] = len(values)
19
+ types[path] = {jsonpaths.typename(value) for value in values}
20
+ else:
21
+ primary = {}
22
+ for node in parse_html(raw).descendants(visible=True):
23
+ names = labels(node)
24
+ if names:
25
+ counts.update(names)
26
+ primary[node] = names[0]
27
+ if node.parent in primary:
28
+ edges[primary[node.parent], names[0]] += 1
29
+ return counts, types, edges
30
+
31
+
32
+ def _best_migration(key, additions, old, new, old_types, new_types):
33
+ def rank(label):
34
+ cardinality = min(old[key], new[label]) / max(old[key], new[label])
35
+ same_type = bool(old_types.get(key, set()) & new_types.get(label, set()))
36
+ return jsonpaths.similarity(key, label) + cardinality + same_type
37
+
38
+ return max(additions, key=rank)
39
+
40
+
41
+ def diff_snapshots(old_raw: str, new_raw: str, *, fmt: str = "auto", max_bytes: int = 2048,
42
+ output_format: str = "text") -> CheckResult:
43
+ validate_budget(max_bytes)
44
+ if new_raw.lstrip().startswith("<"):
45
+ block = detect_soft_block(new_raw, parse_html(new_raw))
46
+ if block:
47
+ result = CheckResult.blocked(block)
48
+ result.report = format_repair_bundle(result, max_bytes, output_format)
49
+ return result
50
+ contract = infer_contract(old_raw, fmt)
51
+ result = check_contract(contract, new_raw, no_soft_block=True)
52
+ old, old_types, old_edges = _inventory(old_raw, contract["format"])
53
+ new, new_types, new_edges = _inventory(new_raw, contract["format"])
54
+ # Preserve moves between surviving containers even if all global counts are unchanged.
55
+ for edge in old_edges.keys() | new_edges.keys():
56
+ if old_edges[edge] != new_edges[edge] and all(old[k] == new[k] for k in edge):
57
+ selector = " > ".join(edge)
58
+ old[selector], new[selector] = old_edges[edge], new_edges[edge]
59
+ field = "path" if contract["format"] == "json" else "selector"
60
+ diagnosed = {v[field] for v in result.violations}
61
+ additions = sorted(k for k in new if new[k] and not old[k])
62
+ for key in sorted(old.keys() | new.keys()):
63
+ if new[key] != old[key]:
64
+ change = "added" if not old[key] else "vanished" if not new[key] else "count shift"
65
+ result.violation(**{field: key}, reason=change, old=old[key], new=new[key])
66
+ if key not in diagnosed and key in old_types and key in new_types and old_types[key] != new_types[key]:
67
+ result.violation(path=key, reason="type changed", old="|".join(sorted(old_types[key])),
68
+ new="|".join(sorted(new_types[key])))
69
+ if key not in diagnosed and not new[key] and additions and len(result.candidates) < 3:
70
+ label = _best_migration(key, additions, old, new, old_types, new_types)
71
+ result.candidates.append(safe_record({"from": key, field: label, "count": new[label]}))
72
+ if result.exit_code:
73
+ result.report = format_repair_bundle(result, max_bytes, output_format)
74
+ return result