jevblock 0.2.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,188 @@
1
+ """Drop-in helpers that connect JevBlock decisions to a MemBlock instance.
2
+
3
+ Nothing here imports memblock at module import time, so the package works standalone.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any, Callable
9
+
10
+ from jevblock.classifier import Decision, JevBlockClassifier
11
+ from jevblock.presets import memory_conflict, memory_pipeline, memory_relevance
12
+
13
+ STORE_FIELDS = {"type", "source", "confidence", "encryption_level", "decay_rate", "temporal_precision", "tags", "metadata"}
14
+
15
+
16
+ def decision_to_store_kwargs(decisions: list[Decision]) -> dict[str, Any] | None:
17
+ """Merge write-path decisions into `MemBlock.store(**kwargs)`. Returns None if skipped/blocked."""
18
+ merged: dict[str, Any] = {}
19
+ for d in decisions:
20
+ if d.blocked:
21
+ return None
22
+ merged.update(d.all_fields())
23
+ if merged.get("skip"):
24
+ return None
25
+ out = {k: v for k, v in merged.items() if k in STORE_FIELDS}
26
+ extra = {k: v for k, v in merged.items() if k not in STORE_FIELDS and k != "skip"}
27
+ if extra:
28
+ out["metadata"] = {f"jevblock_{k}": v for k, v in extra.items()}
29
+ return out
30
+
31
+
32
+ def classify_and_store(mem, classifier: JevBlockClassifier, content: str, *,
33
+ escalate: Callable[[str, list[Decision]], dict[str, Any] | None] | None = None,
34
+ record_decisions: bool = True, **extra_store_kwargs):
35
+ """Classify `content` with the write-path blocks, then call `mem.store`.
36
+
37
+ `escalate(content, decisions)` is called when a gate fires; it may return store kwargs
38
+ (for example from the existing LLM extractor) or None to fall back to the System One answer.
39
+ Every decision is stored as an `event` block tagged `jevblock:decision` (the flywheel).
40
+ """
41
+ from memblock import BlockType, EncryptionLevel, SourceType # imported lazily
42
+
43
+ decisions = classifier.run({"content": content})
44
+ kwargs = decision_to_store_kwargs(decisions)
45
+ if kwargs is None:
46
+ return None, decisions
47
+
48
+ if escalate and any(d.escalate for d in decisions):
49
+ override = escalate(content, decisions)
50
+ if override:
51
+ kwargs.update(override)
52
+
53
+ kwargs["type"] = BlockType(kwargs.get("type", "fact"))
54
+ if "source" in kwargs:
55
+ kwargs["source"] = SourceType(kwargs["source"])
56
+ if "encryption_level" in kwargs:
57
+ kwargs["encryption_level"] = EncryptionLevel(kwargs["encryption_level"])
58
+ kwargs.update(extra_store_kwargs)
59
+ block = mem.store(content, **kwargs)
60
+
61
+ if record_decisions and block is not None:
62
+ import json
63
+ for d in decisions:
64
+ mem.store(
65
+ json.dumps(d.to_record(), ensure_ascii=False),
66
+ type=BlockType.EVENT, source=SourceType.OBSERVED,
67
+ tags=["jevblock:decision", d.block_id], decay_rate=0.0,
68
+ metadata={"classified_block": block.id, "fingerprint": d.fingerprint},
69
+ )
70
+ return block, decisions
71
+
72
+
73
+ def resolve_conflicts(classifier_backend, new_content: str, existing_blocks: list[Any],
74
+ ensemble: int = 3) -> list[dict[str, Any]]:
75
+ """Run memory.conflict against each candidate. Returns a list of {block_id, action, edges, escalate}.
76
+
77
+ Uses a shuffle ensemble by default because RETRACT/DELETE are destructive.
78
+ """
79
+ clf = JevBlockClassifier(classifier_backend, [memory_conflict()], ensemble=ensemble)
80
+ out = []
81
+ for b in existing_blocks:
82
+ content = getattr(b, "content", b)
83
+ bid = getattr(b, "id", None)
84
+ d = clf.run_block(clf.blocks["memory.conflict"], {"new": new_content, "existing": content})
85
+ out.append({
86
+ "block_id": bid,
87
+ "action": d.fields["conflict_action"],
88
+ "confidence": d.answers["action"]["confidence"],
89
+ "edges": [r for r, on in (("contradicts", d.fields["edge_contradicts"]),
90
+ ("supersedes", d.fields["edge_supersedes"])) if on],
91
+ "escalate": d.escalate,
92
+ "decision": d,
93
+ })
94
+ return out
95
+
96
+
97
+ def rerank(classifier_backend, query: str, blocks: list[Any], top_k: int | None = None) -> list[tuple[Any, float]]:
98
+ """Rerank candidate blocks by calibrated relevance. One block per state; batch at the backend."""
99
+ clf = JevBlockClassifier(classifier_backend, [memory_relevance()])
100
+ scored = []
101
+ for b in blocks:
102
+ d = clf.run_block(clf.blocks["memory.relevance"], {"query": query, "block": getattr(b, "content", b)})
103
+ scored.append((b, float(d.fields["relevance"]) / 3.0))
104
+ scored.sort(key=lambda x: x[1], reverse=True)
105
+ return scored[:top_k] if top_k else scored
106
+
107
+
108
+ def default_write_classifier(backend, ensemble: int = 1) -> JevBlockClassifier:
109
+ return JevBlockClassifier(backend, memory_pipeline(), ensemble=ensemble)
110
+
111
+
112
+ # ═══════════════════════════════════════════════════════════════════════════
113
+ # Phase 3: objects MemBlock can hold directly (classifier= and reranker=)
114
+ # ═══════════════════════════════════════════════════════════════════════════
115
+
116
+ class MemoryClassifier:
117
+ """Adapter that MemBlock(classifier=...) calls on every store() and conflict check.
118
+
119
+ Duck-typed contract (see memblock/classifier.py):
120
+ classify(content) -> {"fields": {...}, "skip": bool, "escalate": bool, "record": {...}} | None
121
+ resolve_conflict(new_content, existing_blocks) -> [{"block_id", "action", "confidence",
122
+ "escalate", "record"}] | None
123
+ """
124
+
125
+ name = "jevblock"
126
+
127
+ def __init__(self, backend, *, blocks=None, conflict_block=None, ensemble: int = 1,
128
+ conflict_ensemble: int = 1, conflicts: bool = False):
129
+ """`conflicts` is off by default: Phase 2 measured memory.conflict at 0.18 zero-shot on
130
+ base Laya (100% escalated), and Phase 3 measured the gate at ~950 ms per store with a
131
+ 3-way ensemble over five candidates. Turn it on with an LLM backend or a fine-tuned
132
+ checkpoint; `resolve_conflict` returns None when off so MemBlock falls back to its LLM
133
+ resolver.
134
+ """
135
+ from jevblock.presets import memory_conflict as _conflict, memory_pipeline as _pipeline
136
+ self._write = JevBlockClassifier(backend, blocks or _pipeline(), ensemble=ensemble)
137
+ self._conflict = JevBlockClassifier(backend, [conflict_block or _conflict()], ensemble=conflict_ensemble) if conflicts else None
138
+ self.backend_name = getattr(backend, "name", "?")
139
+
140
+ def classify(self, content: str) -> dict[str, Any] | None:
141
+ decisions = self._write.run({"content": content})
142
+ kwargs = decision_to_store_kwargs(decisions)
143
+ record = {"backend": self.backend_name, "decisions": [d.to_record() for d in decisions]}
144
+ if kwargs is None:
145
+ return {"fields": {}, "skip": True, "escalate": False, "record": record}
146
+ meta = kwargs.pop("metadata", {})
147
+ fields = dict(kwargs)
148
+ fields.update({k: v for k, v in meta.items()}) # e.g. jevblock_sensitivity
149
+ return {"fields": fields, "skip": False, "escalate": any(d.escalate for d in decisions), "record": record}
150
+
151
+ def resolve_conflict(self, new_content: str, existing_blocks: list[Any]) -> list[dict[str, Any]] | None:
152
+ if self._conflict is None:
153
+ return None
154
+ blk = self._conflict.blocks["memory.conflict"]
155
+ out = []
156
+ for b in existing_blocks:
157
+ d = self._conflict.run_block(blk, {"new": new_content, "existing": getattr(b, "content", b)})
158
+ out.append({"block_id": getattr(b, "id", None), "action": d.fields["conflict_action"],
159
+ "confidence": d.answers["action"]["confidence"], "escalate": d.escalate,
160
+ "edges": [r for r, on in (("contradicts", d.fields["edge_contradicts"]),
161
+ ("supersedes", d.fields["edge_supersedes"])) if on],
162
+ "record": d.to_record()})
163
+ return out
164
+
165
+
166
+ class JevBlockReranker:
167
+ """memblock.rerankers.Reranker implementation backed by the memory.relevance block.
168
+
169
+ Replaces the fixed 0.70/0.10/0.05/0.05/0.10 ranking weights with a calibrated per-(query,
170
+ block) relevance level. Score = expected rubric level / 3, ties broken by answerable P(true).
171
+ """
172
+
173
+ def __init__(self, backend):
174
+ self._clf = JevBlockClassifier(backend, [memory_relevance()])
175
+ self._blk = self._clf.blocks["memory.relevance"]
176
+ self._name = f"jevblock:{getattr(backend, 'name', '?')}"
177
+
178
+ @property
179
+ def name(self) -> str:
180
+ return self._name
181
+
182
+ def rerank(self, query: str, blocks: list[Any], top_k: int = 10) -> list[Any]:
183
+ scored = []
184
+ for b in blocks:
185
+ d = self._clf.run_block(self._blk, {"query": query, "block": getattr(b, "content", b)})
186
+ scored.append((float(d.fields["relevance"]) / 3.0, float(d.fields["answerable"]), b))
187
+ scored.sort(key=lambda x: (x[0], x[1]), reverse=True)
188
+ return [b for _, _, b in scored[:top_k]]
jevblock/presets.py ADDED
@@ -0,0 +1,188 @@
1
+ """Ready-made JevBlocks for the MemBlock lifecycle (design §2.5).
2
+
3
+ Each block is small, atomic, and backend-neutral. Bindings target memblock `store()` kwargs and
4
+ conflict actions; thresholds are starting points to be tuned after calibration.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from jevblock.criteria import Binding, Gate, JevBlock, Question
10
+
11
+
12
+ def memory_noise() -> JevBlock:
13
+ """Drop filler before it reaches typing. Replaces the static 35-word NoiseFilter list.
14
+
15
+ Measured on base Laya (multilingual, zero-shot): a `noul` "is this noise?" question scored
16
+ 0.63 on "hello thanks bye" but 0.03 on "ok sounds good", so this is a `choice`; the base
17
+ checkpoints answer `choice` far more reliably than abstract `noul` propositions.
18
+ """
19
+ return JevBlock(
20
+ id="memory.noise",
21
+ purpose="Drop filler before it reaches typing. Replaces the static 35-word NoiseFilter list.",
22
+ state_fields=["content"],
23
+ questions={
24
+ "kind": Question("choice", "What is `content`?", {
25
+ "filler": "a greeting, thanks, acknowledgement, or small talk with no information",
26
+ "information": "states something about the user, their work, their world, or an event",
27
+ }),
28
+ },
29
+ # Threshold from the Phase 2 sweep on base laya-multilingual (269 rows, zero-shot):
30
+ # gate 0.90 -> 28/30 filler caught but 61/239 real memories blocked (25%)
31
+ # gate 0.98 -> 17/30 filler caught, 5/239 real memories blocked (2%)
32
+ # Base Laya calls most short factual sentences "filler", so on that backend this block is a
33
+ # low-recall safety net, not a filter; an LLM backend or a fine-tune is needed for recall.
34
+ # memblock's static NoiseFilter word list should stay in front of it. Refit per backend.
35
+ bindings=[Binding("skip", "kind.probabilities.filler", threshold=(">=", 0.98, True, False))],
36
+ gates=[Gate("kind.probabilities.filler", ">=", 0.98, action="block")],
37
+ )
38
+
39
+
40
+ def memory_typing() -> JevBlock:
41
+ """Classify one memory sentence into MemBlock fields: type, source, sensitivity, durability.
42
+
43
+ `sensitivity` is a `choice`, not a `noul`: on base Laya a "is this sensitive?" noul scored
44
+ 0.11 on an API key and 0.10 on a password, while the choice form labelled credential,
45
+ financial and medical cases correctly. Worth-storing is handled by `memory.noise`.
46
+ """
47
+ return JevBlock(
48
+ id="memory.typing",
49
+ purpose="Classify one memory sentence into MemBlock fields: type, source, sensitivity, durability.",
50
+ state_fields=["content", "speaker", "conversation_snippet"],
51
+ questions={
52
+ "block_type": Question("choice", "What kind of memory is `content`?", {
53
+ "fact": "objective, verifiable statement about the world or the user",
54
+ "preference": "what the user likes, dislikes, prefers, or wants",
55
+ "event": "something that happened at a point in time",
56
+ "entity": "a named thing: a person, project, tool, product, or company",
57
+ "relation": "how two named things relate to each other",
58
+ }),
59
+ "source": Question("choice", "How was `content` known?", {
60
+ "explicit": "the user stated it directly",
61
+ "inferred": "derived from context, not stated outright",
62
+ "observed": "noticed from behaviour or repeated patterns",
63
+ }),
64
+ "sensitivity": Question("choice", "What kind of information is `content`?", {
65
+ "credential": "password, API key, token, secret",
66
+ "financial": "salary, bank account, card, money amounts",
67
+ "medical": "health condition, diagnosis, medication",
68
+ "identity": "ID numbers, home address, date of birth",
69
+ "ordinary": "nothing sensitive",
70
+ }),
71
+ "durable": Question("score", "How long will `content` stay true?",
72
+ ["minutes to hours", "days to weeks", "months", "years or permanent"]),
73
+ },
74
+ bindings=[
75
+ Binding("type", "block_type.choice"),
76
+ Binding("source", "source.choice"),
77
+ Binding("confidence", "block_type.confidence"),
78
+ Binding("sensitivity", "sensitivity.choice"),
79
+ Binding("encryption_level", "sensitivity.choice",
80
+ map={"credential": "sensitive", "financial": "sensitive", "medical": "sensitive",
81
+ "identity": "sensitive", "ordinary": "none"}),
82
+ Binding("decay_rate", "durable.level", map={0: 0.10, 1: 0.04, 2: 0.01, 3: 0.001}),
83
+ ],
84
+ gates=[Gate("block_type.confidence", "<", 0.55, action="escalate")],
85
+ )
86
+
87
+
88
+ def memory_event_temporal() -> JevBlock:
89
+ """Chained: runs only when memory.typing says `event`."""
90
+ return JevBlock(
91
+ id="memory.event_temporal",
92
+ purpose="For events, decide how precise the time reference is (feeds temporal_precision).",
93
+ state_fields=["content"],
94
+ run_if=("memory.typing", "block_type.choice", "event"),
95
+ questions={
96
+ "precision": Question("choice", "How precisely does `content` say when it happened?", {
97
+ "exact": "a specific date or datetime",
98
+ "day": "a specific day without time",
99
+ "week": "a week or 'last week'",
100
+ "month": "a month or 'last month'",
101
+ "year": "a year or 'last year'",
102
+ "approximate": "vague: 'a while ago', 'recently', no time given",
103
+ }),
104
+ },
105
+ bindings=[Binding("temporal_precision", "precision.choice")],
106
+ )
107
+
108
+
109
+ def memory_conflict() -> JevBlock:
110
+ """State: {"new": ..., "existing": ...}. Replaces the LLM ConflictResolver in the confident band."""
111
+ return JevBlock(
112
+ id="memory.conflict",
113
+ purpose="Decide what to do with `new` given one `existing` memory.",
114
+ state_fields=["new", "existing"],
115
+ questions={
116
+ "action": Question("choice", "Given `existing`, what should happen with `new`?", {
117
+ "ADD": "new is different information; keep both",
118
+ "UPDATE": "new refines or supersedes existing; merge into one",
119
+ "RETRACT": "existing was true but is now closed out: sold, moved, cancelled, no longer",
120
+ "DELETE": "existing was never true and new corrects it",
121
+ "NONE": "new says nothing existing does not already say",
122
+ }),
123
+ "contradicts": Question("noul", "Does `new` contradict `existing`?"),
124
+ "supersedes": Question("noul", "Is `new` a newer version of the same information as `existing`?"),
125
+ },
126
+ bindings=[
127
+ Binding("conflict_action", "action.choice"),
128
+ Binding("edge_contradicts", "contradicts.noul", threshold=(">=", 0.6, True, False)),
129
+ Binding("edge_supersedes", "supersedes.noul", threshold=(">=", 0.6, True, False)),
130
+ ],
131
+ # Destructive actions need higher confidence; below it, escalate to the LLM resolver.
132
+ gates=[Gate("action.confidence", "<", 0.65, action="escalate")],
133
+ )
134
+
135
+
136
+ def memory_relevance() -> JevBlock:
137
+ """State: {"query": ..., "block": ...}. Batched over top-N candidates for reranking."""
138
+ return JevBlock(
139
+ id="memory.relevance",
140
+ purpose="Calibrated relevance of one block to a query; replaces fixed ranking weights.",
141
+ state_fields=["query", "block"],
142
+ questions={
143
+ "relevance": Question("score", "How relevant is `block` to answering `query`?",
144
+ ["unrelated", "same topic, does not answer", "partially answers", "directly answers"]),
145
+ "answerable": Question("noul", "Can `query` be answered using only `block`?"),
146
+ },
147
+ bindings=[Binding("relevance", "relevance.score"), Binding("answerable", "answerable.noul")],
148
+ )
149
+
150
+
151
+ def memory_pipeline() -> list[JevBlock]:
152
+ """The write-path DAG: noise -> typing -> (event_temporal if event)."""
153
+ return [memory_noise(), memory_typing(), memory_event_temporal()]
154
+
155
+
156
+ def fin_query() -> JevBlock:
157
+ """Financial-services chatbot: understand what the customer wants in `message`."""
158
+ return JevBlock(
159
+ id="fin.query",
160
+ purpose="Understand a customer's query to a financial services chatbot: route, auth, compliance, urgency, tone.",
161
+ state_fields=["message", "last_bot_turn"],
162
+ questions={
163
+ "intent": Question("choice", "What does the customer want in `message`?", {
164
+ "balance_or_holdings": "current balance, portfolio value, what they hold",
165
+ "transaction": "buy, sell, redeem, start or stop a SIP, transfer money",
166
+ "statement_or_tax": "statements, capital gains, tax documents, XIRR or returns report",
167
+ "kyc_or_account": "KYC, nominee, bank mandate, account details, login or password",
168
+ "product_info": "what a fund or product is, its returns, risk, or a comparison",
169
+ "complaint": "something went wrong: failed payment, wrong deduction, missing units",
170
+ "advice": "asking what they should invest in, or whether to buy or sell",
171
+ "other": "none of the above, small talk, or unclear",
172
+ }),
173
+ "needs_auth": Question("noul", "Does answering `message` require the customer's private account data?"),
174
+ "is_advice": Question("noul", "Is the customer asking for a personal investment recommendation?"),
175
+ "urgency": Question("score", "How urgent is `message`?",
176
+ ["no time pressure", "wants it resolved today", "money is stuck or at risk right now"]),
177
+ "sentiment": Question("score", "How does the customer sound?", ["calm", "concerned", "frustrated", "angry"]),
178
+ },
179
+ bindings=[
180
+ Binding("route", "intent.choice"),
181
+ Binding("route_confidence", "intent.confidence"),
182
+ Binding("require_login", "needs_auth.noul", threshold=(">=", 0.6, True, False)),
183
+ Binding("compliance_flag", "is_advice.noul", threshold=(">=", 0.5, True, False)),
184
+ Binding("urgency", "urgency.level"),
185
+ Binding("sentiment", "sentiment.level"),
186
+ ],
187
+ gates=[Gate("intent.confidence", "<", 0.6, action="escalate")],
188
+ )
jevblock/radar.py ADDED
@@ -0,0 +1,65 @@
1
+ """Radar: observations computed from the raw state before a decision.
2
+
3
+ A typed-decision engine judges the present from what it is shown. It does not search the
4
+ future and it does not perceive images. A radar closes that gap outside the model: a cheap,
5
+ deterministic (or cached) function that scans ahead, or looks up context, and reports *facts*
6
+ the engine can weigh. Never the answer. The block stays a one-step judgment over better evidence.
7
+
8
+ Radars are registered by name and named in a block's `observations` list:
9
+
10
+ @radar("snake.lookahead")
11
+ def snake_lookahead(state): ... # returns a dict merged into the state
12
+
13
+ Three families are expected: simulation/search (games, navigation, dependencies), memory /
14
+ retrieval (conversation history, stored facts; e.g. a MemBlock query), perception (a vision
15
+ model turning an image into typed observations). Only the first ships here.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import Any, Callable
21
+
22
+ _RADARS: dict[str, Callable[[Any], dict[str, Any]]] = {}
23
+
24
+
25
+ def radar(name: str):
26
+ def deco(fn):
27
+ _RADARS[name] = fn
28
+ return fn
29
+ return deco
30
+
31
+
32
+ def observe(names: list[str], state: Any) -> Any:
33
+ """Run each named radar on the raw state and merge its observations in. Dict states only."""
34
+ if not isinstance(state, dict):
35
+ return state
36
+ out = dict(state)
37
+ for n in names:
38
+ if n not in _RADARS:
39
+ raise KeyError(f"unknown radar {n!r}; registered: {sorted(_RADARS)}")
40
+ out.update(_RADARS[n](state))
41
+ return out
42
+
43
+
44
+ def registered() -> list[str]:
45
+ return sorted(_RADARS)
46
+
47
+
48
+ # ─── simulation radar for snake ─────────────────────────────────────────────
49
+
50
+ @radar("snake.lookahead")
51
+ def snake_lookahead(state: dict[str, Any]) -> dict[str, Any]:
52
+ """Per direction: free cells reachable after the move, steps to food, eats now. Requires the
53
+ raw state to carry `_game` (a SnakeGame) as the snake state does; strips it from the output."""
54
+ game = state.get("_game")
55
+ if game is None:
56
+ return {}
57
+ info = game.analyse()
58
+ look = {}
59
+ for d, i in info.items():
60
+ if not i["legal"]:
61
+ look[d] = "blocked"
62
+ else:
63
+ fp = i["food_path"]
64
+ look[d] = f"{i['space']} free cells, " + ("eats food now" if i.get("eats") else f"food in {fp} steps" if fp is not None else "food unreachable")
65
+ return {"lookahead": look, "_game": None}
jevblock/registry.py ADDED
@@ -0,0 +1,71 @@
1
+ """Block registry: blocks as versioned JSON files people can install, fork and share.
2
+
3
+ python -m jevblock.registry export blocks/ # write every preset to blocks/<id>.json
4
+ python -m jevblock.registry list blocks/ # id, version, fingerprint, purpose
5
+ python -m jevblock.registry validate blocks/x.json # bounds check a block file
6
+
7
+ A registry directory is just files plus an `index.json` mapping id -> {version, fingerprint, file}.
8
+ Fingerprints are stored on every decision, so a block can always be traced back to its file.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import sys
16
+
17
+ from jevblock import presets
18
+ from jevblock.criteria import JevBlock
19
+
20
+ PRESETS = {
21
+ "memory.noise": presets.memory_noise, "memory.typing": presets.memory_typing,
22
+ "memory.event_temporal": presets.memory_event_temporal, "memory.conflict": presets.memory_conflict,
23
+ "memory.relevance": presets.memory_relevance, "fin.query": presets.fin_query,
24
+ }
25
+
26
+
27
+ def export(directory: str, blocks: dict[str, JevBlock] | None = None) -> dict[str, dict]:
28
+ os.makedirs(directory, exist_ok=True)
29
+ blocks = blocks or {k: f() for k, f in PRESETS.items()}
30
+ index = {}
31
+ for bid, blk in blocks.items():
32
+ blk.validate()
33
+ fn = f"{bid}.json"
34
+ blk.save(os.path.join(directory, fn))
35
+ index[bid] = {"version": blk.version, "fingerprint": blk.fingerprint(), "file": fn, "purpose": blk.purpose}
36
+ with open(os.path.join(directory, "index.json"), "w", encoding="utf-8") as f:
37
+ json.dump(index, f, indent=2, ensure_ascii=False)
38
+ return index
39
+
40
+
41
+ def load_all(directory: str) -> dict[str, JevBlock]:
42
+ with open(os.path.join(directory, "index.json"), encoding="utf-8") as f:
43
+ index = json.load(f)
44
+ out = {}
45
+ for bid, meta in index.items():
46
+ blk = JevBlock.load(os.path.join(directory, meta["file"]))
47
+ if blk.fingerprint() != meta["fingerprint"]:
48
+ raise ValueError(f"{bid}: file fingerprint {blk.fingerprint()} != index {meta['fingerprint']}")
49
+ out[bid] = blk
50
+ return out
51
+
52
+
53
+ def main(argv=None):
54
+ argv = argv if argv is not None else sys.argv[1:]
55
+ if not argv or argv[0] not in ("export", "list", "validate"):
56
+ print(__doc__); return 2
57
+ cmd, arg = argv[0], (argv[1] if len(argv) > 1 else "blocks")
58
+ if cmd == "export":
59
+ idx = export(arg)
60
+ print(f"exported {len(idx)} blocks to {arg}/")
61
+ elif cmd == "list":
62
+ for bid, blk in load_all(arg).items():
63
+ print(f"{bid:24} v{blk.version} {blk.fingerprint().split(':')[1]} {len(blk.questions)}q {blk.purpose[:60]}")
64
+ elif cmd == "validate":
65
+ blk = JevBlock.load(arg)
66
+ print(f"ok: {blk.fingerprint()}")
67
+ return 0
68
+
69
+
70
+ if __name__ == "__main__":
71
+ sys.exit(main())
jevblock/replay.py ADDED
@@ -0,0 +1,144 @@
1
+ """Replay and ablation: measure the layer with the model held constant.
2
+
3
+ Every harness run stores the engine's raw answers per row. `ReplayBackend` serves those answers
4
+ back for the same states, so the model becomes a fixed input and everything JevBlock does on top
5
+ (bindings, calibration, gates, chaining) can be tested deterministically, offline, in seconds.
6
+
7
+ `ablate()` reports what each part of the layer contributes on a recording:
8
+
9
+ * bindings : recorded answers -> fields, compared with the fields recorded at run time (must be 100%)
10
+ * raw : the engine's accuracy and calibration error as it came out of the model
11
+ * calibrated : temperatures fitted on the even rows, scored on the odd rows (ECE down, argmax unchanged)
12
+ * gate curve : for each confidence threshold, coverage (share automated), automated accuracy,
13
+ escalated accuracy. The layer's value is automated accuracy above raw at useful coverage.
14
+ * oracle : accuracy if every escalated row were answered correctly (the ceiling escalation buys)
15
+
16
+ python -m jevblock.replay benchmarks/results_ollama/fin.query__ollama-gemma4-e2b-logprobs__gemma4__test.json data/fin_query.jsonl
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import math
23
+ import sys
24
+ from typing import Any
25
+
26
+ from jevblock.bindings import resolve_bindings
27
+ from jevblock.classifier import JevBlockClassifier, _recalibrate, _temp_bucket
28
+ from jevblock.eval import _metrics, _pred, _probs, ece, get_block, load_jsonl
29
+
30
+
31
+ def _key(state: Any) -> str:
32
+ return json.dumps(state, sort_keys=True, ensure_ascii=False, default=str)
33
+
34
+
35
+ class ReplayBackend:
36
+ """Serve recorded answers for recorded states. Unknown states raise, so a replay can never
37
+ silently fall back to a live model."""
38
+
39
+ def __init__(self, results_path: str, data_path: str):
40
+ rep = json.load(open(results_path, encoding="utf-8"))
41
+ rows = {r.get("id", i): r for i, r in enumerate(load_jsonl(data_path))}
42
+ self.name = f"replay:{rep['backend']}"
43
+ self.block_fingerprint = rep["block"]
44
+ self._answers: dict[str, dict[str, Any]] = {}
45
+ self.items = rep["_items"]
46
+ for it in self.items:
47
+ r = rows.get(it["id"])
48
+ if r is None:
49
+ continue
50
+ state = r.get("state_hinted", r["state"]) if rep["block"].startswith("snake.move_hinted") else r["state"]
51
+ self._answers[_key(state)] = it["answers"]
52
+
53
+ def predict(self, state: Any, questions: dict[str, dict[str, Any]]) -> dict[str, Any]:
54
+ from jevblock.llm import public_state
55
+ k = _key(public_state(state))
56
+ if k not in self._answers:
57
+ raise KeyError("state not in recording; replay never calls a live model")
58
+ a = self._answers[k]
59
+ return {"model": self.name, "answers": {q: dict(a[q]) for q in questions if q in a},
60
+ "usage": {"input_tokens": 0, "output_tokens": 0}}
61
+
62
+
63
+ # --------------------------------------------------------------------------- ablation
64
+ def gate_curve(rows: list[tuple[dict[str, Any], str]], thresholds=(0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)) -> list[dict[str, float]]:
65
+ out = []
66
+ for t in thresholds:
67
+ auto = [(a, g) for a, g in rows if max(_probs(a).values()) >= t or a.get("confidence", 0) >= t]
68
+ esc = [(a, g) for a, g in rows if (a, g) not in auto]
69
+ n = len(rows)
70
+ acc_auto = round(sum(_pred(a) == g for a, g in auto) / len(auto), 3) if auto else None
71
+ acc_esc = round(sum(_pred(a) == g for a, g in esc) / len(esc), 3) if esc else None
72
+ oracle = round((sum(_pred(a) == g for a, g in auto) + len(esc)) / n, 3) if n else None
73
+ out.append({"threshold": t, "coverage": round(len(auto) / n, 3), "acc_automated": acc_auto,
74
+ "acc_escalated": acc_esc, "acc_with_perfect_escalation": oracle})
75
+ return out
76
+
77
+
78
+ def ablate(results_path: str, data_path: str | None = None) -> dict[str, Any]:
79
+ rep = json.load(open(results_path, encoding="utf-8"))
80
+ block = get_block(rep["block"].split("@")[0])
81
+ items = rep["_items"]
82
+ report: dict[str, Any] = {"recording": results_path, "backend": rep["backend"], "block": rep["block"], "n": len(items), "questions": {}}
83
+
84
+ # bindings: pure code, must reproduce the fields recorded at run time
85
+ mism = 0
86
+ for it in items:
87
+ try:
88
+ f = resolve_bindings(it["answers"], block.bindings)
89
+ except Exception:
90
+ mism += 1
91
+ continue
92
+ if any(f.get(k) != v for k, v in it["fields"].items() if k in f):
93
+ mism += 1
94
+ report["bindings"] = {"rows": len(items), "mismatches": mism, "ok": mism == 0}
95
+
96
+ for qid in block.questions:
97
+ rows = [(it["answers"][qid], str(it["gold"][qid])) for it in items if qid in it["gold"] and qid in it["answers"]]
98
+ if not rows:
99
+ continue
100
+ train = [rw for it, rw in zip([i for i in items if qid in i["gold"] and qid in i["answers"]], rows) if it["split"] == "train"]
101
+ test = [rw for it, rw in zip([i for i in items if qid in i["gold"] and qid in i["answers"]], rows) if it["split"] == "test"]
102
+ temps = JevBlockClassifier.fit_temperatures(train)
103
+ recal = []
104
+ flips = 0
105
+ for a, g in test:
106
+ t = temps.get(_temp_bucket(a["type"], len(_probs(a))))
107
+ b = _recalibrate(a, t) if t else a
108
+ flips += _pred(a) != _pred(b)
109
+ recal.append((b, g))
110
+ report["questions"][qid] = {
111
+ "raw": _metrics(rows),
112
+ "calibration": {"fitted_temperatures": temps, "test_raw": _metrics(test), "test_calibrated": _metrics(recal),
113
+ "argmax_changed": flips},
114
+ "gate_curve": gate_curve(recal if recal else rows),
115
+ }
116
+ return report
117
+
118
+
119
+ def to_markdown(rep: dict[str, Any]) -> str:
120
+ L = [f"### Layer ablation on `{rep['backend']}` · {rep['block']} · n={rep['n']}", "",
121
+ f"bindings: {rep['bindings']['rows']} rows, {rep['bindings']['mismatches']} mismatches → {'OK' if rep['bindings']['ok'] else 'FAIL'}", ""]
122
+ for qid, q in rep["questions"].items():
123
+ r, c = q["raw"], q["calibration"]
124
+ L += [f"**{qid}** raw: acc {r['accuracy']} · ECE {r['ece']} · n {r['n']}",
125
+ f"calibration (fit even, score odd): ECE {c['test_raw'].get('ece','-')} → {c['test_calibrated'].get('ece','-')}, "
126
+ f"acc {c['test_raw'].get('accuracy','-')} → {c['test_calibrated'].get('accuracy','-')}, argmax changed on {c['argmax_changed']} rows, T={c['fitted_temperatures']}",
127
+ "", "| gate ≥ | coverage | acc automated | acc escalated | acc if escalations were perfect |", "|---:|---:|---:|---:|---:|"]
128
+ for g in q["gate_curve"]:
129
+ L.append(f"| {g['threshold']} | {g['coverage']} | {g['acc_automated']} | {g['acc_escalated']} | {g['acc_with_perfect_escalation']} |")
130
+ L.append("")
131
+ return "\n".join(L)
132
+
133
+
134
+ def main(argv=None):
135
+ argv = argv if argv is not None else sys.argv[1:]
136
+ if not argv:
137
+ print(__doc__); return 2
138
+ rep = ablate(argv[0], argv[1] if len(argv) > 1 else None)
139
+ print(to_markdown(rep))
140
+ return 0
141
+
142
+
143
+ if __name__ == "__main__":
144
+ sys.exit(main())