forgeproof-cli 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.
Files changed (89) hide show
  1. forge_gate/__init__.py +44 -0
  2. forge_gate/_deprecated_cli.py +16 -0
  3. forgeproof/__init__.py +3 -0
  4. forgeproof/catalog.py +110 -0
  5. forgeproof/cli.py +560 -0
  6. forgeproof/config.py +339 -0
  7. forgeproof/data/gate_catalog.json +66 -0
  8. forgeproof/data/host_sets.json +7 -0
  9. forgeproof/debug_caller.py +271 -0
  10. forgeproof/debug_core.py +368 -0
  11. forgeproof/fixture_engine.py +81 -0
  12. forgeproof/fixtures/__init__.py +19 -0
  13. forgeproof/fixtures/decision_tree_id3.py +90 -0
  14. forgeproof/fixtures/gradient_descent_momentum.py +73 -0
  15. forgeproof/fixtures/kmeans_clustering.py +98 -0
  16. forgeproof/fixtures/knn_classifier.py +79 -0
  17. forgeproof/fixtures/linear_regression_gd.py +77 -0
  18. forgeproof/fixtures/logistic_regression.py +85 -0
  19. forgeproof/fixtures/naive_bayes_text.py +114 -0
  20. forgeproof/fixtures/perceptron.py +84 -0
  21. forgeproof/fixtures/polynomial_regression.py +67 -0
  22. forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
  23. forgeproof/ledger.py +633 -0
  24. forgeproof/lens_tools/__init__.py +11 -0
  25. forgeproof/lens_tools/guard_lens.py +1250 -0
  26. forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
  27. forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
  28. forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
  29. forgeproof/lens_tools/invariant_gate.py +199 -0
  30. forgeproof/lens_tools/metamorphic/__init__.py +9 -0
  31. forgeproof/lens_tools/metamorphic/relations.py +962 -0
  32. forgeproof/lens_tools/metamorphic/runner.py +112 -0
  33. forgeproof/lens_tools/twin_consensus.py +395 -0
  34. forgeproof/lenses.py +923 -0
  35. forgeproof/paths.py +56 -0
  36. forgeproof/reference/ORIGIN.md +29 -0
  37. forgeproof/reference/decision_tree_id3.py +197 -0
  38. forgeproof/reference/gradient_descent_momentum.py +141 -0
  39. forgeproof/reference/kmeans_clustering.py +139 -0
  40. forgeproof/reference/knn_classifier.py +118 -0
  41. forgeproof/reference/linear_regression_gd.py +106 -0
  42. forgeproof/reference/logistic_regression.py +141 -0
  43. forgeproof/reference/naive_bayes_text.py +152 -0
  44. forgeproof/reference/perceptron.py +123 -0
  45. forgeproof/reference/polynomial_regression.py +125 -0
  46. forgeproof/reference/ridge_regression_normal_eq.py +165 -0
  47. forgeproof/runner.py +147 -0
  48. forgeproof/scout/__init__.py +7 -0
  49. forgeproof/scout/behaviour.py +365 -0
  50. forgeproof/scout/box.py +581 -0
  51. forgeproof/scout/cards.py +180 -0
  52. forgeproof/scout/contract.py +37 -0
  53. forgeproof/scout/corpus.py +104 -0
  54. forgeproof/scout/embed.py +217 -0
  55. forgeproof/scout/engines/__init__.py +1 -0
  56. forgeproof/scout/engines/chaos.py +454 -0
  57. forgeproof/scout/engines/chaos_port.py +1331 -0
  58. forgeproof/scout/engines/chaos_runner.py +178 -0
  59. forgeproof/scout/engines/executor_port.py +239 -0
  60. forgeproof/scout/envfit.py +54 -0
  61. forgeproof/scout/experience.py +161 -0
  62. forgeproof/scout/fetchproxy.py +368 -0
  63. forgeproof/scout/ghcache.py +395 -0
  64. forgeproof/scout/ghpool.py +253 -0
  65. forgeproof/scout/ghsearch.py +248 -0
  66. forgeproof/scout/ids.py +82 -0
  67. forgeproof/scout/intent_lens.py +170 -0
  68. forgeproof/scout/learn.py +583 -0
  69. forgeproof/scout/meaning_lens.py +231 -0
  70. forgeproof/scout/outcomes.py +42 -0
  71. forgeproof/scout/plant.py +327 -0
  72. forgeproof/scout/ratify.py +214 -0
  73. forgeproof/scout/report.py +448 -0
  74. forgeproof/scout/rule2.py +177 -0
  75. forgeproof/scout/shape.py +107 -0
  76. forgeproof/scout/shape_lens.py +71 -0
  77. forgeproof/scout/signature.py +52 -0
  78. forgeproof/scout/slots.py +39 -0
  79. forgeproof/scout/upstream_facts.py +536 -0
  80. forgeproof/unsupported.py +83 -0
  81. forgeproof/verifier.py +208 -0
  82. forgeproof/view_coverage.py +166 -0
  83. forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
  84. forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
  85. forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
  86. forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
  87. forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
  88. forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
  89. forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,178 @@
1
+ """Child process for scout's chaos engine (build step 6b-2; design v1.4.5 §4.3, decision L3).
2
+
3
+ Run as ``python -I chaos_runner.py <lib_root> <probe> <out.json>`` by ``engines/chaos.py`` only.
4
+ It loads the ported validator (``chaos_port.py``) from its own folder, points the port's ``LIB``
5
+ at ``<lib_root>`` and its ``HERE`` at the out file's folder, and then:
6
+
7
+ 1. THE GATE: runs the port's own ``negative_controls()``, the exact code the validator's
8
+ ``main()`` runs before any probe, GATE_RUNS times in a row. One survival in any run fails the
9
+ gate. Some NCs are races (on the deploy host ``seqlock_snapshot``'s NC dies about 1 run in 50),
10
+ so one lucky run must not pass a gate the validator's own run would fail. With repeats, a
11
+ scout PASS is strictly rarer than a validator PASS (p^3 <= p), never easier. The validator writes no report when it returns False (ABORT).
12
+ Scout is STRICTER in one way. The validator counts these as a clean death of an unsafe twin:
13
+ - a raise inside the NC;
14
+ - a failed Rust compile, a missing ``rustc``, or a timeout.
15
+ This child records each such case as ``unclean``, and the parent reads any ``unclean`` NC as
16
+ a gate failure. So scout's gate can never pass where the NCs did not really run.
17
+ 2. THE PROBE: runs the port's own ``scan(only={probe})``, so the card and its verdict are made
18
+ by the validator's code, not a re-implementation.
19
+ 3. Records which attributes the probe read on the loaded pattern module (``touched``), so the
20
+ parent backs only the functions the probe drove directly.
21
+
22
+ The JSON written to ``<out.json>``: ``{"probe", "gate": {"ok", "survived", "unclean"}, "card",
23
+ "touched"}``, or ``{"error": ...}`` if the harness itself failed. Everything the port or a
24
+ pattern prints goes to stderr. The parent never reads stdout.
25
+ """
26
+ import contextlib
27
+ import importlib.util
28
+ import json
29
+ import os
30
+ import sys
31
+ import traceback
32
+ import types
33
+ from pathlib import Path
34
+
35
+ GATE_RUNS = 3
36
+ GATE_ONLY = "__gate_only__" # must equal engines/chaos.py GATE_ONLY
37
+ _TOUCHED: set = set()
38
+ _RECORD = [False]
39
+
40
+
41
+ class _Recording(types.ModuleType):
42
+ """A loaded pattern module that records the public names read on it while recording is on."""
43
+
44
+ def __getattribute__(self, name):
45
+ if _RECORD[0] and not name.startswith("_"):
46
+ _TOUCHED.add(name)
47
+ return super().__getattribute__(name)
48
+
49
+
50
+ def _port(lib_root: Path, here: Path):
51
+ spec = importlib.util.spec_from_file_location("forgeproof_chaos_port",
52
+ Path(__file__).with_name("chaos_port.py"))
53
+ port = importlib.util.module_from_spec(spec)
54
+ spec.loader.exec_module(port)
55
+ port.LIB = Path(lib_root)
56
+ port.HERE = Path(here)
57
+ orig_load = port._load
58
+
59
+ def _load(relpath, name):
60
+ m = orig_load(relpath, name)
61
+ m.__class__ = _Recording
62
+ return m
63
+
64
+ port._load = _load
65
+ return port
66
+
67
+
68
+ def _gate(port) -> dict:
69
+ """The validator's own negative_controls(), with each NC wrapped to record an unclean death."""
70
+ unclean: dict = {}
71
+ current = [None]
72
+ orig_rust = port._rust_chaos
73
+
74
+ def rust_spy(relpath, probe_main, fixture=False):
75
+ try:
76
+ h = orig_rust(relpath, probe_main, fixture)
77
+ except BaseException as e: # missing rustc, TimeoutExpired, ...
78
+ unclean.setdefault(current[0], f"rust harness raised {type(e).__name__}")
79
+ raise
80
+ if "compile_err" in h:
81
+ unclean.setdefault(current[0], "rust compile failed")
82
+ return h
83
+
84
+ def wrap(name, nc):
85
+ def run():
86
+ current[0] = name
87
+ try:
88
+ return nc()
89
+ except BaseException as e:
90
+ unclean.setdefault(name, f"raised {type(e).__name__}: {e}"[:300])
91
+ raise
92
+ return run
93
+
94
+ died: dict = {}
95
+ real = port.PROBES
96
+ wrapped = []
97
+ for name, rel, probe, nc, fault in real:
98
+ w = wrap(name, nc)
99
+
100
+ def record(w=w, name=name):
101
+ r = w()
102
+ died[name] = bool(r)
103
+ return r
104
+ wrapped.append((name, rel, probe, record, fault))
105
+ port.PROBES = wrapped
106
+ port._rust_chaos = rust_spy
107
+ try:
108
+ ok = port.negative_controls()
109
+ finally:
110
+ port.PROBES = real
111
+ port._rust_chaos = orig_rust
112
+ # negative_controls() counts a raise as a death; died[] holds only the NCs that returned.
113
+ survived = sorted(n for n, d in died.items() if d is False)
114
+ return {"ok": bool(ok), "survived": survived, "unclean": unclean}
115
+
116
+
117
+ def _gates(port, runs: int = GATE_RUNS, on_run=None) -> dict:
118
+ """The gate GATE_RUNS times; ok only if every run was ok. Survived/unclean are unions.
119
+ ``on_run`` gets the running union after EACH run, so a child that dies or hangs later has
120
+ already written what it saw (review F2: a survival must never go unrecorded)."""
121
+ survived, unclean, ok = set(), {}, True
122
+ for i in range(runs):
123
+ g = _gate(port)
124
+ ok = ok and g["ok"]
125
+ survived |= set(g["survived"])
126
+ for k, v in g["unclean"].items():
127
+ unclean.setdefault(k, v)
128
+ if on_run is not None:
129
+ on_run({"ok": ok, "survived": sorted(survived), "unclean": dict(unclean), "runs": i + 1})
130
+ return {"ok": ok, "survived": sorted(survived), "unclean": unclean, "runs": runs}
131
+
132
+
133
+ def _write(out: Path, obj) -> None:
134
+ """Atomic replace: the parent reads the last whole write, never half a file."""
135
+ tmp = out.with_name(out.name + ".part")
136
+ tmp.write_text(json.dumps(obj))
137
+ os.replace(tmp, out)
138
+
139
+
140
+ def main(argv) -> int:
141
+ lib_root, probe, out = Path(argv[1]), argv[2], Path(argv[3])
142
+ seen = {}
143
+
144
+ def on_run(g):
145
+ seen["gate"] = g
146
+ _write(out, {"probe": probe, "partial_gate": g})
147
+ try:
148
+ with contextlib.redirect_stdout(sys.stderr):
149
+ port = _port(lib_root, out.parent)
150
+ if probe == GATE_ONLY: # calibration: the gate alone, no probe
151
+ gate = _gates(port, on_run=on_run)
152
+ elif probe not in {p[0] for p in port.PROBES}:
153
+ raise ValueError(f"no such probe: {probe!r}")
154
+ else:
155
+ gate = _gates(port, on_run=on_run)
156
+ if probe == GATE_ONLY:
157
+ _write(out, {"probe": probe, "gate": gate})
158
+ return 0
159
+ with contextlib.redirect_stdout(sys.stderr):
160
+ _TOUCHED.clear()
161
+ _RECORD[0] = True
162
+ try:
163
+ cards = port.scan(only={probe}, verbose=False)
164
+ finally:
165
+ _RECORD[0] = False
166
+ if len(cards) != 1:
167
+ raise ValueError(f"scan(only={{{probe!r}}}) returned {len(cards)} cards, want 1")
168
+ res = {"probe": probe, "gate": gate, "card": cards[0], "touched": sorted(_TOUCHED)}
169
+ except BaseException as e:
170
+ res = {"error": f"{type(e).__name__}: {e}"[:500], "trace": traceback.format_exc()[-1500:]}
171
+ if "gate" in seen: # the gate runs it finished still count (review F2)
172
+ res["partial_gate"] = seen["gate"]
173
+ _write(out, res)
174
+ return 0
175
+
176
+
177
+ if __name__ == "__main__":
178
+ sys.exit(main(sys.argv))
@@ -0,0 +1,239 @@
1
+ # Ported from /home/me/ai-lab/c1-measurement/validator-COPY-from-dot5/executor.py on the deploy host,
2
+ # lines 14-243, byte for byte below the marker. That folder is not a git checkout, so the pin is
3
+ # the source file's sha256 03ce6d10c70afad81f427f6a67d32c4f24b3ec08387bd7596ef1e3e354ec4361 (design §2.3 asks for a checkout hash; none exists).
4
+ # Edits after the port (2026-11-12, standard §7b: personal names stay in the private repo): two
5
+ # comments that named a person now say "Ruling" / "ruling". The private-only test
6
+ # tests/test_port_provenance.py reverses them and checks the source md5.
7
+ # Used inside the isolation box only (input generation for the behaviour lens). Not imported elsewhere.
8
+ import importlib.util, inspect, io, contextlib, math, os, signal, ast, re # the source's own imports, minus oracle
9
+ # --- ported body below ---
10
+
11
+ LIB = os.path.expanduser("~/aura-pattern-library")
12
+
13
+ _CONC_RE = re.compile(r"\b(Atomic\w*|compare_exchange|thread(ing)?\.|Thread\(|Lock\(|"
14
+ r"Mutex|RwLock|multiprocessing\.|std::thread|std::sync|tokio|rayon|sync\.)\b")
15
+ def _scan_concurrency(relpath): # 4Q #4: apply the third boundary in the generic executor too
16
+ try:
17
+ return bool(_CONC_RE.search(open(os.path.join(LIB, relpath), encoding="utf-8", errors="replace").read()))
18
+ except OSError:
19
+ return False
20
+
21
+ # ---------- safe module load (module-level demo may run; suppress + time-guard) ----------
22
+ class _Timeout(Exception): pass
23
+ def _alarm(sec):
24
+ def handler(signum, frame): raise _Timeout()
25
+ signal.signal(signal.SIGALRM, handler); signal.alarm(sec)
26
+ def _cancel(): signal.alarm(0)
27
+
28
+ def load_module(relpath):
29
+ p = os.path.join(LIB, relpath)
30
+ spec = importlib.util.spec_from_file_location("pat_" + str(abs(hash(relpath))), p)
31
+ m = importlib.util.module_from_spec(spec)
32
+ try:
33
+ _alarm(20)
34
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
35
+ spec.loader.exec_module(m)
36
+ _cancel()
37
+ return m, None
38
+ except Exception as e:
39
+ _cancel()
40
+ return None, f"{type(e).__name__}: {e}"
41
+
42
+ # ---------- entry-function discovery ----------
43
+ def entry_functions(module, relpath):
44
+ """Public functions defined IN this module (not imports), with >=1 arg. Prefer annotated."""
45
+ fns = []
46
+ src_names = set()
47
+ try:
48
+ tree = ast.parse(open(os.path.join(LIB, relpath), encoding="utf-8", errors="replace").read())
49
+ src_names = {n.name for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)}
50
+ except Exception:
51
+ pass
52
+ for name, fn in inspect.getmembers(module, inspect.isfunction):
53
+ if name.startswith("_") or name not in src_names:
54
+ continue
55
+ try:
56
+ sig = inspect.signature(fn)
57
+ except Exception:
58
+ # py3.14 lazy annotations: a missing typing import (e.g. Tuple) passes
59
+ # health but raises NameError only on introspection (pca_power_iteration find)
60
+ continue
61
+ params = [p for p in sig.parameters.values() if p.kind in
62
+ (p.POSITIONAL_OR_KEYWORD, p.POSITIONAL_ONLY)]
63
+ if params:
64
+ fns.append((name, fn, sig, params))
65
+ return fns
66
+
67
+ # ---------- baseline valid-arg builder from type hints ----------
68
+ def _valid_for(ann, default, pname=""):
69
+ if default is not inspect.Parameter.empty and default is not None:
70
+ return default, True
71
+ s = str(ann).lower()
72
+ if "list[list" in s: return [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], True
73
+ if "list[int]" in s: return [0, 1, 0, 1, 1, 0], True
74
+ if "list" in s or "sequence" in s or "vector" in s: return [1.0, 2.0, 3.0, 4.0, 5.0], True
75
+ if "tuple" in s: return (1.0, 2.0), True
76
+ if "int" in s: return 5, True
77
+ if "float" in s or "number" in s: return 0.5, True
78
+ if "str" in s: return "the quick brown fox", True
79
+ if "bool" in s: return True, True
80
+ if "dict" in s: return {"a": 1.0, "b": 2.0}, True
81
+ # 5S hole 3: unannotated params -> guess from the NAME (fewer SKIPs).
82
+ n = pname.lower()
83
+ if any(w in n for w in ("data", "samples", "values", "series", "arr", "xs", "ys", "points", "scores", "counts")):
84
+ return [1.0, 2.0, 3.0, 4.0, 5.0], True
85
+ if any(w in n for w in ("text", "name", "key", "line", "doc", "word")):
86
+ return "the quick brown fox", True
87
+ if n in ("x", "y", "z") or any(w in n for w in ("num", "count", "n_", "size", "k", "depth", "width", "seed")):
88
+ return 5, True
89
+ if any(w in n for w in ("prob", "rate", "alpha", "p1", "p2", "u", "var", "mean", "mu", "threshold", "eps", "value", "val")):
90
+ return 0.5, True
91
+ return None, False # genuinely unknown -> honest SKIP (routed to manual/hand-probe)
92
+
93
+ def build_baseline(params):
94
+ args, buildable = [], True
95
+ for p in params:
96
+ v, ok = _valid_for(p.annotation, p.default, p.name)
97
+ if not ok: buildable = False
98
+ args.append(v)
99
+ return args, buildable
100
+
101
+ # ---------- fire one call under guard ----------
102
+ def _call(fn, args):
103
+ try:
104
+ _alarm(10)
105
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
106
+ out = fn(*args)
107
+ _cancel()
108
+ return {"raised": False, "output": out}
109
+ except _Timeout:
110
+ _cancel(); return {"raised": True, "error_text": "Timeout", "output": None}
111
+ except Exception as e:
112
+ _cancel(); return {"raised": True, "error_text": f"{type(e).__name__}: {e}", "output": None}
113
+
114
+ # ---------- recipe fixtures over baseline args (generic) ----------
115
+ def _finite(x): return isinstance(x,(int,float)) and not isinstance(x,bool) and math.isfinite(x)
116
+ def _finite_or_full(x): # 5S hole 4: include set/frozenset so degenerate collections count
117
+ return _finite(x) or (isinstance(x,(list,tuple,dict,str,set,frozenset)) and len(x) > 0)
118
+ def _has_nan_out(x):
119
+ try:
120
+ if isinstance(x,float): return math.isnan(x) or math.isinf(x)
121
+ if isinstance(x,(list,tuple)): return any(_has_nan_out(v) for v in x)
122
+ except TypeError: return False
123
+ return False
124
+
125
+ # 4Q finding 2/3: DOMAIN-AWARE attack values — the E001-E009 catalog turned executable.
126
+ # map parameter NAME -> semantically-invalid values (the subtle finds -1e9 can't reproduce).
127
+ DOMAIN_ATTACKS = [
128
+ (("p1", "p2", "prob", "probability", "p_", "rate_a", "rate_b"), [1.5, -0.5], "E003 prob out of [0,1]"),
129
+ (("alpha", "significance", "level"), [-0.05, 1.5], "E001 alpha out of (0,1)"),
130
+ (("rate", "lambda", "lam", "beta"), [-2.0, 0.0], "E001 rate <= 0"),
131
+ (("u", "quantile", "q", "percentile"), [1.5, 1.0], "E003 u out of [0,1)"),
132
+ (("var", "variance", "sigma", "std", "sd"), [-1.0], "E-B5 variance < 0"),
133
+ ]
134
+ # 5S hole 5: positive-parameter families — any numeric param whose name contains one of these
135
+ # stems must be > 0; attack with negative + zero.
136
+ POSITIVE_STEMS = ("rate", "size", "capacity", "limit", "timeout", "ttl", "threshold", "window",
137
+ "step", "decay", "throughput", "tokens_per", "duration", "expiry", "epsilon",
138
+ "learning", "momentum", "bound", "cutoff", "n_", "num_",
139
+ # GO batch 1: negative recoveryTimeout made the breaker's fail-fast theater;
140
+ # negative baseDelay made the backoff vanish. Config-poison params:
141
+ "recovery", "delay", "backoff", "interval", "attempts", "retries")
142
+
143
+ # Ruling 2026-07-21: params that LEGITIMATELY accept 0 / negative — attacking these
144
+ # is a tool false-positive, not a pattern defect. Longitude (0 = prime meridian) + signed
145
+ # rates (risk-free / decay / growth / interest / return can be 0 or negative in real markets).
146
+ _SIGNED_OK_EXACT = {"lon", "lng", "longitude", "lon1", "lon2", "long"}
147
+ _SIGNED_OK_SUFFIX = ("_rate",) # risk_free_rate, decay_rate, growth_rate, interest_rate
148
+ _SIGNED_OK_STEMS = ("longitude", "risk_free", "decay_rate", "growth_rate", "interest_rate",
149
+ "return", "drift", "log_return")
150
+
151
+ def _signed_ok(pname):
152
+ pl = pname.lower()
153
+ if pl in _SIGNED_OK_EXACT:
154
+ return True
155
+ if pl.endswith(_SIGNED_OK_SUFFIX) and pl not in ("rate",):
156
+ # a bare "rate"/"lambda" is an exponential rate (>0); "*_rate" compounds are signed-ok
157
+ return True
158
+ return any(s in pl for s in _SIGNED_OK_STEMS)
159
+
160
+ def _domain_values(pname):
161
+ if _signed_ok(pname):
162
+ return []
163
+ pl = pname.lower()
164
+ vals = []
165
+ for names, vs, _ in DOMAIN_ATTACKS:
166
+ if pl in names or any(pl == n or pl.endswith("_" + n) for n in names):
167
+ vals += vs
168
+ if not vals and any(stem in pl for stem in POSITIVE_STEMS):
169
+ vals += [-1.0] # positive-param fallback: negative is clearly invalid (0 is often a valid
170
+ # boundary — timeout=0, epsilon=0 — so 4Q v18 N5: dropped 0.0 to cut false-FLAGs)
171
+ return vals
172
+
173
+ def attack_fixtures(params, baseline):
174
+ """Generate (recipe, mutated_args, e_class) by replacing ONE arg with an attack value.
175
+ Domain-aware where the param name implies a domain (4Q finding 2/3)."""
176
+ out = []
177
+ numeric_idx = []
178
+ for i, (p, base) in enumerate(zip(params, baseline)):
179
+ s = str(p.annotation).lower()
180
+ def sub(v, _i=i):
181
+ a = list(baseline); a[_i] = v; return a
182
+ if "int" in s or "float" in s or "number" in s:
183
+ numeric_idx.append(i)
184
+ # R2 domain-aware (the subtle finds): probability->1.5, alpha->-0.05, rate->-1, u->1.5
185
+ for dv in _domain_values(p.name):
186
+ out.append(("R2_domain_aware", sub(dv), "E001/E003", i))
187
+ # R1 blunt underflow (still useful for unnamed numerics)
188
+ out.append(("R1_domain_under", sub(-1e9), "E001/E003", i))
189
+ out.append(("R6_wrong_type", sub(None), "E006", i))
190
+ out.append(("R6_wrong_type", sub("сорок два"), "E006", i))
191
+ # R15 scalar NaN/Inf (GO batch 1, csv_validator find): poison into scalar floats.
192
+ # Finite output + no raise = fabricated certainty; NaN output = visible poison.
193
+ if "float" in s or "number" in s:
194
+ out.append(("R15_scalar_nan_inf", sub(float("nan")), "E008", i))
195
+ out.append(("R15_scalar_nan_inf", sub(float("inf")), "E008", i))
196
+ # NOTE R14_int_overflow (E013) deliberately NOT fired here: python ints are
197
+ # arbitrary-precision (class can't exist) and 1<<62 loop-params hang in-process.
198
+ # It lives in recipes.py for the typed-language harness lanes (LANG_PRIORS).
199
+ # R9 degenerate (count param == 0). Single-letter stems k/n must match at a WORD
200
+ # boundary — bare "n" as a substring wrongly hit lon1/mean/min (ruling
201
+ # 2026-07-21: longitude=0 is valid). Multi-char stems keep substring matching.
202
+ _pl = p.name.lower()
203
+ _is_count = (any(w in _pl for w in ("window","breaks","bins","num","order","size","trials","count"))
204
+ or _pl in ("k", "n") or _pl.startswith(("k_", "n_", "num_"))
205
+ or _pl.endswith(("_k", "_n")))
206
+ if _is_count and not _signed_ok(_pl):
207
+ out.append(("R9_degenerate_param", sub(0), "E009", i))
208
+ if "list" in s or "vector" in s or "sequence" in s:
209
+ out.append(("R5_no_data", sub([]), "E005", i))
210
+ out.append(("R8_nan_inf_poison", sub([float("nan")]+list(base)[1:] if isinstance(base,list) and base else [float("nan")]), "E008", i))
211
+ out.append(("R6_wrong_type", sub(None), "E006", i))
212
+ # R3 degenerate-equal: make two numeric params equal (zero effect/difference) — E002.
213
+ # 5S/4Q v17: SKIP if the baseline already equalizes them (mutation == baseline, a no-op false-FLAG).
214
+ if len(numeric_idx) >= 2 and baseline[numeric_idx[0]] != baseline[numeric_idx[1]]:
215
+ a = list(baseline); a[numeric_idx[1]] = a[numeric_idx[0]]
216
+ out.append(("R3_degenerate_equal", a, "E002", numeric_idx[0]))
217
+ # R4 cross-param impossible (4Q/5S): part > whole (successes>trials) — E004.
218
+ # 5S/4Q v17: only CLEAR part-whole containment pairs; the generic ("k","n") pair removed (too broad).
219
+ names = [p.name.lower() for p in params]
220
+ for part_stem, whole_stem in (("success", "trial"), ("count", "total"), ("hit", "total")):
221
+ pi = next((i for i, n in enumerate(names) if part_stem in n), None)
222
+ wi = next((i for i, n in enumerate(names) if whole_stem == n or n.startswith(whole_stem)), None)
223
+ if pi is not None and wi is not None and pi != wi \
224
+ and isinstance(baseline[pi], (int, float)) and isinstance(baseline[wi], (int, float)):
225
+ a = list(baseline); a[wi] = 10; a[pi] = 999 # part hugely exceeds whole
226
+ out.append(("R4_cross_param_impossible", a, "E004", pi))
227
+ # R7 shape-mismatch (4Q/5S): two parallel collections of unequal length — E007
228
+ coll_idx = [i for i, (p, b) in enumerate(zip(params, baseline))
229
+ if isinstance(b, list) and "list[list" not in str(p.annotation).lower()]
230
+ if len(coll_idx) >= 2:
231
+ a = list(baseline)
232
+ a[coll_idx[0]] = list(baseline[coll_idx[0]]) + [1.0] # one longer
233
+ out.append(("R7_shape_mismatch", a, "E007", coll_idx[0]))
234
+ b = list(baseline)
235
+ b[coll_idx[1]] = list(baseline[coll_idx[1]])[:-1] if len(baseline[coll_idx[1]]) > 1 else []
236
+ out.append(("R7_shape_mismatch", b, "E007", coll_idx[1]))
237
+ return out
238
+
239
+ # ---------- judge one pattern ----------
@@ -0,0 +1,54 @@
1
+ """Environment fit (design §4a.3 gate; §4a.7 / Q11: built just before behaviour, it decides
2
+ whether a run is attempted). The facts are the BOX's: which modules import inside the box is
3
+ measured by running a check there, never assumed from this host.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import ast
8
+
9
+
10
+ def imports(source: str) -> tuple[set[str], bool]:
11
+ """Top-level module names a source imports, and whether it has a relative import (which can
12
+ never resolve for a lone file). Text only."""
13
+ names, relative = set(), False
14
+ for node in ast.walk(ast.parse(source)):
15
+ if isinstance(node, ast.Import):
16
+ names |= {a.name.split(".")[0] for a in node.names}
17
+ elif isinstance(node, ast.ImportFrom):
18
+ if node.level:
19
+ relative = True
20
+ elif node.module:
21
+ names.add(node.module.split(".")[0])
22
+ return names, relative
23
+
24
+
25
+ def fits(source_imports: tuple[set[str], bool], available: dict[str, bool]) -> tuple[bool, str]:
26
+ names, relative = source_imports
27
+ if relative:
28
+ return False, "relative import"
29
+ missing = sorted(n for n in names if not available.get(n, False))
30
+ return (False, "missing: " + ",".join(missing)) if missing else (True, "fits")
31
+
32
+
33
+ def _no_call(node) -> bool:
34
+ return not any(isinstance(n, (ast.Call, ast.Await, ast.Yield)) for n in ast.walk(node))
35
+
36
+
37
+ def runs_at_import(source: str) -> str | None:
38
+ """Text only. None when loading the module only defines things; else what it would run.
39
+ A script that reads files, exits or fetches at import cannot be compared as a library: its
40
+ pairs would all fail at load (measured on the corpus 2026-11-11: 30 of 80 pairs)."""
41
+ for node in ast.parse(source).body:
42
+ if isinstance(node, (ast.Import, ast.ImportFrom, ast.FunctionDef, ast.AsyncFunctionDef, ast.Pass)):
43
+ continue
44
+ if isinstance(node, ast.ClassDef) and all(_no_call(d) for d in node.decorator_list) and all(_no_call(b) for b in node.bases):
45
+ continue
46
+ if isinstance(node, (ast.Assign, ast.AnnAssign)) and _no_call(node):
47
+ continue
48
+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):
49
+ continue # docstring
50
+ if (isinstance(node, ast.If) and isinstance(node.test, ast.Compare)
51
+ and "__name__" in ast.unparse(node.test) and "__main__" in ast.unparse(node.test)):
52
+ continue # the main guard does not run on import
53
+ return f"line {node.lineno}: {type(node).__name__}"
54
+ return None
@@ -0,0 +1,161 @@
1
+ """Lens 6, experience (design §4a.5; build step 8b s5; DECISIONS-8b H8, H9, H11).
2
+
3
+ Experience is EVIDENCE, not similarity: "shown beside a result and never counted as a vote". For every
4
+ shown hit it reads the three outcome counts from the ledgers (8a's reader: oracle, person outcome with
5
+ a result id, person outcome without one) and pending marks, side by side, never blended. It may
6
+ change ORDER only inside one (score, trust) group (H9: the band is the exact score until a band width
7
+ is measured), lexicographically: oracle, then with-id, then without-id. It never changes a lens's
8
+ outcome, the k-of-n line, or which hits are FOUND.
9
+
10
+ Rule 2 for experience (H11, a named deviation: §4a.5's cases, not the similarity cases) runs on a
11
+ synthetic, in-memory ledger view on every invocation. It passes only if the real ordering passes
12
+ every case AND each of three selection-rewarding variants (counts exposures; counts pending marks;
13
+ blends the counts into one sum) FAILS: "its Rule-2 cases go red when it rewards selection" (§4a.5).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from .. import ledger
18
+
19
+ NAME = "experience"
20
+ # §4a.4 Rule 3: library > registry > corpus / GitHub. Lower sorts first.
21
+ TRUST_RANK = {"signed": 0, "tier": 1, "raw": 2}
22
+
23
+
24
+ def _real(c: "ledger.Counts", n_exposed: int) -> tuple:
25
+ return (-c.oracle, -c.person_with_id, -c.person_without_id)
26
+
27
+
28
+ def _rewards_exposure(c, n_exposed): # the popularity baseline: being shown scores
29
+ return (-n_exposed,)
30
+
31
+
32
+ def _rewards_pending(c, n_exposed): # a mark without a passing event scores
33
+ return (-c.oracle, -c.person_with_id, -(c.person_without_id + c.pending))
34
+
35
+
36
+ def _blended(c, n_exposed): # one number: any outcome is as good as any other
37
+ return (-(c.oracle + c.person_with_id + c.person_without_id),)
38
+
39
+
40
+ VARIANTS = {"rewards-exposure": _rewards_exposure, "rewards-pending": _rewards_pending, "blended": _blended}
41
+
42
+
43
+ def order(hits: list, key, counts_of, exposed_of) -> list:
44
+ """Stable order: score first, then trust, then experience, then the lens's own tie order (item)."""
45
+ def k(h):
46
+ item = f"{h['pool']}:{h['item_id']}"
47
+ return (-h["score"], TRUST_RANK.get(h["trust"], 9), key(counts_of(item), exposed_of(item)), h["item_id"])
48
+ return sorted(hits, key=k)
49
+
50
+
51
+ # ---------------------------------------------------------------- Rule 2 on a synthetic view
52
+
53
+ def _hit(i, score=0.9, trust="raw"):
54
+ return {"item_id": i, "score": score, "trust": trust, "pool": "corpus"}
55
+
56
+
57
+ def synthetic_view() -> "ledger.View":
58
+ v = ledger.View()
59
+ t0, t1 = "2026-01-01T00:00:00.000000Z", "2026-01-02T00:00:00.000000Z"
60
+ n = [0]
61
+
62
+ def expose(item, k=1, slot="top"):
63
+ rids = []
64
+ for _ in range(k):
65
+ n[0] += 1
66
+ rid = f"fgr-{n[0]:012x}-shape-1"
67
+ v.exposure[rid] = {"result_id": rid, "item": f"corpus:{item}", "slot": slot}
68
+ rids.append(rid)
69
+ return rids
70
+
71
+ def mark(item, who, rid=None, event_rc=None, event_time=t1):
72
+ n[0] += 1
73
+ mid = f"fgm-{n[0]:012x}"
74
+ v.marks[mid] = {"mark_id": mid, "item": f"corpus:{item}", "who": who, "result_id": rid, "time": t0}
75
+ if event_rc is not None:
76
+ v.events[mid] = [{"mark_id": mid, "rc": event_rc, "event_time": event_time}]
77
+
78
+ def oracle(item, root):
79
+ rid = expose(item)[0]
80
+ n[0] += 1
81
+ v.oracle[(rid, f"fgv-{n[0]:012x}")] = {"result_id": rid, "reused_at": {"root_sha256": root}}
82
+
83
+ expose("c_a_popular", 40) # E1: shown often, never helped
84
+ expose("c_a_popular", 10, slot="explore")
85
+ mark("c_b_helped", "ann", expose("c_b_helped")[0], event_rc=0)
86
+ mark("c_zc_pending", "ann") # E2: three marks, none scored
87
+ mark("c_zc_pending", "bob", event_rc=1) # failed event
88
+ mark("c_zc_pending", "cyd", event_rc=0, event_time="2025-12-31T00:00:00.000000Z") # before its mark
89
+ for i in range(100): # E3: 100 person outcomes, no id
90
+ mark("c_p_people", f"p{i}", event_rc=0)
91
+ oracle("c_q_oracle", "r" * 64) # E3: one oracle outcome
92
+ mark("c_x_noid", "ann", event_rc=0) # E4: two without id
93
+ mark("c_x_noid", "bob", event_rc=0)
94
+ mark("c_y_withid", "ann", expose("c_y_withid")[0], event_rc=0) # E4: one with id
95
+ for _ in range(5): # E6: lots of history, lower score
96
+ oracle("c_low_score", "s" * 64 + str(_))
97
+ return v
98
+
99
+
100
+ def rule2_cases(key, v=None) -> list:
101
+ v = synthetic_view() if v is None else v
102
+ co = lambda item: ledger.counts(item, v=v) # noqa: E731
103
+ ex = lambda item: len(ledger.exposures(item, v=v)) # noqa: E731
104
+ fails = []
105
+
106
+ def first(hits):
107
+ return order(hits, key, co, ex)[0]["item_id"]
108
+ if first([_hit("c_a_popular"), _hit("c_b_helped")]) != "c_b_helped":
109
+ fails.append("E1 selection only: 50 exposures without an outcome ranked ahead of one scored outcome")
110
+ if first([_hit("c_d_none"), _hit("c_zc_pending")]) != "c_d_none":
111
+ fails.append("E2 pending: marks without a passing later event moved an item up")
112
+ if first([_hit("c_p_people"), _hit("c_q_oracle")]) != "c_q_oracle":
113
+ fails.append("E3 lexicographic: 100 person outcomes ranked ahead of one oracle outcome")
114
+ if first([_hit("c_x_noid"), _hit("c_y_withid")]) != "c_y_withid":
115
+ fails.append("E4 lexicographic: two outcomes without an id ranked ahead of one with an id")
116
+ if first([_hit("c_high", 0.95), _hit("c_low_score", 0.9)]) != "c_high":
117
+ fails.append("E6 never a vote: history moved a hit across a score")
118
+ if first([_hit("c_low_score", 0.9, "raw"), _hit("c_signed", 0.9, "signed")]) != "c_signed":
119
+ fails.append("E6 never a vote: history moved a hit across a trust level")
120
+ c = co("corpus:c_a_popular")
121
+ if (c.oracle, c.person_with_id, c.person_without_id) != (0, 0, 0) or ex("corpus:c_a_popular") != 50:
122
+ fails.append(f"E1 counts: a selection-only history must read 0 outcomes, read {c}")
123
+ return fails
124
+
125
+
126
+ def rule2() -> list:
127
+ """Failed cases: the real ordering's, plus one line per selection-rewarding variant that PASSES
128
+ (a variant that passes means the set cannot see selection being rewarded)."""
129
+ fails = rule2_cases(_real)
130
+ for name, var in VARIANTS.items():
131
+ if not rule2_cases(var):
132
+ fails.append(f"red arm: variant {name!r} passed the set; the set cannot see it reward selection")
133
+ return fails
134
+
135
+
136
+ # ---------------------------------------------------------------- in a report
137
+
138
+ HIT_LISTS = ("shape_hits", "meaning_hits", "behaviour_hits", "intent_hits")
139
+
140
+
141
+ def apply(c: dict, v: "ledger.View") -> tuple:
142
+ """Annotate every shown hit of the corpus block ``c`` with its counts and order each list inside
143
+ (score, trust) ties. Returns (hits with any outcome, lists whose order changed)."""
144
+ co = lambda item: ledger.counts(item, v=v) # noqa: E731
145
+ ex = lambda item: len(ledger.exposures(item, v=v)) # noqa: E731
146
+ with_history = moved = 0
147
+ for key in HIT_LISTS:
148
+ hits = c.get(key) or []
149
+ if not hits:
150
+ continue
151
+ for h in hits:
152
+ k = co(f"{h['pool']}:{h['item_id']}")
153
+ h["experience"] = {"oracle": k.oracle, "with_id": k.person_with_id,
154
+ "without_id": k.person_without_id, "pending": k.pending}
155
+ with_history += bool(k.oracle or k.person_with_id or k.person_without_id)
156
+ top = [h for h in hits if h.get("slot", "top") == "top"]
157
+ rest = [h for h in hits if h.get("slot", "top") != "top"]
158
+ new = order(top, _real, co, ex)
159
+ moved += new != top
160
+ c[key] = new + rest
161
+ return with_history, moved