metaformat 0.1.0a1__tar.gz

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,38 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+ permissions:
7
+ contents: read
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: actions/setup-python@v5
15
+ with:
16
+ python-version: "3.12"
17
+ - name: Build distributions
18
+ run: |
19
+ python -m pip install --upgrade build
20
+ python -m build
21
+ - uses: actions/upload-artifact@v4
22
+ with:
23
+ name: python-package-distributions
24
+ path: dist/
25
+
26
+ publish:
27
+ needs: build
28
+ runs-on: ubuntu-latest
29
+ environment: pypi
30
+ permissions:
31
+ id-token: write
32
+ steps:
33
+ - uses: actions/download-artifact@v4
34
+ with:
35
+ name: python-package-distributions
36
+ path: dist/
37
+ - name: Publish to PyPI
38
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.5
2
+ Name: metaformat
3
+ Version: 0.1.0a1
4
+ Summary: Experimental locus/relation engine for attributable semantic facts over heterogeneous records
5
+ Project-URL: Homepage, https://github.com/saya-si/metaformat
6
+ Project-URL: Repository, https://github.com/saya-si/metaformat
7
+ Project-URL: Issues, https://github.com/saya-si/metaformat/issues
8
+ Author-email: Saya <saya@mindey.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: data-integration,interoperability,metadata,provenance,semantic-data
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+
21
+ # metaformat
22
+
23
+ Experimental alpha. Not a frozen protocol specification.
24
+
25
+ metaformat is a small locus/relation engine for turning heterogeneous source records into attributable semantic facts without destructively replacing the source representation.
26
+
27
+ The motivating model is:
28
+
29
+ raw record + sparse relation sets
30
+ |
31
+ v
32
+ attributable semantic facts
33
+ |
34
+ v
35
+ cheap deterministic joins and comparisons
36
+
37
+ A semantic fact retains a reversible route back toward the source:
38
+
39
+ fact -> locus -> record -> origin -> affordance -> authority resolver
40
+
41
+ ## Core ideas
42
+
43
+ - Loci identify a path inside an interpretation/source context.
44
+ - Relative loci let a relation set attach mid-context and remain relocatable.
45
+ - Sparse relation sets attach meaning, normalization, provenance, modality, affordances, authority references, and other open-ended relations to loci.
46
+ - Content-addressed relation sets make interpretations versionable without requiring mutable global schema IDs.
47
+ - Semantic facts retain both raw and normalized values plus source/provenance information.
48
+ - Cross-source joins operate on semantic coordinates such as (subject, concept) after mappings have been established.
49
+ - Unknown relation names remain ordinary data; partial understanding should not invalidate the rest.
50
+
51
+ ## Example
52
+
53
+ from metaformat import emit_facts, seal_relation_set
54
+
55
+ profile = seal_relation_set({
56
+ "base": {"context": "ctx:example", "path": "/devices/*"},
57
+ "relations": {
58
+ ".": [
59
+ ["identity_by", {"path": "./id", "prefix": "device:"}],
60
+ ],
61
+ "./active": [
62
+ ["means", "runtime:active"],
63
+ ["normalize", "runtime:active-bool"],
64
+ ],
65
+ },
66
+ })
67
+
68
+ raw = {
69
+ "devices": [
70
+ {"id": "alpha", "active": "active"},
71
+ ]
72
+ }
73
+
74
+ facts = emit_facts(raw, [profile], context="ctx:example")
75
+
76
+ ## Status
77
+
78
+ This package began as an experimental kernel for a broader Metaformat idea: preserving interpretability, meta-addressability, provenance, semantic pluralism, composability, modality, affordances, authority separation, and partial intelligibility across heterogeneous information systems.
79
+
80
+ The current release intentionally implements only the small reusable kernel that has survived practical experiments so far. Expect API changes during the alpha series.
81
+
82
+ ## License
83
+
84
+ Apache-2.0.
@@ -0,0 +1,64 @@
1
+ # metaformat
2
+
3
+ Experimental alpha. Not a frozen protocol specification.
4
+
5
+ metaformat is a small locus/relation engine for turning heterogeneous source records into attributable semantic facts without destructively replacing the source representation.
6
+
7
+ The motivating model is:
8
+
9
+ raw record + sparse relation sets
10
+ |
11
+ v
12
+ attributable semantic facts
13
+ |
14
+ v
15
+ cheap deterministic joins and comparisons
16
+
17
+ A semantic fact retains a reversible route back toward the source:
18
+
19
+ fact -> locus -> record -> origin -> affordance -> authority resolver
20
+
21
+ ## Core ideas
22
+
23
+ - Loci identify a path inside an interpretation/source context.
24
+ - Relative loci let a relation set attach mid-context and remain relocatable.
25
+ - Sparse relation sets attach meaning, normalization, provenance, modality, affordances, authority references, and other open-ended relations to loci.
26
+ - Content-addressed relation sets make interpretations versionable without requiring mutable global schema IDs.
27
+ - Semantic facts retain both raw and normalized values plus source/provenance information.
28
+ - Cross-source joins operate on semantic coordinates such as (subject, concept) after mappings have been established.
29
+ - Unknown relation names remain ordinary data; partial understanding should not invalidate the rest.
30
+
31
+ ## Example
32
+
33
+ from metaformat import emit_facts, seal_relation_set
34
+
35
+ profile = seal_relation_set({
36
+ "base": {"context": "ctx:example", "path": "/devices/*"},
37
+ "relations": {
38
+ ".": [
39
+ ["identity_by", {"path": "./id", "prefix": "device:"}],
40
+ ],
41
+ "./active": [
42
+ ["means", "runtime:active"],
43
+ ["normalize", "runtime:active-bool"],
44
+ ],
45
+ },
46
+ })
47
+
48
+ raw = {
49
+ "devices": [
50
+ {"id": "alpha", "active": "active"},
51
+ ]
52
+ }
53
+
54
+ facts = emit_facts(raw, [profile], context="ctx:example")
55
+
56
+ ## Status
57
+
58
+ This package began as an experimental kernel for a broader Metaformat idea: preserving interpretability, meta-addressability, provenance, semantic pluralism, composability, modality, affordances, authority separation, and partial intelligibility across heterogeneous information systems.
59
+
60
+ The current release intentionally implements only the small reusable kernel that has survived practical experiments so far. Expect API changes during the alpha series.
61
+
62
+ ## License
63
+
64
+ Apache-2.0.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "metaformat"
7
+ version = "0.1.0a1"
8
+ description = "Experimental locus/relation engine for attributable semantic facts over heterogeneous records"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ authors = [
13
+ {name = "Saya", email = "saya@mindey.com"}
14
+ ]
15
+ keywords = ["metadata", "semantic-data", "data-integration", "provenance", "interoperability"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "Intended Audience :: Science/Research",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/saya-si/metaformat"
27
+ Repository = "https://github.com/saya-si/metaformat"
28
+ Issues = "https://github.com/saya-si/metaformat/issues"
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/metaformat"]
32
+
33
+ [tool.pytest.ini_options]
34
+ testpaths = ["tests"]
@@ -0,0 +1,50 @@
1
+ """Metaformat: experimental locus/relation engine for attributable semantic facts."""
2
+
3
+ from .engine import (
4
+ INHERITED_RELATIONS,
5
+ Locus,
6
+ NormalizerRegistry,
7
+ NORMALIZERS,
8
+ ResolvedRelation,
9
+ SemanticFact,
10
+ canonical_json,
11
+ content_id,
12
+ display_path,
13
+ emit_facts,
14
+ expand_relation_set,
15
+ get_at_path,
16
+ group_by_coordinate,
17
+ join_on_coordinate,
18
+ parse_path,
19
+ path_matches,
20
+ relations_for_path,
21
+ resolve_path,
22
+ seal_relation_set,
23
+ walk_nodes,
24
+ )
25
+
26
+ __version__ = "0.1.0a1"
27
+
28
+ __all__ = [
29
+ "__version__",
30
+ "INHERITED_RELATIONS",
31
+ "Locus",
32
+ "NormalizerRegistry",
33
+ "NORMALIZERS",
34
+ "ResolvedRelation",
35
+ "SemanticFact",
36
+ "canonical_json",
37
+ "content_id",
38
+ "display_path",
39
+ "emit_facts",
40
+ "expand_relation_set",
41
+ "get_at_path",
42
+ "group_by_coordinate",
43
+ "join_on_coordinate",
44
+ "parse_path",
45
+ "path_matches",
46
+ "relations_for_path",
47
+ "resolve_path",
48
+ "seal_relation_set",
49
+ "walk_nodes",
50
+ ]
@@ -0,0 +1,483 @@
1
+ """Metaformat v0 experimental semantic-fact engine.
2
+
3
+ Small, deliberately non-standardized substrate:
4
+ raw records + sparse relation sets -> attributable semantic facts.
5
+
6
+ No external dependencies.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, asdict, field
11
+ from typing import Any, Callable, Iterable
12
+ import hashlib
13
+ import json
14
+ import re
15
+ from datetime import datetime, timezone
16
+
17
+
18
+ INHERITED_RELATIONS = {
19
+ "origin",
20
+ "modality",
21
+ "affords",
22
+ "authority_ref",
23
+ "identity_by",
24
+ "observed_at_by",
25
+ "context",
26
+ }
27
+
28
+
29
+ def canonical_json(value: Any) -> str:
30
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
31
+
32
+
33
+ def content_id(value: Any) -> str:
34
+ raw = canonical_json(value).encode("utf-8")
35
+ return "sha256:" + hashlib.sha256(raw).hexdigest()
36
+
37
+
38
+ def parse_path(path: str) -> tuple[str, ...]:
39
+ if path in ("", "/"):
40
+ return ()
41
+ if not path.startswith("/"):
42
+ raise ValueError(f"absolute path required: {path!r}")
43
+ return tuple(part for part in path.split("/") if part)
44
+
45
+
46
+ def display_path(path: tuple[str, ...]) -> str:
47
+ return "/" + "/".join(path) if path else "/"
48
+
49
+
50
+ def resolve_path(base: tuple[str, ...], ref: str) -> tuple[str, ...]:
51
+ """Resolve a filesystem-like ref against a possibly-wildcard base path."""
52
+ if ref.startswith("/"):
53
+ return parse_path(ref)
54
+
55
+ out = list(base)
56
+ for atom in ref.split("/"):
57
+ if atom in ("", "."):
58
+ continue
59
+ if atom == "..":
60
+ if not out:
61
+ raise ValueError(f"cannot resolve {ref!r} above root")
62
+ out.pop()
63
+ else:
64
+ out.append(atom)
65
+ return tuple(out)
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class Locus:
70
+ context: str
71
+ path: tuple[str, ...]
72
+
73
+ @classmethod
74
+ def from_strings(cls, context: str, path: str) -> "Locus":
75
+ return cls(context=context, path=parse_path(path))
76
+
77
+ def resolve(self, ref: str) -> "Locus":
78
+ return Locus(self.context, resolve_path(self.path, ref))
79
+
80
+ def __str__(self) -> str:
81
+ return f"{self.context}:{display_path(self.path)}"
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class ResolvedRelation:
86
+ name: str
87
+ value: Any
88
+ relation_set_id: str
89
+ pattern: tuple[str, ...]
90
+
91
+
92
+ @dataclass
93
+ class SemanticFact:
94
+ subject: str | None
95
+ concept: str
96
+ raw_value: Any
97
+ value: Any
98
+ unit: str | None
99
+ locus: Locus
100
+ origin: Any = None
101
+ modality: Any = None
102
+ observed_at: Any = None
103
+ captured_at: Any = None
104
+ affords: Any = None
105
+ authority_ref: Any = None
106
+ derivation: dict[str, Any] = field(default_factory=dict)
107
+
108
+ def coordinate(self) -> tuple[str | None, str]:
109
+ return (self.subject, self.concept)
110
+
111
+ def to_dict(self) -> dict[str, Any]:
112
+ out = asdict(self)
113
+ out["locus"] = {
114
+ "context": self.locus.context,
115
+ "path": display_path(self.locus.path),
116
+ }
117
+ return out
118
+
119
+
120
+ class NormalizerRegistry:
121
+ def __init__(self) -> None:
122
+ self._funcs: dict[str, Callable[[Any], Any]] = {}
123
+
124
+ def register(self, name: str, fn: Callable[[Any], Any]) -> None:
125
+ self._funcs[name] = fn
126
+
127
+ def apply(self, name: str | None, value: Any) -> Any:
128
+ if not name:
129
+ return value
130
+ if name not in self._funcs:
131
+ raise KeyError(f"unknown normalizer: {name}")
132
+ return self._funcs[name](value)
133
+
134
+ def names(self) -> tuple[str, ...]:
135
+ return tuple(sorted(self._funcs))
136
+
137
+
138
+ NORMALIZERS = NormalizerRegistry()
139
+
140
+
141
+ def _to_int(value: Any) -> int | None:
142
+ if value in (None, "", "[not set]"):
143
+ return None
144
+ return int(value)
145
+
146
+
147
+ def _active_bool(value: Any) -> bool | None:
148
+ if isinstance(value, bool):
149
+ return value
150
+ if value is None:
151
+ return None
152
+ s = str(value).strip().lower()
153
+ if s in {"active", "running", "true", "yes", "1"}:
154
+ return True
155
+ if s in {"inactive", "dead", "false", "no", "0"}:
156
+ return False
157
+ if s in {"unknown", "not_applicable", "not-applicable", ""}:
158
+ return None
159
+ return None
160
+
161
+
162
+ _SYSTEMCTL_PROBE_RE = re.compile(
163
+ r"(?:^|\s)systemctl\s+--user\s+is-active\s+([^\s;]+)"
164
+ )
165
+
166
+
167
+ def _systemctl_probe_to_unit(value: Any) -> str | None:
168
+ if not value:
169
+ return None
170
+ m = _SYSTEMCTL_PROBE_RE.search(str(value))
171
+ return m.group(1) if m else None
172
+
173
+
174
+ NORMALIZERS.register("to:int", _to_int)
175
+ NORMALIZERS.register("runtime:active-bool", _active_bool)
176
+ NORMALIZERS.register("systemctl-probe:unit-id", _systemctl_probe_to_unit)
177
+
178
+
179
+ def _unix_to_iso(value: Any) -> str | None:
180
+ if value in (None, ""):
181
+ return None
182
+ return datetime.fromtimestamp(float(value), tz=timezone.utc).isoformat().replace("+00:00", "Z")
183
+
184
+
185
+ NORMALIZERS.register("time:unix-to-iso", _unix_to_iso)
186
+
187
+
188
+ def seal_relation_set(relation_set: dict[str, Any]) -> dict[str, Any]:
189
+ """Return a copy with a content ID over all fields except any prior id."""
190
+ body = {k: v for k, v in relation_set.items() if k != "id"}
191
+ out = dict(body)
192
+ out["id"] = content_id(body)
193
+ return out
194
+
195
+
196
+ def expand_relation_set(relation_set: dict[str, Any]) -> list[ResolvedRelation]:
197
+ rs = seal_relation_set(relation_set)
198
+ base = parse_path(rs["base"]["path"])
199
+ rows: list[ResolvedRelation] = []
200
+ for ref, relations in rs.get("relations", {}).items():
201
+ pattern = resolve_path(base, ref)
202
+ for relation in relations:
203
+ if not isinstance(relation, (list, tuple)) or len(relation) != 2:
204
+ raise ValueError(f"relation must be [name, value], got {relation!r}")
205
+ name, value = relation
206
+ rows.append(
207
+ ResolvedRelation(
208
+ name=str(name),
209
+ value=value,
210
+ relation_set_id=rs["id"],
211
+ pattern=pattern,
212
+ )
213
+ )
214
+ return rows
215
+
216
+
217
+ def _atom_matches(pattern_atom: str, concrete_atom: str) -> bool:
218
+ return pattern_atom == "*" or pattern_atom == concrete_atom
219
+
220
+
221
+ def path_matches(
222
+ pattern: tuple[str, ...],
223
+ concrete: tuple[str, ...],
224
+ *,
225
+ prefix: bool = False,
226
+ ) -> bool:
227
+ if prefix:
228
+ if len(pattern) > len(concrete):
229
+ return False
230
+ elif len(pattern) != len(concrete):
231
+ return False
232
+
233
+ return all(
234
+ _atom_matches(p, c)
235
+ for p, c in zip(pattern, concrete)
236
+ )
237
+
238
+
239
+ def concrete_prefix_for_pattern(
240
+ pattern: tuple[str, ...],
241
+ concrete: tuple[str, ...],
242
+ ) -> tuple[str, ...]:
243
+ if not path_matches(pattern, concrete, prefix=True):
244
+ raise ValueError("pattern is not a prefix match")
245
+ return concrete[: len(pattern)]
246
+
247
+
248
+ def walk_nodes(value: Any, path: tuple[str, ...] = ()) -> Iterable[tuple[tuple[str, ...], Any]]:
249
+ yield path, value
250
+ if isinstance(value, dict):
251
+ for key, child in value.items():
252
+ yield from walk_nodes(child, path + (str(key),))
253
+ elif isinstance(value, list):
254
+ for index, child in enumerate(value):
255
+ yield from walk_nodes(child, path + (str(index),))
256
+
257
+
258
+ def get_at_path(value: Any, path: tuple[str, ...]) -> Any:
259
+ cur = value
260
+ for atom in path:
261
+ if isinstance(cur, list):
262
+ cur = cur[int(atom)]
263
+ elif isinstance(cur, dict):
264
+ cur = cur[atom]
265
+ else:
266
+ raise KeyError(display_path(path))
267
+ return cur
268
+
269
+
270
+ def relations_for_path(
271
+ relations: list[ResolvedRelation],
272
+ path: tuple[str, ...],
273
+ ) -> list[ResolvedRelation]:
274
+ out: list[ResolvedRelation] = []
275
+ for rel in relations:
276
+ if rel.name in INHERITED_RELATIONS:
277
+ if path_matches(rel.pattern, path, prefix=True):
278
+ out.append(rel)
279
+ elif path_matches(rel.pattern, path, prefix=False):
280
+ out.append(rel)
281
+ return out
282
+
283
+
284
+ def _values(rels: Iterable[ResolvedRelation], name: str) -> list[Any]:
285
+ return [r.value for r in rels if r.name == name]
286
+
287
+
288
+ def _most_specific_relation(
289
+ relations: list[ResolvedRelation],
290
+ path: tuple[str, ...],
291
+ name: str,
292
+ ) -> ResolvedRelation | None:
293
+ candidates = [
294
+ r
295
+ for r in relations
296
+ if r.name == name and path_matches(r.pattern, path, prefix=True)
297
+ ]
298
+ if not candidates:
299
+ return None
300
+ candidates.sort(key=lambda r: len(r.pattern), reverse=True)
301
+ return candidates[0]
302
+
303
+
304
+ def _most_specific_identity_relation(
305
+ relations: list[ResolvedRelation],
306
+ path: tuple[str, ...],
307
+ ) -> ResolvedRelation | None:
308
+ return _most_specific_relation(relations, path, "identity_by")
309
+
310
+
311
+ def _value_from_pointer_relation(
312
+ raw: Any,
313
+ relation: ResolvedRelation | None,
314
+ concrete_path: tuple[str, ...],
315
+ normalizers: NormalizerRegistry,
316
+ ) -> Any:
317
+ if relation is None:
318
+ return None
319
+ spec = relation.value
320
+ if isinstance(spec, str):
321
+ spec = {"path": spec}
322
+ if not isinstance(spec, dict) or "path" not in spec:
323
+ raise ValueError(f"pointer relation expects string or mapping with path: {spec!r}")
324
+ base = concrete_prefix_for_pattern(relation.pattern, concrete_path)
325
+ target_path = resolve_path(base, spec["path"])
326
+ try:
327
+ value = get_at_path(raw, target_path)
328
+ except (KeyError, IndexError, ValueError, TypeError):
329
+ return None
330
+ return normalizers.apply(spec.get("normalize"), value)
331
+
332
+
333
+ def _subject_from_identity(
334
+ raw: Any,
335
+ relation: ResolvedRelation | None,
336
+ concrete_path: tuple[str, ...],
337
+ normalizers: NormalizerRegistry,
338
+ ) -> str | None:
339
+ if relation is None:
340
+ return None
341
+
342
+ spec = relation.value
343
+ if isinstance(spec, str):
344
+ spec = {"path": spec}
345
+ if not isinstance(spec, dict) or "path" not in spec:
346
+ raise ValueError(f"identity_by expects string or mapping with path: {spec!r}")
347
+
348
+ base = concrete_prefix_for_pattern(relation.pattern, concrete_path)
349
+ identity_path = resolve_path(base, spec["path"])
350
+ try:
351
+ identity = get_at_path(raw, identity_path)
352
+ except (KeyError, IndexError, ValueError, TypeError):
353
+ return None
354
+
355
+ identity = normalizers.apply(spec.get("normalize"), identity)
356
+ if identity in (None, ""):
357
+ return None
358
+ prefix = spec.get("prefix", "")
359
+ return f"{prefix}{identity}"
360
+
361
+
362
+ def emit_facts(
363
+ raw: Any,
364
+ relation_sets: Iterable[dict[str, Any]],
365
+ *,
366
+ context: str,
367
+ normalizers: NormalizerRegistry = NORMALIZERS,
368
+ observed_at: Any = None,
369
+ captured_at: Any = None,
370
+ ) -> list[SemanticFact]:
371
+ """Emit attributed semantic facts for every node carrying an exact means relation."""
372
+ expanded: list[ResolvedRelation] = []
373
+ relation_set_ids: list[str] = []
374
+
375
+ for rs in relation_sets:
376
+ sealed = seal_relation_set(rs)
377
+ if sealed["base"]["context"] != context:
378
+ continue
379
+ relation_set_ids.append(sealed["id"])
380
+ expanded.extend(expand_relation_set(sealed))
381
+
382
+ facts: list[SemanticFact] = []
383
+
384
+ for path, raw_value in walk_nodes(raw):
385
+ applicable = relations_for_path(expanded, path)
386
+ means = [
387
+ r for r in applicable
388
+ if r.name == "means" and path_matches(r.pattern, path)
389
+ ]
390
+ if not means:
391
+ continue
392
+
393
+ exact = [r for r in applicable if path_matches(r.pattern, path)]
394
+ normalizer_names = _values(exact, "normalize")
395
+ unit_values = _values(exact, "unit")
396
+
397
+ normalized = raw_value
398
+ applied_normalizers: list[str] = []
399
+ for normalizer_name in normalizer_names:
400
+ normalized = normalizers.apply(str(normalizer_name), normalized)
401
+ applied_normalizers.append(str(normalizer_name))
402
+
403
+ identity_relation = _most_specific_identity_relation(expanded, path)
404
+ subject = _subject_from_identity(
405
+ raw, identity_relation, path, normalizers
406
+ )
407
+ observed_relation = _most_specific_relation(expanded, path, "observed_at_by")
408
+ fact_observed_at = _value_from_pointer_relation(
409
+ raw, observed_relation, path, normalizers
410
+ )
411
+ if fact_observed_at is None:
412
+ fact_observed_at = observed_at if observed_at is not None else captured_at
413
+
414
+ origins = _values(applicable, "origin")
415
+ modalities = _values(applicable, "modality")
416
+ affordances = _values(applicable, "affords")
417
+ authorities = _values(applicable, "authority_ref")
418
+
419
+ relevant_ids = sorted({r.relation_set_id for r in applicable})
420
+
421
+ for means_relation in means:
422
+ facts.append(
423
+ SemanticFact(
424
+ subject=subject,
425
+ concept=str(means_relation.value),
426
+ raw_value=raw_value,
427
+ value=normalized,
428
+ unit=str(unit_values[-1]) if unit_values else None,
429
+ locus=Locus(context=context, path=path),
430
+ origin=origins[-1] if origins else None,
431
+ modality=modalities[-1] if modalities else None,
432
+ observed_at=fact_observed_at,
433
+ captured_at=captured_at,
434
+ affords=affordances[-1] if affordances else None,
435
+ authority_ref=authorities[-1] if authorities else None,
436
+ derivation={
437
+ "relation_set_ids": relevant_ids,
438
+ "normalizers": applied_normalizers,
439
+ "raw_path": display_path(path),
440
+ },
441
+ )
442
+ )
443
+
444
+ return facts
445
+
446
+
447
+ def group_by_coordinate(
448
+ facts: Iterable[SemanticFact],
449
+ ) -> dict[tuple[str | None, str], list[SemanticFact]]:
450
+ out: dict[tuple[str | None, str], list[SemanticFact]] = {}
451
+ for fact in facts:
452
+ out.setdefault(fact.coordinate(), []).append(fact)
453
+ return out
454
+
455
+
456
+ def join_on_coordinate(
457
+ left: Iterable[SemanticFact],
458
+ right: Iterable[SemanticFact],
459
+ ) -> list[dict[str, Any]]:
460
+ li = group_by_coordinate(left)
461
+ ri = group_by_coordinate(right)
462
+ rows: list[dict[str, Any]] = []
463
+ for coordinate in sorted(set(li) & set(ri), key=lambda x: (str(x[0]), x[1])):
464
+ for a in li[coordinate]:
465
+ for b in ri[coordinate]:
466
+ rows.append(
467
+ {
468
+ "subject": coordinate[0],
469
+ "concept": coordinate[1],
470
+ "left": a.value,
471
+ "right": b.value,
472
+ "agreement": a.value == b.value,
473
+ "left_origin": a.origin,
474
+ "right_origin": b.origin,
475
+ "left_observed_at": a.observed_at,
476
+ "right_observed_at": b.observed_at,
477
+ "left_captured_at": a.captured_at,
478
+ "right_captured_at": b.captured_at,
479
+ "left_locus": str(a.locus),
480
+ "right_locus": str(b.locus),
481
+ }
482
+ )
483
+ return rows
@@ -0,0 +1,52 @@
1
+ from metaformat import Locus, content_id, emit_facts, join_on_coordinate, seal_relation_set
2
+
3
+
4
+ def test_relative_locus_resolution():
5
+ base = Locus.from_strings("ctx:test", "/units/*")
6
+ assert base.resolve("./MemoryCurrent").path == ("units", "*", "MemoryCurrent")
7
+ assert base.resolve("../host").path == ("units", "host")
8
+
9
+
10
+ def test_content_id_is_order_stable():
11
+ assert content_id({"a": 1, "b": 2}) == content_id({"b": 2, "a": 1})
12
+
13
+
14
+ def test_semantic_join_preserves_provenance_and_detects_disagreement():
15
+ left_profile = seal_relation_set({
16
+ "base": {"context": "ctx:left", "path": "/"},
17
+ "relations": {
18
+ ".": [["origin", "left://source"], ["modality", "live-observation"]],
19
+ "./units/*": [["identity_by", {"path": "./id", "prefix": "unit:"}]],
20
+ "./units/*/active": [
21
+ ["means", "runtime:active"],
22
+ ["normalize", "runtime:active-bool"],
23
+ ],
24
+ },
25
+ })
26
+ right_profile = seal_relation_set({
27
+ "base": {"context": "ctx:right", "path": "/"},
28
+ "relations": {
29
+ ".": [["origin", "right://source"], ["modality", "registry-assertion"]],
30
+ "./records/*": [["identity_by", {"path": "./unit", "prefix": "unit:"}]],
31
+ "./records/*/active": [
32
+ ["means", "runtime:active"],
33
+ ["normalize", "runtime:active-bool"],
34
+ ],
35
+ },
36
+ })
37
+
38
+ left = {"units": [{"id": "a", "active": "active"}, {"id": "b", "active": "active"}]}
39
+ right = {"records": [{"unit": "a", "active": True}, {"unit": "b", "active": False}]}
40
+
41
+ lf = emit_facts(left, [left_profile], context="ctx:left", observed_at="2026-01-02T00:00:00Z")
42
+ rf = emit_facts(right, [right_profile], context="ctx:right", observed_at="2026-01-01T00:00:00Z")
43
+ joined = [r for r in join_on_coordinate(lf, rf) if r["concept"] == "runtime:active"]
44
+
45
+ assert len(joined) == 2
46
+ disagreements = [r for r in joined if not r["agreement"]]
47
+ assert len(disagreements) == 1
48
+ assert disagreements[0]["subject"] == "unit:b"
49
+ assert disagreements[0]["left_origin"] == "left://source"
50
+ assert disagreements[0]["right_origin"] == "right://source"
51
+ assert disagreements[0]["left_observed_at"] == "2026-01-02T00:00:00Z"
52
+ assert disagreements[0]["right_observed_at"] == "2026-01-01T00:00:00Z"