collationdelta 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.
@@ -0,0 +1,3 @@
1
+ """Portable evidence for changes in application string comparisons."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env node
2
+ // One batch, no npm dependencies. All comparisons call the actual Intl API.
3
+ import fs from 'node:fs';
4
+
5
+ const runtime = {
6
+ node: process.version,
7
+ icu: process.versions.icu ?? null,
8
+ cldr: process.versions.cldr ?? null,
9
+ unicode: process.versions.unicode ?? null,
10
+ platform: process.platform,
11
+ arch: process.arch,
12
+ };
13
+ const adapter = {
14
+ name: 'collationdelta-intl',
15
+ version: '0.1.0',
16
+ contract: 'intl.collator.v1',
17
+ };
18
+
19
+ function observe(request) {
20
+ if (request.protocol_version !== 1 || !Array.isArray(request.corpus?.entries)) {
21
+ throw new Error('invalid request/protocol version');
22
+ }
23
+ const profile = request.profile;
24
+ const base = { protocol_version: 1, runtime, adapter, effective: null, results: [] };
25
+ function unsupported(reason, effective = null) {
26
+ return { ...base, status: 'unsupported', reason, effective };
27
+ }
28
+ if (profile?.contract !== adapter.contract)
29
+ return unsupported('unsupported application comparator contract');
30
+ const allowed = {
31
+ sensitivity: ['base', 'accent', 'case', 'variant'],
32
+ caseFirst: ['upper', 'lower', 'false'],
33
+ usage: ['sort', 'search'],
34
+ numeric: 'boolean',
35
+ ignorePunctuation: 'boolean',
36
+ collation: 'string',
37
+ };
38
+ if (
39
+ !profile.options ||
40
+ typeof profile.options !== 'object' ||
41
+ Array.isArray(profile.options)
42
+ ) {
43
+ return unsupported('options must be an object');
44
+ }
45
+ for (const [key, value] of Object.entries(profile.options)) {
46
+ if (!(key in allowed)) return unsupported(`unsupported option: ${key}`);
47
+ const rule = allowed[key];
48
+ if (Array.isArray(rule) ? !rule.includes(value) : typeof value !== rule) {
49
+ return unsupported(`invalid option value: ${key}`);
50
+ }
51
+ }
52
+ let canonical, collator;
53
+ try {
54
+ canonical = Intl.getCanonicalLocales(profile.locale)[0];
55
+ if (
56
+ !canonical ||
57
+ !Intl.Collator.supportedLocalesOf([canonical], { localeMatcher: 'lookup' }).length
58
+ ) {
59
+ return unsupported('requested locale has no supported lookup match');
60
+ }
61
+ collator = new Intl.Collator(canonical, {
62
+ ...profile.options,
63
+ localeMatcher: 'lookup',
64
+ });
65
+ } catch (error) {
66
+ return unsupported(`Intl configuration rejected: ${error.message}`);
67
+ }
68
+ const effective = collator.resolvedOptions();
69
+ const locale = new Intl.Locale(canonical);
70
+ const expectedCollation = profile.options.collation ?? locale.collation;
71
+ if (expectedCollation && expectedCollation !== effective.collation) {
72
+ return unsupported(
73
+ `requested collation ${expectedCollation} did not resolve`,
74
+ effective,
75
+ );
76
+ }
77
+ // Unicode extensions are requests too. Unsupported kn/kf must not disappear.
78
+ const extensions = new Map();
79
+ const u = canonical.toLowerCase().split('-x-')[0].split('-u-')[1]?.split('-') ?? [];
80
+ for (let i = 0; i < u.length; i++) {
81
+ if (u[i].length === 1) break; // The next locale extension starts here.
82
+ if (u[i].length === 2) {
83
+ const key = u[i];
84
+ const parts = [];
85
+ while (i + 1 < u.length && u[i + 1].length > 2) parts.push(u[++i]);
86
+ extensions.set(key, parts.join('-') || 'true');
87
+ }
88
+ }
89
+ const expected = { ...profile.options };
90
+ if (!('numeric' in expected) && extensions.has('kn')) {
91
+ if (!['true', 'false'].includes(extensions.get('kn')))
92
+ return unsupported('unsupported kn extension', effective);
93
+ expected.numeric = extensions.get('kn') === 'true';
94
+ }
95
+ if (!('caseFirst' in expected) && extensions.has('kf'))
96
+ expected.caseFirst = extensions.get('kf');
97
+ for (const [key, value] of Object.entries(expected)) {
98
+ if (effective[key] !== value)
99
+ return unsupported(`requested ${key} did not resolve`, effective);
100
+ }
101
+ const results = [];
102
+ for (const left of request.corpus.entries) {
103
+ for (const right of request.corpus.entries) {
104
+ try {
105
+ const value = collator.compare(left.value, right.value);
106
+ if (!Number.isFinite(value)) throw new Error('non-finite comparator return');
107
+ results.push({ left: left.id, right: right.id, status: 'ok', value });
108
+ } catch (error) {
109
+ results.push({
110
+ left: left.id,
111
+ right: right.id,
112
+ status: 'error',
113
+ reason: error.message,
114
+ });
115
+ }
116
+ }
117
+ }
118
+ return { ...base, status: 'ok', effective, results };
119
+ }
120
+
121
+ try {
122
+ const request = JSON.parse(fs.readFileSync(0, 'utf8'));
123
+ process.stdout.write(JSON.stringify(observe(request)) + '\n');
124
+ } catch (error) {
125
+ process.stderr.write(`adapter error: ${error.message}\n`);
126
+ process.exitCode = 1;
127
+ }
collationdelta/cli.py ADDED
@@ -0,0 +1,86 @@
1
+ """Command line entry point. Exit codes are part of the v0.1 public contract."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from . import __version__
9
+ from .evidence import capture, compare, coverage_text, human_report
10
+ from .formats import DeltaError, dump, load, require
11
+
12
+
13
+ class Parser(argparse.ArgumentParser):
14
+ def error(self, message):
15
+ raise DeltaError(message)
16
+
17
+
18
+ def parser():
19
+ root = Parser(
20
+ description="Detect string ordering and equality changes before a runtime upgrade."
21
+ )
22
+ root.add_argument("--version", action="version", version=f"CollationDelta {__version__}")
23
+ commands = root.add_subparsers(dest="command", required=True, parser_class=Parser)
24
+ cap = commands.add_parser(
25
+ "capture", help="observe every ordered pair through an executable adapter"
26
+ )
27
+ cap.add_argument("--corpus", required=True, help="corpus JSON file, at most 256 records")
28
+ cap.add_argument("--profile", required=True, help="requested comparison profile JSON file")
29
+ cap.add_argument("--output", required=True, help="capture JSON destination")
30
+ cap.add_argument(
31
+ "--timeout",
32
+ type=float,
33
+ default=30.0,
34
+ help="whole-process deadline in seconds (default: 30)",
35
+ )
36
+ cap.add_argument("--stdout-limit", type=int, default=16 * 1024 * 1024, help="stdout byte limit")
37
+ cap.add_argument("--stderr-limit", type=int, default=1024 * 1024, help="stderr byte limit")
38
+ cap.add_argument(
39
+ "adapter", nargs=argparse.REMAINDER, help="adapter argv after --; executed without a shell"
40
+ )
41
+ diff = commands.add_parser("compare", help="compare two captures completely offline")
42
+ diff.add_argument("old")
43
+ diff.add_argument("new")
44
+ diff.add_argument("--format", choices=("human", "json"), default="human")
45
+ diff.add_argument("--json-output", help="also save the full versioned JSON report")
46
+ diff.add_argument("--limit", type=int, default=20, help="maximum findings in human output only")
47
+ commands.add_parser("node-adapter", help="print the bundled Intl.Collator adapter path")
48
+ return root
49
+
50
+
51
+ def main(argv=None):
52
+ try:
53
+ args = parser().parse_args(argv)
54
+ if args.command == "node-adapter":
55
+ print(Path(__file__).parent / "adapters" / "node.mjs")
56
+ return 0
57
+ if args.command == "capture":
58
+ adapter = args.adapter[1:] if args.adapter[:1] == ["--"] else args.adapter
59
+ value = capture(
60
+ load(args.corpus),
61
+ load(args.profile),
62
+ adapter,
63
+ timeout=args.timeout,
64
+ stdout_limit=args.stdout_limit,
65
+ stderr_limit=args.stderr_limit,
66
+ )
67
+ dump(args.output, value)
68
+ print(
69
+ f"{'CAPTURED' if value['coverage']['complete'] else 'INCOMPLETE'} | {coverage_text(value['coverage'])}"
70
+ )
71
+ if value["observation"].get("reason"):
72
+ print(json.dumps(value["observation"]["reason"], ensure_ascii=True))
73
+ return 0 if value["coverage"]["complete"] else 2
74
+ require(args.limit >= 0, "human finding limit must be nonnegative")
75
+ report = compare(load(args.old), load(args.new))
76
+ if args.json_output:
77
+ dump(args.json_output, report)
78
+ if args.format == "json":
79
+ json.dump(report, sys.stdout, ensure_ascii=True, sort_keys=True, indent=2)
80
+ print()
81
+ else:
82
+ print(human_report(report, args.limit), end="")
83
+ return {"STABLE": 0, "DRIFT": 1, "INCOMPLETE": 2, "DRIFT_INCOMPLETE": 2}[report["status"]]
84
+ except (DeltaError, OSError, RecursionError) as exc:
85
+ print(f"ERROR: {str(exc)!a}", file=sys.stderr)
86
+ return 3
@@ -0,0 +1,231 @@
1
+ """Capture persistence and deterministic offline relation reports."""
2
+
3
+ import datetime
4
+ import itertools
5
+ import json
6
+ import os
7
+ import platform
8
+
9
+ from . import __version__
10
+ from .formats import canonical, corpus, decode, digest, fields, profile, require
11
+ from .observations import response
12
+ from .transport import run
13
+
14
+
15
+ def capture(entries_document, requested, argv, **limits):
16
+ corpus(entries_document)
17
+ profile(requested)
18
+ request = {"protocol_version": 1, "corpus": entries_document, "profile": requested}
19
+ out, err = run(argv, canonical(request), **limits)
20
+ observed, coverage, _ = response(decode(out, exact_results=True), entries_document["entries"])
21
+ payload = {
22
+ "format_version": 1,
23
+ "corpus": entries_document,
24
+ "requested": requested,
25
+ "observation": observed,
26
+ "coverage": coverage,
27
+ "run": {
28
+ "argv": list(argv),
29
+ "cwd": os.getcwd(),
30
+ "platform": platform.platform(),
31
+ "captured_at": datetime.datetime.now(datetime.UTC).isoformat(),
32
+ "tool_version": __version__,
33
+ "timeout_seconds": limits.get("timeout", 30.0),
34
+ "stdout_limit_bytes": limits.get("stdout_limit", 16 * 1024 * 1024),
35
+ "stderr_limit_bytes": limits.get("stderr_limit", 1024 * 1024),
36
+ "stderr": err.decode("utf-8", errors="replace"),
37
+ },
38
+ }
39
+ return dict(payload, digest=digest(payload))
40
+
41
+
42
+ def validate_capture(value):
43
+ fields(
44
+ value, ("format_version", "corpus", "requested", "observation", "coverage", "run", "digest")
45
+ )
46
+ require(
47
+ type(value["format_version"]) is int and value["format_version"] == 1,
48
+ "unsupported capture format version",
49
+ )
50
+ require(
51
+ isinstance(value["digest"], str)
52
+ and value["digest"] == digest({k: v for k, v in value.items() if k != "digest"}),
53
+ "capture digest mismatch",
54
+ )
55
+ corpus(value["corpus"])
56
+ profile(value["requested"])
57
+ _, coverage, relations = response(
58
+ value["observation"], value["corpus"]["entries"], normalized=True
59
+ )
60
+ require(
61
+ canonical(coverage) == canonical(value["coverage"]),
62
+ "capture coverage does not match observations",
63
+ )
64
+ info = value["run"]
65
+ fields(
66
+ info,
67
+ (
68
+ "argv",
69
+ "cwd",
70
+ "platform",
71
+ "captured_at",
72
+ "tool_version",
73
+ "timeout_seconds",
74
+ "stdout_limit_bytes",
75
+ "stderr_limit_bytes",
76
+ "stderr",
77
+ ),
78
+ )
79
+ require(
80
+ isinstance(info["argv"], list)
81
+ and info["argv"]
82
+ and all(isinstance(arg, str) and arg for arg in info["argv"]),
83
+ "invalid capture argv",
84
+ )
85
+ for key in ("cwd", "platform", "captured_at", "tool_version", "stderr"):
86
+ require(isinstance(info[key], str), f"invalid run field: {key}")
87
+ for key in ("stdout_limit_bytes", "stderr_limit_bytes"):
88
+ require(type(info[key]) is int and info[key] > 0, f"invalid run limit: {key}")
89
+ require(
90
+ type(info["timeout_seconds"]) in (int, float)
91
+ and 0 < info["timeout_seconds"] < float("inf"),
92
+ "invalid run timeout",
93
+ )
94
+ return relations
95
+
96
+
97
+ def compare(old, new):
98
+ old_rel, new_rel = validate_capture(old), validate_capture(new)
99
+ left = {entry["id"]: entry["value"] for entry in old["corpus"]["entries"]}
100
+ right = {entry["id"]: entry["value"] for entry in new["corpus"]["entries"]}
101
+ require(left == right, "incompatible corpora: IDs and exact scalar strings must match")
102
+ require(
103
+ canonical(old["requested"]) == canonical(new["requested"]),
104
+ "incompatible requested profiles",
105
+ )
106
+ sides = {
107
+ label: {
108
+ "capture_digest": side["digest"],
109
+ "effective": side["observation"]["effective"],
110
+ "runtime": side["observation"]["runtime"],
111
+ "adapter": side["observation"]["adapter"],
112
+ "status": side["observation"]["status"],
113
+ "reason": side["observation"].get("reason"),
114
+ "coverage": side["coverage"],
115
+ }
116
+ for label, side in (("old", old), ("new", new))
117
+ }
118
+ findings = []
119
+ records_by_id = {}
120
+
121
+ def record(entry_id):
122
+ if entry_id not in records_by_id:
123
+ value = left[entry_id]
124
+ records_by_id[entry_id] = {
125
+ "id": entry_id,
126
+ "value": value,
127
+ "escaped": json.dumps(value, ensure_ascii=True),
128
+ "code_points": [f"U+{ord(c):04X}" for c in value],
129
+ }
130
+ return records_by_id[entry_id]
131
+
132
+ def oriented_relation(relations, a, b):
133
+ if (a, b) in relations:
134
+ return relations[a, b]
135
+ reverse = relations.get((b, a))
136
+ return -reverse if reverse is not None else None
137
+
138
+ for a, b in itertools.combinations(sorted(left), 2):
139
+ # Each side can observe either direction of the same unordered pair.
140
+ # Normalize signs without counting the missing direction as completed.
141
+ before = oriented_relation(old_rel, a, b)
142
+ after = oriented_relation(new_rel, a, b)
143
+ if before is None or after is None:
144
+ continue
145
+ kind = None
146
+ if before != 0 and after == 0:
147
+ kind = "equality_merge"
148
+ elif before == 0 and after != 0:
149
+ kind = "equality_split"
150
+ elif before * after < 0:
151
+ kind = "order_reversal"
152
+ if kind:
153
+ records = [record(a), record(b)]
154
+ identity = {
155
+ "requested": old["requested"],
156
+ "records": records,
157
+ "kind": kind,
158
+ "old_relation": before,
159
+ "new_relation": after,
160
+ }
161
+ findings.append(
162
+ {
163
+ "id": "cd1-" + digest(identity)[7:],
164
+ "kind": kind,
165
+ "records": records,
166
+ "old_relation": before,
167
+ "new_relation": after,
168
+ }
169
+ )
170
+ complete = old["coverage"]["complete"] and new["coverage"]["complete"]
171
+ status = (
172
+ ("DRIFT" if complete else "DRIFT_INCOMPLETE")
173
+ if findings
174
+ else ("STABLE" if complete else "INCOMPLETE")
175
+ )
176
+ return {
177
+ "report_version": 1,
178
+ "status": status,
179
+ "complete": complete,
180
+ "requested": old["requested"],
181
+ "sides": sides,
182
+ "finding_count": len(findings),
183
+ "findings": findings,
184
+ }
185
+
186
+
187
+ def coverage_text(coverage):
188
+ return (
189
+ f"entries={coverage['entries']} comparisons={coverage['completed_comparisons']}/"
190
+ f"{coverage['expected_comparisons']} missing={coverage['missing_comparisons']} "
191
+ f"failed={coverage['failed_comparisons']} complete={str(coverage['complete']).lower()}"
192
+ )
193
+
194
+
195
+ def human_report(report, limit=20):
196
+ lines = [
197
+ f"{report['status']} | findings={report['finding_count']} | complete={str(report['complete']).lower()}"
198
+ ]
199
+ for label, side in report["sides"].items():
200
+ lines.append(f"{label}: {coverage_text(side['coverage'])}")
201
+ if side["reason"]:
202
+ lines.append(f" {side['status']}: {json.dumps(side['reason'], ensure_ascii=True)}")
203
+ lines.append("Equality means compare(a, b) == 0.")
204
+ for finding in report["findings"][:limit]:
205
+ lines.extend(["", f"{finding['id']} {finding['kind']}"])
206
+ for record in finding["records"]:
207
+ points = " ".join(record["code_points"]) or "(empty)"
208
+ lines.append(
209
+ f" {json.dumps(record['id'], ensure_ascii=True)}: {record['escaped']} [{points}]"
210
+ )
211
+ lines.append(f" relation: {finding['old_relation']:+d} -> {finding['new_relation']:+d}")
212
+ for label, side in report["sides"].items():
213
+ lines.append(
214
+ f" {label} runtime={json.dumps(side['runtime'], ensure_ascii=True, sort_keys=True)}"
215
+ )
216
+ lines.append(
217
+ f" {label} effective={json.dumps(side['effective'], ensure_ascii=True, sort_keys=True)}"
218
+ )
219
+ if len(report["findings"]) > limit:
220
+ lines.append(
221
+ f"\nShown {limit} of {report['finding_count']} findings; JSON contains all evidence."
222
+ )
223
+ if not report["findings"]:
224
+ for label, side in report["sides"].items():
225
+ lines.append(
226
+ f"{label} runtime={json.dumps(side['runtime'], ensure_ascii=True, sort_keys=True)}"
227
+ )
228
+ lines.append(
229
+ f"{label} effective={json.dumps(side['effective'], ensure_ascii=True, sort_keys=True)}"
230
+ )
231
+ return "\n".join(lines) + "\n"
@@ -0,0 +1,168 @@
1
+ """Strict JSON and finite Unicode inputs; no string transformations."""
2
+
3
+ import hashlib
4
+ import json
5
+ import math
6
+ import os
7
+ import tempfile
8
+ from decimal import Decimal, DecimalException
9
+ from pathlib import Path
10
+
11
+ MAX_ENTRIES = 256
12
+ MAX_FILE_BYTES = 32 * 1024 * 1024
13
+
14
+
15
+ class DeltaError(ValueError):
16
+ """Invalid input, inconsistent evidence, or adapter transport failure."""
17
+
18
+
19
+ def require(condition, message):
20
+ if not condition:
21
+ raise DeltaError(message)
22
+
23
+
24
+ def fields(value, required, optional=()):
25
+ require(isinstance(value, dict), "expected JSON object")
26
+ require(set(required) <= value.keys(), f"missing fields: {set(required) - value.keys()}")
27
+ require(value.keys() <= set(required) | set(optional), "unexpected object fields")
28
+
29
+
30
+ def scalar_strings(value):
31
+ if isinstance(value, str):
32
+ require(
33
+ not any(0xD800 <= ord(c) <= 0xDFFF for c in value), "unpaired surrogate in JSON string"
34
+ )
35
+ elif isinstance(value, list):
36
+ for item in value:
37
+ scalar_strings(item)
38
+ elif isinstance(value, dict):
39
+ for key, item in value.items():
40
+ scalar_strings(key)
41
+ scalar_strings(item)
42
+
43
+
44
+ def _object(pairs):
45
+ result = {}
46
+ for key, value in pairs:
47
+ require(key not in result, f"duplicate JSON key: {key!r}")
48
+ result[key] = value
49
+ return result
50
+
51
+
52
+ def _constant(value):
53
+ raise DeltaError(f"non-finite JSON number: {value}")
54
+
55
+
56
+ def _float(token):
57
+ number = float(token)
58
+ require(math.isfinite(number), "JSON number exceeds finite float range")
59
+ require(number != 0 or Decimal(token).is_zero(), "nonzero JSON number underflows to zero")
60
+ return number
61
+
62
+
63
+ def _ordinary_numbers(value):
64
+ if isinstance(value, Decimal):
65
+ return _float(str(value))
66
+ if isinstance(value, list):
67
+ return [_ordinary_numbers(item) for item in value]
68
+ if isinstance(value, dict):
69
+ return {key: _ordinary_numbers(item) for key, item in value.items()}
70
+ return value
71
+
72
+
73
+ def decode(data, *, exact_results=False):
74
+ try:
75
+ value = json.loads(
76
+ data.decode("utf-8", errors="strict"),
77
+ object_pairs_hook=_object,
78
+ parse_constant=_constant,
79
+ parse_float=Decimal if exact_results else _float,
80
+ )
81
+ if exact_results:
82
+ # Normalize comparator returns before conversion to binary floats.
83
+ # Metadata and configuration keep the ordinary JSON representation.
84
+ if isinstance(value, dict) and isinstance(value.get("results"), list):
85
+ for item in value["results"]:
86
+ if isinstance(item, dict) and item.get("status") == "ok":
87
+ number = item.get("value")
88
+ if isinstance(number, Decimal):
89
+ require(number.is_finite(), "comparator result must be finite")
90
+ item["value"] = (number > 0) - (number < 0)
91
+ value = _ordinary_numbers(value)
92
+ scalar_strings(value)
93
+ # Reject overflow such as 1e999 as well as explicit NaN/Infinity.
94
+ canonical(value)
95
+ return value
96
+ except (UnicodeError, ValueError, RecursionError, DecimalException) as exc:
97
+ raise DeltaError(f"invalid UTF-8/Unicode JSON: {exc}") from exc
98
+
99
+
100
+ def load(path):
101
+ with Path(path).open("rb") as stream:
102
+ data = stream.read(MAX_FILE_BYTES + 1)
103
+ require(len(data) <= MAX_FILE_BYTES, "JSON file exceeds 32 MiB limit")
104
+ return decode(data)
105
+
106
+
107
+ def canonical(value):
108
+ return json.dumps(
109
+ value, ensure_ascii=True, sort_keys=True, separators=(",", ":"), allow_nan=False
110
+ ).encode("ascii")
111
+
112
+
113
+ def digest(value):
114
+ return "sha256:" + hashlib.sha256(canonical(value)).hexdigest()
115
+
116
+
117
+ def dump(path, value):
118
+ # ASCII escaping preserves scalar strings and keeps control characters inert.
119
+ destination = Path(path)
120
+ temporary = None
121
+ try:
122
+ with tempfile.NamedTemporaryFile(
123
+ mode="wb", dir=destination.parent, prefix=".collationdelta-", delete=False
124
+ ) as stream:
125
+ temporary = Path(stream.name)
126
+ size = 0
127
+ encoder = json.JSONEncoder(ensure_ascii=True, sort_keys=True, indent=2, allow_nan=False)
128
+ for chunk in encoder.iterencode(value):
129
+ data = chunk.encode("ascii")
130
+ size += len(data)
131
+ require(size + 1 <= MAX_FILE_BYTES, "output exceeds 32 MiB file limit")
132
+ stream.write(data)
133
+ stream.write(b"\n")
134
+ stream.flush()
135
+ os.fsync(stream.fileno())
136
+ os.replace(temporary, destination)
137
+ finally:
138
+ if temporary is not None:
139
+ temporary.unlink(missing_ok=True)
140
+
141
+
142
+ def corpus(value):
143
+ fields(value, ("version", "entries"))
144
+ require(type(value["version"]) is int and value["version"] == 1, "unsupported corpus version")
145
+ entries = value["entries"]
146
+ require(
147
+ isinstance(entries, list) and 1 <= len(entries) <= MAX_ENTRIES,
148
+ f"corpus requires 1..{MAX_ENTRIES} entries",
149
+ )
150
+ ids = set()
151
+ for entry in entries:
152
+ fields(entry, ("id", "value"))
153
+ require(isinstance(entry["id"], str) and entry["id"], "entry ID must be a nonempty string")
154
+ require(isinstance(entry["value"], str), "entry value must be a string")
155
+ scalar_strings(entry)
156
+ require(entry["id"] not in ids, f"duplicate entry ID: {entry['id']!r}")
157
+ ids.add(entry["id"])
158
+ return value
159
+
160
+
161
+ def profile(value):
162
+ fields(value, ("version", "contract", "locale", "options"))
163
+ require(type(value["version"]) is int and value["version"] == 1, "unsupported profile version")
164
+ for key in ("contract", "locale"):
165
+ require(isinstance(value[key], str) and value[key], f"{key} must be a nonempty string")
166
+ require(isinstance(value["options"], dict), "options must be an object")
167
+ scalar_strings(value)
168
+ return value
@@ -0,0 +1,154 @@
1
+ """Validate a finite total preorder, including partial-observation contradictions."""
2
+
3
+ import math
4
+
5
+ from .formats import fields, require
6
+
7
+
8
+ def response(value, entries, *, normalized=False):
9
+ fields(
10
+ value,
11
+ ("protocol_version", "status", "effective", "runtime", "adapter", "results"),
12
+ ("reason",),
13
+ )
14
+ require(
15
+ type(value["protocol_version"]) is int and value["protocol_version"] == 1,
16
+ "unsupported adapter protocol version",
17
+ )
18
+ require(value["status"] in ("ok", "unsupported", "unresolved"), "invalid adapter status")
19
+ if "reason" in value:
20
+ require(
21
+ isinstance(value["reason"], str) and value["reason"], "reason must be a nonempty string"
22
+ )
23
+ if value["status"] != "ok":
24
+ require(
25
+ isinstance(value.get("reason"), str) and value["reason"],
26
+ "configuration failure requires reason",
27
+ )
28
+ require(
29
+ value["effective"] is None or isinstance(value["effective"], dict),
30
+ "invalid effective settings",
31
+ )
32
+ if value["status"] == "ok":
33
+ require(
34
+ isinstance(value["effective"], dict) and value["effective"],
35
+ "ok requires effective settings",
36
+ )
37
+ for key in ("runtime", "adapter"):
38
+ require(isinstance(value[key], dict) and value[key], f"{key} metadata required")
39
+ require(isinstance(value["results"], list), "results must be an array")
40
+ require(len(value["results"]) <= len(entries) ** 2, "too many results")
41
+ if value["status"] == "unsupported":
42
+ require(not value["results"], "unsupported configuration must not report comparisons")
43
+ ids = {e["id"] for e in entries}
44
+ seen, relations, results = set(), {}, []
45
+ failed = 0
46
+ for item in value["results"]:
47
+ fields(item, ("left", "right", "status"), ("value", "reason"))
48
+ require(
49
+ isinstance(item["left"], str) and isinstance(item["right"], str),
50
+ "pair IDs must be strings",
51
+ )
52
+ pair = item["left"], item["right"]
53
+ require(pair[0] in ids and pair[1] in ids, "unrequested pair in results")
54
+ require(pair not in seen, f"duplicate pair result: {pair!r}")
55
+ seen.add(pair)
56
+ status = item["status"]
57
+ require(status in ("ok", "error", "unresolved"), "invalid pair status")
58
+ result = dict(item)
59
+ if status == "ok":
60
+ require("value" in item and "reason" not in item, "ok requires value only")
61
+ number = item["value"]
62
+ require(type(number) in (int, float), "comparator result must be a finite number")
63
+ require(
64
+ type(number) is int or math.isfinite(number), "comparator result must be finite"
65
+ )
66
+ if normalized:
67
+ require(
68
+ type(number) is int and number in (-1, 0, 1),
69
+ "capture relation must be integer sign",
70
+ )
71
+ result["value"] = (number > 0) - (number < 0)
72
+ relations[pair] = result["value"]
73
+ else:
74
+ require(
75
+ "value" not in item and isinstance(item.get("reason"), str) and item["reason"],
76
+ "failed comparison requires reason and no value",
77
+ )
78
+ failed += 1
79
+ results.append(result)
80
+ require(
81
+ not relations or bool(value["effective"]), "observed comparisons require effective settings"
82
+ )
83
+ consistency(entries, relations)
84
+ complete = value["status"] == "ok" and len(relations) == len(entries) ** 2
85
+ coverage = {
86
+ "entries": len(entries),
87
+ "expected_comparisons": len(entries) ** 2,
88
+ "completed_comparisons": len(relations),
89
+ "failed_comparisons": failed,
90
+ "missing_comparisons": len(entries) ** 2 - len(seen),
91
+ "complete": complete,
92
+ "consistency": "verified" if complete else "consistent_partial",
93
+ }
94
+ clean = dict(value, results=sorted(results, key=lambda x: (x["left"], x["right"])))
95
+ return clean, coverage, relations
96
+
97
+
98
+ def consistency(entries, relations):
99
+ # Equality components, followed by strict-order DAG. A cycle or an edge
100
+ # inside a component contradicts any extension to a total preorder.
101
+ values = {entry["id"]: entry["value"] for entry in entries}
102
+ parent = {i: i for i in values}
103
+ rank = {i: 0 for i in values}
104
+
105
+ def find(i):
106
+ while parent[i] != i:
107
+ parent[i] = parent[parent[i]]
108
+ i = parent[i]
109
+ return i
110
+
111
+ def union(a, b):
112
+ a, b = find(a), find(b)
113
+ if a == b:
114
+ return
115
+ if rank[a] < rank[b]:
116
+ a, b = b, a
117
+ parent[b] = a
118
+ if rank[a] == rank[b]:
119
+ rank[a] += 1
120
+
121
+ representatives = {}
122
+ for entry_id, value in values.items():
123
+ if value in representatives:
124
+ union(entry_id, representatives[value])
125
+ else:
126
+ representatives[value] = entry_id
127
+
128
+ for (a, b), sign in relations.items():
129
+ require(a != b or sign == 0, f"nonzero self comparison: {a!r}")
130
+ require(values[a] != values[b] or sign == 0, "nonzero comparison of identical strings")
131
+ reverse = relations.get((b, a))
132
+ require(reverse is None or reverse == -sign, f"inconsistent reverse comparison: {(a, b)!r}")
133
+ if sign == 0:
134
+ union(a, b)
135
+ graph = {find(i): set() for i in values}
136
+ for (a, b), sign in relations.items():
137
+ if sign:
138
+ a, b = find(a), find(b)
139
+ require(a != b, "strict relation contradicts equality transitivity")
140
+ graph[a if sign < 0 else b].add(b if sign < 0 else a)
141
+ indegree = {i: 0 for i in graph}
142
+ for neighbors in graph.values():
143
+ for node in neighbors:
144
+ indegree[node] += 1
145
+ ready = [i for i in graph if indegree[i] == 0]
146
+ visited = 0
147
+ while ready:
148
+ node = ready.pop()
149
+ visited += 1
150
+ for neighbor in graph[node]:
151
+ indegree[neighbor] -= 1
152
+ if indegree[neighbor] == 0:
153
+ ready.append(neighbor)
154
+ require(visited == len(graph), "strict-order cycle contradicts transitivity")
@@ -0,0 +1,92 @@
1
+ """One bounded batch process, with concurrent stdin/stdout/stderr I/O on POSIX."""
2
+
3
+ import os
4
+ import selectors
5
+ import signal
6
+ import subprocess
7
+ import time
8
+
9
+ from .formats import DeltaError, require
10
+
11
+
12
+ def run(argv, request, *, timeout=30.0, stdout_limit=16 * 1024 * 1024, stderr_limit=1024 * 1024):
13
+ require(os.name == "posix", "adapter execution currently requires Linux or macOS")
14
+ require(
15
+ argv and all(isinstance(arg, str) and arg for arg in argv),
16
+ "adapter argv is empty or invalid",
17
+ )
18
+ require(timeout > 0 and timeout < float("inf"), "timeout must be positive and finite")
19
+ require(stdout_limit > 0 and stderr_limit > 0, "output limits must be positive")
20
+ try:
21
+ proc = subprocess.Popen(
22
+ argv,
23
+ stdin=subprocess.PIPE,
24
+ stdout=subprocess.PIPE,
25
+ stderr=subprocess.PIPE,
26
+ shell=False,
27
+ start_new_session=True,
28
+ )
29
+ except (OSError, ValueError) as exc:
30
+ raise DeltaError(f"adapter launch failed: {exc}") from exc
31
+ output = {"stdout": bytearray(), "stderr": bytearray()}
32
+ limits = {"stdout": stdout_limit, "stderr": stderr_limit}
33
+ deadline = time.monotonic() + timeout
34
+ offset = 0
35
+ try:
36
+ with selectors.DefaultSelector() as selector:
37
+ for stream, label in (
38
+ (proc.stdin, "stdin"),
39
+ (proc.stdout, "stdout"),
40
+ (proc.stderr, "stderr"),
41
+ ):
42
+ os.set_blocking(stream.fileno(), False)
43
+ selector.register(
44
+ stream,
45
+ selectors.EVENT_WRITE if label == "stdin" else selectors.EVENT_READ,
46
+ label,
47
+ )
48
+ while selector.get_map():
49
+ remaining = deadline - time.monotonic()
50
+ if remaining <= 0:
51
+ raise DeltaError(f"adapter timeout after {timeout:g}s")
52
+ for key, _ in selector.select(min(remaining, 0.1)):
53
+ stream, label = key.fileobj, key.data
54
+ if label == "stdin":
55
+ try:
56
+ offset += os.write(stream.fileno(), request[offset : offset + 65536])
57
+ except BrokenPipeError:
58
+ offset = len(request)
59
+ if offset == len(request):
60
+ selector.unregister(stream)
61
+ stream.close()
62
+ else:
63
+ chunk = os.read(stream.fileno(), 65536)
64
+ if not chunk:
65
+ selector.unregister(stream)
66
+ stream.close()
67
+ else:
68
+ if len(output[label]) + len(chunk) > limits[label]:
69
+ raise DeltaError(
70
+ f"adapter {label} exceeds {limits[label]} byte limit"
71
+ )
72
+ output[label].extend(chunk)
73
+ remaining = deadline - time.monotonic()
74
+ if remaining <= 0:
75
+ raise DeltaError(f"adapter timeout after {timeout:g}s")
76
+ try:
77
+ code = proc.wait(timeout=remaining)
78
+ except subprocess.TimeoutExpired as exc:
79
+ raise DeltaError(f"adapter timeout after {timeout:g}s") from exc
80
+ if code != 0:
81
+ diagnostic = bytes(output["stderr"]).decode("utf-8", errors="replace")
82
+ raise DeltaError(f"adapter exited {code}; stderr={diagnostic!r}")
83
+ return bytes(output["stdout"]), bytes(output["stderr"])
84
+ finally:
85
+ # Also close descendant-held pipes and stop descendants on timeout/limits.
86
+ try:
87
+ os.killpg(proc.pid, signal.SIGKILL)
88
+ except ProcessLookupError:
89
+ pass
90
+ proc.wait()
91
+ for stream in (proc.stdin, proc.stdout, proc.stderr):
92
+ stream.close()
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.4
2
+ Name: collationdelta
3
+ Version: 0.1.0
4
+ Summary: Detect string ordering and equality changes before a runtime upgrade.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/0then0/collationdelta
7
+ Project-URL: Repository, https://github.com/0then0/collationdelta
8
+ Project-URL: Documentation, https://github.com/0then0/collationdelta/blob/main/README.md
9
+ Project-URL: Issues, https://github.com/0then0/collationdelta/issues
10
+ Project-URL: Changelog, https://github.com/0then0/collationdelta/blob/main/CHANGELOG.md
11
+ Keywords: collation,unicode,cli,runtime-upgrade,drift-detection
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Operating System :: MacOS :: MacOS X
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Software Development :: Testing
22
+ Requires-Python: >=3.12
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Dynamic: license-file
26
+
27
+ <p align="center"><img src="https://raw.githubusercontent.com/0then0/collationdelta/main/docs/icon.svg" width="88" height="88" alt="CollationDelta: two string relations joined by a delta" /></p>
28
+
29
+ # CollationDelta
30
+
31
+ **Detect string ordering and equality changes before a runtime upgrade.**
32
+
33
+ [![PyPI](https://img.shields.io/pypi/v/collationdelta)](https://pypi.org/project/collationdelta/)
34
+ ![Python requirement](https://img.shields.io/badge/requires-Python%203.12%2B-blue)
35
+ ![Runtime dependencies](https://img.shields.io/badge/core-runtime%20dependencies%200-green)
36
+ ![License](https://img.shields.io/badge/license-Apache%202.0-blue)
37
+
38
+ CollationDelta records the actual comparison results for your finite string corpus through an executable adapter. Capture a baseline in the old environment, capture the same corpus and requested profile in the new environment, then compare the two files offline. The old runtime is no longer needed.
39
+
40
+ It reports equality merges, equality splits, and order reversals as individual pair witnesses. **Equality means `compare(a, b) == 0`**, not matching bytes, Unicode identity, or SQL equality. A runtime version change alone is not drift; a changed relation is drift even when version labels stay the same.
41
+
42
+ ## Install and try
43
+
44
+ Python 3.12 or newer is required. Node is needed only to capture through the included `Intl.Collator` adapter. There are no Python runtime dependencies and no npm dependencies.
45
+
46
+ For a published release, install from PyPI:
47
+
48
+ ```sh
49
+ pip install collationdelta==0.1.0
50
+ collationdelta --help
51
+ ```
52
+
53
+ To try the source checkout, including the example input files:
54
+
55
+ ```sh
56
+ git clone https://github.com/0then0/collationdelta.git
57
+ cd collationdelta
58
+ ```
59
+
60
+ Then run:
61
+
62
+ ```sh
63
+ uv sync --locked --python 3.12
64
+ uv run collationdelta --help
65
+ uv run collationdelta capture \
66
+ --corpus examples/corpus.json --profile examples/profile.json \
67
+ --output /tmp/baseline.json -- node "$(uv run collationdelta node-adapter)"
68
+ uv run collationdelta capture \
69
+ --corpus examples/corpus.json --profile examples/profile.json \
70
+ --output /tmp/current.json -- node "$(uv run collationdelta node-adapter)"
71
+ uv run collationdelta compare /tmp/baseline.json /tmp/current.json \
72
+ --json-output /tmp/report.json
73
+ ```
74
+
75
+ The same-runtime control returns `STABLE`. Use the old environment for the first command and the upgraded environment for the second to check an upgrade. The shell substitution above locates the installed adapter; CollationDelta itself runs the supplied argv without shell interpolation.
76
+
77
+ To build and install locally:
78
+
79
+ ```sh
80
+ uv build
81
+ uv venv /tmp/collationdelta-install --python 3.12
82
+ uv pip install --python /tmp/collationdelta-install/bin/python dist/collationdelta-0.1.0-py3-none-any.whl
83
+ /tmp/collationdelta-install/bin/collationdelta --help
84
+ ```
85
+
86
+ The Node adapter ships inside the wheel; `collationdelta node-adapter` prints its location after installation.
87
+
88
+ ## Inputs and guarantees
89
+
90
+ Corpus JSON:
91
+
92
+ ```json
93
+ {
94
+ "version": 1,
95
+ "entries": [
96
+ { "id": "rupee", "value": "₨" },
97
+ { "id": "letters", "value": "Rs" },
98
+ { "id": "zero", "value": "0" }
99
+ ]
100
+ }
101
+ ```
102
+
103
+ Profile JSON:
104
+
105
+ ```json
106
+ {
107
+ "version": 1,
108
+ "contract": "intl.collator.v1",
109
+ "locale": "en",
110
+ "options": { "sensitivity": "base" }
111
+ }
112
+ ```
113
+
114
+ IDs are unique, nonempty, stable strings. Duplicate values under different IDs are allowed. Values are preserved exactly: no trimming, case folding, normalization, control-character removal, or deduplication. Empty strings, embedded U+0000, newlines, combining marks, and supplementary characters are supported. Invalid UTF-8 and unpaired surrogates are rejected. JSON-escaped valid surrogate pairs decode to their scalar character.
115
+
116
+ The corpus must have **1–256 entries**. Each capture requests all `n²` ordered comparisons, including the diagonal, in a single process. A complete capture of 256 entries contains 65,536 comparisons. No sampling is used. JSON input/output files are limited to 32 MiB; long strings may reach transport or file limits before the entry limit.
117
+
118
+ The requested profile is distinct from adapter-reported effective settings and runtime/provider metadata. The Node adapter reports `process.version`, ICU, CLDR and Unicode versions when available, and `resolvedOptions()`. A custom adapter's version claim is evidence supplied by that adapter, not independent verification of its environment.
119
+
120
+ Supported Node options are `sensitivity`, `numeric`, `caseFirst`, `ignorePunctuation`, `usage`, and `collation`. The adapter delegates every comparison to `Intl.Collator`. It allows locale canonicalization and lookup negotiation, such as `EN-us` or a supported language with an unavailable region. Unsupported locales and silently ignored explicit collations are reported as unsupported. Explicit options and the recognized `co`, `kn`, `kf` locale extensions must resolve; explicit options take precedence over extensions. Other locale extensions do not define this adapter's comparison contract. See [the protocol guide](https://github.com/0then0/collationdelta/blob/main/docs/protocol.md) for the exact option values and custom adapters.
121
+
122
+ ## Results and exit codes
123
+
124
+ Human reports begin with status and coverage: entries, expected/completed comparisons, missing/failed comparisons, and completeness. Each finding contains both IDs, safely escaped original values, Unicode code points, old/new relation signs, runtime metadata, and effective settings. Reciprocal comparisons validate the observation; findings appear once per unordered pair. A pair is a direct witness, not a claim of global minimization.
125
+
126
+ `compare --format json` emits a versioned, deterministic full report. `--json-output FILE` also saves it alongside human output. `--limit N` affects only the number of findings shown in human output; total counts and JSON evidence remain complete. The full JSON report contains shared old/new runtime and effective metadata in `sides`, referenced by every finding's old/new relations.
127
+
128
+ - **0:** `STABLE` for complete, valid, compatible captures; `CAPTURED` for a successful complete capture; informational commands.
129
+ - **1:** `DRIFT`, with complete observations and one or more findings.
130
+ - **2:** `INCOMPLETE` or `DRIFT_INCOMPLETE`. Capture also returns 2 for unsupported/unresolved configuration or missing/failed comparisons and saves the valid partial evidence.
131
+ - **3:** `ERROR`: invalid input, incompatible captures, inconsistent relations, digest failure, launch/crash/timeout/output limit failure, or malformed protocol. No new capture is written on a transport/protocol error.
132
+
133
+ Incomplete comparison preserves findings for a pair observed successfully in either direction on each side, even when diagonal or reciprocal observations are missing. Each side is independently oriented by stable IDs; the inferred reverse sign does not increase completed coverage. Unknown results are never equality. A successful process with missing pair responses produces explicit incomplete coverage; duplicate or unrequested pair responses are protocol errors. A crash with partial stdout is a transport error because a single-batch response cannot be trusted as a finished protocol document.
134
+
135
+ ## Real runtime upgrade evidence
136
+
137
+ The [reproducible case study](https://github.com/0then0/collationdelta/blob/main/docs/case-study.md) compares the official Node **18.20.8 / ICU 74.2 / CLDR 44.1** and **24.21.0 / ICU 78.3 / CLDR 48.0** binaries with the same `en` / `sensitivity: base` profile. Saved captures and reports are in [evidence/node-upgrade](https://github.com/0then0/collationdelta/tree/main/evidence/node-upgrade). They show an equality merge for `₨` / `Rs` and an order reversal for `₨` / `0`, a same-runtime control, repeated observations, and offline analysis.
138
+
139
+ The two-element sorted snapshot `["₨", "Rs"]` stays the same while equality changes. The included **demonstration application example** sorts and removes adjacent collation-equal strings; its result changes from two records to one. This is a demonstration, not an external production incident. The experiment upgrades the entire Node runtime and does not isolate the effect of ICU alone.
140
+
141
+ ## Evidence and consistency
142
+
143
+ Captures embed corpus, requested profile, effective settings, normalized signs, explicit failures, coverage, runtime/adapter metadata, invocation argv, working directory, platform, UTC timestamp, limits, diagnostics, and a SHA-256 content digest. The digest detects accidental or uncoordinated content alteration; anyone able to edit a capture can recompute it. It is not a signature or proof of runtime authenticity. Environment variables, application configuration files, and executable contents are not bundled; preserve them separately when needed for reproduction. Captures may contain sensitive corpus values and command arguments.
144
+
145
+ On load, CollationDelta validates the schema, digest, observations, and recomputed coverage. Corpus ID/value mappings must match exactly, although record order may differ. Requested profiles must match exactly, including locale spelling; canonicalization is an adapter operation during capture. Effective settings may differ and are exposed for interpretation rather than silently requiring agreement.
146
+
147
+ The consistency check treats identical string values under different IDs as equal and rejects nonzero comparisons between them, nonzero self comparisons, inconsistent reciprocal results, contradictions in equality components, and cycles of strict order. Union-find constructs equality components, then topological traversal checks the graph of strict relations. Time is `O(n² α(n))` and memory `O(n²)` for a full corpus; `α(n)` is the near-constant inverse Ackermann cost of union-find. For partial observations this checks whether known relations can extend to a total preorder; it cannot verify unknown relations. Contradictory observations are errors, never equivalence classes or stability claims.
148
+
149
+ ## Related work and boundaries
150
+
151
+ [Unicode Conformance](https://github.com/unicode-org/conformance) provides data-driven testing against Unicode/CLDR specifications across implementations. CollationDelta shares the idea of executable comparison observations, but its reference is your saved application baseline rather than specification conformance.
152
+
153
+ [glibc-unicode-sorting](https://github.com/ardentperf/glibc-unicode-sorting) studies sorting changes across OS/ICU versions through PostgreSQL, including sorted-output checksums over large datasets. CollationDelta uses a bounded user corpus and explicit equality/order pair witnesses. The distinction is the combination of **your corpus, your actual application comparator, a portable baseline, and separate equality drift detection**. It does not imply that other tools cannot compare pairs or accept custom data.
154
+
155
+ [ICU 76 release notes](https://unicode-org.github.io/icu/download/76.html) document root-collation changes, including currency-symbol ordering; [the ICU Collation API guide](https://unicode-org.github.io/icu/userguide/collation/api.html) describes direct string comparisons and warns that keys from different collators are not comparable. CollationDelta compares observed relation signs, never persisted sort-key bytes, and adds no bytewise tiebreaker. The release notes provide context for the case, not proof of its isolated cause.
156
+
157
+ Stability on a finite corpus says nothing about all Unicode strings. Drift means a change relative to the selected baseline, not an error in the new implementation. Node comparison evidence does not establish SQL `UNIQUE`, `GROUP BY`, or any database collation's behavior. This tool checks neither physical database index correctness nor provider/database rebuild requirements.
158
+
159
+ v0.1 is a local capture/compare CLI. It does not implement UCA, offer a universal conformance suite, fuzz all Unicode, scan production databases, manage runtimes/Docker, migrate databases, run `REINDEX`, accept new baselines automatically, or recommend remediation without application evidence. It has one reference Node adapter and one custom-adapter example; no web UI, daemon, SaaS, or plugin registry.
160
+
161
+ ## Development and validation
162
+
163
+ ```sh
164
+ uv sync --locked --python 3.12
165
+ uv run --locked ruff check .
166
+ uv run --locked ruff format --check .
167
+ uv run --locked pytest
168
+ uv build
169
+ ```
170
+
171
+ Tests cover drift types, Unicode preservation, finite-order consistency, strict protocol/transport failures, partial evidence, corruption, deterministic reports, offline comparison, and the actual Node adapter. Unit tests use synthetic fixtures only for controlled core and failure cases; the historical upgrade uses official binaries. Unit tests never download historical runtimes.
172
+
173
+ Ruff checks Python errors, imports, Python 3.12 modernization, and common bug patterns with a 100-column formatting target. To apply formatting, run `uv run --locked ruff format .`. The formatter controls wrapping; long strings and comments are exempt from the linter's line-length check.
174
+
175
+ The CLI's POSIX process transport targets Linux and macOS. CI is configured for both with Python 3.12–3.14 and Node 24.21.0, including clean-wheel installation. Local verification results and unverified platform claims are recorded in the [validation report](https://github.com/0then0/collationdelta/blob/main/docs/validation.md). Windows adapter execution is unsupported in v0.1.
176
+
177
+ The existing [Apache-2.0 license](https://github.com/0then0/collationdelta/blob/main/LICENSE) applies to this project. Node downloads remain separate, external artifacts with their own licensing.
178
+
179
+ ## Releases
180
+
181
+ Release notes are in the [changelog](https://github.com/0then0/collationdelta/blob/main/CHANGELOG.md). Maintainers can follow the [release guide](https://github.com/0then0/collationdelta/blob/main/docs/releasing.md) to publish a version through PyPI Trusted Publishing.
@@ -0,0 +1,14 @@
1
+ collationdelta/__init__.py,sha256=KtvEE669twu53fhDe8woZfE9dZtPPcOKWCiq5Ho3N2w,94
2
+ collationdelta/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ collationdelta/cli.py,sha256=Mhk6E1PVvJoapez6O4yvkqu-xCnDDPzXmhNByst-PBo,3745
4
+ collationdelta/evidence.py,sha256=sL2KUxiQoWACdAjVR2UX2DWKuPjZUUigP-HZUblc3nY,8618
5
+ collationdelta/formats.py,sha256=kR7NN8fs_in6JAHTJoSWyRzlN4SCrxqRrFK8zSO2lGU,5892
6
+ collationdelta/observations.py,sha256=Fo0YnJ5zJLdu7bhtkZ173se6AQSu5Q_wUXgz1-LIYa4,6092
7
+ collationdelta/transport.py,sha256=ksFR4mVN8056bdStRcCj8GVyiNRRd3dOVATUk6PhX0E,3956
8
+ collationdelta/adapters/node.mjs,sha256=vmwXi99626yGjTDvJMTvRRa57WWkGi9KkzWlhKoSUfU,4511
9
+ collationdelta-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
10
+ collationdelta-0.1.0.dist-info/METADATA,sha256=FRymiPN3ThbWR1Sf-aMoNz9JDDF598XJmnUhIjYoy0g,14994
11
+ collationdelta-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
12
+ collationdelta-0.1.0.dist-info/entry_points.txt,sha256=9m4gb09NKOV2Yd2_IYn5YQFd17WNQLgYtOA-Ymar-uU,59
13
+ collationdelta-0.1.0.dist-info/top_level.txt,sha256=MA4uT07GsPNQmWeCKvF48E1GldsTh7_Q8K88ngA3IRA,15
14
+ collationdelta-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ collationdelta = collationdelta.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ collationdelta