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.
jevblock/classifier.py ADDED
@@ -0,0 +1,254 @@
1
+ """Run JevBlocks: single block, chained DAG, shuffle-ensemble, temperature calibration, gates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import random
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+ from jevblock.bindings import evaluate_gates, resolve_bindings
12
+ from jevblock.criteria import JevBlock
13
+
14
+
15
+ def _temp_bucket(qtype: str, k: int) -> str:
16
+ size = "2" if k <= 2 else "3-5" if k <= 5 else "6-10" if k <= 10 else "11+"
17
+ return f"{qtype}:{size}"
18
+
19
+
20
+ def _confidence(p: list[float]) -> float:
21
+ k = len(p)
22
+ if k < 2:
23
+ return 1.0
24
+ ent = -sum(v * math.log(max(v, 1e-12)) for v in p)
25
+ return max(0.0, min(1.0, 1.0 - ent / math.log(k)))
26
+
27
+
28
+ def _recalibrate(answer: dict[str, Any], temperature: float) -> dict[str, Any]:
29
+ """Apply a per-block temperature on top of the backend's probabilities (clamped like Laya)."""
30
+ t = min(5.0, max(0.5, float(temperature)))
31
+ probs = answer.get("probabilities")
32
+ if not probs:
33
+ if answer["type"] == "noul":
34
+ p1 = answer["noul"]
35
+ z = [math.log(max(1 - p1, 1e-9)) / t, math.log(max(p1, 1e-9)) / t]
36
+ m = max(z)
37
+ e = [math.exp(v - m) for v in z]
38
+ p1 = e[1] / sum(e)
39
+ answer = {**answer, "noul": round(p1, 4), "confidence": round(max(p1, 1 - p1), 4)}
40
+ return answer
41
+ keys = list(probs.keys())
42
+ z = [math.log(max(probs[k], 1e-9)) / t for k in keys]
43
+ m = max(z)
44
+ e = [math.exp(v - m) for v in z]
45
+ s = sum(e)
46
+ p = [v / s for v in e]
47
+ new = {**answer, "probabilities": {k: round(v, 4) for k, v in zip(keys, p)}, "confidence": round(_confidence(p), 4)}
48
+ if answer["type"] == "choice":
49
+ new["choice"] = keys[max(range(len(p)), key=p.__getitem__)]
50
+ elif answer["type"] == "score":
51
+ new["score"] = round(sum(int(k) * v for k, v in zip(keys, p)), 4)
52
+ return new
53
+
54
+
55
+ @dataclass
56
+ class Decision:
57
+ block_id: str
58
+ fingerprint: str
59
+ backend: str
60
+ answers: dict[str, Any]
61
+ fields: dict[str, Any]
62
+ gates_fired: list[dict[str, Any]]
63
+ latency_ms: float
64
+ ensemble_runs: int = 1
65
+ children: list["Decision"] = field(default_factory=list)
66
+ log_id: str | None = None
67
+ radar_ms: float = 0.0
68
+
69
+ @property
70
+ def escalate(self) -> bool:
71
+ return any(g["action"] == "escalate" for g in self.gates_fired)
72
+
73
+ @property
74
+ def blocked(self) -> bool:
75
+ return any(g["action"] == "block" for g in self.gates_fired)
76
+
77
+ def all_fields(self) -> dict[str, Any]:
78
+ """Fields from this decision and every chained child, children overriding parents."""
79
+ out = dict(self.fields)
80
+ for c in self.children:
81
+ out.update(c.all_fields())
82
+ return out
83
+
84
+ def to_record(self) -> dict[str, Any]:
85
+ """Compact form for storing as a memblock event (the flywheel, design §4)."""
86
+ return {
87
+ "block": self.fingerprint,
88
+ "backend": self.backend,
89
+ "answers": {q: {k: v for k, v in a.items() if k in ("choice", "score", "noul", "probabilities", "confidence")}
90
+ for q, a in self.answers.items()},
91
+ "fields": self.fields,
92
+ "gates": self.gates_fired,
93
+ "latency_ms": round(self.latency_ms, 2),
94
+ "children": [c.to_record() for c in self.children],
95
+ }
96
+
97
+
98
+ class JevBlockClassifier:
99
+ """Runs one or more JevBlocks against a state on a System One backend.
100
+
101
+ `blocks` may include chained blocks (`run_if=(parent_id, "<qid>.choice", value)`); they run only
102
+ when the parent's answer matches. `ensemble` > 1 shuffles choice option order and averages
103
+ probabilities (mitigates the measured 4 to 23% option-order flip rate).
104
+ """
105
+
106
+ def __init__(self, backend, blocks: list[JevBlock], ensemble: int = 1, seed: int = 0, log=None):
107
+ self.backend = backend
108
+ self.blocks = {b.validate().id: b for b in blocks}
109
+ self.ensemble = max(1, int(ensemble))
110
+ self._rng = random.Random(seed)
111
+ self.log = log # optional jevblock.log.DecisionLog; every run_block() is appended
112
+
113
+ # ------------------------------------------------------------------ single block
114
+ def run_block(self, block: JevBlock, state: Any) -> Decision:
115
+ t0 = time.perf_counter()
116
+ radar_ms = 0.0
117
+ if block.observations:
118
+ from jevblock.radar import observe
119
+ t_r = time.perf_counter()
120
+ state = observe(block.observations, state)
121
+ radar_ms = (time.perf_counter() - t_r) * 1000
122
+ questions = block.to_laya_questions()
123
+ if self.ensemble == 1:
124
+ answers = self.backend.predict(state, questions)["answers"]
125
+ else:
126
+ answers = self._ensemble(block, state, questions)
127
+ # Per-block calibration on top of the backend's own, keyed by backend name when nested:
128
+ # {"choice:3-5": 1.4} -> applies to every backend
129
+ # {"anthropic:claude-opus-5": {"choice:3-5": 1.4}, "laya-mlx": {...}}
130
+ cal = self._calibration_for(block)
131
+ if cal:
132
+ for qid, a in answers.items():
133
+ k = len(a.get("probabilities", {})) or 2
134
+ t = cal.get(_temp_bucket(a["type"], k)) or cal.get(qid)
135
+ if t:
136
+ answers[qid] = _recalibrate(a, t)
137
+ fields = resolve_bindings(answers, block.bindings)
138
+ fired = [{"source": g.source, "op": g.op, "value": g.value, "action": g.action, "observed": round(v, 4)}
139
+ for g, v in evaluate_gates(answers, block.gates)]
140
+ d = Decision(
141
+ block_id=block.id, fingerprint=block.fingerprint(), backend=getattr(self.backend, "name", "?"),
142
+ answers=answers, fields=fields, gates_fired=fired,
143
+ latency_ms=(time.perf_counter() - t0) * 1000, ensemble_runs=self.ensemble, radar_ms=radar_ms,
144
+ )
145
+ if self.log is not None:
146
+ try:
147
+ d.log_id = self.log.record(d, state)
148
+ except Exception:
149
+ pass # logging must never break a decision
150
+ return d
151
+
152
+ def _calibration_for(self, block: JevBlock) -> dict[str, float]:
153
+ cal = block.calibration or {}
154
+ name = getattr(self.backend, "name", "")
155
+ if any(isinstance(v, dict) for v in cal.values()):
156
+ # nested by backend; exact name first, then prefix match ("anthropic" matches "anthropic:claude-opus-5")
157
+ if name in cal:
158
+ return cal[name]
159
+ for k, v in cal.items():
160
+ if isinstance(v, dict) and name.startswith(k):
161
+ return v
162
+ return {}
163
+ return cal
164
+
165
+ def _ensemble(self, block: JevBlock, state: Any, questions: dict) -> dict[str, Any]:
166
+ acc: dict[str, dict[str, float]] = {}
167
+ base: dict[str, Any] = {}
168
+ for _ in range(self.ensemble):
169
+ shuffled = {}
170
+ for qid, q in questions.items():
171
+ q2 = dict(q)
172
+ if q["type"] == "choice" and isinstance(q.get("criteria"), dict):
173
+ items = list(q["criteria"].items())
174
+ self._rng.shuffle(items)
175
+ q2["criteria"] = dict(items)
176
+ shuffled[qid] = q2
177
+ ans = self.backend.predict(state, shuffled)["answers"]
178
+ for qid, a in ans.items():
179
+ base.setdefault(qid, a)
180
+ probs = a.get("probabilities") or {"false": 1 - a["noul"], "true": a["noul"]}
181
+ bucket = acc.setdefault(qid, {})
182
+ for k, v in probs.items():
183
+ bucket[k] = bucket.get(k, 0.0) + v / self.ensemble
184
+ out = {}
185
+ for qid, probs in acc.items():
186
+ a = dict(base[qid])
187
+ keys = list(questions[qid]["criteria"].keys()) if a["type"] == "choice" else list(probs.keys())
188
+ p = [probs[k] for k in keys]
189
+ if a["type"] == "choice":
190
+ a["probabilities"] = {k: round(v, 4) for k, v in zip(keys, p)}
191
+ a["choice"] = keys[max(range(len(p)), key=p.__getitem__)]
192
+ a["confidence"] = round(_confidence(p), 4)
193
+ elif a["type"] == "score":
194
+ a["probabilities"] = {k: round(v, 4) for k, v in zip(keys, p)}
195
+ a["score"] = round(sum(int(k) * v for k, v in zip(keys, p)), 4)
196
+ a["confidence"] = round(_confidence(p), 4)
197
+ else:
198
+ p1 = probs["true"]
199
+ a["noul"] = round(p1, 4)
200
+ a["confidence"] = round(max(p1, 1 - p1), 4)
201
+ out[qid] = a
202
+ return out
203
+
204
+ # ------------------------------------------------------------------ DAG
205
+ def run(self, state: Any, root: str | None = None) -> list[Decision]:
206
+ """Run every root block (no `run_if`) or the named root, then chained children."""
207
+ roots = [b for b in self.blocks.values() if b.run_if is None] if root is None else [self.blocks[root]]
208
+ return [self._run_tree(b, state) for b in roots]
209
+
210
+ def _run_tree(self, block: JevBlock, state: Any) -> Decision:
211
+ d = self.run_block(block, state)
212
+ if d.blocked:
213
+ return d
214
+ for child in self.blocks.values():
215
+ if child.run_if and child.run_if[0] == block.id:
216
+ _, src, want = child.run_if
217
+ from jevblock.bindings import read_source
218
+ if read_source(d.answers, src) == want:
219
+ d.children.append(self._run_tree(child, state))
220
+ return d
221
+
222
+ # ------------------------------------------------------------------ calibration
223
+ @staticmethod
224
+ def fit_temperatures(records: list[tuple[dict[str, Any], str]], bins: int = 15) -> dict[str, float]:
225
+ """Fit one temperature per (qtype:bucket) by grid search minimising NLL on labelled answers.
226
+
227
+ `records`: [(answer_dict, gold_label)] where gold_label is the correct key in
228
+ `probabilities` (or "true"/"false" for noul). Returns {"choice:3-5": 1.4, ...}.
229
+ Mirrors Laya's per-bucket approach; refit as escalations accumulate (design §4).
230
+ """
231
+ groups: dict[str, list[tuple[dict[str, float], str]]] = {}
232
+ for a, gold in records:
233
+ probs = a.get("probabilities") or {"false": 1 - a["noul"], "true": a["noul"]}
234
+ groups.setdefault(_temp_bucket(a["type"], len(probs)), []).append((probs, str(gold)))
235
+ fitted: dict[str, float] = {}
236
+ grid = [x / 10 for x in range(5, 51)]
237
+ for bucket, rows in groups.items():
238
+ if len(rows) < 10:
239
+ continue
240
+ best_t, best_nll = 1.0, float("inf")
241
+ for t in grid:
242
+ nll = 0.0
243
+ for probs, gold in rows:
244
+ keys = list(probs)
245
+ z = [math.log(max(probs[k], 1e-9)) / t for k in keys]
246
+ m = max(z)
247
+ e = [math.exp(v - m) for v in z]
248
+ s = sum(e)
249
+ pg = e[keys.index(gold)] / s if gold in keys else 1e-9
250
+ nll -= math.log(max(pg, 1e-12))
251
+ if nll < best_nll:
252
+ best_t, best_nll = t, nll
253
+ fitted[bucket] = best_t
254
+ return fitted
jevblock/criteria.py ADDED
@@ -0,0 +1,189 @@
1
+ """JevBlock schema: a bounded, backend-neutral set of typed questions plus bindings.
2
+
3
+ The `questions` dictionary is a plain Jev / Laya question dict and is passed to any
4
+ backend unchanged. Everything else (bindings, gates, calibration) is application logic.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ from dataclasses import dataclass, field
12
+ from typing import Any
13
+
14
+ QTYPES = ("choice", "score", "noul")
15
+
16
+ # Bounds derived from the research (see JEVBLOCK_DESIGN.md §2.1).
17
+ MAX_QUESTIONS = 6
18
+ MAX_CHOICE_OPTIONS = 12
19
+ MIN_SCORE_LEVELS = 3
20
+ MAX_SCORE_LEVELS = 5
21
+ MAX_OPTION_DESC_CHARS = 120
22
+
23
+
24
+ class BoundsError(ValueError):
25
+ """A JevBlock violates the small-block bounds."""
26
+
27
+
28
+ @dataclass
29
+ class Question:
30
+ type: str
31
+ instructions: str
32
+ criteria: dict[str, str | None] | list[str] | None = None
33
+
34
+ def to_laya(self) -> dict[str, Any]:
35
+ q: dict[str, Any] = {"type": self.type, "instructions": self.instructions}
36
+ if self.criteria is not None:
37
+ q["criteria"] = self.criteria
38
+ return q
39
+
40
+ @classmethod
41
+ def from_dict(cls, d: dict[str, Any]) -> "Question":
42
+ return cls(type=d["type"], instructions=d["instructions"], criteria=d.get("criteria"))
43
+
44
+ def validate(self, qid: str) -> None:
45
+ if self.type not in QTYPES:
46
+ raise BoundsError(f"{qid}: type must be one of {QTYPES}, got {self.type!r}")
47
+ if not self.instructions or not self.instructions.strip():
48
+ raise BoundsError(f"{qid}: instructions must not be empty")
49
+ if self.type == "choice":
50
+ if not isinstance(self.criteria, dict) or len(self.criteria) < 2:
51
+ raise BoundsError(f"{qid}: choice needs a dict of >= 2 options")
52
+ if len(self.criteria) > MAX_CHOICE_OPTIONS:
53
+ raise BoundsError(
54
+ f"{qid}: {len(self.criteria)} options exceeds {MAX_CHOICE_OPTIONS}; "
55
+ "split into coarse -> fine blocks or use a shortlist"
56
+ )
57
+ for k, v in self.criteria.items():
58
+ if v is not None and len(str(v)) > MAX_OPTION_DESC_CHARS:
59
+ raise BoundsError(f"{qid}.{k}: option description too long (> {MAX_OPTION_DESC_CHARS} chars)")
60
+ elif self.type == "score":
61
+ if not isinstance(self.criteria, list) or not (MIN_SCORE_LEVELS <= len(self.criteria) <= MAX_SCORE_LEVELS):
62
+ raise BoundsError(f"{qid}: score needs {MIN_SCORE_LEVELS}-{MAX_SCORE_LEVELS} ordered levels")
63
+ elif self.type == "noul":
64
+ if self.criteria is not None and not isinstance(self.criteria, dict):
65
+ raise BoundsError(f"{qid}: noul criteria, if given, must be a dict with 'true'/'false'")
66
+
67
+
68
+ @dataclass
69
+ class Binding:
70
+ """Map one or more answers to a memory field.
71
+
72
+ `field`: target key (e.g. "type", "confidence", "encryption_level", "skip").
73
+ `source`: "<qid>.<attr>" where attr is choice | score | noul | confidence | probabilities.
74
+ `map`: optional dict for value remapping (score level -> value, label -> value).
75
+ `threshold`: optional (op, value, if_true, if_false) for noul/score gating.
76
+ """
77
+ field: str
78
+ source: str
79
+ map: dict[Any, Any] | None = None
80
+ threshold: tuple[str, float, Any, Any] | None = None
81
+
82
+ @classmethod
83
+ def from_dict(cls, d: dict[str, Any]) -> "Binding":
84
+ thr = d.get("threshold")
85
+ return cls(field=d["field"], source=d["source"], map=d.get("map"), threshold=tuple(thr) if thr else None)
86
+
87
+
88
+ @dataclass
89
+ class Gate:
90
+ """Confidence gate: if `source` compared with `op` to `value` is true, `action` fires."""
91
+ source: str # "<qid>.confidence" or "<qid>.noul"
92
+ op: str # "<", "<=", ">", ">="
93
+ value: float
94
+ action: str = "escalate" # escalate | ask_user | block
95
+
96
+ @classmethod
97
+ def from_dict(cls, d: dict[str, Any]) -> "Gate":
98
+ return cls(source=d["source"], op=d["op"], value=float(d["value"]), action=d.get("action", "escalate"))
99
+
100
+
101
+ @dataclass
102
+ class JevBlock:
103
+ id: str
104
+ purpose: str
105
+ questions: dict[str, Question]
106
+ bindings: list[Binding] = field(default_factory=list)
107
+ gates: list[Gate] = field(default_factory=list)
108
+ state_fields: list[str] = field(default_factory=list)
109
+ calibration: dict[str, Any] = field(default_factory=dict) # "qtype:bucket" -> T, or backend -> {bucket -> T}
110
+ version: int = 1
111
+ # Optional chaining: run this block only when parent answer matches.
112
+ run_if: tuple[str, str, Any] | None = None # (parent_block_id, "<qid>.choice", value)
113
+ # Optional radar: names of observation functions (see jevblock.radar) computed from the raw
114
+ # state before the decision and merged into what the engine sees. Evidence, never the answer.
115
+ observations: list[str] = field(default_factory=list)
116
+
117
+ # ------------------------------------------------------------------ validation
118
+ def validate(self) -> "JevBlock":
119
+ if not self.id or "." not in self.id:
120
+ raise BoundsError("block id must be namespaced, e.g. 'memory.typing'")
121
+ if not self.questions:
122
+ raise BoundsError(f"{self.id}: at least one question required")
123
+ if len(self.questions) > MAX_QUESTIONS:
124
+ raise BoundsError(
125
+ f"{self.id}: {len(self.questions)} questions exceeds {MAX_QUESTIONS}; split into chained blocks"
126
+ )
127
+ for qid, q in self.questions.items():
128
+ q.validate(f"{self.id}.{qid}")
129
+ for b in self.bindings:
130
+ qid = b.source.split(".")[0]
131
+ if qid not in self.questions:
132
+ raise BoundsError(f"{self.id}: binding {b.field} references unknown question {qid!r}")
133
+ for g in self.gates:
134
+ qid = g.source.split(".")[0]
135
+ if qid not in self.questions:
136
+ raise BoundsError(f"{self.id}: gate references unknown question {qid!r}")
137
+ return self
138
+
139
+ # ------------------------------------------------------------------ serialisation
140
+ def to_laya_questions(self) -> dict[str, dict[str, Any]]:
141
+ """The backend-neutral payload: exactly what Jev / Laya `predict` accepts."""
142
+ return {qid: q.to_laya() for qid, q in self.questions.items()}
143
+
144
+ def to_dict(self) -> dict[str, Any]:
145
+ return {
146
+ "id": self.id,
147
+ "version": self.version,
148
+ "purpose": self.purpose,
149
+ "state_fields": self.state_fields,
150
+ "questions": self.to_laya_questions(),
151
+ "bindings": [
152
+ {"field": b.field, "source": b.source, "map": b.map, "threshold": list(b.threshold) if b.threshold else None}
153
+ for b in self.bindings
154
+ ],
155
+ "gates": [{"source": g.source, "op": g.op, "value": g.value, "action": g.action} for g in self.gates],
156
+ "calibration": self.calibration,
157
+ "run_if": list(self.run_if) if self.run_if else None,
158
+ "observations": list(self.observations),
159
+ }
160
+
161
+ @classmethod
162
+ def from_dict(cls, d: dict[str, Any]) -> "JevBlock":
163
+ blk = cls(
164
+ id=d["id"],
165
+ purpose=d.get("purpose", ""),
166
+ questions={k: Question.from_dict(v) for k, v in d["questions"].items()},
167
+ bindings=[Binding.from_dict(b) for b in d.get("bindings", [])],
168
+ gates=[Gate.from_dict(g) for g in d.get("gates", [])],
169
+ state_fields=list(d.get("state_fields", [])),
170
+ calibration=dict(d.get("calibration", {})),
171
+ version=int(d.get("version", 1)),
172
+ run_if=tuple(d["run_if"]) if d.get("run_if") else None,
173
+ observations=list(d.get("observations", [])),
174
+ )
175
+ return blk.validate()
176
+
177
+ def fingerprint(self) -> str:
178
+ """Stable hash of the question payload; stored on every decision for audit."""
179
+ payload = json.dumps(self.to_laya_questions(), sort_keys=True, ensure_ascii=False)
180
+ return f"{self.id}@v{self.version}:{hashlib.sha256(payload.encode()).hexdigest()[:12]}"
181
+
182
+ def save(self, path: str) -> None:
183
+ with open(path, "w", encoding="utf-8") as f:
184
+ json.dump(self.to_dict(), f, indent=2, ensure_ascii=False)
185
+
186
+ @classmethod
187
+ def load(cls, path: str) -> "JevBlock":
188
+ with open(path, encoding="utf-8") as f:
189
+ return cls.from_dict(json.load(f))