jep-runtime 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ """JEP Reference Runtime.
2
+
3
+ Executable, portable accountability runtime for Judgment, Delegation,
4
+ Termination, and Verification events.
5
+ """
6
+
7
+ from jep_runtime.core.event import EventType, JEPEvent
8
+ from jep_runtime.events.factory import create_event
9
+ from jep_runtime.canonicalization.json import canonicalize_event, compute_event_hash
10
+ from jep_runtime.verification.runtime import verify_event, verify_chain, verify_replay
11
+
12
+ __all__ = [
13
+ "EventType",
14
+ "JEPEvent",
15
+ "create_event",
16
+ "canonicalize_event",
17
+ "compute_event_hash",
18
+ "verify_event",
19
+ "verify_chain",
20
+ "verify_replay",
21
+ ]
File without changes
@@ -0,0 +1,78 @@
1
+ """Append-only JSONL archive runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from filelock import FileLock
8
+ from jep_runtime.canonicalization.json import compute_event_hash
9
+ from typing import Iterable
10
+
11
+ from jep_runtime.core.event import JEPEvent
12
+ from jep_runtime.replay.engine import replay_events
13
+ from jep_runtime.verification.runtime import VerificationResult, verify_chain
14
+
15
+
16
+ class JSONLArchive:
17
+ def __init__(self, path: str | Path):
18
+ self.path = Path(path).resolve()
19
+ self.path.parent.mkdir(parents=True, exist_ok=True)
20
+ self._lock = FileLock(str(self.path) + ".lock", timeout=10)
21
+
22
+ def append_event(self, event: JEPEvent) -> None:
23
+ with self._lock:
24
+ existing = self.import_archive()
25
+ previous = None
26
+ ids = set()
27
+ for candidate in [*existing, event]:
28
+ if candidate.event_hash != compute_event_hash(candidate) or candidate.previous_event_hash != previous:
29
+ raise ValueError("archive hash mismatch or stale previous_event_hash")
30
+ if candidate.event_id in ids:
31
+ raise ValueError("duplicate event identifier")
32
+ ids.add(candidate.event_id)
33
+ previous = candidate.event_hash
34
+ with self.path.open("a", encoding="utf-8") as handle:
35
+ handle.write(json.dumps(event.to_dict(), sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False) + "\n")
36
+
37
+ def import_archive(self) -> list[JEPEvent]:
38
+ with self._lock:
39
+ return self._read_archive()
40
+
41
+ def _read_archive(self) -> list[JEPEvent]:
42
+ if not self.path.exists():
43
+ return []
44
+ events: list[JEPEvent] = []
45
+ with self.path.open("r", encoding="utf-8") as handle:
46
+ for line in handle:
47
+ if line.strip():
48
+ events.append(JEPEvent.from_dict(json.loads(line)))
49
+ return events
50
+
51
+ def export_archive(self) -> str:
52
+ return self.path.read_text(encoding="utf-8") if self.path.exists() else ""
53
+
54
+ def verify_archive(self) -> VerificationResult:
55
+ return verify_chain(self.import_archive())
56
+
57
+ def replay_archive(self) -> dict:
58
+ return replay_events(self.import_archive())
59
+
60
+
61
+ def append_event(path: str | Path, event: JEPEvent) -> None:
62
+ JSONLArchive(path).append_event(event)
63
+
64
+
65
+ def import_archive(path: str | Path) -> list[JEPEvent]:
66
+ return JSONLArchive(path).import_archive()
67
+
68
+
69
+ def export_archive(path: str | Path) -> str:
70
+ return JSONLArchive(path).export_archive()
71
+
72
+
73
+ def verify_archive(path: str | Path) -> VerificationResult:
74
+ return JSONLArchive(path).verify_archive()
75
+
76
+
77
+ def replay_archive(path: str | Path) -> dict:
78
+ return JSONLArchive(path).replay_archive()
File without changes
@@ -0,0 +1,39 @@
1
+ """Deterministic JSON canonicalization and SHA-256 event hashing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import unicodedata
8
+ from typing import Any, Mapping
9
+
10
+ from jep_runtime.core.event import JEPEvent
11
+
12
+
13
+ def _normalize(value: Any) -> Any:
14
+ if isinstance(value, str):
15
+ return unicodedata.normalize("NFC", value)
16
+ if isinstance(value, Mapping):
17
+ return {unicodedata.normalize("NFC", str(k)): _normalize(v) for k, v in value.items()}
18
+ if isinstance(value, list | tuple):
19
+ return [_normalize(v) for v in value]
20
+ return value
21
+
22
+
23
+ def canonicalize_event(event: JEPEvent | Mapping[str, Any], *, include_hash: bool = False) -> bytes:
24
+ """Canonicalize an event as UTF-8 JSON with stable ordering and no whitespace."""
25
+
26
+ if isinstance(event, JEPEvent):
27
+ data = event.to_dict(include_hash=include_hash)
28
+ else:
29
+ data = dict(event)
30
+ if not include_hash:
31
+ data.pop("event_hash", None)
32
+ normalized = _normalize(data)
33
+ return json.dumps(normalized, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
34
+
35
+
36
+ def compute_event_hash(event: JEPEvent | Mapping[str, Any]) -> str:
37
+ """Compute a platform-stable SHA-256 hash over canonical event JSON."""
38
+
39
+ return hashlib.sha256(canonicalize_event(event, include_hash=False)).hexdigest()
File without changes
@@ -0,0 +1,97 @@
1
+ """Command line interface for the JEP Reference Runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ from jep_runtime.archive.jsonl import JSONLArchive
10
+ from jep_runtime.conformance.runtime import run_conformance
11
+ from jep_runtime.core.event import JEPEvent
12
+ from jep_runtime.events.factory import create_event
13
+ from jep_runtime.replay.engine import replay_events
14
+ from jep_runtime.verification.runtime import verify_event
15
+
16
+
17
+ def _load_event(path: str) -> JEPEvent:
18
+ with open(path, "r", encoding="utf-8") as handle:
19
+ return JEPEvent.from_dict(json.load(handle))
20
+
21
+
22
+ def _print(data: object) -> None:
23
+ print(json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False))
24
+
25
+
26
+ def build_parser() -> argparse.ArgumentParser:
27
+ parser = argparse.ArgumentParser(prog="jep", description="JEP Reference Runtime CLI")
28
+ sub = parser.add_subparsers(dest="command", required=True)
29
+
30
+ create = sub.add_parser("create-event", help="Create and hash a J/D/T/V event")
31
+ create.add_argument("--type", required=True, choices=["J", "D", "T", "V"])
32
+ create.add_argument("--actor", required=True)
33
+ create.add_argument("--subject", required=True)
34
+ create.add_argument("--agent-id")
35
+ create.add_argument("--session-id")
36
+ create.add_argument("--scope-json", default="{}")
37
+ create.add_argument("--intent-json", default="{}")
38
+ create.add_argument("--justification", default="")
39
+ create.add_argument("--previous-event-hash")
40
+ create.add_argument("--profile", default="mock")
41
+ create.add_argument("--credential-reference")
42
+ create.add_argument("--archive", help="Append created event to JSONL archive")
43
+
44
+ verify = sub.add_parser("verify", help="Verify one event JSON file")
45
+ verify.add_argument("event")
46
+
47
+ replay = sub.add_parser("replay", help="Replay a JSONL archive")
48
+ replay.add_argument("archive")
49
+
50
+ archive_verify = sub.add_parser("archive-verify", help="Verify an append-only JSONL archive")
51
+ archive_verify.add_argument("archive")
52
+
53
+ sub.add_parser("conformance-test", help="Run conformance suite and emit vectors/report")
54
+ return parser
55
+
56
+
57
+ def main(argv: list[str] | None = None) -> int:
58
+ args = build_parser().parse_args(argv)
59
+ if args.command == "create-event":
60
+ event = create_event(
61
+ args.type,
62
+ actor=args.actor,
63
+ subject=args.subject,
64
+ agent_id=args.agent_id,
65
+ session_id=args.session_id,
66
+ authority_scope=json.loads(args.scope_json),
67
+ intent=json.loads(args.intent_json),
68
+ justification=args.justification,
69
+ previous_event_hash=args.previous_event_hash,
70
+ profile=args.profile,
71
+ credential_reference=args.credential_reference,
72
+ )
73
+ if args.archive:
74
+ JSONLArchive(args.archive).append_event(event)
75
+ _print(event.to_dict())
76
+ return 0
77
+ if args.command == "verify":
78
+ result = verify_event(_load_event(args.event))
79
+ _print({"valid": result.valid, "errors": list(result.errors)})
80
+ return 0 if result.valid else 1
81
+ if args.command == "replay":
82
+ archive = JSONLArchive(args.archive)
83
+ _print(archive.replay_archive())
84
+ return 0 if archive.verify_archive().valid else 1
85
+ if args.command == "archive-verify":
86
+ result = JSONLArchive(args.archive).verify_archive()
87
+ _print({"valid": result.valid, "errors": list(result.errors)})
88
+ return 0 if result.valid else 1
89
+ if args.command == "conformance-test":
90
+ report = run_conformance()
91
+ _print(report)
92
+ return 0 if report["passed"] else 1
93
+ return 2
94
+
95
+
96
+ if __name__ == "__main__":
97
+ raise SystemExit(main(sys.argv[1:]))
File without changes
@@ -0,0 +1,71 @@
1
+ """Conformance vectors and checks for interoperable JEP runtimes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from jep_runtime.canonicalization.json import canonicalize_event, compute_event_hash
6
+ from jep_runtime.core.event import EventType
7
+ from jep_runtime.delegation.runtime import delegate_authority, verify_delegation_chain
8
+ from jep_runtime.events.factory import create_event
9
+ from jep_runtime.profiles.adapter import MockProfileAdapter
10
+ from jep_runtime.replay.engine import replay_events
11
+ from jep_runtime.verification.runtime import verify_chain, verify_event
12
+
13
+
14
+ def generate_test_vectors() -> dict:
15
+ adapter = MockProfileAdapter()
16
+ ref = adapter.issue_reference("human:alice", "mock")
17
+ root = create_event(
18
+ EventType.JUDGMENT,
19
+ actor="human:alice",
20
+ subject="agent:planner",
21
+ agent_id="agent:planner",
22
+ session_id="session:conformance",
23
+ authority_scope={"actions": ["read", "summarize"], "resources": ["repo:jep"], "valid_until": 4102444800},
24
+ intent={"task": "summarize current JEP draft"},
25
+ justification="human delegated bounded judgment authority",
26
+ timestamp=1700000000,
27
+ nonce="00000000-0000-4000-8000-000000000001",
28
+ profile="mock",
29
+ credential_reference=ref,
30
+ )
31
+ child = delegate_authority(root, delegatee="agent:worker", agent_id="agent:worker", scope={"actions": ["read"], "resources": ["repo:jep"], "valid_until": 4102444700})
32
+ verify = create_event(
33
+ EventType.VERIFICATION,
34
+ actor="verifier:local",
35
+ subject=child.subject,
36
+ agent_id=child.agent_id,
37
+ session_id=root.session_id,
38
+ delegation_chain=child.delegation_chain,
39
+ authority_scope=child.authority_scope,
40
+ intent={"target_event_hash": child.event_hash, "result": "VALID"},
41
+ previous_event_hash=child.event_hash,
42
+ timestamp=child.timestamp + 1,
43
+ nonce="00000000-0000-4000-8000-000000000003",
44
+ profile="mock",
45
+ credential_reference=ref,
46
+ )
47
+ return {
48
+ "events": [root.to_dict(), child.to_dict(), verify.to_dict()],
49
+ "canonical_root": canonicalize_event(root).decode("utf-8"),
50
+ "root_hash": root.event_hash,
51
+ }
52
+
53
+
54
+ def run_conformance() -> dict:
55
+ vectors = generate_test_vectors()
56
+ reconstructed = [__import__("jep_runtime.core.event", fromlist=["JEPEvent"]).JEPEvent.from_dict(e) for e in vectors["events"]]
57
+ matrix = {
58
+ "canonicalization": canonicalize_event(reconstructed[0]).decode("utf-8") == vectors["canonical_root"],
59
+ "deterministic_hashing": compute_event_hash(reconstructed[0]) == vectors["root_hash"],
60
+ "delegation_semantics": verify_delegation_chain(reconstructed[:2])[0],
61
+ "verification_semantics": verify_event(reconstructed[2]).valid,
62
+ "profile_compatibility": verify_chain(reconstructed).valid,
63
+ "replay_correctness": replay_events(reconstructed)["valid"],
64
+ }
65
+ return {
66
+ "passed": all(matrix.values()),
67
+ "matrix": matrix,
68
+ "test_vectors": vectors,
69
+ "signed_vectors": {"mode": "mock", "signature": "mock-signature-over-canonical-vectors"},
70
+ "compatibility_report": "reference runtime uses stable UTF-8 sorted JSON, SHA-256, JSONL archives, and neutral mock profiles",
71
+ }
File without changes
@@ -0,0 +1,163 @@
1
+ """Core immutable event model for the JEP Reference Runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field, replace
6
+ from enum import Enum
7
+ from types import MappingProxyType
8
+ from typing import Any, Mapping
9
+ import copy
10
+ import time
11
+ import uuid
12
+
13
+
14
+ class EventType(str, Enum):
15
+ """JEP judgment event primitives."""
16
+
17
+ JUDGMENT = "J"
18
+ DELEGATION = "D"
19
+ TERMINATION = "T"
20
+ VERIFICATION = "V"
21
+
22
+
23
+ _REQUIRED_SCHEMA_FIELDS = [
24
+ "event_id",
25
+ "event_type",
26
+ "actor",
27
+ "subject",
28
+ "agent_id",
29
+ "session_id",
30
+ "delegation_chain",
31
+ "authority_scope",
32
+ "intent",
33
+ "justification",
34
+ "previous_event_hash",
35
+ "event_hash",
36
+ "nonce",
37
+ "timestamp",
38
+ "profile",
39
+ "credential_reference",
40
+ "verification_state",
41
+ ]
42
+
43
+
44
+ def _freeze(value: Any) -> Any:
45
+ if isinstance(value, Mapping):
46
+ return MappingProxyType({str(k): _freeze(v) for k, v in value.items()})
47
+ if isinstance(value, list | tuple):
48
+ return tuple(_freeze(v) for v in value)
49
+ return value
50
+
51
+
52
+ def _thaw(value: Any) -> Any:
53
+ if isinstance(value, Mapping):
54
+ return {k: _thaw(v) for k, v in value.items()}
55
+ if isinstance(value, tuple):
56
+ return [_thaw(v) for v in value]
57
+ return copy.deepcopy(value)
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class JEPEvent:
62
+ """Immutable JEP event after hash assignment.
63
+
64
+ The runtime keeps J/D/T/V semantics minimal: events are typed evidence
65
+ records, linked by previous_event_hash, scoped by authority_scope, and
66
+ replayable through nonce, timestamp, profile, and delegation_chain.
67
+ """
68
+
69
+ event_id: str
70
+ event_type: EventType | str
71
+ actor: str
72
+ subject: str
73
+ agent_id: str | None
74
+ session_id: str
75
+ delegation_chain: tuple[str, ...] = field(default_factory=tuple)
76
+ authority_scope: Mapping[str, Any] = field(default_factory=dict)
77
+ intent: Mapping[str, Any] = field(default_factory=dict)
78
+ justification: str = ""
79
+ previous_event_hash: str | None = None
80
+ event_hash: str | None = None
81
+ nonce: str = field(default_factory=lambda: str(uuid.uuid4()))
82
+ timestamp: int = field(default_factory=lambda: int(time.time()))
83
+ profile: str = "mock"
84
+ credential_reference: str | None = None
85
+ verification_state: Mapping[str, Any] = field(default_factory=dict)
86
+
87
+ def __post_init__(self) -> None:
88
+ object.__setattr__(self, "event_type", EventType(self.event_type))
89
+ object.__setattr__(self, "delegation_chain", tuple(self.delegation_chain))
90
+ object.__setattr__(self, "authority_scope", _freeze(self.authority_scope))
91
+ object.__setattr__(self, "intent", _freeze(self.intent))
92
+ object.__setattr__(self, "verification_state", _freeze(self.verification_state))
93
+
94
+ def to_dict(self, *, include_hash: bool = True) -> dict[str, Any]:
95
+ """Return a deterministic dictionary representation."""
96
+
97
+ data = {
98
+ "event_id": self.event_id,
99
+ "event_type": self.event_type.value,
100
+ "actor": self.actor,
101
+ "subject": self.subject,
102
+ "agent_id": self.agent_id,
103
+ "session_id": self.session_id,
104
+ "delegation_chain": list(self.delegation_chain),
105
+ "authority_scope": _thaw(self.authority_scope),
106
+ "intent": _thaw(self.intent),
107
+ "justification": self.justification,
108
+ "previous_event_hash": self.previous_event_hash,
109
+ "event_hash": self.event_hash if include_hash else None,
110
+ "nonce": self.nonce,
111
+ "timestamp": self.timestamp,
112
+ "profile": self.profile,
113
+ "credential_reference": self.credential_reference,
114
+ "verification_state": _thaw(self.verification_state),
115
+ }
116
+ if not include_hash:
117
+ data.pop("event_hash")
118
+ return data
119
+
120
+ @classmethod
121
+ def from_dict(cls, data: Mapping[str, Any]) -> "JEPEvent":
122
+ return cls(**{field_name: data.get(field_name) for field_name in _REQUIRED_SCHEMA_FIELDS})
123
+
124
+ def with_hash(self, event_hash: str) -> "JEPEvent":
125
+ """Return a hashed immutable event.
126
+
127
+ Existing event_hash values cannot be replaced, making post-hash objects
128
+ append-only evidence records rather than mutable workflow state.
129
+ """
130
+
131
+ if self.event_hash and self.event_hash != event_hash:
132
+ raise ValueError("event_hash is immutable once assigned")
133
+ return replace(self, event_hash=event_hash)
134
+
135
+ @staticmethod
136
+ def json_schema() -> dict[str, Any]:
137
+ return {
138
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
139
+ "$id": "https://example.org/jep-runtime/schemas/jep-event.schema.json",
140
+ "title": "JEP Reference Runtime Event",
141
+ "type": "object",
142
+ "required": _REQUIRED_SCHEMA_FIELDS,
143
+ "additionalProperties": False,
144
+ "properties": {
145
+ "event_id": {"type": "string"},
146
+ "event_type": {"enum": ["J", "D", "T", "V"]},
147
+ "actor": {"type": "string"},
148
+ "subject": {"type": "string"},
149
+ "agent_id": {"type": ["string", "null"]},
150
+ "session_id": {"type": "string"},
151
+ "delegation_chain": {"type": "array", "items": {"type": "string"}},
152
+ "authority_scope": {"type": "object"},
153
+ "intent": {"type": "object"},
154
+ "justification": {"type": "string"},
155
+ "previous_event_hash": {"type": ["string", "null"]},
156
+ "event_hash": {"type": ["string", "null"]},
157
+ "nonce": {"type": "string"},
158
+ "timestamp": {"type": "integer"},
159
+ "profile": {"type": "string"},
160
+ "credential_reference": {"type": ["string", "null"]},
161
+ "verification_state": {"type": "object"},
162
+ },
163
+ }
@@ -0,0 +1,13 @@
1
+ """Protocol and runtime version metadata for the JEP reference runtime."""
2
+
3
+ JEP_DRAFT_VERSION = "jep-v06"
4
+ JEP_DRAFT_REFERENCE = "Judgment Event Protocol Internet-Draft v06"
5
+ JEP_DRAFT_REPOSITORY = "jep-v06"
6
+ RUNTIME_VERSION = "0.1.1"
7
+
8
+ __all__ = [
9
+ "JEP_DRAFT_VERSION",
10
+ "JEP_DRAFT_REFERENCE",
11
+ "JEP_DRAFT_REPOSITORY",
12
+ "RUNTIME_VERSION",
13
+ ]
File without changes
@@ -0,0 +1,137 @@
1
+ """Delegation authority propagation runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from typing import Any, Iterable, Mapping
7
+
8
+ from jep_runtime.core.event import EventType, JEPEvent
9
+ from jep_runtime.events.factory import create_event
10
+
11
+
12
+ def _scope_items(scope: Mapping[str, Any]) -> dict[str, Any]:
13
+ return dict(scope or {})
14
+
15
+
16
+ def validate_scope(
17
+ parent_scope: Mapping[str, Any],
18
+ child_scope: Mapping[str, Any],
19
+ *,
20
+ now: int | None = None,
21
+ ) -> bool:
22
+ """Return true when child_scope is bounded by parent_scope."""
23
+
24
+ if not isinstance(parent_scope, Mapping) or not isinstance(child_scope, Mapping):
25
+ return False
26
+ parent, child = dict(parent_scope), dict(child_scope)
27
+ # This local runtime profile grants only explicitly listed capabilities.
28
+ for dimension in ("actions", "resources"):
29
+ parent_items, child_items = parent.get(dimension, []), child.get(dimension, [])
30
+ if not isinstance(parent_items, (list, tuple)) or not isinstance(
31
+ child_items, (list, tuple)
32
+ ):
33
+ return False
34
+ if not all(isinstance(item, str) for item in [*parent_items, *child_items]):
35
+ return False
36
+ if not set(child_items).issubset(parent_items):
37
+ return False
38
+ # Unknown constraints may be preserved but never added, changed, or dropped.
39
+ for key in (parent.keys() | child.keys()) - {"actions", "resources", "valid_until"}:
40
+ if key not in parent or key not in child or child[key] != parent[key]:
41
+ return False
42
+ parent_until, child_until = parent.get("valid_until"), child.get("valid_until")
43
+ if any(
44
+ value is not None and type(value) is not int
45
+ for value in (parent_until, child_until)
46
+ ):
47
+ return False
48
+ if parent_until is not None and (child_until is None or child_until > parent_until):
49
+ return False
50
+ effective_now = int(datetime.now(timezone.utc).timestamp()) if now is None else now
51
+ if type(effective_now) is not int:
52
+ return False
53
+ return all(
54
+ value is None or effective_now < value for value in (parent_until, child_until)
55
+ )
56
+
57
+
58
+ def delegate_authority(
59
+ parent_event: JEPEvent,
60
+ *,
61
+ delegatee: str,
62
+ agent_id: str | None,
63
+ scope: Mapping[str, Any],
64
+ justification: str = "",
65
+ ) -> JEPEvent:
66
+ """Create a scoped delegation event from parent authority to a delegatee."""
67
+
68
+ if not validate_scope(
69
+ parent_event.authority_scope, scope, now=parent_event.timestamp + 1
70
+ ):
71
+ raise ValueError("delegation scope exceeds or outlives parent authority")
72
+ chain = [*parent_event.delegation_chain, parent_event.event_hash or ""]
73
+ return create_event(
74
+ EventType.DELEGATION,
75
+ actor=parent_event.subject,
76
+ subject=delegatee,
77
+ agent_id=agent_id,
78
+ session_id=parent_event.session_id,
79
+ delegation_chain=chain,
80
+ authority_scope=scope,
81
+ intent={"delegatee": delegatee, "parent_event_hash": parent_event.event_hash},
82
+ justification=justification,
83
+ previous_event_hash=parent_event.event_hash,
84
+ profile=parent_event.profile,
85
+ credential_reference=parent_event.credential_reference,
86
+ timestamp=parent_event.timestamp + 1,
87
+ )
88
+
89
+
90
+ def verify_delegation_chain(events: Iterable[JEPEvent]) -> tuple[bool, list[str]]:
91
+ """Verify hash lineage and bounded delegation scopes for a sequence."""
92
+
93
+ problems: list[str] = []
94
+ previous: JEPEvent | None = None
95
+ seen_hashes: set[str] = set()
96
+ by_hash: dict[str, JEPEvent] = {}
97
+ seen_ids: set[str] = set()
98
+ for event in events:
99
+ if event.event_id in seen_ids:
100
+ problems.append(f"duplicate event id: {event.event_id}")
101
+ seen_ids.add(event.event_id)
102
+ if event.event_hash in seen_hashes:
103
+ problems.append(f"duplicate event hash: {event.event_hash}")
104
+ if event.event_hash:
105
+ seen_hashes.add(event.event_hash)
106
+ if previous:
107
+ if event.previous_event_hash != previous.event_hash:
108
+ problems.append(f"hash continuity break at {event.event_id}")
109
+
110
+ if event.event_type == EventType.DELEGATION:
111
+ parent_hash = event.intent.get("parent_event_hash")
112
+ parent = by_hash.get(parent_hash) if isinstance(parent_hash, str) else None
113
+ if parent is None:
114
+ problems.append(f"unresolved delegation parent at {event.event_id}")
115
+ else:
116
+ if (
117
+ event.actor != parent.subject
118
+ or event.session_id != parent.session_id
119
+ ):
120
+ problems.append(
121
+ f"delegation actor/session mismatch at {event.event_id}"
122
+ )
123
+ if event.timestamp < parent.timestamp:
124
+ problems.append(f"delegation precedes parent at {event.event_id}")
125
+ if event.delegation_chain != (
126
+ *parent.delegation_chain,
127
+ parent.event_hash,
128
+ ):
129
+ problems.append(f"delegation ancestry mismatch at {event.event_id}")
130
+ if not validate_scope(
131
+ parent.authority_scope, event.authority_scope, now=event.timestamp
132
+ ):
133
+ problems.append(f"scope violation at {event.event_id}")
134
+ if event.event_hash:
135
+ by_hash[event.event_hash] = event
136
+ previous = event
137
+ return not problems, problems
File without changes
@@ -0,0 +1,48 @@
1
+ """Factory helpers for creating hashed JEP events."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Mapping
6
+ import uuid
7
+
8
+ from jep_runtime.canonicalization.json import compute_event_hash
9
+ from jep_runtime.core.event import EventType, JEPEvent
10
+
11
+
12
+ def create_event(
13
+ event_type: EventType | str,
14
+ *,
15
+ actor: str,
16
+ subject: str,
17
+ agent_id: str | None = None,
18
+ session_id: str | None = None,
19
+ delegation_chain: list[str] | tuple[str, ...] | None = None,
20
+ authority_scope: Mapping[str, Any] | None = None,
21
+ intent: Mapping[str, Any] | None = None,
22
+ justification: str = "",
23
+ previous_event_hash: str | None = None,
24
+ nonce: str | None = None,
25
+ timestamp: int | None = None,
26
+ profile: str = "mock",
27
+ credential_reference: str | None = None,
28
+ verification_state: Mapping[str, Any] | None = None,
29
+ ) -> JEPEvent:
30
+ event = JEPEvent(
31
+ event_id=str(uuid.uuid4()),
32
+ event_type=event_type,
33
+ actor=actor,
34
+ subject=subject,
35
+ agent_id=agent_id,
36
+ session_id=session_id or str(uuid.uuid4()),
37
+ delegation_chain=tuple(delegation_chain or ()),
38
+ authority_scope=dict(authority_scope or {}),
39
+ intent=dict(intent or {}),
40
+ justification=justification,
41
+ previous_event_hash=previous_event_hash,
42
+ nonce=nonce or str(uuid.uuid4()),
43
+ timestamp=timestamp or 0,
44
+ profile=profile,
45
+ credential_reference=credential_reference,
46
+ verification_state=dict(verification_state or {}),
47
+ )
48
+ return event.with_hash(compute_event_hash(event))
File without changes
File without changes
@@ -0,0 +1,38 @@
1
+ """Identity-neutral, credential-neutral profile adapter interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Protocol, Mapping
7
+
8
+
9
+ class ProfileAdapter(Protocol):
10
+ def issue_reference(self, actor: str, profile: str, claims: Mapping[str, Any] | None = None) -> str: ...
11
+ def verify_reference(self, reference: str, profile: str) -> bool: ...
12
+ def resolve_identity(self, reference: str) -> str: ...
13
+ def validate_authority(self, reference: str, authority_scope: Mapping[str, Any]) -> bool: ...
14
+
15
+
16
+ @dataclass
17
+ class MockProfileAdapter:
18
+ """Reference profile adapter for OAuth/OIDC, X509, DID/VC, and Local IAM labels.
19
+
20
+ It performs deterministic reference checks only; it is not a production
21
+ credential verifier and intentionally hardcodes no identity provider.
22
+ """
23
+
24
+ supported_profiles: tuple[str, ...] = ("mock", "oauth-oidc", "x509", "did-vc", "local-iam")
25
+
26
+ def issue_reference(self, actor: str, profile: str = "mock", claims: Mapping[str, Any] | None = None) -> str:
27
+ if profile not in self.supported_profiles:
28
+ raise ValueError(f"unsupported profile: {profile}")
29
+ return f"jep-ref:{profile}:{actor}"
30
+
31
+ def verify_reference(self, reference: str | None, profile: str) -> bool:
32
+ return bool(reference and profile in self.supported_profiles and reference.startswith(f"jep-ref:{profile}:"))
33
+
34
+ def resolve_identity(self, reference: str) -> str:
35
+ return reference.split(":", 2)[-1]
36
+
37
+ def validate_authority(self, reference: str, authority_scope: Mapping[str, Any]) -> bool:
38
+ return bool(reference and isinstance(authority_scope, Mapping))
File without changes
@@ -0,0 +1,42 @@
1
+ """Replay engine that reconstructs lineage, authority, and termination state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from jep_runtime.core.event import EventType, JEPEvent
6
+ from jep_runtime.verification.runtime import verify_chain
7
+
8
+
9
+ def replay_events(events: list[JEPEvent]) -> dict:
10
+ verification = verify_chain(events)
11
+ nodes = []
12
+ edges = []
13
+ authority_lineage: dict[str, dict] = {}
14
+ terminated: set[str] = set()
15
+ for event in events:
16
+ nodes.append({
17
+ "event_id": event.event_id,
18
+ "event_hash": event.event_hash,
19
+ "event_type": event.event_type.value,
20
+ "actor": event.actor,
21
+ "subject": event.subject,
22
+ "scope": dict(event.authority_scope),
23
+ })
24
+ if event.previous_event_hash:
25
+ edges.append({"from": event.previous_event_hash, "to": event.event_hash, "type": "hash_chain"})
26
+ for parent in event.delegation_chain:
27
+ edges.append({"from": parent, "to": event.event_hash, "type": "delegation"})
28
+ if event.event_type in (EventType.JUDGMENT, EventType.DELEGATION):
29
+ authority_lineage[event.subject] = {
30
+ "event_hash": event.event_hash,
31
+ "scope": dict(event.authority_scope),
32
+ "delegation_chain": list(event.delegation_chain),
33
+ }
34
+ if event.event_type == EventType.TERMINATION:
35
+ terminated.add(event.subject)
36
+ return {
37
+ "valid": verification.valid,
38
+ "errors": list(verification.errors),
39
+ "lineage_graph": {"nodes": nodes, "edges": edges},
40
+ "authority_lineage": authority_lineage,
41
+ "termination_state": sorted(terminated),
42
+ }
File without changes
File without changes
File without changes
@@ -0,0 +1,77 @@
1
+ """Replayable verification runtime for JEP event chains."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Iterable
7
+
8
+ from jep_runtime.canonicalization.json import compute_event_hash
9
+ from jep_runtime.core.event import JEPEvent
10
+ from jep_runtime.delegation.runtime import verify_delegation_chain
11
+ from jep_runtime.profiles.adapter import MockProfileAdapter, ProfileAdapter
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class VerificationResult:
16
+ valid: bool
17
+ errors: tuple[str, ...] = ()
18
+ profile_checked: bool = False
19
+
20
+
21
+ def verify_profile(event: JEPEvent, adapter: ProfileAdapter | None = None) -> VerificationResult:
22
+ if (adapter is None or isinstance(adapter, MockProfileAdapter)) and event.profile != "mock":
23
+ return VerificationResult(False, (f"no verifier configured for profile {event.profile}",))
24
+ profile_adapter = adapter or MockProfileAdapter()
25
+ if event.credential_reference is None:
26
+ if event.profile == "mock":
27
+ return VerificationResult(True)
28
+ return VerificationResult(False, ("credential reference is required",))
29
+ if not profile_adapter.verify_reference(event.credential_reference, event.profile):
30
+ return VerificationResult(False, (f"invalid credential reference for profile {event.profile}",))
31
+ if not profile_adapter.validate_authority(event.credential_reference, event.authority_scope):
32
+ return VerificationResult(False, ("profile adapter rejected authority scope",))
33
+ return VerificationResult(True, profile_checked=not isinstance(profile_adapter, MockProfileAdapter))
34
+
35
+
36
+ def verify_event(event: JEPEvent, *, adapter: ProfileAdapter | None = None) -> VerificationResult:
37
+ errors: list[str] = []
38
+ if compute_event_hash(event) != event.event_hash:
39
+ errors.append("event_hash mismatch")
40
+ if not event.nonce:
41
+ errors.append("missing nonce")
42
+ if type(event.timestamp) is not int:
43
+ errors.append("timestamp must be an integer")
44
+ profile_result = verify_profile(event, adapter)
45
+ errors.extend(profile_result.errors)
46
+ return VerificationResult(not errors, tuple(errors), profile_result.profile_checked)
47
+
48
+
49
+ def verify_chain(events: Iterable[JEPEvent], *, adapter: ProfileAdapter | None = None) -> VerificationResult:
50
+ errors: list[str] = []
51
+ materialized = list(events)
52
+ nonces: set[str] = set()
53
+ previous_hash: str | None = None
54
+ for index, event in enumerate(materialized):
55
+ result = verify_event(event, adapter=adapter)
56
+ errors.extend(f"{event.event_id}: {error}" for error in result.errors)
57
+ if event.nonce in nonces:
58
+ errors.append(f"{event.event_id}: duplicate nonce")
59
+ nonces.add(event.nonce)
60
+ if index == 0:
61
+ if event.previous_event_hash is not None:
62
+ errors.append(f"{event.event_id}: first event must not reference previous_event_hash")
63
+ elif event.previous_event_hash != previous_hash:
64
+ errors.append(f"{event.event_id}: previous_event_hash does not match prior event_hash")
65
+ previous_hash = event.event_hash
66
+ ok, delegation_errors = verify_delegation_chain(materialized)
67
+ if not ok:
68
+ errors.extend(delegation_errors)
69
+ return VerificationResult(not errors, tuple(errors))
70
+
71
+
72
+ def detect_tampering(events: Iterable[JEPEvent]) -> list[str]:
73
+ return list(verify_chain(events).errors)
74
+
75
+
76
+ def verify_replay(events: Iterable[JEPEvent]) -> VerificationResult:
77
+ return verify_chain(events)
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: jep-runtime
3
+ Version: 0.1.1
4
+ Summary: Reference runtime for Judgment Event Protocol executable accountability semantics
5
+ Author: JEP Runtime Contributors
6
+ License: MIT
7
+ Keywords: JEP,accountability,protocol,runtime,verification
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Security :: Cryptography
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: filelock>=3.12
13
+
14
+ # JEP Reference Runtime
15
+
16
+ `jep-runtime` is a runnable reference implementation for the Judgment Event Protocol (JEP). It turns the current JEP Internet-Draft primitives — Judgment (`J`), Delegation (`D`), Termination (`T`), and Verification (`V`) — into executable accountability semantics: create an event, canonicalize it, hash it, chain it, archive it, replay it, and verify it across neutral profile adapters.
17
+
18
+ This repository is intentionally **not** an agent framework, workflow orchestrator, blockchain, consensus layer, payment executor, or production security system. Mock signatures and mock credential references are provided so protocol semantics can be tested before deployment-specific cryptography is plugged in.
19
+
20
+ ## Architecture
21
+
22
+ ```text
23
+ +-------------------+ +------------------------+ +------------------+
24
+ | Event Runtime | ---> | Canonicalization | ---> | SHA-256 Hashing |
25
+ | J / D / T / V | | UTF-8 sorted JSON | | event_hash |
26
+ +---------+---------+ +-----------+------------+ +---------+--------+
27
+ | | |
28
+ v v v
29
+ +-------------------+ +------------------------+ +------------------+
30
+ | Delegation | ---> | Append-only Archive | ---> | Verification |
31
+ | scoped authority | | JSONL import/export | | chain/replay |
32
+ +---------+---------+ +-----------+------------+ +---------+--------+
33
+ | | |
34
+ v v v
35
+ +-------------------+ +------------------------+ +------------------+
36
+ | Profile Adapters | ---> | Replay Engine | ---> | Conformance |
37
+ | OAuth/X509/DID/IAM| | lineage graph/state | | vectors/report |
38
+ +-------------------+ +------------------------+ +------------------+
39
+ ```
40
+
41
+ ## Runtime data flow
42
+
43
+ 1. A caller creates a `JEPEvent` with the required core fields.
44
+ 2. The event is canonicalized as normalized UTF-8 JSON with stable field ordering and no insignificant whitespace.
45
+ 3. `event_hash = SHA256(canonical_event_without_event_hash)` is assigned once; changing a hashed event requires creating a new event.
46
+ 4. New events reference `previous_event_hash`, producing an append-only event chain.
47
+ 5. Delegation events carry bounded `authority_scope` and `delegation_chain` entries so authority lineage can be replayed.
48
+ 6. JSONL archives append one canonical event record per line.
49
+ 7. Verification recomputes hashes, validates nonce uniqueness, checks hash continuity, validates delegation scope, and invokes the configured neutral profile adapter.
50
+
51
+ ## Replay flow
52
+
53
+ ```text
54
+ archive.jsonl
55
+ |
56
+ v
57
+ import events -> verify entire chain -> replay J/D/T/V semantics
58
+ | | |
59
+ | | +--> termination_state
60
+ | +--> tamper/nonce/profile/delegation errors
61
+ +--> lineage_graph: hash-chain edges + delegation edges
62
+ ```
63
+
64
+ Run it with:
65
+
66
+ ```bash
67
+ jep replay archive.jsonl
68
+ ```
69
+
70
+ The replay output is a portable event lineage graph plus authority and termination state. It is evidence reconstruction, not workflow execution.
71
+
72
+ ## CLI
73
+
74
+ ```bash
75
+ jep create-event --type J --actor human:alice --subject agent:planner \
76
+ --agent-id agent:planner \
77
+ --scope-json '{"actions":["read"],"resources":["repo:jep"]}' \
78
+ --intent-json '{"task":"summarize JEP"}' \
79
+ --archive archive.jsonl
80
+
81
+ jep verify event.json
82
+ jep archive-verify archive.jsonl
83
+ jep replay archive.jsonl
84
+ jep conformance-test
85
+ ```
86
+
87
+ ## Conformance matrix
88
+
89
+ | Capability | Runtime check |
90
+ | --- | --- |
91
+ | Canonicalization | Stable UTF-8 JSON with sorted keys and normalized strings |
92
+ | Deterministic hashing | SHA-256 over canonical event without `event_hash` |
93
+ | Delegation semantics | Parent/child scope and expiration checks |
94
+ | Verification semantics | Hash, nonce, timestamp, profile, and chain integrity checks |
95
+ | Profile compatibility | Neutral `ProfileAdapter` contract with mock OAuth/OIDC, X509, DID/VC, Local IAM labels |
96
+ | Replay correctness | Archive replay must re-verify the full chain and emit lineage graph/state |
97
+
98
+ `jep conformance-test` emits test vectors, mock signed vectors, and a compatibility report.
99
+
100
+ ## Correspondence with the JEP draft
101
+
102
+ | Draft primitive / concept | Runtime implementation |
103
+ | --- | --- |
104
+ | `J` Judgment | `EventType.JUDGMENT` and `create_event("J", ...)` |
105
+ | `D` Delegation | `delegate_authority()`, scoped delegation events, `verify_delegation_chain()` |
106
+ | `T` Termination | `EventType.TERMINATION`, replayed into `termination_state` |
107
+ | `V` Verification | `verify_event()`, `verify_chain()`, `verify_replay()`, verification events |
108
+ | Replay protection | Required `nonce` and duplicate nonce validation |
109
+ | Signed/verifiable event format | Immutable hashed event model plus mock profile references |
110
+ | Optional profiles | `ProfileAdapter` interface; provider-neutral mock adapter |
111
+ | Append-only receipts | JSONL archive with chain verification on replay |
112
+
113
+ ## Repository structure
114
+
115
+ ```text
116
+ jep_runtime/
117
+ core/ # immutable event model and JSON schema generation
118
+ events/ # event factories
119
+ canonicalization/ # deterministic JSON + SHA-256 hashing
120
+ delegation/ # authority propagation and scope validation
121
+ verification/ # event, chain, replay, tamper, profile verification
122
+ profiles/ # provider-neutral profile adapter interface and mock adapter
123
+ archive/ # append-only JSONL archive runtime
124
+ replay/ # lineage graph and termination replay
125
+ conformance/ # conformance vectors and matrix
126
+ cli/ # jep command line entry point
127
+ schemas/ # generated JSON schema
128
+ examples/ # example event scenarios
129
+ tests/ # executable conformance/runtime tests
130
+ ```
131
+
132
+ ## Limitations
133
+
134
+ - Signatures are mock/reference only.
135
+ - Profile adapters do not verify real OAuth/OIDC, X509, DID/VC, or IAM credentials.
136
+ - No blockchain, distributed consensus, real payment execution, or production key management is included.
137
+ - The runtime enforces executable protocol invariants, not legal liability, governance policy, or workflow lifecycle orchestration.
138
+
139
+ ## Runtime governance extension points
140
+
141
+ - Replace `MockProfileAdapter` with production credential adapters.
142
+ - Add signature suites while preserving the canonicalization boundary.
143
+ - Add draft-version-specific schema adapters without changing the pinned v06 J/D/T/V primitive meaning.
144
+ - Add draft-version-specific schema adapters without changing J/D/T/V primitive meaning.
145
+ - Publish conformance vectors for independent implementations.
146
+ - Add governance-specific validation modules outside the core minimal runtime.
147
+
148
+ ## Runtime and verification notes
149
+
150
+ See [HARDENING.md](HARDENING.md) for supported behavior, regression checks, and compatibility boundaries.
@@ -0,0 +1,30 @@
1
+ jep_runtime/__init__.py,sha256=JhLqtSj_sjd77PxbDY4YSEf-5IqobPXAAKiZICNgW1M,600
2
+ jep_runtime/archive/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ jep_runtime/archive/jsonl.py,sha256=a8EMi3I7ntZWXatj5BldoVwMvc-vMI5bokvlucWq5dw,2794
4
+ jep_runtime/canonicalization/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ jep_runtime/canonicalization/json.py,sha256=zihMTZJlRoznk-aCAkgwhch5dlwj7eITITa0Jm_DA1s,1345
6
+ jep_runtime/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ jep_runtime/cli/main.py,sha256=MSr2G4pQ-r-0E-s6WAaGzsOuw1fp_2qVUVd6aXDnW3o,3713
8
+ jep_runtime/conformance/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ jep_runtime/conformance/runtime.py,sha256=k7on185FugRsz4oI3QwFN2Xnu9sPkR_xSz9sCGSvahs,3267
10
+ jep_runtime/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ jep_runtime/core/event.py,sha256=NhZZL64TS9oeADSFkeuW8rIxChcd2d9R3U41PMQxwvY,5853
12
+ jep_runtime/core/version.py,sha256=Bj1xWRaavM7IB3lem-TDouzjSkNgLibpNBsokPfHxA8,350
13
+ jep_runtime/delegation/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ jep_runtime/delegation/runtime.py,sha256=r2sBgjfuoH7CXfU_tMX5dq2zKRQqCVgnoZXY0WUffM0,5501
15
+ jep_runtime/events/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ jep_runtime/events/factory.py,sha256=q9wX7b6F3N4x8dwB1m0UN2rhMK9VgTxiHEkHGAbzNcY,1578
17
+ jep_runtime/examples/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ jep_runtime/profiles/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ jep_runtime/profiles/adapter.py,sha256=L8OspdywHFoLk6_jZZnB7W3b5cY6ewj04me0Xko9z7M,1673
20
+ jep_runtime/replay/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
+ jep_runtime/replay/engine.py,sha256=2WbY5GfdIfy11YHV8Cr4NuxbUzUTrj6iCcGjEZC2lQs,1686
22
+ jep_runtime/schemas/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
+ jep_runtime/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ jep_runtime/verification/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
+ jep_runtime/verification/runtime.py,sha256=hQNuPqB9pRXAauewmP7ZtVUSMhqvARNqBGkNRtvCdlY,3470
26
+ jep_runtime-0.1.1.dist-info/METADATA,sha256=22ZGQt3P-8iDlbNvAuiwJmjlyfRTyUE4V-bwo5ofi5c,7493
27
+ jep_runtime-0.1.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
28
+ jep_runtime-0.1.1.dist-info/entry_points.txt,sha256=okT3GtAUVAtXv1-hDxX18i7qAnOxlSfPkVzP_zFeGzg,50
29
+ jep_runtime-0.1.1.dist-info/top_level.txt,sha256=EDPCSbjtYVoxMAKBz62JFHA18FQUNyySPr0kI3bH5Tc,12
30
+ jep_runtime-0.1.1.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
+ jep = jep_runtime.cli.main:main
@@ -0,0 +1 @@
1
+ jep_runtime