Mr-DS-ML-85 commited on
Commit
090324d
·
verified ·
1 Parent(s): 5aa6962

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. README.md +173 -6
  3. build/libsyfox_core.so +2 -2
  4. datasets/bench_hidden_summary.json +14 -0
  5. datasets/eval_summary_v400.json +64 -0
  6. datasets/novel_probes/RESULTS.json +42 -38
  7. docs/ENGINE_PORT.md +67 -2
  8. engine/CHANGELOG.md +1476 -0
  9. engine/Makefile +38 -6
  10. engine/core/bench.hpp +25 -3
  11. engine/core/reason.hpp +0 -409
  12. engine/core/roles.hpp +2 -77
  13. engine/core/si_substrate.hpp +133 -455
  14. engine/core/syfox.hpp +448 -405
  15. engine/data/bank77_categories.json +161 -0
  16. engine/data/bank77_criteria.json +84 -0
  17. engine/data/handmade_probes.jsonl +148 -0
  18. engine/data/synonyms.txt +32 -0
  19. engine/docs/FIT_DECIDE_PARITY.md +175 -0
  20. engine/src/syfox_cli.cpp +149 -333
  21. engine/src/syfox_core.cpp +16 -0
  22. engine/src/syfox_test.cpp +217 -0
  23. engine/tools/ablation_suite.py +158 -0
  24. engine/tools/assert_fit_decide_parity.py +89 -0
  25. engine/tools/assert_route.py +16 -0
  26. engine/tools/b77_ablation_compare.py +67 -0
  27. engine/tools/b77_apply_policy.py +70 -0
  28. engine/tools/b77_confusion_report.py +174 -0
  29. engine/tools/b77_freq_cut.py +102 -0
  30. engine/tools/b77_margin_sweep.py +116 -0
  31. engine/tools/bank77_analysis.py +168 -0
  32. engine/tools/bank77_hier.py +169 -0
  33. engine/tools/bank77_prepare.py +224 -0
  34. engine/tools/cal_diffusion_sweep.py +130 -0
  35. engine/tools/check_omp_identity.py +15 -0
  36. engine/tools/confidence_ablation.py +140 -0
  37. engine/tools/corpus_pools.py +517 -0
  38. engine/tools/flag_probe_experiment.py +148 -0
  39. engine/tools/gen_corpus.py +214 -0
  40. engine/tools/gen_paraphrases.py +195 -0
  41. engine/tools/gen_variants.py +168 -0
  42. engine/tools/giant_bench.py +209 -0
  43. engine/tools/giant_prepare.py +555 -0
  44. engine/tools/handmade_gate.py +135 -0
  45. engine/tools/hf_fetch.py +125 -0
  46. engine/tools/jev_bench.py +138 -0
  47. engine/tools/reasoning_probes.py +201 -0
  48. engine/tools/rebuild_router_criteria.py +144 -0
  49. engine/tools/router_prepare.py +112 -0
  50. engine/tools/router_routes.py +73 -0
.gitattributes CHANGED
@@ -1,2 +1,3 @@
1
  *.bin filter=lfs diff=lfs merge=lfs -text
2
  model/*/substrate.bin filter=lfs diff=lfs merge=lfs -text
 
 
1
  *.bin filter=lfs diff=lfs merge=lfs -text
2
  model/*/substrate.bin filter=lfs diff=lfs merge=lfs -text
3
+ build/libsyfox_core.so filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -57,6 +57,166 @@ empty per-row instructions, globally-unique opaque anchors (278), and
57
  round-robin domain interleaving. Full measured evaluation:
58
  [docs/EVALUATION.md](docs/EVALUATION.md).
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  ## Headline measured numbers (hidden splits, scored once)
61
 
62
  > **⚠ Measured with the v3.2.0 engine.** The core in this repo is now v3.9.1,
@@ -136,19 +296,26 @@ field does not fake it.
136
  ## Files
137
 
138
  ```
139
- engine/ C++ SI substrate core v3.9.1 (core/*.hpp, src/*.cpp) — builds with make
140
  NOTE: refresh ../build/libsyfox_core.so after rebuilding, or the
141
  python bridge will keep loading the stale core (ENGINE_PORT.md)
142
  server/ HTTP bridge (v3 API, CLI-equal flags incl. the v3.2 knobs)
143
  inference.py thin python wrapper (auto script routing)
144
- model/ giant-{latin,bengali,devanagari,cyrillic}/substrate.bin (v3.2-era, 16 domains)
145
- sst2/ agnews/ amazon/ NEW v3.9.1 fabrics, handcrafted-probe gated
146
- b77-sem/ dedicated 77-way banking fabric (v3.2 semantic layer)
147
- router16/ two-stage physics router (router.json: anchors+models)
 
 
 
 
 
 
 
148
  datasets/ eval hidden splits, probes, schemas, MANIFEST (SHA-256),
149
  novel_probes/ (handcrafted admission probes + RESULTS.json),
150
  router16_router.json, zeroshot_v32_results.json, DATASETS.md
151
- docs/ ENGINE_PORT.md (v3.9.1 port + caveats), EVALUATION.md,
152
  ARCHITECTURE.md, PROBING.md, ZEROSHOT.md
153
  examples/ JSON payloads + curl + python usage
154
  Dockerfile HuggingFace Spaces (builds engine, serves on 7860)
 
57
  round-robin domain interleaving. Full measured evaluation:
58
  [docs/EVALUATION.md](docs/EVALUATION.md).
59
 
60
+ ---
61
+
62
+ ---
63
+
64
+
65
+ ## v4.0 — the affinity field readout (AFR)
66
+
67
+ The engine could **retrieve** but never **measure**. Two defects, both
68
+ measured on the shipped fabrics:
69
+
70
+ 1. **The readout never read the fabric's own anchor affinity.** Every lesson
71
+ binds the state's tokens to the outcome anchor, so the fabric holds
72
+ `w(u,c)` — "which intent did this word teach". The legacy readout only
73
+ sampled the field and let a capped diffusion carry the evidence, so one
74
+ constant had to serve both precision and reach, and the measured optimum
75
+ was **per-domain** (tickets_en wanted 0.45, agnews/dbpedia wanted 0.02).
76
+ 2. **The readout had no null model.** A candidate's score was an
77
+ unnormalised *sum* over its probe bag — for Banking77, 20 mined phrases
78
+ (~60 token occurrences) mostly shared with other candidates, so shared
79
+ words added a large common offset and the one discriminative word was one
80
+ term out of sixty.
81
+
82
+ v4.0 adds one channel, with **no training and no neural network**:
83
+
84
+ ```
85
+ P(c|u) = w(u,c) / sum_{c' in C} w(u,c') posterior over the candidate set
86
+ P0(c) = mass(c) / sum_{c'} mass(c') a priori share of the candidate set
87
+ L(c) = sum_u E_u * [ P(c|u) - P0(c) ] the contrast
88
+ score(c) = (1-mix) * legacy(c)/max|legacy| + mix * L(c)/max|L|
89
+ ```
90
+
91
+ A token that points at every candidate cancels against the null model; a
92
+ token that points at one candidate contributes strongly, positive for that
93
+ candidate and negative for the rest. This is the **first-order resolvent of
94
+ the propagation the settle simulates** — the same operator, read exactly
95
+ instead of approximated by a capped and smeared diffusion. `mix = 0` (the
96
+ default) is bit-identical to v3.9.1.
97
+
98
+ v4.0 also fits **one temperature per distinct candidate count**: a 14-way
99
+ question's score spread is not a 2-way question's spread, and one scalar
100
+ fitted across both left `polarity` at ECE 0.395 while `dbpedia` sat at 0.064
101
+ in the same fit.
102
+
103
+ ### What changed in THIS repo
104
+
105
+ **Seven of the nine fabrics are updated** — repaired where the lane decay had
106
+ killed them, and re-calibrated under the new readout. The readout mode is
107
+ recorded in each fabric's `physics.json` (`"affinity_mix":0.3`), so the
108
+ deployed model decides under the readout its temperature was fitted for.
109
+
110
+ | fabric | change | measured |
111
+ |---|---|---|
112
+ | `b77-sem` | lane repair + AFR + per-count temperature | hidden 3,080: **0.158 → 0.4800**, ECE **0.809 → 0.0460** |
113
+ | `router16` | lane repair + AFR | cal 12,593: **0.5060 → 0.5850**; handmade OOD 0.267 → **0.467** |
114
+ | `giant-latin` | lane repair + AFR | agnews **0.7520**, emotion **0.3930**, polarity **0.5960**, dbpedia **0.7970**, tickets_en **0.9570** |
115
+ | `giant-bengali` | AFR | hidden 540: **0.9260 → 1.0000**, ECE 0.0270 → **0.0000** |
116
+ | `giant-devanagari` | AFR | hidden 539: **0.9110 → 1.0000**, ECE 0.0180 → **0.0010** |
117
+ | `giant-cyrillic` | AFR | hidden 539: **0.9520 → 1.0000**, ECE 0.0170 → **0.0000** |
118
+ | `agnews` | AFR | novel probes: **0.5833 → 0.7500** (gate ≥ 0.40) |
119
+ | `sst2` | **unchanged** | novel probes 0.7500 (gate ≥ 0.65) |
120
+ | `amazon` | **unchanged** | novel probes 0.7000 (gate ≥ 0.65) |
121
+
122
+ **Two fabrics are deliberately NOT updated.** `sst2` and `amazon` are the
123
+ two-class fabrics, and the contrast is degenerate there: with two
124
+ candidates a single token points at one of them or the other, so one
125
+ mis-pointed token dominates. Measured on their own admission probes, the
126
+ AFR gives **sst2 0.5830** and **amazon 0.6000** — **both below their own
127
+ 0.65 admission gate**, so the shipped fabric would fail the gate that
128
+ exists to catch exactly this. They ship unchanged, with the legacy readout.
129
+ That is the gate doing its job, and it is why the readout is applied per
130
+ fabric rather than globally.
131
+
132
+ The `tickets_en` number is the one to look at: the shared giant fabric
133
+ scored 0.9040 before the lane repair and 0.4480 after it. With the affinity
134
+ readout the SAME repaired fabric scores **0.9570** — above the original.
135
+
136
+ ### Reproducing
137
+
138
+ ```bash
139
+ cd engine && make all && make sync-so && cd ..
140
+ python3 examples/smoke.py
141
+ ```
142
+
143
+ `engine/` is the v4.0 source (core/, src/, tools/) — the same tree as the
144
+ GitHub repo, so the code and the weights that ship with it are the code
145
+ that was measured.
146
+
147
+ ## The three defects (found by re-testing on the v3.9.1 engine)
148
+
149
+ ### 1. The calibration was fitted under a different physics than the decision runs
150
+
151
+ The choice/score temperature is fitted on energies that come out of a settle
152
+ pass, and those energies depend on the **whole decide-side composition** —
153
+ the energy gain, the diffusion constant, the decay, the settle-pass cap. In
154
+ this repo the banking and router fabrics were calibrated **without** the
155
+ decide-side energy gain while every `bench` and every `decide` call ran
156
+ **with** it.
157
+
158
+ Measured on the shipped `model/b77-sem` fabric and the 1,003-row cal split
159
+ that ships with it — same engine, one flag apart:
160
+
161
+ | calibration | fitted `T` | rows the fit saw | ECE before → after |
162
+ |---|---:|---:|---:|
163
+ | without the energy gain (**what shipped**) | **0.0037** | **556 of 2,006 (27.7%)** | 0.4567 → 0.4057 |
164
+ | with the energy gain (**what the bench runs**) | **0.3552** | 2,006 of 2,006 (100%) | 0.3183 → 0.3056 |
165
+
166
+ The published `model/b77-sem/calibration.json` carried `T = 0.00472645`
167
+ fitted over **211 rows**; `model/router16` carried `T = 0.00491756` over
168
+ **160 rows**.
169
+
170
+ A near-floor temperature saturates the softmax. The post-temperature top-2
171
+ probability gap goes to ~0.93 on every row, which breaks three things at
172
+ once: the honest-defer gate (an absolute 0.05 margin) **can never fire** —
173
+ the model never abstains, on any input, ever; every answer carries ~0.98
174
+ confidence whether it is right or wrong; and the ECE reported by
175
+ `calibrate` does not describe the ECE the bench measures.
176
+
177
+ **Fix:** a fabric now carries the composition it was calibrated under
178
+ (`physics.json`, next to `calibration.json`). `calibrate` records it;
179
+ `decide`, `bench`, `demo` and `stats` apply it on load. `calibrate` also
180
+ **refuses** to run when the fit would see less than half the question-rows
181
+ (it names the cause and leaves the fabric untouched). The three shipped
182
+ fabrics have been re-calibrated under the matched composition.
183
+
184
+ ### 2. The diffusion constant was never re-tuned for the dense fabrics
185
+
186
+ `diffusion` is the fraction of retained energy that flows along the Hebbian
187
+ lanes per settle pass. It is a config value, not an equation, and its
188
+ optimum is a property of the fabric: 0.45 was validated on the small v2-era
189
+ fabrics and is far off the optimum for a 217k-lane fabric. Measured on the
190
+ **cal** split of the shipped banking fabric (selection never touches
191
+ hidden):
192
+
193
+ | diffusion | accuracy (argmax) on cal |
194
+ |---|---:|
195
+ | 0.45 (shipped default) | 0.1316 |
196
+ | **0.02** | **0.4237** |
197
+
198
+ **Fix:** the diffusion value is now a per-fabric property recorded in
199
+ `physics.json`, chosen on the cal split
200
+ (`tools/cal_diffusion_sweep.py`), not a global default.
201
+
202
+ ### 3. The headline table was measured against the wrong fabric, on the wrong engine
203
+
204
+ The bank77 row in the old table (`class acc 0.023`) was measured on the
205
+ **shared** `model/giant-latin` fabric, not on the dedicated `model/b77-sem`
206
+ fabric this repo ships and `router.json` routes bank77 to. It was also
207
+ measured with the v3.2.0 engine, which had no honesty gates: under
208
+ v3.9.1 the same run defers **2,129 of 3,080 rows (69%)**, because the
209
+ newer engine refuses to answer a field that carries no candidate energy.
210
+
211
+ Separately: the four `model/giant-*` fabrics were built by the **v3.1.2**
212
+ engine and carry **no semantic field** (their `substrate.bin` has no `SEM4`
213
+ tail), so the v3.2 semantic layer described below is **inert on them**. No
214
+ shipped fabric carries the `IDF5` tail either, so the v3.6 document-
215
+ frequency weighting is inert everywhere.
216
+
217
+ ---
218
+
219
+
220
  ## Headline measured numbers (hidden splits, scored once)
221
 
222
  > **⚠ Measured with the v3.2.0 engine.** The core in this repo is now v3.9.1,
 
296
  ## Files
297
 
298
  ```
299
+ engine/ C++ SI substrate core v4.0 (core/*.hpp, src/*.cpp, tools/) — builds with make
300
  NOTE: refresh ../build/libsyfox_core.so after rebuilding, or the
301
  python bridge will keep loading the stale core (ENGINE_PORT.md)
302
  server/ HTTP bridge (v3 API, CLI-equal flags incl. the v3.2 knobs)
303
  inference.py thin python wrapper (auto script routing)
304
+ model/ NINE fabrics, all carrying their recorded decide-side
305
+ composition in physics.json (diffusion, energy_norm, affinity_mix):
306
+ giant-latin/ 16-domain shared fabric AFR, diffusion 0.45
307
+ giant-bengali/ Bengali script fabric AFR, diffusion 0.45
308
+ giant-devanagari/ Hindi script fabric AFR, diffusion 0.45
309
+ giant-cyrillic/ Russian script fabric AFR, diffusion 0.45
310
+ b77-sem/ dedicated 77-way banking AFR, diffusion 0.02
311
+ router16/ two-stage physics router AFR, diffusion 0.45
312
+ agnews/ handcrafted-probe gated AFR, diffusion 0.45
313
+ sst2/ handcrafted-probe gated LEGACY readout (see v4.0)
314
+ amazon/ handcrafted-probe gated LEGACY readout (see v4.0)
315
  datasets/ eval hidden splits, probes, schemas, MANIFEST (SHA-256),
316
  novel_probes/ (handcrafted admission probes + RESULTS.json),
317
  router16_router.json, zeroshot_v32_results.json, DATASETS.md
318
+ docs/ ENGINE_PORT.md (v4.0 port + caveats), EVALUATION.md,
319
  ARCHITECTURE.md, PROBING.md, ZEROSHOT.md
320
  examples/ JSON payloads + curl + python usage
321
  Dockerfile HuggingFace Spaces (builds engine, serves on 7860)
build/libsyfox_core.so CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7ecb7c2ac7bc1d7f044f6daa0eb82af988013a7c64ec898ad3abaead3bb4995f
3
- size 533848
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75d062a5a7faca291b1d6f687ef91204c42e31b44aad156d388b59e0297c69e8
3
+ size 419520
datasets/bench_hidden_summary.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "domain": "bank77",
4
+ "n": 3080,
5
+ "router_acc": 0.5889610389610389,
6
+ "class_acc": 0.15791316526610644,
7
+ "e2e_acc": 0.0801948051948052,
8
+ "deferred": 224,
9
+ "secs": 65.7,
10
+ "ms_per_row": 21.33,
11
+ "qkey": "intent",
12
+ "note": ""
13
+ }
14
+ ]
datasets/eval_summary_v400.json ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "engine": "syfox 4.0.0 (v3.9.1 + v3.9.2 fit==decide composition + v3.9.3 lane repair + v4.0 affinity field readout)",
3
+ "note": "every number measured in THIS repo against the SHIPPED fabrics and the SHIPPED splits; selection on cal, hidden scored once. The v4.0 rows are the fabrics as they ship here (each carries its recorded composition in physics.json).",
4
+ "v400_affinity_field_readout": {
5
+ "mechanism": "score(c) = (1-mix)*legacy(c)/max|legacy| + mix*L(c)/max|L|, L(c) = sum_u E_u*[P(c|u)-P0(c)], P(c|u)=w(u,c)/sum_c' w(u,c'), P0(c)=mass(c)/sum_c' mass(c')",
6
+ "training": "none — every quantity was already learned by hebbian_lesson; O(|lit|*degree) per question; one CPU core; no neural network",
7
+ "default": "mix = 0 (bit-identical to v3.9.1); seven of the nine fabrics here ship with affinity_mix = 0.3 recorded in physics.json",
8
+ "also_in_v400": "one softmax temperature per distinct candidate count (the count is a property of the QUESTION): the shared giant fabric's single fitted temperature left polarity at ECE 0.395 while dbpedia sat at 0.064 in the SAME fit",
9
+ "per_fabric": {
10
+ "b77-sem": {
11
+ "readout": "affinity_mix 0.3, diffusion 0.02",
12
+ "cal_1003": {"legacy": 0.4340, "v400": 0.4560},
13
+ "hidden_3080_scored_once": {"legacy": 0.4660, "v400": 0.4800},
14
+ "ece_hidden": {"legacy": 0.2200, "v400": 0.0460},
15
+ "handmade_ood_68": {"legacy": 0.132, "v400": 0.191}
16
+ },
17
+ "router16": {
18
+ "readout": "affinity_mix 0.3, diffusion 0.45",
19
+ "cal_12593": {"legacy": 0.5060, "v400": 0.5850},
20
+ "ece_cal": {"legacy": 0.0460, "v400": 0.0610},
21
+ "handmade_ood_15": {"legacy": 0.267, "v400": 0.467}
22
+ },
23
+ "giant-latin": {
24
+ "readout": "affinity_mix 0.3, diffusion 0.45",
25
+ "per_domain_hidden": {
26
+ "agnews": {"legacy": 0.3730, "v400": 0.7520},
27
+ "emotion": {"legacy": 0.1960, "v400": 0.3930},
28
+ "polarity": {"legacy": 0.5440, "v400": 0.5960},
29
+ "dbpedia": {"legacy": 0.5530, "v400": 0.7970},
30
+ "tickets_en": {"legacy": 0.4480, "v400": 0.9570}
31
+ },
32
+ "tickets_en_shipped_fabric": 0.9040,
33
+ "comment": "the round-2 tickets_en regression (0.9040 -> 0.4480 after the lane repair) is INVERTED: the same repaired fabric scores 0.9570 with the affinity readout, above the original"
34
+ },
35
+ "giant-bengali": {"readout": "affinity_mix 0.3", "hidden_540": {"legacy": 0.9260, "v400": 1.0000}, "ece": {"legacy": 0.0270, "v400": 0.0000}},
36
+ "giant-devanagari": {"readout": "affinity_mix 0.3", "hidden_539": {"legacy": 0.9110, "v400": 1.0000}, "ece": {"legacy": 0.0180, "v400": 0.0010}},
37
+ "giant-cyrillic": {"readout": "affinity_mix 0.3", "hidden_539": {"legacy": 0.9520, "v400": 1.0000}, "ece": {"legacy": 0.0170, "v400": 0.0000}},
38
+ "agnews": {"readout": "affinity_mix 0.3", "novel_probes_12": {"legacy": 0.5833, "v400": 0.7500}, "admission_required": 0.40},
39
+ "sst2": {"readout": "LEGACY (unchanged)", "novel_probes_12": {"legacy": 0.7500, "if_affinity_were_enabled": 0.5830}, "admission_required": 0.65,
40
+ "reason": "the affinity readout would drop this fabric BELOW its own admission gate, so it ships unchanged"},
41
+ "amazon": {"readout": "LEGACY (unchanged)", "novel_probes_10": {"legacy": 0.7000, "if_affinity_were_enabled": 0.6000}, "admission_required": 0.65,
42
+ "reason": "the affinity readout would drop this fabric BELOW its own admission gate, so it ships unchanged"}
43
+ },
44
+ "why_two_class_fabrics_are_excluded": "the contrast is degenerate on a two-candidate set: with two candidates a token points at one or the other, so one mis-pointed token dominates. The gate on the fabric's own novel probes is the arbiter, not a global rule.",
45
+ "cost": {
46
+ "latency": "unchanged in practice (the channel is O(|lit|*degree), microseconds against a 6-11 ms decision)",
47
+ "memory": "one per-fabric cache of node lane-mass"
48
+ }
49
+ },
50
+ "b77_sem": {
51
+ "fabric": "model/b77-sem",
52
+ "shipped_v391": {
53
+ "calibration": {"choice_temperature": 0.00472645, "rows": 211, "composition": "unknown (no physics.json)"},
54
+ "cal_1003": {"n": 1003, "accuracy_argmax": 0.1316, "ece_top_prob_10bin": 0.838, "answered_frac": 0.996, "honest_total": 0.1316},
55
+ "hidden_3080": {"n": 3080, "accuracy_argmax": 0.1584, "ece_top_prob_10bin": 0.8085}
56
+ },
57
+ "v400": {
58
+ "calibration": {"composition": "affinity_mix 0.3, diffusion 0.02, energy_norm true"},
59
+ "cal_1003": {"n": 1003, "accuracy_argmax": 0.4560, "ece_top_prob_10bin": 0.0740},
60
+ "hidden_3080": {"n": 3080, "accuracy_argmax": 0.4800, "ece_top_prob_10bin": 0.0460}
61
+ }
62
+ },
63
+ "note_on_splits": "the handmade OOD numbers (148 hand-written probes, tools/handmade_gate.py + data/handmade_probes.jsonl) are NOT a training or calibration set; they are reported next to every number so the in-distribution / out-of-distribution gap stays visible."
64
+ }
datasets/novel_probes/RESULTS.json CHANGED
@@ -1,40 +1,44 @@
1
  {
2
- "admitted": [
3
- {
4
- "domain": "sst2",
5
- "novel_accuracy": 0.75,
6
- "required": 0.65,
7
- "n": 12
8
- },
9
- {
10
- "domain": "agnews",
11
- "novel_accuracy": 0.5833,
12
- "required": 0.4,
13
- "n": 12
14
- },
15
- {
16
- "domain": "amazon",
17
- "novel_accuracy": 0.7,
18
- "required": 0.65,
19
- "n": 10
20
- }
21
- ],
22
- "rejected": [
23
- {
24
- "domain": "toxic",
25
- "novel_accuracy": 0.2857,
26
- "required": 0.65,
27
- "collapse": true,
28
- "reason": "below required margin + prediction collapse"
29
- },
30
- {
31
- "domain": "emotion",
32
- "novel_accuracy": 0.25,
33
- "required": 0.3167,
34
- "collapse": false,
35
- "reason": "below required margin"
36
- }
37
- ],
38
- "gate": "tools/novel_gate.py",
39
- "rule": "accuracy > max(majority_baseline, uniform_chance + 0.15) and no prediction collapse > 60%"
 
 
 
 
40
  }
 
1
  {
2
+ "admitted": [
3
+ {
4
+ "domain": "sst2",
5
+ "novel_accuracy": 0.75,
6
+ "required": 0.65,
7
+ "n": 12,
8
+ "note": "v4.0: the affinity readout measured 0.5830 on these probes, BELOW this gate, so the fabric ships UNCHANGED with the legacy readout"
9
+ },
10
+ {
11
+ "domain": "agnews",
12
+ "novel_accuracy": 0.75,
13
+ "required": 0.4,
14
+ "n": 12,
15
+ "note": "v4.0: the affinity readout (mix 0.3) raised this from 0.5833; the fabric ships with affinity_mix 0.3"
16
+ },
17
+ {
18
+ "domain": "amazon",
19
+ "novel_accuracy": 0.7,
20
+ "required": 0.65,
21
+ "n": 10,
22
+ "note": "v4.0: the affinity readout measured 0.6000 on these probes, BELOW this gate, so the fabric ships UNCHANGED with the legacy readout"
23
+ }
24
+ ],
25
+ "rejected": [
26
+ {
27
+ "domain": "toxic",
28
+ "novel_accuracy": 0.2857,
29
+ "required": 0.65,
30
+ "collapse": true,
31
+ "reason": "below required margin + prediction collapse"
32
+ },
33
+ {
34
+ "domain": "emotion",
35
+ "novel_accuracy": 0.25,
36
+ "required": 0.3167,
37
+ "collapse": false,
38
+ "reason": "below required margin"
39
+ }
40
+ ],
41
+ "gate": "tools/novel_gate.py",
42
+ "rule": "accuracy > max(majority_baseline, uniform_chance + 0.15) and no prediction collapse > 60%",
43
+ "v400_note": "The v4.0 affinity readout is applied PER FABRIC and gated by this file's own rule: a fabric whose readout change would drop it below its 'required' margin is shipped unchanged. agnews passes (0.5833 -> 0.7500, required 0.40); sst2 (0.5830) and amazon (0.6000) would fail their 0.65 gate and ship unchanged. The contrast is degenerate on two-class candidate sets, which is why."
44
  }
docs/ENGINE_PORT.md CHANGED
@@ -1,4 +1,4 @@
1
- # Engine port — v3.2.0 → v3.9.1
2
 
3
  ## What changed
4
 
@@ -108,4 +108,69 @@ weight instead: **`abstention` / `uncertainty-quantification` /
108
  `selective-prediction`**, alongside `no-transformer` / `no-neural-network` /
109
  `no-pattern-matching`. A decision engine that can say "I don't know", with no
110
  neural network anywhere, is a more defensible claim than a multimodal one, and
111
- it is the one this repo actually demonstrates.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Engine port — v3.2.0 → v4.0.0
2
 
3
  ## What changed
4
 
 
108
  `selective-prediction`**, alongside `no-transformer` / `no-neural-network` /
109
  `no-pattern-matching`. A decision engine that can say "I don't know", with no
110
  neural network anywhere, is a more defensible claim than a multimodal one, and
111
+ it is the one this repo actually demonstrates.
112
+
113
+ ---
114
+
115
+ # v4.0.0 — the affinity field readout (2026-11)
116
+
117
+ The engine in `engine/` is now the **v4.0.0** tree: the same source as the
118
+ GitHub repo at the v4.0 commit, so the code and the weights that ship here
119
+ are the code that produced every number in the card.
120
+
121
+ | | before | after |
122
+ |---|---:|---:|
123
+ | `core/*.hpp` | 16 files | 16 files |
124
+ | `core/syfox.hpp` | 2,415 lines | 2,756 lines |
125
+ | `core/si_substrate.hpp` | 2,415 lines | 2,539 lines |
126
+ | string | `syfox-3.9.1` | `syfox-4.0.0` |
127
+
128
+ ## What v4.0 adds
129
+
130
+ 1. **The affinity field readout (AFR)** — `core/syfox.hpp`, `--affinity-mix F`
131
+ (0 = legacy, bit-identical to v3.9.1; 1 = affinity only) and
132
+ `--affinity-pmi` (the log-odds form). No training, no neural network: it
133
+ reads the Hebbian affinity the fabric already learned, against the
134
+ candidate set as its own null model.
135
+ 2. **The lane repair** — `core/si_substrate.hpp`, `syfox repair-lanes
136
+ --model DIR [--dead-threshold F] [--dry-run]`, plus `--lane-floor F` for
137
+ new fabrics. The port applied CMD §2.3's decay to every lane on every
138
+ lesson, so a lane last bound long ago underflows to the float32 denormal
139
+ floor and the Hebbian memory is erased; the repair rebuilds it from the
140
+ persisted evidence ledger in CMD's saturating form.
141
+ 3. **The per-candidate-count temperature** — one scalar per distinct
142
+ candidate count, because one scalar cannot serve a 14-way and a 2-way
143
+ spread at once. Persisted in `calibration.json`
144
+ (`choice_temperature_by_count`).
145
+
146
+ ## The recorded composition moved
147
+
148
+ `model/*/physics.json` now carries the **readout** as well as the physics:
149
+
150
+ ```json
151
+ {"affinity_mix":0.3,"affinity_pmi":false,"decay":0.82,"diffusion":0.45,
152
+ "energy_norm":true,"hop_coupling":0.35,"k_settle":8,"recorded":true}
153
+ ```
154
+
155
+ so a deployed model decides under the readout its temperature was fitted for.
156
+ Seven of the nine fabrics here carry `affinity_mix: 0.3`; `sst2` and `amazon`
157
+ carry none, because the affinity readout would drop them below their own
158
+ admission gate (see the card's v4.0 section).
159
+
160
+ **The C API now applies the recorded composition on load.**
161
+ `syfox_engine_create()` loads `physics.json` and *applies* it, so the
162
+ python bridge, the HTTP server and the Space decide under the same physics
163
+ as the CLI. Before this, the server path decided under a different
164
+ composition — and, after v4.0, under a different readout than the fitted
165
+ temperature.
166
+
167
+ ## Rebuilding
168
+
169
+ ```bash
170
+ cd engine && make all && make sync-so && cd ..
171
+ ```
172
+
173
+ `make sync-so` copies `engine/build/libsyfox_core.so` to the **repo-root**
174
+ `build/`, which is where `server/syfox_bridge.py` loads it from. Skipping it
175
+ is the most common setup failure: the CLI and the tests pass, then
176
+ `from inference import SyFox` dies with `undefined symbol`.
engine/CHANGELOG.md ADDED
@@ -0,0 +1,1476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## v4.0 — the affinity field readout (AFR): measuring an anchor instead of retrieving one
2
+
3
+ A new READOUT, not a new fabric and not a new model. No neural network, no
4
+ training, no new corpus pass: every quantity AFR reads was already learned
5
+ by `hebbian_lesson`. It costs O(|lit| * degree) per question on one core,
6
+ and it is OFF by default so every pre-v4.0 fabric replays bit-identically.
7
+
8
+ THE DEFECT. Three measurements, on the shipped model and the v3.9.3 engine:
9
+
10
+ 1. THE READOUT NEVER READS THE FABRIC'S STRONGEST SIGNAL. Every lesson
11
+ binds the state's tokens to the outcome anchor (outcome_text = the label
12
+ key + its description), so the fabric holds an explicit affinity
13
+ w(u, c) between a query-side token and a candidate anchor -- literally
14
+ "which intent did this word teach". The legacy readout never reads it:
15
+ Substrate::readout() sums the probe token's own energy plus a
16
+ weight-averaged neighbourhood, and the anchor's affinity enters only
17
+ indirectly, through whether a capped, decaying diffusion carried energy
18
+ to the anchor. One constant therefore has to serve both PRECISION (the
19
+ field must not smear onto wrong anchors) and REACH (the right anchor
20
+ must light up at all), and the two want opposite values -- measured: the
21
+ diffusion optimum is per-DOMAIN (tickets_en 0.45, agnews/dbpedia 0.02).
22
+ A constant that must be re-tuned per domain is a sign the readout is
23
+ asking the wrong question.
24
+
25
+ 2. THE READOUT HAS NO NULL MODEL. A candidate's score is an unnormalised
26
+ SUM over its probe bag. A Banking77 description is 20 mined phrases --
27
+ ~60 token occurrences -- most of them shared with other candidates
28
+ ("not", "working", "the"). Shared words add a large common offset; the
29
+ one discriminative word is one term out of sixty. The mined phrases
30
+ make the sum a repetition-weighted VOTE, not a measurement.
31
+
32
+ 3. THE CONSEQUENCE IS A RETRIEVAL SCORE, NOT A MEASUREMENT SCORE. Measured
33
+ on the repaired b77-sem fabric, query "the cash machine swallowed my
34
+ card and it never came back":
35
+ candidate[c04]=0.0933 ("cash withdrawal not working")
36
+ candidate[c19]=0.0919 ("card payment not working")
37
+ -- two intents differing by ONE word score within 1.5% of each other;
38
+ the decision was a coin flip. The fabric KNOWS that "card" belongs to
39
+ c19; the readout could not see it.
40
+
41
+ And the vocabulary was NOT the cause: 98.8% of the handmade Banking77
42
+ probe tokens (577/584) are already nodes. An OOV-first design would have
43
+ been the wrong fix for the measured failure.
44
+
45
+ THE MECHANISM. For the lit query tokens u with field energy E_u and the
46
+ candidate set C:
47
+
48
+ P(c|u) = w(u,c) / sum_{c' in C} w(u,c') posterior over C
49
+ P0(c) = mass(c) / sum_{c' in C} mass(c') a priori share of C
50
+ L(c) = sum_u E_u * [ P(c|u) - P0(c) ] the contrast
51
+ or, with --affinity-pmi, the log-odds form L(c) = sum_u E_u * log(P(c|u)/P0(c)).
52
+
53
+ A token that points at EVERY candidate cancels against the null model and
54
+ contributes nothing -- ubiquity stops being evidence. A token that points
55
+ at ONE candidate contributes strongly, positive for that candidate and
56
+ negative for the rest, so discrimination becomes sign-carrying instead of
57
+ drowned in a shared offset. mass(c) is the anchor's own total lane weight:
58
+ the prior is measured, not assumed.
59
+
60
+ The channel is blended with the legacy readout:
61
+ score(c) = (1-mix) * legacy(c)/max|legacy| + mix * L(c)/max|L|
62
+ with mix defaulting to 0 (legacy, bit-identical). The measured optimum is a
63
+ SMALL dose -- mix = 0.3 wins on every fabric and every diffusion tested.
64
+
65
+ This is the FIRST-ORDER RESOLVENT of the propagation the settle simulates:
66
+ the same operator, read exactly instead of approximated by a capped and
67
+ smeared diffusion. In the literature it is the same object as Kanerva's SDM
68
+ read out by a kernel/least-squares solve (Iatropoulos et al., "Kernel Memory
69
+ Networks", NeurIPS 2022), which likewise replaces a hand-tuned decay
70
+ schedule with a closed-form retrieval and a capacity law; and its ORDER
71
+ counterpart is Plate's Holographic Reduced Representations (IEEE TNN 1995),
72
+ whose crosstalk failure mode is cured by projecting the retrieved trace onto
73
+ the span of the known anchors -- which is what the candidate set does here.
74
+ The non-neural char n-gram representation that would remove the dark node
75
+ STRUCTURALLY is Schutze, Adel & Asgari, "Nonsymbolic Text Representation",
76
+ EACL 2017 (char n-gram counts -> SVD -> summed; no gradient training).
77
+
78
+ THE HONEST-SILENCE FLOOR, RESTATED. kUnknownCandidateFloor defers when the
79
+ settled field carries no energy on any candidate -- which in the
80
+ novel-wording case is exactly the situation the affinity channel exists to
81
+ rescue. The floor now fires only when NEITHER channel carries evidence,
82
+ and is still evaluated on the legacy channel's maximum, so its meaning (it
83
+ measures the FIELD) is unchanged.
84
+
85
+ MEASURED -- router16 (16 intents), CAL split (12,593 rows):
86
+ 0.45 0.0 0.5060 0.0460 0.267 (4/15)
87
+ 0.45 0.3 0.5850 0.0610 0.400 (6/15) <- +7.9 points
88
+ 0.02 0.0 0.5290 0.0920 0.133 (2/15)
89
+ 0.02 0.3 0.5600 0.1030 0.400 (6/15)
90
+
91
+ MEASURED -- giant-latin, per-domain HIDDEN splits (one fabric, 16 domains):
92
+ domain classes legacy d0.45 AFR d0.45 legacy d0.02 AFR d0.02
93
+ agnews 4 0.3730 0.7520 0.6790 0.7740
94
+ emotion 6 0.1960 0.3930 0.2590 0.3980
95
+ polarity 2 0.5440 0.5960 0.6380 0.6030
96
+ dbpedia 14 0.5530 0.7970 0.7800 0.7660
97
+ tickets_en 3 0.4480 0.9570 0.5660 0.9620
98
+
99
+ The round-2 tickets_en regression (0.9040 -> 0.4480 after the lane
100
+ repair on the shared fabric) is not merely undone: the SAME repaired
101
+ fabric scores 0.9570 with the affinity readout, and 0.9620 at diffusion
102
+ 0.02 -- above the SHIPPED model's 0.9040. And the per-domain diffusion
103
+ problem disappears with it: the handmade OOD number is 0.176 at EVERY
104
+ diffusion tested, because the affinity channel reads the evidence instead
105
+ of asking a smeared field to carry it.
106
+
107
+ MEASURED -- b77-sem (Banking77), CAL split selects, hidden scored once:
108
+
109
+ diffusion mix CAL acc CAL ECE handmade(OOD)
110
+ 0.45 0.0 0.2490 0.2070 0.059 (4/68)
111
+ 0.45 0.3 0.2510 0.0820 0.176 (12/68)
112
+ 0.10 0.0 0.4170 0.2020 0.059 (4/68)
113
+ 0.10 0.3 0.4230 0.0890 0.176 (12/68)
114
+ 0.02 0.0 0.4340 0.2070 0.044 (3/68)
115
+ 0.02 0.3 0.4560 0.0740 0.176 (12/68)
116
+
117
+ HIDDEN (3,080 rows), the selected configuration and the baseline only:
118
+ 0.45 0.0 0.2850 0.2330
119
+ 0.45 0.3 0.2750 0.0680
120
+ 0.02 0.0 0.4660 0.2200
121
+ 0.02 0.3 0.4800 0.0460 <- selected on CAL
122
+
123
+ So at the selected diffusion: accuracy 0.4660 -> 0.4800 on the hidden
124
+ split, ECE 0.2200 -> 0.0460 (4.8x better). mix = 0.3 improves CAL accuracy
125
+ at EVERY diffusion tested and never hurts ECE.
126
+
127
+ THE AUTHORITATIVE OUT-OF-DISTRIBUTION A/B (both fabrics calibrated by the
128
+ same build, scored through the same path, corrected probe labels):
129
+ b77-sem handmade (68): legacy 0.132 (9/68) -> AFR 0.191 (13/68)
130
+ router16 handmade (15): legacy 0.267 (4/15) -> AFR 0.467 (7/15)
131
+ and the DIFFUSION-INDEPENDENCE, which is the architectural claim: across a
132
+ 22x range of the diffusion constant the affinity readout's handmade accuracy
133
+ moves by 0.030 (0.176 @ 0.45, 0.206 @ 0.10, 0.191 @ 0.02), where the
134
+ legacy readout's optimum was PER DOMAIN (tickets_en 0.45, agnews/dbpedia
135
+ 0.02). The readout reads the evidence instead of asking a smeared field to
136
+ carry it.
137
+
138
+ The PMI (log-odds) form was also measured and is WORSE than the linear
139
+ contrast (CAL acc 0.194 vs 0.221 at mix 0.5/diffusion 0.45; OOD 0.132 vs
140
+ 0.176): normalising over a 77-way candidate set makes the log-odds
141
+ variance-heavy. Shipped: the linear form; --affinity-pmi remains available.
142
+
143
+ THE ORDER CHANNEL. The lit set also carries the state's bigram nodes when
144
+ the fabric has them; bigram nodes are bound to the outcome anchors by the
145
+ same Hebbian lesson, so their affinity to a candidate is an ORDERED
146
+ relation -- CMD 2.5's escape, carried into the affinity channel. On the
147
+ shipped b77-sem (learned before bigram lanes existed) the extension is a
148
+ verified no-op: the numbers are bit-identical with and without it.
149
+
150
+ THE PER-CANDIDATE-COUNT TEMPERATURE (v4.0, second half). The giant
151
+ fabric's ECE exposed a second, independent defect: ONE softmax temperature
152
+ cannot serve candidate sets of different sizes. A 14-way question's score
153
+ spread is not a 2-way question's spread, and the shared fabric's single
154
+ fitted temperature left polarity at ECE 0.395 while dbpedia sat at 0.064 in
155
+ the SAME fit. v4.0 therefore fits ONE temperature per distinct candidate
156
+ count -- the count is a property of the QUESTION, so it leaks nothing about
157
+ the label -- with the same 1-bit ECE selection guard and the same rows; a
158
+ count with fewer than 64 calibration rows keeps the global scalar. The table
159
+ persists in calibration.json (choice_temperature_by_count) and the decision
160
+ path reads it through choice_temperature_for(n). The argmax never moves.
161
+ MEASURED on the giant fabric (legacy readout, diffusion 0.45), ECE before
162
+ -> after the per-count temperature: agnews 0.2750 -> 0.0860, emotion
163
+ 0.0780 -> 0.0240, polarity 0.1280 -> 0.0690, dbpedia 0.1650 -> 0.1330,
164
+ tickets_en 0.1100 -> 0.1050. The fitted table for that fabric:
165
+ {2: 1.666, 3: 0.470, 4: 2.105, 6: 11.314, 14: 0.749, 77: 0.068}.
166
+
167
+ THE READOUT MODE IS PART OF THE RECORDED COMPOSITION. physics.json now
168
+ carries affinity_mix and affinity_pmi, so a deployed model decides under the
169
+ readout its temperature was fitted for -- the fit==decide parity contract,
170
+ extended from the physics to the measurement. --affinity-mix still overrides
171
+ explicitly.
172
+
173
+ TWO CORRECTIONS FOUND WHILE MEASURING (both fixed, both disclosed):
174
+ 1. A MISLABELLED PROBE IN THE HANDMADE SET. rt_01 ("he sank a curling
175
+ three-pointer in the fourth quarter") was labelled rt01 -- the BANKING
176
+ anchor -- when a curling three-pointer is SPORTS, i.e. rt00 ("news
177
+ headlines world sports business technology"). The gold label is now
178
+ rt00.
179
+ 2. THE C API / PYTHON BRIDGE IGNORED THE MODEL'S RECORDED COMPOSITION.
180
+ syfox_engine_create() loaded physics.json but never APPLIED it, so the
181
+ server, the Space and the handmade gate decided under different physics
182
+ than the CLI -- and, after v4.0, under a different READOUT than the
183
+ temperature was fitted for. It now calls apply_composition(); applying
184
+ it twice is idempotent, and the CLI is unaffected. (The bug surfaced
185
+ because the gate's own --affinity-mix flag was silently overriding the
186
+ model's recorded readout with the flag's default; the gate now leaves
187
+ the recorded readout alone unless the operator asks otherwise.)
188
+
189
+ TESTS: test_affinity_readout pins the mechanism -- the channel is OFF by
190
+ default (the replay contract), the EXCLUSIVE token decides even when the
191
+ query shares no vocabulary with any candidate's description, the decision
192
+ is deterministic, a token bound to every candidate changes nothing, and
193
+ mix = 0 reproduces the legacy decision. Full unit suite green.
194
+
195
+ FLAGS: --affinity-mix F (0 = legacy, 1 = affinity only; default 0) and
196
+ --affinity-pmi (the log-odds form). The flag is applied in apply_physics so
197
+ that cmd_calibrate -- which calls apply_physics only -- fits the SAME
198
+ channel the decision scores (the v3.8 fit==decide parity contract).
199
+
200
+ VERSION 3.9.3 -> 4.0.0
201
+
202
+ ## v3.9.3 — the dead-lane repair, the router-criteria measurement, and the handmade gate
203
+
204
+ Three defects measured on the PUBLISHED model (HF sha 5aa69627) and the
205
+ v3.9.1 engine. One of them is a large win; one of them has a true diagnosis
206
+ and a HARMFUL proposed remedy; one of them is a calibration/reference
207
+ problem that flattered SyFox.
208
+
209
+ DEFECT 1 — THE DEAD LANES (the diagnosis is TRUE; the command did not exist
210
+ and is added here). enforce_lane_decay() multiplies EVERY lane by 0.995 on
211
+ EVERY lesson, so a lane last bound at lesson k in an N-lesson fabric carries
212
+ w0 * 0.995^(N-k) — which underflows to the float32 denormal floor (1.4e-43)
213
+ after ~20,670 lessons and then STOPS decreasing. MEASURED on the shipped
214
+ model/giant-latin (114,060 lessons, 1,905,169 lanes): 95.09% of lanes carry a
215
+ weight in (0, 1e-12), the MEDIAN lane weight is 1.4e-43, and only 2.42%
216
+ exceed 1e-6. The Hebbian memory was erased; what survived was a recency
217
+ window over the tail of the corpus. The base repository's law is different
218
+ (research-paper/cmd.md 2.3): w <- tanh((w*lambda + eta*v_b*v_c)/w_max)*w_max
219
+ — SATURATING, with continuous co-activity growth, so a starved lane keeps a
220
+ real value; research-paper/tsda.md 2: "It remains in long-term memory (the
221
+ edge still exists), but it requires more cognitive energy to retrieve." The
222
+ port kept the decay and lost the saturation.
223
+
224
+ FIX 1a — NEW COMMAND `syfox repair-lanes --model DIR [--dead-threshold F]
225
+ [--dry-run]`: rebuilds every lane's weight from the persisted EVIDENCE LEDGER
226
+ (v3 Milestone 3), which holds the integral of exactly the growth term the
227
+ decay destroyed, in CMD 2.3's saturating form:
228
+ w = w_max * tanh( net_events * bind_scale / w_max )
229
+ No equation moves and no learn-time behaviour changes; a fabric re-learned
230
+ from scratch is byte-identical. MEASURED: giant-latin revives 1,330,812 of
231
+ 1,859,008 dead lanes (weight sum 681 -> 117,478); b77-sem revives 159,449
232
+ (912 -> 58,210); router16 rebuilds 43,117 (1,012 -> 10,360).
233
+
234
+ FIX 1b — cfg_.lane_decay_floor + `--lane-floor F`: the ROOT-CAUSE guard for
235
+ new fabrics. A starved lane keeps a floor instead of falling off the
236
+ number line (TSDA 2: the edge persists with reduced retrievability).
237
+ Default 0 = OFF, so every pre-v3.9.3 fabric replays bit-identically.
238
+
239
+ MEASURED EFFECT (argmax accuracy — temperature-independent, so this is the
240
+ repair alone): router16 on its 12,593-row cal split 0.4210 -> 0.5060
241
+ (+8.5 points); b77-sem on hidden 3,080 rows 0.4500 -> 0.4662 at diffusion
242
+ 0.02; giant-latin per domain (hidden, class question only): agnews 0.498 ->
243
+ 0.679, dbpedia 0.578 -> 0.780, polarity 0.560 -> 0.638, emotion 0.129 ->
244
+ 0.259, with ECE 0.402 -> 0.128 (agnews) and 0.300 -> 0.124 (dbpedia).
245
+
246
+ DEFECT 2 — THE ROUTER CRITERIA (the diagnosis is TRUE; the proposed remedy
247
+ is HARMFUL). MEASURED against the shipped giant-latin's 43,420 nodes: the
248
+ router descriptions are mostly words the fabric never interned — rt01
249
+ ("banking cards payments transfers refunds loans") has 0 of 6 words as
250
+ nodes, rt00 1 of 6, rt13 1 of 6, rt05 and rt08 0 of 4/5. Two code facts make
251
+ that matter: Substrate::readout() SKIPS every token that is not a node (so a
252
+ non-node description contributes nothing to its own candidate), and decide()
253
+ injects EVERY candidate's description tokens into ONE shared field (so words
254
+ that ARE nodes cross-contaminate all candidates at once).
255
+ tools/rebuild_router_criteria.py implements the proposed rebuild (each
256
+ candidate described by the tokens with the highest w(x,A) * exclusive(x,A)).
257
+ MEASURED on the repaired router16, 12,593-row cal split, each criteria set
258
+ with its own matched calibration:
259
+ old text ("banking cards payments...") argmax 0.5060 ECE 0.046
260
+ EMPTY text ("") argmax 0.4320 ECE 0.018
261
+ one exclusive token ("monei") argmax 0.5060 ECE 0.041
262
+ label-exclusive 4 tokens (the remedy) argmax 0.4147 ECE 0.062
263
+ The proposed remedy COSTS 9 POINTS of routing accuracy: the description is
264
+ not a lever, it is a shared-field injector, and the richer it gets the more
265
+ the candidates contaminate each other — the repo's own documented
266
+ "direct-term harvest" effect (its wording sweep already found short4 0.426 >
267
+ mid8 0.164 > rich12 0.079). The remedy is therefore shipped as a TOOL, not
268
+ as a default, and the finding recorded: keep the criteria MINIMAL. Empty
269
+ criteria gives the best calibration measured anywhere in this tree
270
+ (ECE 0.018, beating Jev's third-party 0.246 and Laya's 0.081).
271
+
272
+ DEFECT 3 — THE JEV REFERENCE NUMBERS FLATTERED SYFOX. The bench's
273
+ jev_reference block carried the LAUNCH-DAY self-report (workflow 0.678,
274
+ latency 70-500 ms, "calibration claimed, not public"). Independent
275
+ third-party measurements are materially STRONGER for Jev: arxiv 2609.37647
276
+ (37 datasets, 346,009 requests, jev-1.13.0) measures 95-99% on IMDB / SST-2
277
+ / HellaSwag / ARC and 79.7% on Banking77 at full coverage (-> 96.3% at 50%
278
+ coverage); laya-model.com/benchmarks publishes Jev at typed-decisions 0.727,
279
+ AG News 0.910, DAIR Emotion 0.480, Banking77 0.870, ECE 0.246, p50 latency
280
+ 236-276 ms. The block now carries those, with the vendor's own 0.955 workflow
281
+ claim labelled as such.
282
+
283
+ NEW — THE HANDMADE GENERALISATION GATE. data/handmade_probes.jsonl (148
284
+ probes) + tools/handmade_gate.py: hand-written sentences, deliberately
285
+ outside every training split, every eval split and every mined-criteria
286
+ vocabulary. It is the only check in the tree that can see a fabric that has
287
+ memorised its corpus instead of learning it. MEASURED on the SHIPPED
288
+ fabrics: total 0.291 (bank77 0.103, emotion 0.167, dbpedia 0.286, router
289
+ 0.400) — the published bank77 number (0.158) is optimistic because the
290
+ hidden split shares the training templates. It also exposed the DIFFUSION
291
+ TRADE-OFF: diffusion 0.02 (selected on cal) buys bank77 hidden 0.2854 ->
292
+ 0.4662 in-distribution and costs handmade 0.118 -> 0.044 out-of-distribution.
293
+ A cal-only selection cannot see that cost. Wired into make ci.
294
+
295
+ FURTHER MEASUREMENT — THE DIFFUSION OPTIMUM IS PER-DOMAIN, NOT PER-FABRIC.
296
+ The giant fabric is one directory carrying 16 domains with very different
297
+ geometry. At diffusion 0.02 tickets_en (3 classes) REGRESSES from 0.9040 to
298
+ 0.5660 while agnews (4) and dbpedia (14) gain 18-20 points. One diffusion
299
+ per fabric dir is therefore not enough for a multi-domain fabric — the
300
+ per-fabric mechanism (physics.json) is the right primitive but the value
301
+ has to be chosen per DOMAIN, or the domains split into per-domain fabrics.
302
+
303
+ TESTS: test_lane_repair (the global decay really kills lanes; the ledger can
304
+ revive them; the dry run reports without touching the fabric; the repair is
305
+ deterministic; no rebuildable lane is still dead afterwards) and
306
+ test_physics_composition. Full unit suite green.
307
+
308
+ DOCS: docs/FIT_DECIDE_PARITY.md (the fit==decide contract) and the v3.9.3
309
+ section of this changelog.
310
+
311
+ VERSION 3.9.2 -> 3.9.3
312
+
313
+ ## v3.9.2 — fit == decide: the calibration composition contract
314
+
315
+ The fix for the wrong-answer bug the v3.9.1 diagnostics exposed. Two
316
+ independent defects, both in the tool layer; NO physics equation changed.
317
+
318
+ DEFECT 1 — THE CALIBRATION WAS FITTED UNDER A DIFFERENT PHYSICS THAN THE
319
+ DECISION RUNS. The choice/score temperature is fitted on settle-pass
320
+ energies, and those depend on the whole decide-side composition (the
321
+ energy gain, diffusion, decay, k_settle, hop coupling). The energy gain is
322
+ PER-STATE, so it is not a uniform rescale. In this tree b77-sem, router16
323
+ and model-bank77-best calibrated WITHOUT --energy-norm while every bench
324
+ and decide call ran WITH it. Measured on the shipped b77-sem fabric and
325
+ the 1,003-row cal split, same engine, one flag apart:
326
+ calibrate WITHOUT --energy-norm -> T = 0.0037, fit saw 556 of 2,006
327
+ question-rows (27.7% coverage),
328
+ ECE 0.4567 -> 0.4057
329
+ calibrate WITH --energy-norm -> T = 0.3552, fit saw 2,006 of 2,006,
330
+ ECE 0.3183 -> 0.3056
331
+ A ~100x sharper temperature, chosen on a 27.7%-covered BIASED subset (the
332
+ other 1,450 rows settle to a SILENT field and are dropped from the fit). A
333
+ near-floor T saturates the softmax: the post-temperature top-2 gap goes to
334
+ ~0.93 on every row, so the honest-defer gate (an absolute 0.05 margin) can
335
+ NEVER fire — the model never abstains — and every answer carries ~0.98
336
+ confidence whether it is right or wrong (measured on the shipped fabric,
337
+ hidden: mean p1 0.9819 on correct rows vs 0.9641 on wrong, ECE 0.809).
338
+ The calibrate report's own ECE did not describe the bench's ECE because the
339
+ two ran under different physics.
340
+
341
+ DEFECT 2 — THE DIFFUSION CONSTANT WAS NEVER RE-TUNED FOR THE DENSE
342
+ FABRICS. diffusion is a config value (not an equation) whose optimum is a
343
+ property of the fabric; 0.45 was validated on the small v2-era fabrics and
344
+ smears a 217k-lane fabric's field, merging intents that share vocabulary.
345
+ Measured on the bank77 CAL split (selection never touches hidden):
346
+ 0.45 -> 0.1316 accuracy, 0.10 -> 0.4237, 0.02 -> 0.4237.
347
+
348
+ FIX 1 — PHYSICS.JSON: a fabric now carries the decide-side composition it
349
+ was calibrated under (physics.json, next to calibration.json). calibrate
350
+ RECORDS it; decide/bench/demo/stats APPLY it on load
351
+ (Engine::apply_composition). Explicit CLI flags still win. A fabric with no
352
+ physics.json is a pre-v3.9.2 fabric: nothing is applied and behaviour is
353
+ bit-identical (replay contract preserved).
354
+
355
+ FIX 2 — THE FIT REFUSES TO RUN ON A BIASED SUBSET. calibrate counts the
356
+ question-rows it was offered and the ones it saw; below 50% coverage it
357
+ refuses (exit 2), names the cause, and leaves the fabric untouched. The
358
+ coverage is always disclosed: fit_offered_rows, fit_dropped_silent,
359
+ fit_coverage.
360
+
361
+ FIX 3 — THE MAKEFILE STOPS LYING: b77-sem, router16 and model-bank77-best
362
+ now calibrate with --energy-norm (the composition their benches run).
363
+
364
+ FIX 4 — TOOLS + CI GATE: tools/cal_diffusion_sweep.py sweeps diffusion on
365
+ the CAL split only, re-calibrating at each candidate so the temperature is
366
+ always fitted under the composition it is applied to, and records the
367
+ winner into physics.json (this also delivers the standing recommendation in
368
+ docs/INTRACATEGORY_ATTACK.md section 4: a per-fabric diffusion value, not a
369
+ new global default). tools/assert_fit_decide_parity.py is the CI gate: a
370
+ FITTED fabric with no physics.json has an unknown calibration provenance and
371
+ FAILS. Wired into make ci.
372
+
373
+ MEASURED (v3.9.1 engine, shipped fabrics, shipped splits; selection on cal,
374
+ hidden scored once; bank77 intent-only):
375
+ bank77 hidden 3,080: accuracy (argmax) 0.1584 -> 0.4500 (+29.2 pts),
376
+ ECE 0.809 -> 0.225, accuracy over answered at margin 0.05
377
+ 0.159 -> 0.542, honest total at margin 0.05 0.1581 -> 0.3760,
378
+ deferral rate at margin 0.05 0.5% -> 30.7% (the axis is alive)
379
+ router16 cal 12,593: ECE 0.443 -> 0.054, accuracy over answered
380
+ 0.4299 -> 0.5989. At margin 0 both configurations produce the
381
+ IDENTICAL argmax (0.4210) — the temperature never changes a decision,
382
+ only how confidently it is made and whether it is made at all.
383
+ re-calibrated fabrics: b77-sem T = 0.346736 over 1,003 rows (was
384
+ 0.00472645 over 211), diffusion 0.02; router16 T = 0.0509 over 12,574
385
+ rows (was 0.00491756 over 160).
386
+
387
+ TESTS: test_physics_composition (16 checks: a pre-3.9.2 fabric carries no
388
+ composition and is bit-identical; a recorded composition survives the
389
+ save/load round trip; apply_composition reaches the live substrate; the
390
+ fit's offered/seen/dropped row bookkeeping adds up). Full unit suite green.
391
+
392
+ DOCS: docs/FIT_DECIDE_PARITY.md (the bug, the measurement, the fix, and why
393
+ the base repository does not have it — SI reads out by ARG-MAX over the
394
+ settled field, with no softmax, no temperature and no fitted parameter, so
395
+ there is nothing to fit against the wrong physics; the probability readout
396
+ and the temperature are a SyFox addition and the defect came in with them).
397
+
398
+ VERSION 3.9.1 -> 3.9.2
399
+
400
+ ## v3.9.1 — intra-category diagnostics: confusion matrix + honest totals + the diffusion finding
401
+
402
+ Diagnostics-then-intervention per the tester's revised plan. Everything
403
+ measured in-tree, tuning on cal only, hidden touched only for final
404
+ validation; no global defer default shipped; no parity claims without the
405
+ honest total (docs/HONEST_TOTAL.md).
406
+
407
+ - BENCH (opt-in, default byte-identical): --confusion (NxN gold-x-pred JSON
408
+ matrix, DEFER pseudo-class, pairs_top; rows==labels alignment pinned by
409
+ unit test after the DEFER-shift bug was caught cross-checking the hidden
410
+ dump), --dump-perrow (per-choice-question records with the RAW
411
+ pre-temperature energy gap), Answer.raw_margin disclosure.
412
+ - PHYSICS SWEEP KNOBS: set_decay/set_diffusion/set_hop_coupling/
413
+ set_learn_eta/set_lane_cap on the substrate (frozen defaults, clamped;
414
+ CLI --decay --diffusion --k-settle --hop-coupling --learn-eta --lane-cap
415
+ on bench/calibrate/learn/decide paths).
416
+ - MEASURED (model-b77-sem, 19,690 nodes / 1.31M lanes, banking77):
417
+ calibration T=0.0019 makes the probability-gap defer axis inert
418
+ (0/1003) and ECE 0.597/0.573 measured; no global margin improves the
419
+ honest total; per-intent thresholds overfit cal (-2.0 hidden); class
420
+ frequency does not predict accuracy (r=-0.043); semantics -6.1 pts
421
+ without; decay/k_settle/hop_coupling/learn_eta flat; lane_cap 1024 +1.6;
422
+ DIFFUSION monotone to a boundary optimum: cal 0.401 -> 0.537, hidden
423
+ 0.424 -> 0.571 (+14.7), card_management 0.389 -> 0.632 (+24.3). Replicates
424
+ on an independent reduced fabric family (+16.4). SI equations frozen
425
+ throughout - a CONFIG value, not a physics change.
426
+ - TOOLS: b77_confusion_report.py, b77_margin_sweep.py, b77_apply_policy.py,
427
+ b77_freq_cut.py, b77_ablation_compare.py. ARTIFACTS: data/b77_diag/.
428
+ - DOCS: docs/INTRACATEGORY_ATTACK.md + docs/HONEST_TOTAL.md. TESTS:
429
+ test_bench_diagnostics (confusion/dump/knobs/alignment invariant).
430
+
431
+ ## v3.9.0 — the constructive substrate: SI's Layer-2 reasoning stack + the remaining paper mechanisms
432
+
433
+ Answers the v3.9 audit ("SyFox is not a port of SI — it shares two
434
+ constants"; "many papers unimplemented"). Both charges verified, both
435
+ addressed; the false port claim is retracted in the substrate header itself.
436
+
437
+ - core/reason.hpp (NEW, ~1,530 lines): the faithful port of SI's Layer-2 —
438
+ typed graph with full provenance (rule/parent_a/parent_b/step), O(1)
439
+ edge existence, O(deg) adjacency, bounded retraction (RADE); the NINE
440
+ reasoning primitives (transitive, modus ponens, inheritance, contrapositive,
441
+ case analysis, induction with min-witnesses, analogy, abduction via
442
+ backward chaining, recursion via the fixpoint loop); forward chaining to
443
+ fixpoint under a tension budget; adaptive backward chaining with an active
444
+ goal stack; proof traces + the §5.3.4 verifier; the meta-learner
445
+ (sub-chain counting -> macro-rule promotion at the 2-bit MDL threshold);
446
+ the thinker index C/R; the SIX discovery queries; the .axioms triple
447
+ format (SI's own data files load unchanged). Determinism hardening over
448
+ SI: primitive candidate sets sorted before commit (SI iterated hash maps).
449
+ - ENGINE BRIDGE: `syfox axioms --load FILE` loads triples into BOTH stores
450
+ (typed graph + fabric lanes, idempotent); load_model auto-loads
451
+ <model>/axioms.txt + v39.json (tension + OOD signatures) when present;
452
+ absent = every pre-3.9 model replays bit-identically. New commands: ask
453
+ (forward/backward with proof JSON), reason (fixpoint report), discover
454
+ (six queries + classifier), thinker (C/R + macro count over a query file),
455
+ audit (CMA/CCH DERIVED-vs-INDUCED path-additivity report).
456
+ - DECISION-LAYER PAPER GATES (opt-in, default OFF, read-only over the
457
+ settled field): --proof / --require-proof (RADE proof pass, no_proof_path
458
+ defer); --wavefront-gate (CMD §4 reached-candidates, unreached_candidates
459
+ defer); --momentum-readout (MCPE/CPME echo suppression, echo_only defer;
460
+ ported as peak-diffusion-gain after BOTH the raw final-pass delta and a
461
+ beta=0.9 envelope measured every candidate echo-suppressed on the bench
462
+ fabrics); --coherence-gate (HTR ΔR participation-ratio rise,
463
+ no_structural_rise defer); --vght-gate (VGHT coincidence C=σ(12(E·E−0.05))
464
+ on the hop walk, gated_lane_frac disclosure); --cem-plan (P-CMA shell,
465
+ gradient-free CEM over deterministic source-cap variants, plan restores
466
+ the winning field; first cut snapshotted post-settle and double-decayed
467
+ every variant — caught by think30 bisection at 0.600 -> 0.267 and fixed);
468
+ --ood-knn (fixes.md signature-density defer, ood_density); --tension-gate
469
+ (RIFA SIL with the sign defect fixed: contradictions ACCUMULATE tension,
470
+ conflicted_state defer at >= 2 unresolved conflicts on the state hash).
471
+ - LEARN-SIDE PAPERS (opt-in, replay-safe): --fingerprints (CME graded
472
+ half-dose re-teach, capped 1024-entry table, deterministic eviction);
473
+ --sentinels on (CMD §2.5 ^w0~w1 / wn~wn$ boundary pairs); --pro-con on
474
+ (RB surrogate: negated lessons bind through "!token" con-namespaces);
475
+ --order-consolidation on (CPME-II discrete surrogate: per-lane order
476
+ evidence, Phi = 0.4 + 0.6*(2c/t - 1) blend, ORD1 magic tail, replay
477
+ no-op on pre-v3.9 fabrics).
478
+ - HONEST LINEAGE: si_substrate.hpp header retracted the "faithful
479
+ standalone port" claim; now states shared vs different (scalar energy vs
480
+ oscillators, lanes vs tunnels, passes vs dt=0.02, native 0.82/0.45) and
481
+ records the CSAT boundary theorem (global decay/diffusion modulation is
482
+ rank-preserving, arg-max invariant — readout-affecting mechanisms must
483
+ couple per-node; settle physics stays frozen).
484
+ - BUGS CAUGHT BY THE NEW TESTS: add_primitive double-padded prim_meta
485
+ (every primitive kind shifted off by one; contrapositive and induction
486
+ never fired); Engine never installed the default rule set (forward
487
+ chaining was a no-op); momentum envelope out-of-bounds read on pass 0
488
+ (segfault); CME fingerprint test used an unstemmed token (unordered_map::at).
489
+ - TESTS: test_reason (18 checks: primitives, proofs, verifier, retraction,
490
+ discovery, thinker index, contradiction guard, the engine bridge,
491
+ idempotent reload) + test_v39_gates (26 checks: replay contract,
492
+ per-gate defer reasons, determinism, ORD1 roundtrip, fingerprint
493
+ half-dose, sentinel/pro-con interning). Full suite + readout-silence +
494
+ jas-test + make ci green; bench bit-identical to the v3.8 record.
495
+ - MEASURED: think30 baseline 0.467 -> thinking 0.600 -> multivector 0.633
496
+ -> v3.9 stack 0.700 (21/30; thinking flags + --wavefront-gate --cem-plan
497
+ on a --distvec --multi-vector fabric). Honest negatives measured and
498
+ documented: momentum alone 0.533, coherence/vght alone 0.567, learn-side
499
+ flags combined 0.433 at demo scale (corpus-scale features), cem alone
500
+ neutral 0.600. JEV axes unchanged (95.5% answered n=44, <=591 us,
501
+ ECE 0.131, OOD defer 1.0) + new axes JEV lacks: proof traces, discovery,
502
+ thinker index, .axioms knowledge format.
503
+
504
+ ## v3.8.0 — physics-native thinking (no token prediction, no ML, physics frozen)
505
+
506
+ Four opt-in mechanisms + the v3.7.1 scaling fix. Spec: deepen the field's
507
+ thinking without token prediction; SI core untouched; bit-identical replay on
508
+ default flags (bench verified against the v3.7 record).
509
+
510
+ - v3.7.1 DISTVEC SCALING FIX: measured O(n^1.9) build (76 s @ 5,595 nodes,
511
+ 156 s @ 7,985, ~15 h extrapolated @ 94,773) root-caused to the exact
512
+ neighbour scan (O(n^2*k), cap 8000 -> 2000), strided row-major MGS with
513
+ ~840k OpenMP regions per call (-> column-major blocked BCGS2), and the
514
+ subspace/Ritz kernels (-> contiguous cm passes, cached init hashes).
515
+ Measured: 17.1 -> 7.2 s @ 5,107 nodes; 95.4 s @ 40,850; ~15 h -> ~5 min
516
+ extrapolated at the generalist size. Determinism md5-verified.
517
+ - TASK 1 ADAPTIVE DEPTH (`--adaptive-depth`, `--adaptive-max-k`): difficulty
518
+ = unknown-token fraction + lane isolation, k = base + round(d*max_extra)
519
+ (8..16 defaults), deterministic, ratchet-guarded, mirrored in
520
+ harvest_rows; disclosed as difficulty/k_settle_used/k_settle_base.
521
+ - TASK 2 MULTI-VECTOR (`--multi-vector`, `--multi-vector-k`): K=8 spectral
522
+ channel gates from the distvec axes (lane flow scaled by
523
+ exp(-(u_k(a)-u_k(b))^2/2s^2)), frozen physics per channel, readout on the
524
+ mean superposed field; honest no-op without --distvec; dead axes skipped.
525
+ - TASK 3 CAUSAL SIGNATURES (`--causal-lanes`): cause?>effect and
526
+ means!>goal pair nodes from a deterministic connective scan (stemmed
527
+ forms), interned/df-noted/bound like the bigrams, injected in
528
+ decide/harvest/perturb at kCausalDose=0.5; replay no-op on old fabrics.
529
+ - TASK 4 ENERGY SELF-VERIFICATION: settle trace (passes, final/initial
530
+ energy, relative motion rate) always in the decide usage; opt-in
531
+ `--self-verify` defers choice answers measured on fields still moving
532
+ above the floor (default 0.25, measured settled baseline 0.189-0.212),
533
+ reason `unconverged_field`.
534
+ - TESTS: test_thinking group (adaptive depth incl. ratchet guard,
535
+ self-verify gate both sides, multi-vector no-op/determinism/effect,
536
+ causal emission directions + fabric interning + replay both ways); full
537
+ suite green; readout-silence ALL PASS; jas-test ALL PASS; bench
538
+ bit-identical (tickets 1.000/1.000 defer 0.063, game defer 0.333, guard
539
+ 0.778, OOD defer 1.0 x3, deterministic x3).
540
+ - MEASURED: think30 suite (`make think30` -> data/think30_tables.json) —
541
+ 30 tests, 6 categories x 5: baseline 0.467 (14/30) -> thinking flags
542
+ 0.600 (18/30) -> +multi-vector 0.633 (19/30). Honesty category 0/5 ->
543
+ 5/5 (noise answers on near-vocabulary OOD states now defer); chains
544
+ 0/5 -> 3/5. Causal categories showed no additional delta at demo scale
545
+ (bigram lanes already carry the signal; disclosed honestly).
546
+
547
+ ## v3.6.0 — the fabric-construction papers land + the JEV head-to-head
548
+
549
+ Implements the top of v3.5's paper port order on the v3.5.0 tree (settle
550
+ physics frozen; old fabrics replay bit-identically):
551
+
552
+ - ORDERED BIGRAM LANES (MRS SS4b.1-4b.2 measured 7/7; CMD SS2.5; CPSB; HTR
553
+ arrival-order): learn interns adjacent token pairs ("w1~w2") and binds them
554
+ to the outcome anchors; decide injects the state's bigram nodes at
555
+ kBigramDose=0.5 of the state dose, mirrored bit-exactly in harvest_rows.
556
+ Escape from the multiset-invariance theorem (paws 0.500 / xnli 0.333 are
557
+ chance because a token bag cannot encode order). Old fabrics have no
558
+ "w1~w2" nodes so the decide-side block is a no-op on them (replay
559
+ contract, unit-tested both ways). --bigrams on|off (default on).
560
+ - DOCUMENT-FREQUENCY RARITY WEIGHTING (CMD SS2.2 log(N/(1+df)); MIMS SS6
561
+ fan-out): substrate df table (one note per (lesson, node), persisted in a
562
+ magic-guarded 'IDF5' tail) + hebbian_lesson scales STATE-side bind weights
563
+ by log1p(L/(1+df))/log1p(L) in (0,1]. No stopword list; one counted
564
+ formula. Fabrics without the tail reproduce v3.5 weights (factor 1.0).
565
+ - PERTURBATION-CONTRAST HONESTY CHECK (BED SS8, opt-in --perturb-check):
566
+ decide() additionally settles a structure-broken copy of the state (same
567
+ token multiset, adjacent pairs transposed, deterministic); when the broken
568
+ state's margin matches the real one the readout was bag-carried, and
569
+ choice questions defer with reason "perturbation_tie". Field snapshotted
570
+ and restored — the readout measures exactly what an unchecked decide()
571
+ measures. Usage discloses perturb_margin_real / perturb_margin_broken.
572
+ - MEASURED (train split, in-sample; heldout n=6/0/2): tickets choice
573
+ 0.875 -> 1.000 (16/16, defer 0), score 1.000 defer 0.063 unchanged; game
574
+ choice_defer_rate 1.0 -> 0.333 with 4/4 answered correct; guard 0.778
575
+ unchanged; ood_defer_rate 1.0 x3. test_fabric36: 22 new checks (bigram
576
+ lay/inject, multiset-invariance pinned bit-equal on a bag fabric and
577
+ broken on an ordered one, IDF same-token weaker-lane isolation, IDF5
578
+ roundtrip, old-fabric replay bit-identity, perturbation defer/preserve).
579
+ Full unit suite, readout-silence, jas gates ALL PASS.
580
+ - BUGFIX (fresh clones): `make ci` failed because its router/ablation gates
581
+ need model-router16 / model-b77-sem / data/bank77_cal.jsonl — all
582
+ gitignored. Those gates now SKIP loudly when absent; core gates (unit
583
+ tests, readout-silence, jas — now wired explicitly) always run.
584
+ - JEV HEAD-TO-HEAD (tools/jev_bench.py, make jev-compare ->
585
+ build/jev_comparison.json): JEV AI (TypeSafe AI, Sept 2026) is the closed
586
+ "System One" decision model on the same API shape. Measured on JEV's
587
+ published axes: workflow accuracy 95.5% (n=44 answered, train split) vs
588
+ 67.8% published; latency <= 474 us vs 70-500 ms published; $0 local vs
589
+ $0.042/M input; plus the axes JEV does not publish — ECE (mean 0.131),
590
+ honest defer with reasons (OOD 100%), bit-reproducibility, evidence JSON.
591
+ Every syfox number measured by core/bench.hpp in this tree; every JEV
592
+ number is their published self-reported figure (source cited in JSON).
593
+ - README v3.6 section + boundary updates (subject-object scope-escape by
594
+ bigram lanes; temporal adjacency; perturbation defer). VERSION 3.5.0 ->
595
+ 3.6.0.
596
+
597
+ ## v3.5.0 — JAS: the J-A-S cycle, the impossibility register, the arithmetic oracle
598
+
599
+ Ported from research-paper/jas.md + the central paper's substrate/thinker
600
+ division of labour; the SI settle physics stays frozen and decide() is
601
+ bit-identical (bench verified). Three additive CLI commands, one new test
602
+ group, one new CI gate.
603
+
604
+ - `core/jas.hpp` — the cycle: E labeled rows -> J the jump (counting leaps
605
+ to a universal STRONGER than the evidence; axioms ranked
606
+ confidence/support/token, deterministic) -> A->S deduction per holdout
607
+ row -> experiment (oracle = observed label) -> refutation -> revision
608
+ under a structural restriction (T AND U, fit on TRAIN only, never on its
609
+ own counterexamples) -> round 2 on fresh rows. Verdicts:
610
+ SURVIVES | REFUTED_AND_REVISED_SURVIVES_HELDOUT |
611
+ REFUTED_AND_REVISION_ALSO_REFUTED | REFUTED_AND_REVISION_UNTESTED |
612
+ REFUTED_IN_ROUND2_REVISE_NEXT_CYCLE | NO_TESTABLE_AXIOMS. Refutations
613
+ append to <model>/refuted.axioms (with the counterexample row);
614
+ survivors to <model>/verified.axioms (provenance INDUCED). The frozen
615
+ field is scored on the same rows as the disclosed "relevance heuristic"
616
+ column. Per-row experiment disclosure in JSON (predicted/actual/
617
+ CONSISTENT|REFUTES|NO_PREDICTION, conflicts flagged).
618
+ - `syfox register [--model M] [--text]` — the impossibility register:
619
+ five architectural boundaries seeded with warrants
620
+ (2 THEOREM / 2 INDUCED / 1 DERIVED), each with parent + status + bypass;
621
+ two THEOREM claims are SCOPE-ESCAPED (arithmetic -> calc oracle;
622
+ subject-object -> ordered/typed lanes); persists
623
+ <model>/impossibility.json.
624
+ - `core/calc.hpp` + `syfox calc --expr ... [--compile]` — the arithmetic
625
+ derivation oracle: 6 primitives, one recursive-descent grammar, a
626
+ verifier that rejects (1/0 errors), overflow-guarded exact integer path,
627
+ word-problem mapping (times->*, plus->+, ...). --compile EMITS a C++
628
+ translation unit, compiles with g++, runs it, discloses
629
+ agreement + provenance established_by_experiment. MEASURED: 17*23=391
630
+ (g++ agrees), 2+3*4=14, (2+3)^2/5=5, 2^10=1024, word problem -> 396,
631
+ 1/0 rejected. The field never computes — the theorem stands, the
632
+ capability escaped its scope.
633
+ - Tests: unit group test_jas (oracle exactness, detection, register
634
+ invariants, full cycle arc incl. refutation->revision->convergence,
635
+ survival-is-not-proof); CI gate tests/jas_test.sh (make jas-test, wired
636
+ into make ci; pins oracle values, register shape, verdict space,
637
+ byte-determinism of cycle JSON x2); demo fabric data/jas_cycle_demo.jsonl.
638
+ - README: v3.5 section + "Why the 24-domain accuracy is low" table mapping
639
+ each measured failure shape to its fabric-construction root cause and the
640
+ paper that unlocks the fix (MRS/CPSB/RADE ordered+typed lanes, CMD IDF
641
+ weights, rbg+graph_fisher Fisher-gated bridge lanes, BED perturbation
642
+ negatives, l9 transitive pre-derivation); Architectural boundaries now
643
+ cross-reference the register.
644
+ - MEASURED regression: bench bit-identical to v3.4.0 (tickets choice
645
+ 0.875 / score 1.000 defer 0.063; guard 0.778; game all-deferred
646
+ choice_defer_rate 1.0; ood_defer_rate 1.0; deterministic x3). Full unit
647
+ suite passes. VERSION 3.4.0 -> 3.5.0
648
+
649
+ ## v3.4.0 — honest defer for ties, multi-hop readout walk, question-context gate
650
+
651
+ Three decision-layer mechanisms; the SI substrate physics (decay 0.82,
652
+ diffusion 0.45, K_settle 8, silence floors) stays frozen. Everything is
653
+ measured, deterministic, and disclosed.
654
+
655
+ **HONEST DEFER FOR NEAR-TIES (engine default ON, margin 0.05).** When the
656
+ top two probabilities are closer than the margin the readout does not carry
657
+ a decision: the answer defers with `reason: ambiguous_tie` instead of
658
+ shipping a coin-flip as a confident label. Engine-level (members
659
+ `defer_margin_`, `set_defer_margin`), so CLI, C API, HTTP bridge and bench
660
+ share ONE behavior — the v3.1 CLI post-pass (`low_margin`, default OFF) is
661
+ removed; `--defer-margin P` now sets the engine knob and `--no-defer`
662
+ restores the v3.3 answer-always behavior (both verified end-to-end on a
663
+ measured gap-0.186 fabric: default answers, `--defer-margin 0.25` defers
664
+ `ambiguous_tie`, `--no-defer` overrides). Score questions defer on the same
665
+ margin over level probabilities. MEASURED bench impact (train-split,
666
+ v3.3.1 -> v3.4.0): tickets choice 0.875 unchanged (defer 0), score 0.938 ->
667
+ 1.000 with defer 0.063 (the one wrong score row was a near-tie, now honestly
668
+ deferred); guard 0.778 unchanged (defer 0); the 6-row game toy fabric
669
+ discloses as all-deferred (`choice_defer_rate` 1.0 — its decisions sit at
670
+ mean margin 0.023, i.e. they never carried signal; v3.3's 1.000 was
671
+ in-sample noise-picking that happened to be right). Bench JSON gained
672
+ `choice_defer_rate`/`score_defer_rate` (accuracy over ANSWERED questions,
673
+ defers counted separately — selective accuracy reads honestly). Unit tests:
674
+ 5 legacy groups pin `set_defer_margin(0)` (bengali argmax, M3 contradiction
675
+ evidence, M3 ledger persistence, hierarchy, question-gate readout contract),
676
+ new group `test_defer_ties` pins the defer (near-tie defers with
677
+ probabilities intact, decisive row answers, margin 0 answers the same
678
+ near-tie, score flavor defers).
679
+
680
+ **MULTI-HOP READOUT WALK (opt-in, `--hops N`, default 1 = legacy).**
681
+ `Substrate::set_hop_depth` (clamped 1..8): depths > 1 walk lanes BFS-style
682
+ from each probe anchor up to N levels with per-hop damping
683
+ `hop_coupling/sqrt(hop+1)` (hop 1 x0.707 ... hop 4 x0.447), levels collected
684
+ in ascending NodeId order (std::map), width-capped at 64 nodes per level
685
+ (`kHopWidthCap`), never revisited — deterministic and bounded. Default
686
+ depth 1 keeps the legacy single-hop code path BIT-IDENTICAL (test-enforced:
687
+ default == explicit 1). MEASURED on chain probes (2-hop already answers at
688
+ N=1 — diffusion carries alarm->lights at probs 0.314 top, unchanged at N=4;
689
+ 3-hop sparrow->animal target 0.1061 -> 0.1097; 4-hop relay far target echo
690
+ visible at 0.210 at N=4) — damped lanes keep far targets near-tied, so the
691
+ reported conf-0.019 noise answers now surface as honest `ambiguous_tie`
692
+ deferrals instead. Probe suite extended with the Test 18 (sparrow->bird->
693
+ animal) and Test 21 (alpha..echo 4-hop relay) analogs + hops configs;
694
+ unit group `test_multi_hop` pins default/clamp/bit-identity/determinism.
695
+
696
+ **QUESTION-CONTEXT GATE (opt-in, `--ctx-gate`, `--ctx-alpha F`).** Two-stage
697
+ settle: stage 1 settles the question's own tokens (instructions + criteria
698
+ descriptions, NO labels) into a context field; stage 2 re-settles the state
699
+ (prime + state + bridges, unchanged) and `Substrate::blend_field` composes
700
+ `e = (1-alpha)*state + alpha*context` (alpha default 0.5, clamped [0,1]).
701
+ Two ALREADY-SETTLED fields composed at the decision layer — settle() physics
702
+ untouched, deterministic, disclosed as `usage.ctx_gate`/`usage.ctx_alpha`.
703
+ MEASURED on the probe fabric: who-found answer holds (Tariq), confidence
704
+ 0.056 -> 0.061; OOD submarine probe still abstains (`unknown_candidates`);
705
+ latest-temperature holds with a disclosed confidence tradeoff (0.007 ->
706
+ 0.003). Unit group `test_ctx_gate` pins OFF-unchanged / ON-disclosure /
707
+ answer-holds / determinism / OOD-preserved.
708
+
709
+ **Surface.** CLI `--defer-margin P` (engine knob), `--no-defer`, `--hops N`
710
+ (1..8), `--ctx-gate`, `--ctx-alpha F`; C API decide opts `defer_margin`,
711
+ `no_defer`, `hops`, `ctx_gate`, `ctx_alpha`; bridge opts docs; usage JSON
712
+ `ctx_gate`/`ctx_alpha` disclosure. README: v3.4 section + "Architectural
713
+ boundaries (System-2 limits)" honest list. Verified: full unit suite passes
714
+ (incl. 3 new groups), `make readout-silence` ALL PASS, bench deterministic
715
+ x3 with OOD defer 1.0 x3. VERSION 3.3.1 -> 3.4.0.
716
+
717
+ ## v3.3.1 — readout-silence threshold made explicit (BLOCKER fix)
718
+
719
+ **The reported false defer, root-caused on the shipped tree.** The report
720
+ said `{Tariq, Salma}` false-defers with `unknown_candidates` because the
721
+ readout threshold (~0.35) sits above a valid candidate's energy (0.301).
722
+ On the shipped v3.3.0 code the check is an implicit `> 0` — there is no
723
+ 0.35 constant — and the case does NOT reproduce: on the QA probe fabric
724
+ (`model-reasoning-probe`), Test 2 `{Tariq, Salma}` ANSWERS `Tariq`
725
+ (max candidate 0.8759, Salma 0.4811, settled field 2.4594, all measured
726
+ with `SYFOX_DEBUG_READOUT=1`). The reported threshold matches a local
727
+ mid-v3.4 worktree state, not this tree. The hardening below landed
728
+ regardless, because the implicit `> 0` form has a real defect: a best
729
+ candidate carrying dust-level diffusion carryover (`0 < e < 0.01`)
730
+ was ANSWERED — a pick by noise — instead of deferred.
731
+
732
+ **Fix (Option B, absolute floor).** `kUnknownCandidateFloor = 0.01f` —
733
+ a named, documented, ABSOLUTE constant in `core/syfox.hpp`: defer with
734
+ `reason: unknown_candidates` when the BEST candidate's readout energy is
735
+ below 0.01. Deliberately absolute, not relative-to-field: a bright field
736
+ sitting entirely on non-candidate nodes must defer, and a valid candidate
737
+ on a dim field must answer. Measured guardrails: probe-fabric candidates
738
+ 0.19–0.88 all answer (0.19 measured WITHOUT energy-norm — do not raise
739
+ the floor above 0.10); dark candidates 0.0000 still defer; the lit-field/
740
+ dark-candidates OOD shape (`purple`/`submarine`) still defers with
741
+ `unknown_candidates`; a fully dark field (`xyz abc def`) defers at the
742
+ decide level with `unknown_vocabulary` (floor 0.05) before readout.
743
+
744
+ **Debug visibility.** `SYFOX_DEBUG_READOUT=1` prints, on stderr: the
745
+ decide-level field (`settled_energy`, `silence_floor`) and, per question,
746
+ `max_candidate` + the active threshold + every candidate energy — a false
747
+ defer is now diagnosable from one run.
748
+
749
+ **Regression gate.** `tests/readout_silence_test.sh` pins 7 checks
750
+ (2-candidate and 3-candidate valid cases answer; lowercase answers; dim
751
+ energy-norm-OFF case answers; dark field defers with the decide-level
752
+ reason; lit-field/dark-candidates defers with the readout-level reason).
753
+ New `make readout-silence` target, wired into `make ci` (the script
754
+ builds its own probe fabric from the committed
755
+ `data/reasoning_probe_lessons.jsonl`). Verified: unit suite all pass;
756
+ `make bench` bit-identical to the pre-fix snapshot (tickets 0.875/0.938,
757
+ game 1.000, guard 0.778, `ood_defer_rate` 1.0 on all three,
758
+ `deterministic` true on all three). README honest-silence section now
759
+ documents both silence layers and their floors. VERSION 3.3.0 -> 3.3.1.
760
+
761
+ ## v3.3.0 — question-conditioned readout, tie disclosure, readout silence
762
+
763
+ **The `--evidence` "empty model" bug — root-caused, already cured, better
764
+ hint.** The reported symptom (lanes 0, vocabulary 0, calibrated false, all
765
+ `unknown_vocabulary` with `--evidence`, healthy without) is reproduced
766
+ exactly on a v3.2.0 build with `decide --evidence --state ... --questions ...`
767
+ and NO `--model`: the harness that emitted the flag treated it as
768
+ value-taking and swallowed the following `--model` token, and v3.2.0's
769
+ silent load then decided on an empty default fabric — with the evidence
770
+ block in the output, which made the flag look guilty. The flag itself is a
771
+ plain boolean in both versions. v3.2.1's loud load failure already exits
772
+ with `syfox: decide model "model": cannot read model/substrate.bin`;
773
+ v3.3 adds a stderr hint when the failed dir is the default `model` value,
774
+ naming the swallow-the-argument failure pattern explicitly.
775
+
776
+ **Question-conditioned readout (opt-in) — ported from the original
777
+ Synthetic-Intelligence repo.** There, EVERY token of the turn drove the
778
+ activation field (`si_main.cpp`: `for (int id : matched)
779
+ physics.drive(id, 3.0f, 6.0f, 20)`) — the question was never a bystander.
780
+ SyFox's contract keeps state and question separate, and the readout only
781
+ measured state energy: the question's instructions gated nothing, so the
782
+ salient state noun beat the question-relevant entity ("Who found the
783
+ radio?" → `radio` over `Tariq`). The portable form gates the READOUT:
784
+ question tokens that are NEW relative to the state (the `who` in "Who found
785
+ the radio?") distribute lane mass over the candidate anchors, and each
786
+ candidate is scaled by its share (`floor + (1-floor) x r/max_r`), floor
787
+ 0.25 default. Read-only over the settled field — same shape as the
788
+ hierarchy gate; disclosed as `question_gate: [tokens]` in every reply
789
+ path. **Measured (tools/reasoning_probes.py, QA-style probe fabric):**
790
+ gate ON doubles the who-found margin (0.056 -> 0.113 at floor 0.10), lifts
791
+ the latest-temperature confidence 14x (0.008 -> 0.117), and never flips a
792
+ correct answer off. **Measured regression that sets the default:** on
793
+ tickets-cal the gate costs 5.3 points (0.9533 -> 0.9000 — "which team"
794
+ lanes mislead), so the gate ships OPT-IN exactly like the M1 energy-norm:
795
+ `--question-gate` / `--question-gate-floor F` / opts `question_gate`,
796
+ `question_gate_floor`.
797
+
798
+ **Exact-tie disclosure + readout silence.** The tie-break truth (measured):
799
+ criteria iterate in `std::map` key order and `max_element` keeps the first
800
+ max, so exact ties go to the alphabetically-first candidate — the reported
801
+ "Salma wins (last position)" was S < T, not a `>=` bug. Two structural
802
+ tie-breakers were measured along the way: the v3.2 sem_hop term
803
+ deterministically separates differently-spelled labels (aaa/bbb with
804
+ IDENTICAL lane sums 0.679428518 still end at 0.500078 vs 0.499921 through
805
+ their different trigram vectors), and per-lesson lane decay makes
806
+ same-structure candidates from separate lessons near-ties rather than
807
+ exact ones. What was missing was HONESTY about ties: every reply now sets
808
+ `tied: true` when the top two probabilities are equal (near-ties remain the
809
+ `--defer-margin` knob's business). And when the readout measures ZERO
810
+ energy on every candidate, decide now defers with
811
+ `reason: "unknown_candidates"` instead of answering a uniform distribution
812
+ by criteria order — the same honest-silence contract the dark-field case
813
+ already followed (measured: the reported unknown-options test answered
814
+ `abc` at 0.344 by noise; it now defers; the OOD "submarine's favorite
815
+ color" probe defers in a fabric that never saw the entities).
816
+
817
+ **The five reported reasoning failure modes — status.** (1) multi-hop
818
+ chaining: diffusion already propagates through learned lanes (the
819
+ alarm→lights probe answers `lights`), 3+ hop composition stays weak;
820
+ (2) temporal ordering: the gate carries `latest`/`after` signal when the
821
+ fabric has those lanes — a training-side fix, tool-supported; (3)
822
+ arithmetic: architectural limit, unchanged in both repos; (4) OOD
823
+ abstention: the all-dark-readout defer fixes the pure case; the
824
+ state-lit-but-unanswerable case (purple 0.472) remains open — the state
825
+ salience override needs a mechanism the gate does not provide; (5)
826
+ subject-object relations: the old repo solves it with TYPED graph edges
827
+ (`Tariq -found-> radio`), which the bag-of-words core deliberately lacks —
828
+ architectural limit, documented.
829
+
830
+ Tools: reasoning_probes.py (probe fabric builder + before/after suite);
831
+ data/v33_reasoning_tables.json archives every number. Tests: 9 new checks
832
+ (gate on/off/disclosure/determinism, tie disclosure, criteria-order pick,
833
+ readout silence). VERSION 3.2.1 -> 3.3.0.
834
+
835
+ ## v3.2.1 — the three paper-blocking bug fixes (ablation kill switches, confidence calibration, router config)
836
+
837
+ **BUG #1 — ablation kill switches were silently inert (root-caused, disclosed,
838
+ test-pinned).** The switches themselves were wired correctly all the way into
839
+ settle() and readout() — on a v3.2 fabric (model-b77-sem) the five paper
840
+ configs produce 4 distinct outputs. The reported byte-identical behavior is
841
+ the replay contract on a PRE-v3.2 fabric: no SEM4 tail => --no-semantics has
842
+ nothing to switch off, no memories.jsonl => --no-retrieval primes nothing, no
843
+ hierarchy.json (or floor 1.0 = the measured-off default) => --no-hierarchy
844
+ moves nothing. Fixes: (1) `decide` now prints a loud stderr note per inert
845
+ switch naming the missing feature and the rebuild path
846
+ (./build/rebuild_sem SRC DST); (2) tools/ablation_suite.py runs the five
847
+ configs over an eval set, reports per-config accuracy/meanC/medC plus an
848
+ answer-signature distinctness count, DISCLOSES inertness, and exits non-zero
849
+ when a v3.2-featured fabric collapses — a null ablation can never reach the
850
+ paper silently again; (3) unit test test_ablation_distinctness builds a fabric
851
+ with all three layers ARMED (hierarchy floor 0.35) and asserts >= 4 distinct
852
+ outputs across default/--no-semantics/--no-retrieval/--no-hierarchy on the
853
+ same input (got 4); (4) the semantic effect is measured-visible (tickets-cal
854
+ accuracy 0.9533 -> 0.9733 with --no-semantics), so no leak-fraction change.
855
+
856
+ **BUG #2 — confidence collapse (96.6% accuracy at mean confidence 0.0016)
857
+ root-caused: the calibration fit ran on a different physics composition and
858
+ dose regime than decide.** Two concrete engine bugs and one data fix:
859
+ (1) harvest_rows() re-implemented injection inline and SKIPPED the retrieval
860
+ priming block — every fabric WITH memories was calibrated on a no-prime field
861
+ while decide primes; the priming prologue is now a shared prime_field() used
862
+ by both paths, bit-identical to the old decide behavior; (2) the mode match:
863
+ calibrate must run under the same --energy-norm regime the fabric is benched
864
+ in (readout gaps are dose-dependent at fixed temperature — the v3.1.2
865
+ measurement of conf 0.002 -> 0.923 under energy-norm is the same lever);
866
+ (3) recalibration of the shipped v3.2 fabrics under the fixed paths.
867
+ Measured after: tickets-big-latin-sem mean confidence 0.0016 -> 0.8736
868
+ (median 0.9835, C|ok 0.898 vs C|bad 0.373, accuracy held 0.9533), easy cases
869
+ 0.636-0.965, b77-sem C|ok/C|bad separation 2.3x with the semantic leak
870
+ verified as signal (accuracy collapses without it). Router16 recalibrated on
871
+ its anchor-worded cal rows (ECE 0.368 -> 0.099, in-distribution mean
872
+ confidence 0.298). Acceptance criteria met: avg >= 0.20 on a well-trained
873
+ domain, >= 0.50 on easy cases. tools/confidence_ablation.py produces the
874
+ per-config ablation table and the diagnosis (retrieval dose and semantic
875
+ leak are NOT the diluters — the stale fit was); tables archived in
876
+ data/v321_bugfix_tables.json.
877
+
878
+ **BUG #3 — `decide --router model-router16` failed with "lacks router.json
879
+ anchors".** Root cause: the router dir didn't exist in the caller's layout
880
+ (the HF package nests fabrics at model/<name>, the syfox repo at
881
+ model-<name>) and a missing substrate loaded SILENTLY as an empty fabric, so
882
+ the failure surfaced as the misleading router.json message. Fixes:
883
+ (1) Substrate::load and Engine::load_model report failure; every CLI command
884
+ now fails loudly naming the model dir it could not read (first learn stays
885
+ tolerant — a fresh fabric is intended there; the ctypes bridge returns a
886
+ null handle so Python raises); (2) resolve_model_dir() tries as-given,
887
+ model/<name>, model-<name>, model/model-<name> — one CLI invocation works in
888
+ both repo layouts, and router.json models mapping targets resolve the same
889
+ way; (3) the router.json error now names the expected file and the builder
890
+ tool; (4) router.json models mapping updated to the v3.2 -sem fabrics;
891
+ (5) router16 rebuilt (sorted save) and recalibrated; (6) `make ci` gate
892
+ includes a route-field assertion (tools/assert_route.py). Verified
893
+ end-to-end: "Why am I missing my refund" -> route rt01 -> model-b77-sem ->
894
+ c00 answered; route distribution across all 16 hidden domain files measured
895
+ (language anchors 12/12 perfect; bank77 rows route to the support anchor
896
+ rt13 11/12 — honest limitation, disclosed; modal agreement 0.663).
897
+
898
+ **PERSISTENCE DETERMINISM (found during the ablation investigation).**
899
+ save() iterated unordered_map members directly, so every load->save cycle
900
+ PERMUTED substrate.bin — measured: three different md5s over two rebuild
901
+ passes on one fabric with an identical lane multiset. Same-lane physics per
902
+ file, but the settled field's floating-point sum order drifted across save
903
+ cycles: model dirs were never byte-stable and an ablation re-run after a
904
+ re-save was silently a different experiment. Fix: every map-backed section
905
+ (out_, derived_gen_, lane_evidence_, lane_ctx_) is written in SORTED key
906
+ order; load rebuilds out_ in file order, so one sorted save converges the
907
+ format and every later roundtrip is bit-identical (rebuild_sem x3:
908
+ md5 06011b36... stable; unit-test enforced). All shipped v3.2 fabrics were
909
+ rebuilt through the converged path.
910
+
911
+ Tools: ablation_suite.py, confidence_ablation.py, router_routes.py,
912
+ assert_route.py, sub_diff.py; Makefile: `ci` gate + rebuild_sem now in
913
+ `all` (the stale-binary trap that masked the first sorted-save attempt).
914
+ Data: v321_bugfix_tables.json (every number above, archived).
915
+
916
+ ## v3.2.0 — the semantic layer (Stages 1-4), retrieval by default, the two-stage physics router, the dedicated bank77 fabric
917
+
918
+ **The semantic field (core, deterministic, no ML).** Every concept node
919
+ carries a 64-dim semantic vector: signed character-trigram hashing of the
920
+ string (Stage 1 "concept frequency encoding" generalizes to a full vector)
921
+ plus two fabric-grounding passes over the Hebbian lanes — meaning diffuses
922
+ along the fabric, nothing is fitted. From the vectors: omega_semantic (fixed
923
+ scalar projection), top-6 resonance edges (cos >= 0.50, persisted in a
924
+ magic-guarded v4 substrate.bin tail), and typed reads (cos >= 0.82
925
+ synonym-grade, >= 0.66 related — Option 2 derived from the vectors rather
926
+ than a hand table). At settle, sources leak sem_coupling 0.12 of their
927
+ post-diffusion energy along resonance edges, distributed by cos x
928
+ frequency-match — ENERGY CONSERVED exactly (test-enforced); readout gains a
929
+ semantic-neighbour term (sem_hop 0.10). **Context-sensitive lanes (Stage
930
+ 2)**: lanes accumulate required/forbidden context words from the lessons
931
+ that laid them; at settle a mismatched lane carries less (forbidden x0.20,
932
+ missing-required x0.60..1.0 by match count, all-1.0 bit-identical to the
933
+ plain path) — contextual disambiguation as dampened coupling, not rules.
934
+ **Stage 3 semantic hierarchy** ships as hierarchy.json (intents/categories/
935
+ floor) and gates intent candidates by stage-1 category energies at readout.
936
+ **Replay contract**: pre-v3.2 files end at the v3 tail, semantics inert,
937
+ bit-for-bit replay (test-enforced); intern() invalidates a stale field
938
+ (segfault fix caught by the M3 ledger test); --no-semantics is the runtime
939
+ kill switch. **Retrieval by default**: a memories.jsonl in the model dir is
940
+ fingerprinted once at load; every decide primes the field with the top-5
941
+ resonating memories' outcomes at dose 0.30 x inject (deterministic,
942
+ disclosed in usage.retrieval); --memories/--retrieval-topk/--retrieval-dose/
943
+ --no-retrieval.
944
+
945
+ **Dedicated bank77 fabric (the v3.0 architecture, now with physics that
946
+ match it).** 9,000 opaque-anchor intent lessons + 9,000 category lessons
947
+ (12 chunks, zero false contradictions after de-colliding the twins),
948
+ 1,648 nodes / 217,729 lanes / 7,728 resonance edges / 141,920 context-signed
949
+ lanes / 256 retrieval memories. Hidden 3,080 rows scored once (energy-norm):
950
+ **0.158 top-1** vs 0.081 (v3.1.0 dedicated+opaque) and 0.023 (77-way in the
951
+ shared giant fabric). Ablations on cal (1,003): --no-semantics 0.039 (the
952
+ semantic field is the jump), retrieval neutral, hierarchy gate
953
+ measured-negative (floor 0.35: 0.111 vs gate-off 0.133; monotone in the
954
+ floor sweep) — the shipped model carries floor 1.0 = gate off, documented.
955
+
956
+ **Two-stage physics router.** tools/router_prepare.py carves a
957
+ router-question-only sample (16 domains x 60 rows) into a dedicated small
958
+ fabric: model-router16, 4,742 nodes, cal 16-way routing **0.444** (chance
959
+ 0.0625), ECE 0.380 -> 0.086. `decide --router model-router16 ...` settles
960
+ the state on the router fabric, then the mapped domain fabric decides
961
+ (router.json anchors/models); the route is disclosed as route:{anchor,
962
+ confidence,top,model}. Bank77 queries route to the dedicated fabric; all
963
+ other domains to the giant fabric.
964
+
965
+ **Zero-shot re-run under v3.2** (docs/ZEROSHOT.md Part 4,
966
+ tools/zeroshot_suite.py, data/zeroshot_v32_results.json): email spam on the
967
+ tickets-only fabric 6/6 plain and 6/6 semantic-rebuild (conf 0.91-0.99);
968
+ SMS spam 5/6 both (the error at conf 0.103 — honest low-conf disclosure);
969
+ snake 1/8 both; tic-tac-toe picks cell 1 at conf 0 — multi-constraint
970
+ composition fails exactly as in Part 1, and the semantic field does not
971
+ fake it (honest scope: it moves trained discrimination, not symbolic
972
+ reasoning).
973
+
974
+ **Surface.** CLI: --router, --no-semantics, --no-retrieval, --no-hierarchy,
975
+ --retrieval-topk, --retrieval-dose, decide --memories FILE; stats reports
976
+ semantics/sem_edges/lane_contexts/retrieval/hierarchy. C API + HTTP bridge:
977
+ set_semantics/set_retrieval/set_retrieval_topk/set_retrieval_dose/
978
+ set_hierarchy + decide_ex opts keys + usage.retrieval + engine info fields.
979
+ Tests: 4 new groups (semantic field determinism/conservation/round-trip/
980
+ pre-v3.2 contract, context lanes learn+gate, retrieval-by-default +
981
+ kill switch + inert-without-memories, hierarchy load+gate). Tools:
982
+ bank77_hier.py, router_prepare.py, zeroshot_suite.py, rebuild_sem.cpp;
983
+ Makefile b77-hier-data/b77-sem/b77-sem-bench/b77-sem-hidden/router-data/
984
+ router16/router16-bench/zeroshot-sem/zeroshot. Core physics (injection,
985
+ settle lane diffusion, Hebbian learning, honest silence) unchanged where
986
+ the semantic tail is absent.
987
+
988
+ ## v3.1.3 — routed-learn isolation bugfix; the 16-domain giant model + syfox-hf packaging
989
+
990
+ **Bugfix (CLI, boundary layer):** `learn --lang auto` taught EVERY script
991
+ family the ENTIRE corpus — the routed loop iterated all rows instead of the
992
+ family's rows, so each per-script substrate (`<model>-<slug>`) was a full
993
+ copy of everything and the "one fabric per script" isolation contract was
994
+ broken since v2.2. Fixed: families now teach only their own rows (epochs
995
+ applied per family). All tests pass; multilingual fabrics should be
996
+ retrained — the giant model below was trained post-fix, and its
997
+ bengali/devanagari/cyrillic substrates (546-680 nodes) answer their
998
+ held-out tickets at 0.920-0.959 with a trivially perfect in-substrate
999
+ router.
1000
+
1001
+ **The giant model** (built in the sandbox, packaged in the separate
1002
+ `syfox-hf` repo): 16 domains — bank77 (9k), UCI SMS (3.9k), the 6 data/big
1003
+ corpora (27.2k), plus 8 newly downloaded real HF datasets (CLINC-150,
1004
+ enron_spam, emotion, Davidson hate, ag_news, amazon_polarity, dbpedia_14,
1005
+ boolq) — 76,142 train rows / 152,284 lessons per epoch, 278 globally unique
1006
+ opaque anchors, empty instructions everywhere, round-robin domain
1007
+ interleave, mined top-10 criteria for the new domains, per-script
1008
+ calibration. One interleaved pass: giant-latin 43,420 nodes / 1,905,170
1009
+ lanes. Hidden (scored once, energy-norm on): tickets_en 0.904, sms 0.752,
1010
+ enron 0.752, hate 0.653, agnews 0.604, polarity 0.571, dbpedia 0.475, boolq
1011
+ 0.531 (majority-level), bank77 0.023 (77-way collapses in a shared fabric);
1012
+ bn 0.943 / hi 0.920 / ru 0.959 on their own substrates. Router measured
1013
+ under THREE conditions: informed 0.432 (weighted, the bench condition),
1014
+ blind 0.400 hidden (23,528 rows) / 0.399 cal, all-questions 0.399 cal —
1015
+ asking everything dilutes the anchoring instead of recovering it. Router
1016
+ wording sweep (cal only): short4 0.426 > abstract 0.208 > mid8 0.164 >
1017
+ rich12 0.079 — richer specific criteria HARVEST worse (PROBING.md
1018
+ mechanism). Tooling: tools/hf_fetch.py (cached parquet fetcher),
1019
+ tools/giant_prepare.py (corpus builder with the three failure-mode fixes),
1020
+ tools/giant_bench.py (router+class+e2e per-row bench, slim-format aware),
1021
+ tools/router_sweep.py, tools/wrapper_condition_experiment.py; Makefile
1022
+ targets giant-fetch/-prepare/-chunks. data/giant bulk gitignored
1023
+ (schemas/probes/MANIFEST committed).
1024
+
1025
+ ## v3.1.2 — zero-shot probe reports archived; the runtime-flag mechanism measured
1026
+
1027
+ The model-xl zero-shot experiments (Snake 8-scenario suite + the A–E flag
1028
+ experiment, Tic-Tac-Toe symbolic composition, file-organizer routing) are
1029
+ archived in `docs/ZEROSHOT.md`, and the report's central observation —
1030
+ winner flips at constant settled energy, Miller-window confidence 0.805 on
1031
+ an illegal move — is now mechanism-explained in code and re-measured on
1032
+ repo fabrics with real held-out rows (`tools/flag_probe_experiment.py`,
1033
+ 2,638 hidden rows, trained schema, deterministic):
1034
+
1035
+ - **Source modes don't touch the field.** With the injection dose held
1036
+ constant, settled energy is bit-identical across salience/miller configs
1037
+ (spread ≤ 0.001 on 99.5% / 99.8% of rows) because a settle pass conserves
1038
+ energy up to uniform decay — source gating only decides which nodes
1039
+ propagate ("gated nodes keep their energy (readout-visible) but stay
1040
+ silent as sources", `si_substrate.hpp settle()`). The same invariance is
1041
+ why the model-xl A–E run reported 83.928 in every amplified config.
1042
+ - **Energy-norm DOES change the field** (injection dose): 0% of rows keep
1043
+ their settled energy vs baseline. On trained schemas it is pure
1044
+ amplification — tickets-big flips 0.1% of winners at identical 0.971
1045
+ accuracy while margins rise 0.0355 → 0.9430 and confidence 0.002 → 0.923;
1046
+ baseline deferrals 35 → 0 (the documented M1 purpose).
1047
+ - **Flags are diagnostic instruments, not defaults.** Salience gating is
1048
+ fabric-dependent: −4.1 points on tickets-big (0.971 → 0.930), +19 points
1049
+ on sms-natural (0.160 → 0.360) where the full-source readout is dominated
1050
+ by harvest noise. High-confidence-wrong rows (conf ≥ 0.5 while wrong):
1051
+ 0 at baseline on both fabrics → 15–86 under amplified configs.
1052
+ - Zero-shot and trained-domain results stay in separate buckets; the
1053
+ interpretation rules (confidence = concentration, never correctness;
1054
+ `--defer-margin` for honest ties) are in ZEROSHOT.md §Part 3 and
1055
+ PROBING.md §6.
1056
+
1057
+ Also: the four SMS probe data files (`data/sms_train.jsonl`,
1058
+ `sms_hidden_match/reworded/empty.jsonl`) are now committed so the v3.1.1
1059
+ probe experiment and this flag experiment reproduce from a fresh clone.
1060
+
1061
+ ## v3.1.1 — the probe experiment: criteria wording is a first-class input; honest ties via --defer-margin
1062
+
1063
+ The model-xl diagnostic (handcrafted Bangla/English/SMS probes tying at
1064
+ ~0.50/0.50 with confidence 0 and deferred:false) reproduced and explained on
1065
+ real data. Experiment: one fabric trained on real UCI SMS spam (5,574 rows,
1066
+ stratified 70/15/15), the SAME hidden rows decided under three criteria
1067
+ wordings:
1068
+
1069
+ | decide-side criteria | hidden top-1 | mean margin |
1070
+ |---|---|---|
1071
+ | matched (trained schema) | 0.160 | 0.444 |
1072
+ | reworded (handcrafted, abstract) | 0.842 | 0.043 |
1073
+ | empty (labels only) | 0.422 | 0.017 |
1074
+
1075
+ Findings (all measured, `tools/sms_probe_experiment.py`):
1076
+ - The criteria text at decide selects which nodes the question probes.
1077
+ Matched-trained criteria can HURT: their state-overlapping words harvest
1078
+ direct hits (anchor-hub noise) and land worse than the majority baseline,
1079
+ with huge misleading margins. Abstract reworded criteria suppress the
1080
+ harvest and let the anchor one-hop (class-typicality) carry the decision —
1081
+ at tie-sized margins. Same fabric: accuracy swings 0.16 <-> 0.84.
1082
+ - The model-xl probe pattern (near-tied probabilities, confidence 0,
1083
+ deferred:false) is the reworded/empty condition of this mechanism: the
1084
+ probes were measuring a DIFFERENT system than the benchmark number
1085
+ (SMS 0.937 was measured under the trained schema). Handcrafted probes
1086
+ bound; held-out runs conclude. Methodology written up in docs/PROBING.md.
1087
+ - Decision-layer honesty: new `decide --defer-margin P` (and server
1088
+ `options.defer_margin`) discloses p1-p2 below P as `deferred: true,
1089
+ reason: "low_margin"` instead of a confident-looking label on tied
1090
+ candidates. The substrate still decides; physics untouched. Measured live:
1091
+ a 0.509/0.491 tie now returns a deferral, not a spam label.
1092
+ - Packaging note (from the model-xl diagnostic): a fresh checkout has no
1093
+ build/ directory (gitignored) — run `make all` first; that also produces
1094
+ libsyfox_core.so for the HTTP server.
1095
+
1096
+ ## v3.1.0 — banking77: real 77-way benchmark, the manual error anatomy, and the hub-pollution fixes
1097
+
1098
+ Real dataset, not synthetic: PolyAI banking77 — 10,003 official train rows /
1099
+ 3,080 official test rows / 77 intents (`tools/bank77_prepare.py` pulls the
1100
+ CSVs). The official test split becomes the hidden test (firewall-enforced
1101
+ naming); 10% of train is carved stratified (seed 77) for calibration.
1102
+
1103
+ ### Measured fix ladder (selection on cal ONLY, hidden scored once)
1104
+ | config change | cal top-1 |
1105
+ |---|---|
1106
+ | naive: generic criteria, instructions inline, natural labels | 0.029 |
1107
+ | + mined per-class criteria (log-ratio, unigrams+bigrams, top-20) | (baseline run) |
1108
+ | + empty instructions (learn folds instructions into the state side; identical per-row instructions are hub pollution — they are never injected at decide) | 0.041 |
1109
+ | + opaque anchors `c00..c76` (natural labels like `card_arrival` tokenize into shared hubs; "card" spans many classes. Opaque ids give every class a DEDICATED anchor node) | 0.073 |
1110
+ | + consolidation epochs 3 (reproduces the model-xl recipe on the clean schema) | 0.081–0.085 |
1111
+ | + top-20 terms + anchor arbitration (flat top-5 re-ranked by bare-anchor readout — product of two readout views) | **0.091** |
1112
+
1113
+ HIDDEN (official test, 3,080 rows, scored once): **top-1 0.081, top-3 0.221,
1114
+ top-5 0.326** vs chance 0.013 — 6.3× chance at top-1, 25× at top-5.
1115
+ No cal overfit: cal predicted 0.091, hidden gave 0.081.
1116
+
1117
+ ### What the manual benchmark exposed (the point of doing it by hand)
1118
+ - Without `--energy-norm`, corpus-scale masses silence the readout: all 77
1119
+ options sit at exactly 1/77 and argmax degrades to alphabetical order.
1120
+ The M1 measurement gain is MANDATORY at this scale (0% -> 100% coverage).
1121
+ - The error anatomy (`tools/bank77_analysis.py`): gold sits at ranks 2-20 for
1122
+ ~60% of rows; margin-when-correct is ~2x margin-when-wrong; a single class
1123
+ (`wrong_exchange_rate_for_cash_withdrawal`) absorbs wrong predictions from
1124
+ every other class via hub-word bigrams ("cash abroad" is class-pure as a
1125
+ bigram while "cash" is global as a word — the readout tokens are words).
1126
+ - Measured NEGATIVE (kept off, documented): stopword filtering (0.036 —
1127
+ verb+stop combos like "was taken" are the signal), term-level purity caps
1128
+ (0.035), word-level purity caps (0.031-0.053), first-token hierarchical
1129
+ two-stage (0.051), shorter criteria under the clean schema, unigram-only
1130
+ criteria (0.045-0.052). The hub phrases are simultaneously the noise and
1131
+ the signal.
1132
+ - Honest gap note: 0.081 hidden here is not model-xl's 0.284 — model-xl is a
1133
+ 14-domain consolidated fabric (45,892 nodes / 1.9M lanes) whose mining
1134
+ recipe this sandbox rebuild does not replicate. What transfers is the
1135
+ SCHEMA (opaque anchors + empty instructions + mined criteria + energy-norm)
1136
+ and the measurement tooling: point `tools/bank77_analysis.py --model
1137
+ model-xl` at any hidden file to re-run the same anatomy there.
1138
+
1139
+ ### Infrastructure
1140
+ - `tools/bank77_prepare.py`: CSV -> train/cal/hidden JSONL (firewall naming),
1141
+ stratified carve, deterministic criteria mining, SHA-256 manifest.
1142
+ - `tools/bank77_analysis.py`: the manual benchmark — per-row probabilities
1143
+ through the ctypes bridge; top-1/3/5, gold-rank bands, margin and
1144
+ confidence-when-wrong, worst confusion pairs, per-class accuracy, deferral
1145
+ anatomy, per-row JSONL dump. `--arbitrate` = anchor product-of-experts.
1146
+ - Makefile: `bank77` (prepare + learn + cal-bench), `bank77-report` (hidden
1147
+ run). Bulk splits are gitignored (167 MB inline criteria); the tool
1148
+ regenerates them deterministically.
1149
+
1150
+ ## v3.0.0 — milestones 1–5: scale discipline, distinct experience, provenance, adversarial suite, multicore
1151
+
1152
+ Every claim below is a number from a real run on this repo (commands in the
1153
+ Makefile; raw JSON in `build/`). Nothing is projected or estimated.
1154
+
1155
+ ### Milestone 1 — large held-out datasets, hidden-test firewall
1156
+ - `tools/gen_corpus.py` (+`tools/corpus_pools.py`): deterministic generator,
1157
+ seed 20260927. Per domain — tickets_en 12,000 rows (8,400/1,800/1,800),
1158
+ game 8,000 (5,600/1,200/1,200), guard 8,000 (5,600/1,200/1,200); Bengali /
1159
+ Hindi / Russian tickets 3,600-ish each with hidden splits of 540 / 539 / 539
1160
+ (all ≥ the 500 the milestone requires). 70/15/15 train/cal/hidden, label
1161
+ distributions in `data/big/MANIFEST.json` with a SHA-256 per file.
1162
+ - `core/firewall.hpp` (new): the hidden-test contract ENFORCED in code, not
1163
+ prose. `learn` refuses `_hidden`/`_cal`; `calibrate` refuses `_hidden`;
1164
+ `derive --gate` refuses `_hidden`. `make firewall-check` proves all four
1165
+ refusals on the real CLI.
1166
+ - Hidden-test reports (`make bench-big`, `--energy-norm`, calibration fit on
1167
+ the `_cal` split only): **tickets_en 0.971** (ECE 0.005), **game 0.763**
1168
+ (ECE 0.049), **guard 0.638** (ECE 0.037; guardrail hold precision 0.782,
1169
+ recall 0.910). p95 latency 126–441 µs, decisions bit-deterministic.
1170
+ - Multilingual hidden (`make bench-big-ml`, per-script routing):
1171
+ **Bengali 0.969** (ECE 0.015), **Hindi 0.965** (ECE 0.020),
1172
+ **Russian 0.970** (ECE 0.011).
1173
+ - Coverage-vs-accuracy on the hidden tests (`make coverage-big`), all three
1174
+ operating points feasible: tickets 96.4%@53% / 90.1%@73% / 83.0%@93%;
1175
+ game 94.3%@52% / 86.7%@76% / 80.2%@91%; guard 76.2%@54% / 68.1%@80% /
1176
+ 65.8%@90%. Dose-response (`make scale-probe`): 0.603@250 → 0.825@8,400
1177
+ distinct rows — distinct experience keeps paying at scale.
1178
+
1179
+ ### Milestone 2 — distinct experience beats repeated phrasings (measured)
1180
+ - `learn --dedup`: exact-duplicate lessons skipped, auditable via
1181
+ `dedup_skipped` in the learn report.
1182
+ - The A/B at EQUAL lesson counts (25,200 each; `make ab-distinct`):
1183
+ **8,400 distinct rows 0.825** (39,158 lanes, 1,898 nodes) vs **1,050 rows
1184
+ re-taught 8× 0.782** (18,633 lanes, 530 nodes). Distinct experience wins
1185
+ and builds a 2.1× denser fabric. B-dedup (duplicates skipped) lands at
1186
+ 0.609 with dedup_skipped=22,050 — consistent with the dose-response curve
1187
+ at ~1,000 rows, cross-checking both measurements.
1188
+ - `--novelty` per-lesson novelty weighting: measured NEUTRAL at floor 0.90
1189
+ (0.827 vs 0.825 baseline) — ships OFF; dedup is the mechanism that pays.
1190
+
1191
+ ### Milestone 3 — contradiction handling and machine-auditable evidence
1192
+ - Every lane carries an evidence ledger: support events, counter events
1193
+ (anti-Hebbian dissolutions), generation, first/last teach seq, substrate
1194
+ context. `decide --evidence` prints it per channel — e.g. `department`
1195
+ resolved with 62 supporting lanes, top lane `the -> problem` w=0.2896,
1196
+ 10,870 support events, seq window [1, 25198].
1197
+ - Contradictions (same state+question taught with a different outcome) are
1198
+ DETECTED, counted in the learn report, and recorded — never silently
1199
+ overridden. Live test: teach `a` ×3 then `b` ×3 → decide keeps `a`,
1200
+ `contested: true`, contradiction record carries old/new outcome, both seqs,
1201
+ state hash; lanes show counter events. The ledger is read-only: lane
1202
+ weights drive the field, the ledger never does.
1203
+
1204
+ ### Milestone 4 — adversarial/OOD suite (`bench --adversarial`, `make adv-big`)
1205
+ Deterministic families on the hidden tests, honest per-family metrics:
1206
+ - tickets: reorder 0.971, padding 0.968, typos 0.968, intensifiers 0.976,
1207
+ self-contradiction 0.969, negation 0.974, double-negation 0.942 (weakest),
1208
+ near-miss 0.933, cross-domain 0.908; **unknown concepts defer 100%**
1209
+ (zero false confidence — honest silence under attack).
1210
+ - Conflicting-lessons attack (40 real contradictions taught post-hoc, with a
1211
+ control arm re-taught at gold to isolate the teach-event cost):
1212
+ silent_override = FALSE on all three domains, contested 40/40, decisions
1213
+ bit-deterministic after. Contradiction-specific damage on untouched rows
1214
+ (tickets): 0.7193 → 0.6517 vs control 0.7027 — the anti-Hebbian law costs
1215
+ ~5.1 pts beyond generic re-teaching, now measured instead of guessed.
1216
+
1217
+ ### Milestone 5 — multicore settle, batched throughput, the GPU gate
1218
+ - CSR mirror of the lane fabric (contiguous offsets/targets/weights, lazily
1219
+ rebuilt, order-preserving — every float sum keeps its exact operand order).
1220
+ - OpenMP build (`make omp`, same sources, `-fopenmp`): parallel settle with
1221
+ static partitioning + per-thread scatter buffers combined in fixed thread
1222
+ order. **Bit-identity proven**: `make omp-identity` — sequential and
1223
+ `--threads 2` produce identical routing/calibration/honesty/guardrail
1224
+ blocks at 0.971 on the hidden test. `syfox-test-omp` all-pass.
1225
+ - Honest performance note: at this fabric size on a 2-core sandbox the
1226
+ deterministic parallel settle is SLOWER (p50 620 µs vs 415 µs) — thread
1227
+ coordination exceeds the gain below ~10k nodes. It exists for dense
1228
+ fabrics; the numbers say when to use it.
1229
+ - Batched multicore throughput (`bench --throughput N`, private engine per
1230
+ worker, checksum proves real work): 2,390 → 3,714 decisions/sec
1231
+ (**1.554×** on 2 cores) on the 3,518-node tickets fabric.
1232
+ - GPU gate measured (`make density`): per-fabric density 0.0067 (tickets,
1233
+ 3,518 nodes / 82,655 lanes, degree 23.5) — the SoA/CSR layout is in place;
1234
+ a GPU port stays DESIGN-ONLY until substrates are dense enough to justify
1235
+ it. No GPU claims.
1236
+
1237
+ ### Fixed in v3 (found by running the milestones, not by reading)
1238
+ - `si_substrate.hpp`: Substrate class was left unclosed by an interrupted
1239
+ edit (build broken); CSR cache members needed `mutable`.
1240
+ - Parallel settle segfault: per-thread scatter buffers were constructed
1241
+ EMPTY (n vectors of size 0) → out-of-bounds combine. Now sized n.
1242
+ - `omp-identity`/`throughput`/`density` targets silently measured an EMPTY
1243
+ fabric (missing `--lang auto` on a per-script-routed model) — the "ok"
1244
+ was vacuous. All three now load real substrates; identity re-proven at
1245
+ 0.971, throughput checksum non-zero.
1246
+
1247
+ ## v2.2.0 — multilingual boundary, trigram bridges, active learning
1248
+
1249
+ The language barrier was at the tokenizer: v2.1's byte-level `std::isalnum`
1250
+ scan produced ZERO tokens for any multi-byte UTF-8 query — Bengali, Hindi,
1251
+ Russian, every non-ASCII language deferred forever. v2.2 rebuilds the input
1252
+ boundary (si_substrate.hpp still byte-identical to v0.2):
1253
+
1254
+ ### Multilingual boundary
1255
+ - `core/script.hpp` (new): UTF-8 decode + 35 Unicode script families by
1256
+ block-range majority vote (deterministic; ties by table order; digits
1257
+ neutral; malformed bytes are separators). Families cover 100+ languages.
1258
+ - `core/normalize.hpp`: codepoint-aware tokenization. Pure-ASCII input keeps
1259
+ the byte-identical v2.1 path (test-guarded); non-ASCII decodes UTF-8 into
1260
+ script-homogeneous runs; Cyrillic/Greek/Latin lowercase maps; Porter +
1261
+ synonyms apply to pure-ASCII tokens only (Porter 1980 is English-only).
1262
+ - `--lang auto|<slug>`: per-script routing. learn routes lessons into
1263
+ `<model>-<script>` substrates (one fabric per script family — Latin gets
1264
+ its own); decide/bench/calibrate/recall route queries, with an honest
1265
+ fallback note when the routed substrate is missing.
1266
+ - Seed data: `data/tickets_bn_{train,heldout}.jsonl`, `tickets_hi_train.jsonl`,
1267
+ `tickets_ru_train.jsonl`, plus a disjoint-vocabulary `tickets_eval_extra.jsonl`
1268
+ (unseen words, known intents). `make models-multilingual && make bench-multilingual`.
1269
+ - Measured: Bengali held-out routing 1.000 (n=3); Bengali train 1.000/1.000
1270
+ (in-sample); Hindi/Russian demos route and answer billing; OOD defer 1.00.
1271
+
1272
+ ### Character trigram bridges (typo robustness, traction-gated)
1273
+ - `core/ngram.hpp` (new): literal `g3:`-prefixed trigram lanes (no hashing —
1274
+ every lane inspectable), taught word<->gram fabric + gram<->outcome lanes.
1275
+ - Decide-time protocol: an unknown word injects its trigrams only when >=25%
1276
+ already exist in the fabric (corrupted-form signature: "refnd" keeps
1277
+ g3:ref of "refund"); legitimate unseen words stay dark — honest silence,
1278
+ no manufactured evidence. Non-Latin routed substrates enable bridges
1279
+ automatically; `--ngrams on|off` overrides.
1280
+ - Measured A/B: with the traction gate, clean Latin held-out numbers stay
1281
+ byte-identical to v2.1 (tickets 1.000 / game 0.667 / guard 0.750); the
1282
+ deterministic corruption sweep (`bench --typos P`) quantifies robustness
1283
+ honestly. bench OOD probes now also skip sub-word-entangled nonsense
1284
+ (no fake silence violations).
1285
+
1286
+ ### Mass-guarded variant lessons (measured — still negative, documented)
1287
+ - `learn --augment` + `tools/gen_variants.py` (8-10 variants/state,
1288
+ deterministic, refuses held-out paths): re-teaching skips intern() for
1289
+ known concepts, so lanes strengthen but acoustic mass never re-deposits.
1290
+ - Held-out verdict: STILL regresses (tickets 1.000 -> 0.500, game 0.667 ->
1291
+ 0.000, guard 0.750 -> 0.500 with 199 variants). With the mass confound
1292
+ removed the mechanism is visible: shared vocabulary across labels smears
1293
+ tiny multi-label fabrics. Coverage comes from distinct labelled experience
1294
+ — which the active-learning loop collects. `make models-vast` keeps the
1295
+ A/B reproducible.
1296
+
1297
+ ### Active learning loop
1298
+ - `decide --log-deferrals FILE`: every deferral logged with state + the FULL
1299
+ question schema (a labeled row is directly teachable).
1300
+ - `syfox active --deferrals FILE --out FILE [--min-count N]`: dedups and
1301
+ ranks the log into a labeling worksheet. Deploy -> log -> label -> re-learn.
1302
+
1303
+ ### Other
1304
+ - `bench --typos P`: deterministic word corruption (deletion/swap/duplication
1305
+ by word hash; codepoint-level, works on Bengali/Hindi), reports clean vs
1306
+ corrupted accuracy + delta.
1307
+ - VERSION 2.1.0 -> 2.2.0; tests: +5 suites (script table, UTF-8 boundary,
1308
+ trigram lanes, mass guard, Bengali e2e + determinism, corruption sweep).
1309
+
1310
+ # Changelog
1311
+
1312
+ All notable changes to SyFox. Versions follow the eval-methodology
1313
+ milestones; every number in here is reproducible from the tagged sources
1314
+ (`make models && make bench-heldout && make coverage && make heldout-gate`).
1315
+
1316
+ ## v2.1.0 — evaluation-methodology fix + generalization work
1317
+
1318
+ The v0.2 eval graded the model on its own training rows (in-domain
1319
+ resubstitution) and fitted its calibration the same way. v2.1 replaces the
1320
+ methodology: a real held-out split gates everything, the headline metric is
1321
+ the coverage-vs-accuracy curve, and the harness decides — by measurement —
1322
+ what ships.
1323
+
1324
+ ### P1 — held-out eval split (blocks everything else)
1325
+
1326
+ * `tools/split_data.py`: deterministic 70/30 split of every
1327
+ `data/*_train.jsonl` (which was the FULL dataset), stratified by first
1328
+ label, seeded RNG, refuses to double-split. Pre-split files remain in git
1329
+ history. Result: 31 train / 13 held-out rows; every label class present on
1330
+ both sides.
1331
+ * `make models` now teaches the fabric from `*_train.jsonl` only.
1332
+ * `syfox bench --split train|heldout` scores the right file and labels the
1333
+ source in `eval_source` (`held-out 30% split; fabric never taught from
1334
+ these rows` vs `train split; in-sample for the fabric`).
1335
+
1336
+ ### P2 — coverage-vs-accuracy curve (the headline metric)
1337
+
1338
+ * `syfox bench --coverage-curve` sweeps a confidence threshold τ over
1339
+ 0.0→1.0 (21 steps) and reports emitted / correct / coverage /
1340
+ accuracy-within-coverage, an ASCII accuracy-vs-coverage plot, explicit
1341
+ operating points at ≥50% / ≥70% / ≥90% coverage, and a JSON block.
1342
+ * Engine-level honest silence (unknown vocabulary) is never emitted at any
1343
+ threshold — the curve measures the calibrated-confidence band on top of it.
1344
+ * Choice + score questions on labelled rows; deferred answers stay out of
1345
+ every denominator.
1346
+ * Tickets, held-out: 100% coverage → 83.3% accuracy; ≥70% coverage → 90.0%;
1347
+ 50% coverage → 100%. The confident subset is trustworthy, measurably.
1348
+
1349
+ ### P3 — paraphrase generation (implemented, then gated by measurement)
1350
+
1351
+ * `tools/gen_paraphrases.py`: up to 5 variants per taught state — clause
1352
+ reorders, neutral-politeness fillers, combos. Deterministic (per-row seeded
1353
+ RNG), refuses any held-out path, replaces words only via the single-word
1354
+ synonym table (never inserts domain-significant words), so labels stay
1355
+ valid by construction. Output: `data/*_paraphrased.jsonl` (155 lessons).
1356
+ * Measured verdict on the held-out split: augmentation REGRESSES accuracy —
1357
+ tickets 1.000 → 0.500, guard 0.750 → 0.667, game 0.667 → 0.667 (1 variant
1358
+ per state is equally harmful). Mechanism: `intern()` mass grows linearly
1359
+ and injection damps by 1/√mass, so re-teaching near-duplicate lessons
1360
+ re-weights the field toward the training surface forms. A lesson here is a
1361
+ physical deposition, not a data point.
1362
+ * Consequence: `make models` ships un-augmented; `make models-augmented`
1363
+ reproduces the augmented A/B. Synonym-only variants were dropped from the
1364
+ generator entirely (they normalize to identical token streams — pure
1365
+ repetition, zero novelty).
1366
+
1367
+ ### P4 — tokenization improvement
1368
+
1369
+ * `core/normalize.hpp`: one deterministic pipeline for teach, decide,
1370
+ recall and harvest — lowercase alnum scan → Porter (1980) stemming (faithful
1371
+ port, verified against the reference vocabulary) → synonym folding via
1372
+ `data/synonyms.txt` (embedded copy as fallback; `--synonyms` overrides).
1373
+ "reimbursement" now lands on the same node as "refund" at decide time.
1374
+ * `si_substrate.hpp` is byte-identical to v0.2: this is input encoding at the
1375
+ boundary, not physics. No neural net, no pattern matching added anywhere.
1376
+ * Label-safety rule for the table: a swap must never be able to change a
1377
+ row's labels (no urgency words in fillers, no cross-department drift).
1378
+
1379
+ ### P5 — derivation gated on held-out
1380
+
1381
+ * `syfox derive --gate data/*_heldout.jsonl` (per model, `make heldout-gate`):
1382
+ the no-regression gate now replays the HELD-OUT rows, and the report
1383
+ carries gold-labelled accuracy before/after plus a verdict and revert
1384
+ reason.
1385
+ * Verdicts: tickets **REVERT** (9 held-out flips), guard **REVERT** (1 flip),
1386
+ game **PASS** (253 derived lanes committed, held-out accuracy held
1387
+ 0.667 → 0.667). The §10-era mitigation ("ship seed models un-derived") is
1388
+ now a measured, per-model decision made by the harness.
1389
+
1390
+ ### P6 — calibration on held-out + ECE
1391
+
1392
+ * `syfox calibrate --examples data/*_heldout.jsonl` (wired into
1393
+ `make models`): temperature/Platt fitted on held-out rows. The fabric never
1394
+ learns from held-out rows; the fit sets 2–3 scalars and is monotone, so
1395
+ argmax decisions are unaffected. Disclosed: the reported "after" ECE is
1396
+ measured on the same rows the scalars were fitted on (standard for
1397
+ temperature scaling; 1–2 parameters).
1398
+ * Calibration rows now carry the FULL candidate energy vector + gold label;
1399
+ the fit objective is multi-class NLL over the true softmax (the textbook
1400
+ definition). The old pairwise {correct, worst-wrong} view was structurally
1401
+ blind to argmax errors on near-ties and could drive T to its floor,
1402
+ manufacturing confidence on wrong answers.
1403
+ * 1-bit adoption guard per question type: keep T = 1 / default Platt when the
1404
+ fitted parameters would worsen held-out multi-class ECE.
1405
+ * Two real defects fixed along the way: a 0.005 floor clamp inside the NLL
1406
+ search flattened the objective below 0.005 and hid the true optimum (the
1407
+ max-subtracted softmax is overflow-safe for any T > 0), and the same clamp
1408
+ in the decide path silently discarded any fitted T below it. Also fixed:
1409
+ array-criteria labels (score levels) were compared to level text and
1410
+ silently dropped from every fit.
1411
+ * Results (held-out, multi-class ECE, top-prob confidence): tickets
1412
+ 0.665 → **0.012** (T = 0.0005 adopted; the ECE < 0.1 bar is met), guard
1413
+ 0.496 → 0.200 (T = 0.0107 adopted), game 0.329 kept (fit rejected — the
1414
+ fitted T would have worsened ECE to 0.503). With 1 wrong answer among
1415
+ 3–4 emitted questions, ECE ≥ (1/n)·|0 − conf| ≥ 0.2 is forced by
1416
+ arithmetic at any temperature; the remedy is more held-out data, which the
1417
+ harness now measures.
1418
+ * Bench ECE now uses the standard top-probability confidence (the signal
1419
+ temperature scaling acts on); the entropy confidence remains in the
1420
+ conf-when-correct/wrong fields.
1421
+
1422
+ ### P7 — documentation
1423
+
1424
+ * README: held-out tables replace the resubstitution table (the old numbers
1425
+ are kept only as the labeled in-sample contrast), coverage-vs-accuracy
1426
+ table at 50/70/90% coverage, calibration-before/after table, augmentation
1427
+ dose-response table, per-model gate verdicts, latency + cost section
1428
+ (p50 29–64 µs, CPU-only, no per-decision API cost), tokenizer docs.
1429
+ * `syfox --help` documents the new flags.
1430
+
1431
+ ### Tests
1432
+
1433
+ * New checks: Porter spot-checks against the 1980 reference vocabulary,
1434
+ synonym folding through the stemmed table, normalize determinism.
1435
+ * `test_calibration_tool` updated to the multi-class row shape and now
1436
+ asserts the fit sharpens on clean margins.
1437
+ * Gate test: the harvest-revert branch compares against the pre-derive
1438
+ fabric state (a committed compose gate legitimately changes lanes first).
1439
+ * Full suite: 107 checks, all passing. Substrate physics untouched:
1440
+ `git diff f4dba63 -- core/si_substrate.hpp` is empty — every change in
1441
+ v2.1 lives at the input boundary (normalize.hpp, new) or in tooling
1442
+ (bench / calibrate / gate reporting, Makefile, data split).
1443
+
1444
+ ### Honesty notes
1445
+
1446
+ * The held-out split is small (13 rows total). Every number above carries its
1447
+ n. The harness exists precisely so that growing `data/` makes the numbers
1448
+ *mean more* without changing any code.
1449
+ * Held-out rows touch two consumers beyond eval: the calibration fit (2–3
1450
+ scalars, disclosed above) and the derivation gate (read-only replay). No
1451
+ held-out row ever strengthens a lane. The coverage curve, accuracy, and
1452
+ flips are computed from decisions only.
1453
+ * Jev's published figures remain side-by-side references (`jev_reference`);
1454
+ no parity is claimed beyond sharing the measurement axes.
1455
+
1456
+ ## v0.2.0 — SI salience lineage + Jev-parity bench + gated derivation
1457
+
1458
+ * Real SI salience port: cavity integrator (s = tanh(s·0.995 + 0.05·|v|)),
1459
+ TSDA-lineage Miller window behind runtime flags (`--salience-gating`,
1460
+ `--miller-window`), state-hash-derived draws for bit-exact determinism.
1461
+ * Jev-parity benchmark suite (accuracy, latency, calibration, honesty,
1462
+ guardrail, determinism axes) with published Jev figures carried for
1463
+ side-by-side reading.
1464
+ * Derivation layer: lane induction (compose + harvest), dreamer with
1465
+ human-validated promotion ledger, structural analogy (energy fingerprints).
1466
+ * No-regression derivation gate: transactional derive with bit-exact
1467
+ snapshot/restore; any taught-row argmax flip or manufactured certainty on
1468
+ ambiguous probes reverts.
1469
+
1470
+ ## v0.1.0 — System One decision engine on SI substrate physics
1471
+
1472
+ * Energy injection → dissipative settling → dual-channel readout
1473
+ (Specific mean / Support mass) → Hebbian learning + anti-Hebbian
1474
+ dissolution, honest silence below the floor.
1475
+ * Energy-gated source cap (24 sources/pass), deterministic tie-breaking.
1476
+ * CLI: learn / calibrate / decide / demo / stats.
engine/Makefile CHANGED
@@ -5,6 +5,9 @@ BUILD := build
5
 
6
  all: build/syfox build/syfox-test build/libsyfox_core.so build/rebuild_sem
7
 
 
 
 
8
  # Copy the shared library to the REPO-ROOT build/ dir, which is where
9
  # server/syfox_bridge.py looks for it (ctypes: ../build/libsyfox_core.so).
10
  # Skipping this is the single most common setup failure: the CLI and the tests
@@ -18,9 +21,6 @@ sync-so: build/libsyfox_core.so
18
 
19
  .PHONY: sync-so
20
 
21
- build:
22
- mkdir -p build
23
-
24
  CORE_HDRS := core/syfox.hpp core/si_substrate.hpp core/normalize.hpp core/ngram.hpp core/script.hpp core/derive.hpp core/bench.hpp core/gate.hpp core/recall.hpp core/json.hpp core/firewall.hpp core/calc.hpp core/jas.hpp core/roles.hpp core/distvec.hpp
25
 
26
  build/syfox: src/syfox_cli.cpp $(CORE_HDRS) | build
@@ -289,7 +289,10 @@ coverage-big: models-big
289
  bank77: build/syfox
290
  python3 tools/bank77_prepare.py --topk 20 --opaque-labels --no-instructions
291
  ./build/syfox learn --examples data/bank77_train.jsonl --model model-bank77-best --epochs 3
292
- ./build/syfox calibrate --model model-bank77-best --examples data/bank77_cal.jsonl
 
 
 
293
  ./build/syfox bench --model model-bank77-best --eval data/bank77_cal.jsonl --energy-norm
294
 
295
  bank77-report: bank77
@@ -390,7 +393,11 @@ b77-sem: build/syfox b77-hier-data
390
  bash scripts/b77_train_chunked.sh 0 11
391
  cp data/bank77_hierarchy.json model-b77-sem/hierarchy.json
392
  cp data/bank77_memories.jsonl model-b77-sem/memories.jsonl
393
- ./build/syfox calibrate --model model-b77-sem --examples data/bank77_cal.jsonl
 
 
 
 
394
 
395
  b77-sem-bench: build/syfox
396
  ./build/syfox bench --model model-b77-sem --eval data/bank77_cal.jsonl --energy-norm --replays 1 --latency-reps 1
@@ -407,7 +414,8 @@ router-data:
407
  router16: build/syfox router-data
408
  ./build/syfox learn --model model-router16 --examples data/router16_train.jsonl --epochs 3
409
  cp data/router16_router.json model-router16/router.json
410
- ./build/syfox calibrate --model model-router16 --examples data/router16_cal.jsonl
 
411
 
412
  router16-bench: build/syfox
413
  ./build/syfox bench --model model-router16 --eval data/router16_cal.jsonl --energy-norm --replays 1 --latency-reps 1
@@ -446,3 +454,27 @@ ci: build/syfox test
446
  fi
447
  bash tests/readout_silence_test.sh
448
  bash tests/jas_test.sh
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  all: build/syfox build/syfox-test build/libsyfox_core.so build/rebuild_sem
7
 
8
+ build:
9
+ mkdir -p build
10
+
11
  # Copy the shared library to the REPO-ROOT build/ dir, which is where
12
  # server/syfox_bridge.py looks for it (ctypes: ../build/libsyfox_core.so).
13
  # Skipping this is the single most common setup failure: the CLI and the tests
 
21
 
22
  .PHONY: sync-so
23
 
 
 
 
24
  CORE_HDRS := core/syfox.hpp core/si_substrate.hpp core/normalize.hpp core/ngram.hpp core/script.hpp core/derive.hpp core/bench.hpp core/gate.hpp core/recall.hpp core/json.hpp core/firewall.hpp core/calc.hpp core/jas.hpp core/roles.hpp core/distvec.hpp
25
 
26
  build/syfox: src/syfox_cli.cpp $(CORE_HDRS) | build
 
289
  bank77: build/syfox
290
  python3 tools/bank77_prepare.py --topk 20 --opaque-labels --no-instructions
291
  ./build/syfox learn --examples data/bank77_train.jsonl --model model-bank77-best --epochs 3
292
+ @# v3.9.2: calibrate under the SAME decide-side composition the bench
293
+ @# below uses (--energy-norm) — otherwise the fitted temperature belongs
294
+ @# to a different engine than the one that decides.
295
+ ./build/syfox calibrate --energy-norm --model model-bank77-best --examples data/bank77_cal.jsonl
296
  ./build/syfox bench --model model-bank77-best --eval data/bank77_cal.jsonl --energy-norm
297
 
298
  bank77-report: bank77
 
393
  bash scripts/b77_train_chunked.sh 0 11
394
  cp data/bank77_hierarchy.json model-b77-sem/hierarchy.json
395
  cp data/bank77_memories.jsonl model-b77-sem/memories.jsonl
396
+ @# v3.9.2: same composition as the bench (--energy-norm). The fitted
397
+ @# temperature is a function of the decide-side physics; fitting it under
398
+ @# a different composition shipped a ~100x too-sharp temperature (T 0.0037
399
+ @# vs 0.3552) that saturated the probability gap and killed the defer axis.
400
+ ./build/syfox calibrate --energy-norm --model model-b77-sem --examples data/bank77_cal.jsonl
401
 
402
  b77-sem-bench: build/syfox
403
  ./build/syfox bench --model model-b77-sem --eval data/bank77_cal.jsonl --energy-norm --replays 1 --latency-reps 1
 
414
  router16: build/syfox router-data
415
  ./build/syfox learn --model model-router16 --examples data/router16_train.jsonl --epochs 3
416
  cp data/router16_router.json model-router16/router.json
417
+ @# v3.9.2: same composition as the bench (--energy-norm).
418
+ ./build/syfox calibrate --energy-norm --model model-router16 --examples data/router16_cal.jsonl
419
 
420
  router16-bench: build/syfox
421
  ./build/syfox bench --model model-router16 --eval data/router16_cal.jsonl --energy-norm --replays 1 --latency-reps 1
 
454
  fi
455
  bash tests/readout_silence_test.sh
456
  bash tests/jas_test.sh
457
+ @# v3.9.2 GATE: every FITTED fabric must carry the decide-side composition
458
+ @# it was calibrated under (physics.json). A fitted calibration with an
459
+ @# unknown provenance is the exact state that shipped the wrong-answer
460
+ @# bug: a temperature fitted under a different physics than the decision
461
+ @# runs, on a biased subset of the rows. See docs/FIT_DECIDE_PARITY.md.
462
+ @if [ -d model-router16 ] || [ -d model-b77-sem ]; then \
463
+ python3 tools/assert_fit_decide_parity.py model-router16 model-b77-sem || exit 1; \
464
+ else \
465
+ echo "SKIP fit-decide parity gate: model-router16 / model-b77-sem absent (gitignored; rebuild with make b77-sem router16)"; \
466
+ fi
467
+ @# v3.9.3 GATE: the HANDMADE generalisation probes (data/handmade_probes.jsonl)
468
+ @# — 148 hand-written sentences, deliberately OUTSIDE the training and eval
469
+ @# vocabulary. Every other gate in this tree scores the fabric on rows that
470
+ @# share its templates; this one is the only check that can see a fabric
471
+ @# that has memorised its corpus instead of learning it (it is what
472
+ @# exposed the diffusion trade-off: d=0.02 buys +30 points in-distribution
473
+ @# and costs ~7 points of generalisation).
474
+ @if [ -d model-giant-latin ] || [ -d model-b77-sem ]; then \
475
+ python3 tools/handmade_gate.py --schemas datasets/schemas.json \
476
+ --models "bank77=model-b77-sem,router=model-router16" \
477
+ --model-default model-giant-latin --quiet; \
478
+ else \
479
+ echo "SKIP handmade generalisation gate: no fabric present (gitignored; rebuild with make models)"; \
480
+ fi
engine/core/bench.hpp CHANGED
@@ -462,10 +462,32 @@ struct BenchReport {
462
 
463
  sfx::JVObj jev;
464
  jev["published"] = sfx::JV(true);
465
- jev["workflow_accuracy"] = 0.678;
466
- jev["latency_ms"] = sfx::JV("[70, 500]");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  jev["guardrail_hold_precision"] = 0.88;
468
- jev["source"] = sfx::JV("typesafe.ai launch + press coverage, Sept 2026; axes shared, not numbers");
 
 
469
 
470
  sfx::JVObj o;
471
  o["suite"] = sfx::JV("syfox-jev-parity-v0");
 
462
 
463
  sfx::JVObj jev;
464
  jev["published"] = sfx::JV(true);
465
+ // v3.9.3: the Jev reference block was carrying the LAUNCH-DAY
466
+ // self-reported figures (workflow 0.678, latency 70-500 ms, no
467
+ // calibration study). Third-party measurements since then are
468
+ // materially different and materially STRONGER for Jev, so quoting
469
+ // the old ones flatters SyFox. These are the independent numbers:
470
+ // - arxiv 2609.37647 (37 datasets, 346,009 requests, jev-1.13.0):
471
+ // 95-99% on IMDB / SST-2 / HellaSwag / ARC; 79.7% on Banking77
472
+ // at full coverage -> 96.3% at 50% coverage.
473
+ // - laya-model.com/benchmarks (Jev published column): typed-decisions
474
+ // 0.727, AG News 0.910, DAIR Emotion 0.480, Banking77 0.870,
475
+ // ECE 0.246, p50 latency 236-276 ms.
476
+ // The vendor's own workflow-eval claim (0.955) is kept and labelled
477
+ // as the vendor figure; everything else is third-party.
478
+ jev["workflow_accuracy_vendor"] = 0.955;
479
+ jev["workflow_accuracy"] = 0.678; // launch-day self-report, kept
480
+ jev["banking77"] = 0.870;
481
+ jev["ag_news"] = 0.910;
482
+ jev["emotion"] = 0.480;
483
+ jev["typed_decisions"] = 0.727;
484
+ jev["ece"] = 0.246;
485
+ jev["latency_ms"] = sfx::JV("[236, 276]");
486
+ jev["latency_ms_note"] = sfx::JV("p50, one question, third-party; the launch figure was [70, 500] ms");
487
  jev["guardrail_hold_precision"] = 0.88;
488
+ jev["source"] = sfx::JV("third-party: arxiv 2609.37647 (jev-1.13.0, 37 datasets); "
489
+ "laya-model.com/benchmarks (Jev published column); "
490
+ "typesafe.ai launch + press coverage, Sept 2026 (vendor workflow claim)");
491
 
492
  sfx::JVObj o;
493
  o["suite"] = sfx::JV("syfox-jev-parity-v0");
engine/core/reason.hpp CHANGED
@@ -59,7 +59,6 @@
59
  #pragma once
60
 
61
  #include <algorithm>
62
- #include <array>
63
  #include <cctype>
64
  #include <cstdint>
65
  #include <cmath>
@@ -405,15 +404,6 @@ struct ReasonCore {
405
  rules.push_back(Rule{name, rel_ab, rel_bc, rel_ac, cost, spawn});
406
  while (prim_meta.size() < rules.size()) prim_meta.push_back({});
407
  }
408
- // M2: rule ids are positional and shift whenever the default set gains a
409
- // primitive, so persisted state must be keyed by NAME. This lookup is the
410
- // bridge between a loaded name and the current positional id.
411
- int rule_index_by_name(const std::string& name) const {
412
- for (std::size_t i = 0; i < rules.size(); ++i)
413
- if (rules[i].name == name) return static_cast<int>(i);
414
- return -1;
415
- }
416
-
417
  void add_primitive(const std::string& name, PrimitiveKind kind,
418
  int rel_ab, int rel_bc, int rel_ac,
419
  int rel_extra = -1, int min_witnesses = 3) {
@@ -460,13 +450,6 @@ struct ReasonCore {
460
  add_negation("contrapositive");
461
  add_case_analysis("disjunction_elimination");
462
  add_induction("schematic_generalization", REL_HAS, 3);
463
- // M1: PRIM_ANALOGY was DEFINED but never added to the default set, so
464
- // the advertised "nine primitives" were eight at runtime and
465
- // CHANGELOG v3.9.0's claim was false on the live binary. add_analogy()
466
- // only fires from a graph that contains it, so wiring it here is
467
- // inert on fabrics with no structural gap to bridge -- which is the
468
- // correct behaviour, and restores doc/code parity.
469
- add_analogy("structural_analogy");
470
  }
471
 
472
  // -- assertions ----------------------------------------------------------
@@ -908,45 +891,6 @@ struct ReasonCore {
908
  // -- PATH FINDING (foundation for L3 Transitive + L6 Analogy; l9 paper) ---
909
  // BFS over outgoing edges; relation-agnostic by default. Returns edge
910
  // indices tracing from -> ... -> to (empty = unreachable).
911
- // -- CASE-INSENSITIVE NODE LOOKUP (fixes proof_path_between returning empty) --
912
- //
913
- // The axiom graph stores labels with their ORIGINAL case ("Tariq"), because
914
- // load_axioms hands assert_fact the token as written. But every lookup from
915
- // the decision path goes through si::norm::normalize(), which LOWERCASES
916
- // ("tariq"). graph.by_label is an exact-match unordered_map, so every such
917
- // lookup MISSED:
918
- //
919
- // by_label: 'Tariq' -> 1
920
- // find_path("radio","Tariq") = 1 edge (exact case, works)
921
- // find_path("radio","tariq") = 0 edges (normalized case, silently empty)
922
- //
923
- // Consequence: proof_path_between() returned an empty path for EVERY
924
- // candidate, so decide() never found a typed path, --reason-route never
925
- // fired, and --require-proof deferred everything. Measured directly:
926
- // find_path(radio->Tariq) size=1 / find_path(radio->tariq) size=0
927
- //
928
- // Fix is a lookup, NOT a storage change: rewriting stored labels would
929
- // change every persisted graph and break the replay contract for every model
930
- // built before this. Exact match first (fast path, unchanged behaviour), then
931
- // a case-insensitive scan. Deterministic: by_label iteration order is
932
- // irrelevant because labels are unique under case folding in practice, and we
933
- // take the first match in sorted order to be strictly deterministic.
934
- int find_node_ci(const std::string& label) const {
935
- auto it = graph.by_label.find(label);
936
- if (it != graph.by_label.end()) return it->second;
937
- std::string want = label;
938
- for (char& c : want) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
939
- int hit = -1;
940
- for (const auto& kv : graph.by_label) {
941
- std::string k = kv.first;
942
- for (char& c : k) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
943
- if (k != want) continue;
944
- // deterministic: lowest node id wins, independent of hash order
945
- if (hit < 0 || kv.second < hit) hit = kv.second;
946
- }
947
- return hit;
948
- }
949
-
950
  std::vector<int> find_path(const std::string& from, const std::string& to,
951
  int rel_mask = -1, int max_hops = 12) const {
952
  std::vector<int> path;
@@ -1076,8 +1020,6 @@ struct MacroRule {
1076
  int uses = 0;
1077
  };
1078
 
1079
- struct ThinkerIndex; // M2: defined after the verifier, below
1080
-
1081
  struct MetaLearner {
1082
  ReasonCore* engine = nullptr;
1083
  std::unordered_map<SubChainKey, SubChainStat, SubChainKeyHash> chain_stats;
@@ -1136,192 +1078,8 @@ struct MetaLearner {
1136
  stat.macro_rule_idx = old_size;
1137
  macros.push_back(MacroRule{name, key.rule_ids, rel_ab, rel_bc, rel_ac, 0});
1138
  }
1139
-
1140
- };
1141
-
1142
-
1143
- // ---------------------------------------------------------------------------
1144
- // M4: STRUCTURAL BISOCIATION (CMA port).
1145
- //
1146
- // The only mechanism in the SI corpus that MANUFACTURES a false premise on
1147
- // purpose and then makes the derivation engine try to explain it away. That is
1148
- // rule induction from contradiction rather than from support -- the anti-
1149
- // pattern-matcher move. Everything else in reason.hpp adds edges that follow
1150
- // from existing ones; this one asks "what would have to be true for these two
1151
- // distant facts to connect?", and then checks whether the answer verifies.
1152
- //
1153
- // Ported from the parent's src/bisociation.hpp (CMA paper). Two fidelity notes:
1154
- // * it depended on novelty.hpp (shared_targets / find_paths), which is NOT
1155
- // ported to this tree, so the meeting-in-the-middle fallback is expressed
1156
- // with the structures that ARE here (find_path + in_adj/out_adj).
1157
- // * energy keeps the CMA formula: a bridge through highly connected hubs is
1158
- // CHEAP, one through a rare leaf is EXPENSIVE. A bare hop count cannot
1159
- // express that; U_hyp = sum over hops of 1/log(2 + degree(hub)).
1160
- // ---------------------------------------------------------------------------
1161
- struct BisocResult {
1162
- std::string a_label, b_label;
1163
- int shortest_hop_before = -1; // d(a,b) in the ORIGINAL graph
1164
- bool bridge_found = false;
1165
- std::vector<int> bridge_edges;
1166
- std::string intermediate; // the "hinge" concept, when there is one
1167
- float energy = 0.0f; // U_hyp (lower = better)
1168
- bool validated = false; // U_hyp < u_crit
1169
- float confidence = 0.0f; // 1/(1+U_hyp) when validated
1170
- std::string status;
1171
- };
1172
-
1173
- // structural degree, both directions -- a property of the graph, not the search
1174
- inline int bisoc_degree(const ReasonCore& si, int id) {
1175
- if (id < 0 || id >= static_cast<int>(si.graph.nodes.size())) return 0;
1176
- int d = 0;
1177
- if (id < static_cast<int>(si.graph.out_adj.size()))
1178
- d += static_cast<int>(si.graph.out_adj[static_cast<std::size_t>(id)].size());
1179
- if (id < static_cast<int>(si.graph.in_adj.size()))
1180
- d += static_cast<int>(si.graph.in_adj[static_cast<std::size_t>(id)].size());
1181
- return d;
1182
- }
1183
-
1184
- inline float bisoc_hop_cost(const ReasonCore& si, int via_node) {
1185
- return 1.0f / std::log(2.0f + static_cast<float>(bisoc_degree(si, via_node)));
1186
- }
1187
-
1188
- // One bisociation attempt between two labels.
1189
- inline BisocResult bisociate(const ReasonCore& si,
1190
- const std::string& a_label,
1191
- const std::string& b_label,
1192
- int tau_novelty = 3,
1193
- int max_bridge_hops = 5,
1194
- float u_crit = 5.0f) {
1195
- BisocResult r;
1196
- r.a_label = a_label;
1197
- r.b_label = b_label;
1198
- const int a = si.find_node_ci(a_label);
1199
- const int b = si.find_node_ci(b_label);
1200
- if (a < 0 || b < 0 || a == b) {
1201
- r.status = "one or both concepts are not in the graph";
1202
- return r;
1203
- }
1204
- // distance BEFORE any mutation
1205
- const auto pre = si.find_path(a_label, b_label, -1, max_bridge_hops);
1206
- r.shortest_hop_before = pre.empty() ? -1 : static_cast<int>(pre.size());
1207
- // already close => not a bisociation, this is just a lookup
1208
- if (r.shortest_hop_before >= 0 && r.shortest_hop_before <= tau_novelty) {
1209
- r.status = "concepts are already close (d=" +
1210
- std::to_string(r.shortest_hop_before) + " <= tau_novelty=" +
1211
- std::to_string(tau_novelty) + "); no bisociation attempted";
1212
- return r;
1213
- }
1214
- // Resolution Phase: find a bridge.
1215
- const auto bridge = si.find_path(a_label, b_label, -1, max_bridge_hops);
1216
- if (!bridge.empty()) {
1217
- r.bridge_found = true;
1218
- r.bridge_edges = bridge;
1219
- for (std::size_t i = 0; i < bridge.size(); ++i) {
1220
- const int via = si.graph.edges[static_cast<std::size_t>(bridge[i])].from;
1221
- r.energy += bisoc_hop_cost(si, via);
1222
- }
1223
- if (bridge.size() >= 2) {
1224
- const int mid = si.graph.edges[static_cast<std::size_t>(bridge[0])].to;
1225
- if (mid < static_cast<int>(si.graph.nodes.size()))
1226
- r.intermediate = si.graph.nodes[static_cast<std::size_t>(mid)].label;
1227
- }
1228
- } else {
1229
- // No forward bridge. Meeting-in-the-middle: a node both sides point at.
1230
- //
1231
- // BUG IN THE FIRST PORT: both legs were searched with max_bridge_hops,
1232
- // so whenever a->c and c->b both succeeded, find_path(a,b) would have
1233
- // succeeded too and this branch was unreachable -- dead logic that
1234
- // looked alive. The legs are therefore searched with a WIDER budget
1235
- // (2x), which is the only regime where "no direct path, but a shared
1236
- // hinge exists" is actually reachable. Verified below.
1237
- const int leg_hops = max_bridge_hops * 2;
1238
- for (int c = 0; c < static_cast<int>(si.graph.nodes.size()); ++c) {
1239
- if (c == a || c == b) continue;
1240
- if (bisoc_degree(si, c) == 0) continue;
1241
- const std::string cl = si.graph.nodes[static_cast<std::size_t>(c)].label;
1242
- const auto ac = si.find_path(a_label, cl, -1, leg_hops);
1243
- const auto cb = si.find_path(cl, b_label, -1, leg_hops);
1244
- if (!ac.empty() && !cb.empty()) {
1245
- r.bridge_found = true;
1246
- r.intermediate = si.graph.nodes[static_cast<std::size_t>(c)].label;
1247
- for (int e : ac) r.bridge_edges.push_back(e);
1248
- for (int e : cb) r.bridge_edges.push_back(e);
1249
- r.energy = bisoc_hop_cost(si, c) + static_cast<float>(ac.size() + cb.size());
1250
- break;
1251
- }
1252
- }
1253
- if (!r.bridge_found) {
1254
- r.status = "no bridge within " + std::to_string(max_bridge_hops) + " hops";
1255
- return r;
1256
- }
1257
- }
1258
- r.validated = r.energy < u_crit;
1259
- if (r.validated) r.confidence = 1.0f / (1.0f + r.energy);
1260
- r.status = "U_hyp=" + std::to_string(r.energy) +
1261
- (r.validated ? " < U_crit=" + std::to_string(u_crit) + " ADOPT"
1262
- : " >= U_crit=" + std::to_string(u_crit) + " DISCARD");
1263
- return r;
1264
- }
1265
-
1266
-
1267
- // ---------------------------------------------------------------------------
1268
- // M4b: L9-L8 BRIDGE-NODE SYNTHESIS.
1269
- //
1270
- // The parent's own l9.md §5 calls this "the single highest-value unbuilt link",
1271
- // and candidly "engineering rather than research". Its rule: when a structural
1272
- // GAP is detected (a bisociation that found no bridge), GROW THE ONTOLOGY by
1273
- // synthesising a node constrained to satisfy BOTH sides -- then require that the
1274
- // new node make predictions beyond the gap that motivated it, otherwise it is
1275
- // noise with a name on it.
1276
- //
1277
- // The parent's version is a physical node-spawn (Phase space grows in NODES).
1278
- // Here the substrate cannot spawn nodes at decide time, so this synthesises at
1279
- // the GRAPH level only and says so plainly: it produces a candidate label and
1280
- // the relations that would connect it, for an operator to accept or reject. It
1281
- // does NOT silently mutate the knowledge base -- an unreviewed ontology change
1282
- // is exactly the kind of thing that should not happen unattended.
1283
- // ---------------------------------------------------------------------------
1284
- struct BridgeProposal {
1285
- std::string label; // the proposed new concept
1286
- std::string a_label, b_label; // the gap it is meant to bridge
1287
- struct Triple { std::string subj, rel, obj; };
1288
- std::vector<Triple> rels; // the triples that would connect it
1289
- bool makes_extra_prediction = false; // must be TRUE to be worth accepting
1290
- std::string status;
1291
  };
1292
 
1293
- inline BridgeProposal synthesise_bridge(const ReasonCore& si,
1294
- const std::string& a_label,
1295
- const std::string& b_label) {
1296
- BridgeProposal p;
1297
- p.a_label = a_label;
1298
- p.b_label = b_label;
1299
- const BisocResult r = bisociate(si, a_label, b_label);
1300
- if (r.bridge_found) {
1301
- p.status = "a bridge already exists; no ontology growth needed";
1302
- return p;
1303
- }
1304
- const int a = si.find_node_ci(a_label);
1305
- const int b = si.find_node_ci(b_label);
1306
- if (a < 0 || b < 0) { p.status = "endpoint missing from graph"; return p; }
1307
- // The synthesised concept is named for the gap it closes, not invented
1308
- // arbitrarily: "bridge(a|b)". Deterministic, reversible, and obviously
1309
- // synthetic to a human reading the graph.
1310
- p.label = "bridge(" + a_label + "|" + b_label + ")";
1311
- if (si.find_node_ci(p.label) >= 0) { p.status = "bridge already synthesised"; return p; }
1312
- p.rels.push_back(BridgeProposal::Triple{a_label, "part_of", p.label});
1313
- p.rels.push_back(BridgeProposal::Triple{b_label, "part_of", p.label});
1314
- // The extra-prediction requirement: a bridge that ONLY explains the gap is
1315
- // an epicycle. We demand a second, independent link, which in this port is
1316
- // the reverse direction -- if the new node is part_of BOTH endpoints, then
1317
- // transitivity derives a relation between a and b that did not exist, i.e.
1318
- // the node predicts something beyond its own motivating gap.
1319
- p.makes_extra_prediction = true;
1320
- p.status = "proposed " + p.label + " with " + std::to_string(p.rels.size()) +
1321
- " relations; NOT applied (operator review required)";
1322
- return p;
1323
- }
1324
-
1325
  // VERIFIER (§5.3.4): re-check a candidate answer edge against the rule set,
1326
  // recursively down to its premises. A stale derivation fails; Layer 3 must
1327
  // emit "unknown", not the stale answer.
@@ -1375,173 +1133,6 @@ struct ThinkerIndex {
1375
  }
1376
  };
1377
 
1378
- // -- M2: PERSISTENCE ----------------------------------------------------
1379
- // Before M2 the MetaLearner was populated only inside cmd_ask/cmd_thinker
1380
- // from THAT PROCESS's traces, and nothing serialised it. Every invocation
1381
- // therefore restarted with an empty learner, so the 2-bit MDL promotion
1382
- // threshold could NEVER fire across runs: rule induction was not slow, it
1383
- // was unreachable. (The same defect hit ThinkerIndex — total_queries reset
1384
- // to 0 every process, so thinker_index() reported one process's worth.)
1385
- //
1386
- // FORMAT — plain text, one record per line, space-separated, mirroring the
1387
- // .axioms convention rather than the JSON layer (reason.hpp deliberately
1388
- // has no JSON dependency):
1389
- //
1390
- // chain <len> <r0,r1,...rl> <count> <promoted> <macro_idx>
1391
- // macro <rel_ab> <rel_bc> <rel_ac> <uses> <name>
1392
- // rule <name> <rel_ab> <rel_bc> <rel_ac> <cost>
1393
- // think <total_queries> <retrieval_queries> <sum_length>
1394
- //
1395
- // Rules are keyed by NAME, never by index. Indices shift whenever the
1396
- // default rule set changes (M1 added one), so an index-keyed file would
1397
- // silently bind a promoted chain to the wrong rule after an upgrade. Names
1398
- // are stable across versions; this file survives a v3.9.1 -> v4.0 bump.
1399
- //
1400
- // Round-trip is deterministic: chains are written in sorted key order so a
1401
- // reload produces byte-identical output.
1402
- static std::string csv_ints(const std::vector<int>& v) {
1403
- std::string s;
1404
- for (std::size_t i = 0; i < v.size(); ++i) {
1405
- if (i) s += ',';
1406
- s += std::to_string(v[i]);
1407
- }
1408
- return s;
1409
- }
1410
-
1411
- // Rule names for the default set, indexed by rule id. Persisted so a
1412
- // reload can restore rule ids even if the default set gains or loses a
1413
- // primitive (see the index-stability note above).
1414
- std::string serialize_meta(std::unordered_map<SubChainKey, SubChainStat,
1415
- SubChainKeyHash>& chain_stats,
1416
- const std::vector<MacroRule>& macros,
1417
- const ReasonCore* eng, const ThinkerIndex* ti) {
1418
- std::vector<std::pair<SubChainKey, SubChainStat>> rows;
1419
- rows.reserve(chain_stats.size());
1420
- for (const auto& kv : chain_stats) rows.push_back(kv);
1421
- // deterministic order: chains are compared by their rule-id vector.
1422
- // (unordered_map iteration order is NOT stable across runs, so without
1423
- // this the serialized file would differ byte-for-byte per process.)
1424
- std::sort(rows.begin(), rows.end(),
1425
- [](const std::pair<SubChainKey, SubChainStat>& a,
1426
- const std::pair<SubChainKey, SubChainStat>& b) {
1427
- return a.first.rule_ids < b.first.rule_ids;
1428
- });
1429
- std::ostringstream os;
1430
- os << "M2 1\n";
1431
- if (eng) {
1432
- os << "engine 1 " << eng->rules.size() << "\n";
1433
- for (std::size_t i = 0; i < eng->rules.size(); ++i) {
1434
- const Rule& r = eng->rules[i];
1435
- os << "rule " << r.name << ' ' << r.rel_ab << ' ' << r.rel_bc
1436
- << ' ' << r.rel_ac << ' ' << r.cost << '\n';
1437
- }
1438
- }
1439
- for (const auto& row : rows) {
1440
- os << "chain " << row.first.rule_ids.size() << ' ' << csv_ints(row.first.rule_ids) << ' '
1441
- << row.second.count << ' ' << (row.second.promoted ? 1 : 0) << ' '
1442
- << row.second.macro_rule_idx << '\n';
1443
- }
1444
- for (const auto& m : macros)
1445
- os << "macro " << m.rel_ab << ' ' << m.rel_bc << ' ' << m.rel_ac << ' '
1446
- << m.uses << ' ' << m.name << '\n';
1447
- if (ti)
1448
- os << "think " << ti->total_queries << ' ' << ti->retrieval_queries
1449
- << ' ' << ti->sum_length << '\n';
1450
- return os.str();
1451
- }
1452
-
1453
- // Restores chain counts and macro definitions. MACROS ARE RE-ADDED to the
1454
- // engine as plain transitive rules (exactly what try_promote does), so a
1455
- // promoted chain actually fires on the next run instead of being a number
1456
- // in a file. Returns counts for disclosure: (chains, macros, rules).
1457
- std::array<int, 3> deserialize_meta(
1458
- std::unordered_map<SubChainKey, SubChainStat, SubChainKeyHash>& chain_stats,
1459
- std::vector<MacroRule>& macros,
1460
- ReasonCore* eng, ThinkerIndex* ti, const std::string& text) {
1461
- int n_chains = 0, n_macros = 0, n_rules = 0;
1462
- std::istringstream in(text);
1463
- std::string line;
1464
- if (!std::getline(in, line)) return {0, 0, 0};
1465
- if (line.rfind("M2", 0) != 0) return {0, 0, 0}; // not ours
1466
- std::vector<SubChainStat> pending_stats;
1467
- std::vector<SubChainKey> pending_keys;
1468
- std::vector<MacroRule> loaded_macros;
1469
- while (std::getline(in, line)) {
1470
- if (line.empty()) continue;
1471
- std::istringstream ls(line);
1472
- std::string tag;
1473
- ls >> tag;
1474
- if (tag == "engine") {
1475
- int loaded = 0; std::size_t nrules = 0;
1476
- ls >> loaded >> nrules;
1477
- (void)loaded; (void)nrules;
1478
- } else if (tag == "rule") {
1479
- std::string nm; int ab = 0, bc = 0, ac = 0; float cost = 1.0f;
1480
- ls >> nm >> ab >> bc >> ac >> cost;
1481
- n_rules++;
1482
- } else if (tag == "chain") {
1483
- std::size_t len = 0;
1484
- if (!(ls >> len)) continue;
1485
- // ONE comma-joined token, not len tokens: the writer emits
1486
- // `chain <len> <r0,r1,..> <count> <promoted> <macro_idx>`.
1487
- // (An earlier version looped len times and read the count
1488
- // field as an extra rule id, desyncing the stream and silently
1489
- // dropping every chain record on reload.)
1490
- std::string tok;
1491
- if (!(ls >> tok)) continue;
1492
- SubChainKey k;
1493
- for (std::size_t pos = tok.find(','); ; pos = tok.find(',')) {
1494
- k.rule_ids.push_back(std::atoi(tok.substr(0, pos).c_str()));
1495
- if (pos == std::string::npos) break;
1496
- tok = tok.substr(pos + 1);
1497
- }
1498
- if (k.rule_ids.size() != len) continue;
1499
- SubChainStat st;
1500
- int promoted = 0;
1501
- if (!(ls >> st.count >> promoted >> st.macro_rule_idx)) continue;
1502
- st.length = static_cast<int>(len);
1503
- st.promoted = promoted != 0;
1504
- pending_keys.push_back(k);
1505
- pending_stats.push_back(st);
1506
- n_chains++;
1507
- } else if (tag == "macro") {
1508
- MacroRule m;
1509
- int ab = 0, bc = 0, ac = 0, uses = 0;
1510
- if (!(ls >> ab >> bc >> ac >> uses)) continue;
1511
- std::string nm;
1512
- std::getline(ls, nm);
1513
- while (!nm.empty() && nm.front() == ' ') nm.erase(nm.begin());
1514
- m.name = nm; m.rel_ab = ab; m.rel_bc = bc; m.rel_ac = ac; m.uses = uses;
1515
- loaded_macros.push_back(m);
1516
- n_macros++;
1517
- } else if (tag == "think") {
1518
- if (ti) {
1519
- int total = 0, retr = 0; double slen = 0.0;
1520
- if (ls >> total >> retr >> slen) {
1521
- ti->total_queries = total;
1522
- ti->retrieval_queries = retr;
1523
- ti->sum_length = slen;
1524
- }
1525
- }
1526
- }
1527
- }
1528
- // Re-add macros as firing rules FIRST, so macro_rule_idx values from
1529
- // the file still point at the right slots.
1530
- if (eng) {
1531
- for (const auto& m : loaded_macros) {
1532
- if (eng->rule_index_by_name(m.name) >= 0) continue; // already there
1533
- eng->add_rule(m.name, m.rel_ab, m.rel_bc, m.rel_ac, false, 1.0f);
1534
- eng->prim_meta.back() = {PRIM_TRANSITIVE, -1, 3};
1535
- }
1536
- macros = loaded_macros;
1537
- }
1538
- chain_stats.clear();
1539
- for (std::size_t i = 0; i < pending_keys.size(); ++i)
1540
- chain_stats[pending_keys[i]] = pending_stats[i];
1541
- return {n_chains, n_macros, n_rules};
1542
- }
1543
-
1544
-
1545
  // ---------------------------------------------------------------------------
1546
  // THE SIX DISCOVERY QUERIES (inference.hpp) — find what the graph does NOT
1547
  // say: ungrounded islands, dangling concepts, the exact missing bridge,
 
59
  #pragma once
60
 
61
  #include <algorithm>
 
62
  #include <cctype>
63
  #include <cstdint>
64
  #include <cmath>
 
404
  rules.push_back(Rule{name, rel_ab, rel_bc, rel_ac, cost, spawn});
405
  while (prim_meta.size() < rules.size()) prim_meta.push_back({});
406
  }
 
 
 
 
 
 
 
 
 
407
  void add_primitive(const std::string& name, PrimitiveKind kind,
408
  int rel_ab, int rel_bc, int rel_ac,
409
  int rel_extra = -1, int min_witnesses = 3) {
 
450
  add_negation("contrapositive");
451
  add_case_analysis("disjunction_elimination");
452
  add_induction("schematic_generalization", REL_HAS, 3);
 
 
 
 
 
 
 
453
  }
454
 
455
  // -- assertions ----------------------------------------------------------
 
891
  // -- PATH FINDING (foundation for L3 Transitive + L6 Analogy; l9 paper) ---
892
  // BFS over outgoing edges; relation-agnostic by default. Returns edge
893
  // indices tracing from -> ... -> to (empty = unreachable).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
894
  std::vector<int> find_path(const std::string& from, const std::string& to,
895
  int rel_mask = -1, int max_hops = 12) const {
896
  std::vector<int> path;
 
1020
  int uses = 0;
1021
  };
1022
 
 
 
1023
  struct MetaLearner {
1024
  ReasonCore* engine = nullptr;
1025
  std::unordered_map<SubChainKey, SubChainStat, SubChainKeyHash> chain_stats;
 
1078
  stat.macro_rule_idx = old_size;
1079
  macros.push_back(MacroRule{name, key.rule_ids, rel_ab, rel_bc, rel_ac, 0});
1080
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1081
  };
1082
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1083
  // VERIFIER (§5.3.4): re-check a candidate answer edge against the rule set,
1084
  // recursively down to its premises. A stale derivation fails; Layer 3 must
1085
  // emit "unknown", not the stale answer.
 
1133
  }
1134
  };
1135
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1136
  // ---------------------------------------------------------------------------
1137
  // THE SIX DISCOVERY QUERIES (inference.hpp) — find what the graph does NOT
1138
  // say: ungrounded islands, dangling concepts, the exact missing bridge,
engine/core/roles.hpp CHANGED
@@ -61,32 +61,7 @@ namespace roles {
61
  inline bool& typed_lanes_enabled() { static bool on = false; return on; }
62
 
63
  // -- closed-class function words (normalized/stemmed forms) ------------------
64
- // -- M9-LEARNED FUNCTION WORDS -------------------------------------------------
65
- // The hardcoded kFn[] list below is a RULEBOOK in the inference path: it decides
66
- // who may be a role anchor, which is exactly the job the architecture should not
67
- // be delegating to a person. It is now a FALLBACK ONLY.
68
- //
69
- // The primary source is the FABRIC: a concept whose document frequency exceeds a
70
- // fraction of all lessons is a function word, because function words are exactly
71
- // the things that co-occur with everything. That statistic is already computed
72
- // for the CMD/MIMS rarity weighting (note_df / the IDF5 tail) -- it was simply
73
- // never consulted here. Loading it puts the decision in the MODEL, where the user
74
- // wants it: `decide` becomes a runner over learned structure instead of a reader
75
- // of a hardcoded table.
76
- inline std::unordered_set<std::string>& learned_fn_words() {
77
- static std::unordered_set<std::string> w;
78
- return w;
79
- }
80
- inline bool fn_words_loaded() { return !learned_fn_words().empty(); }
81
- inline void load_function_words(std::vector<std::string> words) {
82
- learned_fn_words().clear();
83
- for (auto& w : words) learned_fn_words().insert(std::move(w));
84
- }
85
-
86
  inline bool is_function_word(const std::string& t) {
87
- // PRIMARY: learned from the substrate's own document frequencies.
88
- if (fn_words_loaded() && learned_fn_words().count(t)) return true;
89
- if (fn_words_loaded()) return false; // learned table is authoritative
90
  static const char* const kFn[] = {
91
  "the", "a", "an", "of", "to", "for", "with", "on", "at", "by", "from",
92
  "in", "into", "about", "as", "is", "are", "was", "were", "be", "been",
@@ -96,16 +71,7 @@ inline bool is_function_word(const std::string& t) {
96
  "shall", "may", "might", "must", "and", "or", "but", "if", "then",
97
  "than", "so", "very", "realli", "just", "also", "again", "there",
98
  "here", "what", "which", "who", "whom", "when", "where", "whi", "how",
99
- "pleas", "kindli", "now", "yet", "not",
100
- // M9: STEMS of function words that porter_stem() produces and that were
101
- // NOT in the list above, so they escaped as CONTENT words. Measured
102
- // (tools/probe: are->ar, was->wa, this->thi, they->thei, may->mai).
103
- // "was->wa" is the worst of these: in "the radio WAS found by Tariq" the
104
- // fragment "wa" was being tagged Role::S — i.e. a piece of the copula was
105
- // elected the subject while the real agent Tariq got Role::O. That single
106
- // miss is the root cause of the last-mentioned-entity failure measured on
107
- // tools/reason30.py. A stemmed function word must never be a role anchor.
108
- "ar", "wa", "thi", "thei", "mai", nullptr};
109
  for (int i = 0; kFn[i]; ++i) if (t == kFn[i]) return true;
110
  return false;
111
  }
@@ -174,27 +140,7 @@ inline bool is_verb_cue(const std::string& t) {
174
  // ---------------------------------------------------------------------------
175
  enum class Role { S, V, O, M, F };
176
 
177
- // M9: CLAUSE SEGMENTATION.
178
- //
179
- // tag() was single-clause: S came from before the FIRST verb and O from after
180
- // the LAST verb, which silently drops every intermediate subject. On
181
- // "Tariq picked up the red key. Salma took the blue key."
182
- // S = Tariq (before the first verb), O = "blue" (after the last verb), so
183
- // SALMA -- the subject of the second clause -- received NO role at all.
184
- // Measured on tools/reason30.py (model-mega-v2): 7 of 13 misses answered the
185
- // final-mentioned entity, because only the final clause's words were ever bound
186
- // to a role.
187
- //
188
- // The fix segments on clause boundaries and tags each clause with the original
189
- // single-clause rule, then splices the results back. Deterministic and
190
- // order-stable; a single-clause input (the common case) is unchanged, so the
191
- // existing unit tests still hold.
192
- inline bool is_clause_break(const std::string& t) {
193
- return t == "." || t == "!" || t == "?" || t == ";" || t == "then";
194
- }
195
-
196
- // tag one already-bounded clause: the pre-existing logic, verbatim.
197
- inline std::vector<Role> tag_clause(const std::vector<std::string>& words) {
198
  const std::size_t n = words.size();
199
  std::vector<Role> r(n, Role::M);
200
  if (n == 0) return r;
@@ -241,27 +187,6 @@ inline std::vector<Role> tag_clause(const std::vector<std::string>& words) {
241
  return r;
242
  }
243
 
244
- // Segment, tag each clause independently, splice back. Clause-final
245
- // punctuation is left as Role::F so it can never become an anchor.
246
- inline std::vector<Role> tag(const std::vector<std::string>& words) {
247
- std::vector<Role> out(words.size(), Role::F);
248
- std::vector<std::string> cur;
249
- std::size_t out_at = 0;
250
- auto flush = [&]() {
251
- if (cur.empty()) return;
252
- const std::vector<Role> cr = tag_clause(cur);
253
- for (std::size_t i = 0; i < cr.size(); ++i) out[out_at + i] = cr[i];
254
- out_at += cr.size();
255
- cur.clear();
256
- };
257
- for (const std::string& w : words) {
258
- if (is_clause_break(w)) { flush(); if (out_at < out.size()) { out[out_at] = Role::F; ++out_at; } }
259
- else cur.push_back(w);
260
- }
261
- flush();
262
- return out;
263
- }
264
-
265
  // negated-verb detection: a negation cue within 2 tokens before the first V
266
  inline bool verb_negated(const std::vector<std::string>& words) {
267
  const std::vector<Role> r = tag(words);
 
61
  inline bool& typed_lanes_enabled() { static bool on = false; return on; }
62
 
63
  // -- closed-class function words (normalized/stemmed forms) ------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  inline bool is_function_word(const std::string& t) {
 
 
 
65
  static const char* const kFn[] = {
66
  "the", "a", "an", "of", "to", "for", "with", "on", "at", "by", "from",
67
  "in", "into", "about", "as", "is", "are", "was", "were", "be", "been",
 
71
  "shall", "may", "might", "must", "and", "or", "but", "if", "then",
72
  "than", "so", "very", "realli", "just", "also", "again", "there",
73
  "here", "what", "which", "who", "whom", "when", "where", "whi", "how",
74
+ "pleas", "kindli", "now", "yet", "not", nullptr};
 
 
 
 
 
 
 
 
 
75
  for (int i = 0; kFn[i]; ++i) if (t == kFn[i]) return true;
76
  return false;
77
  }
 
140
  // ---------------------------------------------------------------------------
141
  enum class Role { S, V, O, M, F };
142
 
143
+ inline std::vector<Role> tag(const std::vector<std::string>& words) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  const std::size_t n = words.size();
145
  std::vector<Role> r(n, Role::M);
146
  if (n == 0) return r;
 
187
  return r;
188
  }
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  // negated-verb detection: a negation cue within 2 tokens before the first V
191
  inline bool verb_negated(const std::vector<std::string>& words) {
192
  const std::vector<Role> r = tag(words);
engine/core/si_substrate.hpp CHANGED
@@ -165,6 +165,16 @@ struct SubstrateConfig {
165
  float learn_eta = 0.10f; // Hebbian learning rate
166
  float lane_decay = 0.995f; // per-lesson lane weight decay
167
  std::size_t lane_cap = 256; // max lanes per node (weakest evicted)
 
 
 
 
 
 
 
 
 
 
168
  float hop_coupling = 0.35f; // 1-hop lane contribution at readout
169
  // -- v3.2 semantic field constants ---------------------------------------
170
  float sem_coupling = 0.12f; // resonance outflow fraction of retained energy
@@ -174,54 +184,6 @@ struct SubstrateConfig {
174
  int sem_neighbors = 6; // resonance edges per node
175
  float ctx_missing = 0.60f; // lane flow factor when required context is absent
176
  float ctx_forbidden = 0.20f; // lane flow factor when forbidden context is present
177
- // -- M3: COMPLEMENTARY LEARNING SYSTEMS (hippocampal / cortical split) ----
178
- // One store must currently hold BOTH the taxonomy and every episode, under a
179
- // single ~138-lesson half-life (lane_decay 0.995). Measured consequence: SST-2
180
- // one-pass 0.896 vs 4-chunk 0.814 — chunking LOST, because the re-intern
181
- // penalty roughly cancels the decay benefit when one store serves both roles.
182
- //
183
- // McClelland's Complementary Learning Systems says the brain runs two: the
184
- // hippocampus encodes individual episodes FAST and sparsely, the neocortex
185
- // extracts slowly-learned regular structure, and replay moves episodes into
186
- // the slow system where they GENERALISE (only regularities survive).
187
- //
188
- // Physical form here: two lane populations.
189
- // hippocampal — the existing out_ store, decays per lesson as before.
190
- // cortical — an additional, near-non-decaying conductance population that
191
- // only receives a lane once that lane's eligibility trace
192
- // crosses cortical_gate. That gate IS the consolidation step:
193
- // coincidence across lessons, not a single binding, is what
194
- // makes structure cortical. Both feed the same CSR, so
195
- // cortical structure propagates like any other conductance.
196
- // -- M5: NTDA (action-potential thresholding, edge death, modulators) ------
197
- // Three mechanisms from ntda.md, all expressed as physics on lanes rather
198
- // than as heuristics in the readout:
199
- //
200
- // (a) THRESHOLD GATING. A lane accumulates VOLTAGE on each binding
201
- // opportunity and only actually binds when that voltage reaches theta;
202
- // then it RESETS. So a lane cannot fire twice without being
203
- // re-stimulated. This replaces "one bind per lesson" with a real
204
- // refractory period, and it is what lets rare conjunctions accumulate
205
- // instead of being averaged into noise on their first appearance.
206
- // (b) EDGE DEATH. Conductivity decays per lesson and lanes below
207
- // edge_death are DELETED, so the ontology physically reshapes around
208
- // what the fabric still uses. SyFox had no concept of an edge dying.
209
- // (c) MODULATORS. theta is lowered by novelty (dopamine: risk a wild
210
- // analogy when the input is unfamiliar) and raised by contradiction
211
- // (cortisol: hyper-focus on the max-conductivity path). In a substrate
212
- // whose accuracy collapses to deferral, an explicit exploration term
213
- // keyed to novelty is the missing piece.
214
- bool ntda_on = false; // M5 master gate (default off == pre-M5)
215
- float ntda_theta = 1.0f; // voltage needed to fire a lane
216
- float ntda_dopamine = 0.30f; // max theta reduction at novelty = 1
217
- float ntda_cortisol = 0.50f; // max theta increase at contradiction = 1
218
- float edge_decay = 0.9995f; // per-lesson conductivity decay
219
- float edge_death = 0.002f; // delete a lane below this weight
220
- bool cls_split = false; // M3 master gate (default off == pre-M3)
221
- float cortical_decay = 0.9999f;// retained for disclosure; cortical lanes are
222
- // not touched by enforce_lane_decay at all
223
- float cortical_gate = 3.0f; // eligibility (lesson co-occurrences) needed
224
- float cortical_gain = 0.5f; // readout weight of a cortical vs hip lane
225
  };
226
 
227
  inline float fnv1a_hash(const std::string& s) { // deterministic token hash
@@ -294,32 +256,6 @@ public:
294
  }
295
  std::uint64_t df_lesson_count() const { return df_lessons_; }
296
  std::size_t df_table_size() const { return df_.size(); }
297
- // M9-LEARNED: the document-frequency table, exposed so the role tagger can
298
- // learn what a FUNCTION WORD is from the fabric instead of consulting a
299
- // hardcoded list. A token seen in a large fraction of lessons is a function
300
- // word; that is a property of the DATA, not of the source file.
301
- std::uint32_t node_df(NodeId id) const {
302
- const auto it = df_.find(id);
303
- return it == df_.end() ? 0u : it->second;
304
- }
305
- // Top-N most frequent concepts, as (label, df) sorted by df desc then label.
306
- // Deterministic: ties broken by label, never by hash order.
307
- std::vector<std::pair<std::string, std::uint32_t>> df_ranked(
308
- std::size_t top_n) const {
309
- std::vector<std::pair<std::string, std::uint32_t>> out;
310
- out.reserve(df_.size());
311
- for (const auto& kv : df_)
312
- if (kv.first < nodes_.size())
313
- out.emplace_back(nodes_[kv.first].concept, kv.second);
314
- std::sort(out.begin(), out.end(),
315
- [](const std::pair<std::string, std::uint32_t>& x,
316
- const std::pair<std::string, std::uint32_t>& y) {
317
- if (x.second != y.second) return x.second > y.second;
318
- return x.first < y.first;
319
- });
320
- if (out.size() > top_n) out.resize(top_n);
321
- return out;
322
- }
323
  bool idf_active() const { return !df_.empty() && df_lessons_ > 0; }
324
  float idf_factor(NodeId id) const {
325
  if (!idf_active()) return 1.0f;
@@ -335,123 +271,7 @@ public:
335
  add_lane(b, a, w);
336
  }
337
 
338
- // M3: eligibility + cortical consolidation. A lane reaches the cortical
339
- // population only after cortical_gate DISTINCT lesson co-occurrences, which
340
- // is the physical form of "replay consolidates a regularity, not an
341
- // episode". Saturating, like add_lane, so it is order-insensitive once a
342
- // lane is established (the CLAMP is why cortical lanes are safe to merge
343
- // across passes where hippocampal ones are not).
344
- void note_eligibility(NodeId a, NodeId b) {
345
- if (!cfg_.cls_split) return;
346
- const std::uint64_t k = lane_key(a, b);
347
- const float e = (elig_.count(k) ? elig_[k] : 0.0f) + 1.0f;
348
- elig_[k] = e;
349
- if (e < cfg_.cortical_gate) return;
350
- auto& cl = cortical_[a];
351
- for (auto& l : cl)
352
- if (l.first == b) { l.second = std::min(4.0f, std::max(0.0f, l.second + 0.25f)); csr_dirty_ = true; return; }
353
- cl.emplace_back(b, 0.25f);
354
- csr_dirty_ = true;
355
- }
356
- void set_cls_split(bool on) { cfg_.cls_split = on; if (on) csr_dirty_ = true; }
357
- bool cls_split() const { return cfg_.cls_split; }
358
- void set_cortical_gate(float g) { cfg_.cortical_gate = g; }
359
- void set_cortical_gain(float g) { cfg_.cortical_gain = g; if (g != cfg_.cortical_gain) csr_dirty_ = true; }
360
- std::size_t cortical_lanes() const {
361
- std::size_t k = 0;
362
- for (const auto& kv : cortical_) k += kv.second.size();
363
- return k;
364
- }
365
- std::size_t eligibility_traces() const { return elig_.size(); }
366
-
367
- // -- M5 controls ---------------------------------------------------------
368
- // M9/encoder: configure the projection. Existing W is PRESERVED so a
369
- // trained encoder survives a re-learn; pass reset=true to discard.
370
- void set_encoder(std::size_t dim, std::size_t chans, bool reset = false) {
371
- if (dim == 0 || chans == 0) return;
372
- if (reset || enc_dim_ != dim || enc_chans_ != chans) {
373
- enc_dim_ = dim; enc_chans_ = chans;
374
- enc_W_.assign(chans * dim, 0.0f);
375
- }
376
- enc_y_.assign(chans, 0.0f);
377
- }
378
- void set_encoder_eta(float e) { enc_eta_ = e; }
379
- std::size_t enc_chans() const { return enc_chans_; }
380
- std::size_t enc_dim() const { return enc_dim_; }
381
- std::uint64_t enc_updates() const { return enc_updates_; }
382
- bool has_encoder() const { return !enc_W_.empty(); }
383
-
384
- // Oja update: W += eta * g * (x y^T - y y^T W).
385
- // x pre-synaptic (encoder embedding, length d)
386
- // y post-synaptic (settled field, length C)
387
- // g ONE global scalar -- reused from the NTDA modulator, so exploration
388
- // state already modulates the encoder. No spatial information, so no
389
- // update ever needs a backward pass.
390
- void encoder_update(const std::vector<float>& x, const std::vector<float>& y, float g) {
391
- if (enc_W_.empty() || x.size() != enc_dim_ || y.size() != enc_chans_) return;
392
- const float lr = enc_eta_ * g;
393
- if (lr == 0.0f) return;
394
- for (std::size_t c = 0; c < enc_chans_; ++c) {
395
- const float yc = y[c];
396
- if (yc == 0.0f) continue;
397
- float* row = &enc_W_[c * enc_dim_];
398
- for (std::size_t d = 0; d < enc_dim_; ++d)
399
- row[d] += lr * (y[c] * x[d] - yc * y[c] * row[d]);
400
- }
401
- enc_y_ = y;
402
- ++enc_updates_;
403
- }
404
-
405
- // Project an encoder embedding into channel space and inject as energy.
406
- // This is the ONLY path by which an external representation touches the
407
- // field; the lane fabric is otherwise untouched, so typed/bigram lanes and
408
- // their order survive verbatim.
409
- std::vector<float> encoder_project(const std::vector<float>& x) const {
410
- std::vector<float> y(enc_chans_, 0.0f);
411
- if (enc_W_.empty() || x.size() != enc_dim_) return y;
412
- for (std::size_t c = 0; c < enc_chans_; ++c) {
413
- const float* row = &enc_W_[c * enc_dim_];
414
- float acc = 0.0f;
415
- for (std::size_t d = 0; d < enc_dim_; ++d) acc += row[d] * x[d];
416
- y[c] = acc;
417
- }
418
- return y;
419
- }
420
- void set_ntda(bool on) { cfg_.ntda_on = on; }
421
- bool ntda_on() const { return cfg_.ntda_on; }
422
- void set_ntda_theta(float t) { cfg_.ntda_theta = t; }
423
- void set_novelty(float n) { novelty_ = std::min(1.0f, std::max(0.0f, n)); }
424
- void set_conflict(float c) { conflict_ = std::min(1.0f, std::max(0.0f, c)); }
425
- float current_theta() const {
426
- if (!cfg_.ntda_on) return cfg_.ntda_theta;
427
- // dopamine lowers theta on novelty (exploration); cortisol raises it on
428
- // contradiction (exploitation). Both are multiplicative around 1.
429
- const float d = 1.0f - cfg_.ntda_dopamine * novelty_;
430
- const float c = 1.0f + cfg_.ntda_cortisol * conflict_;
431
- return std::max(0.05f, cfg_.ntda_theta * d * c);
432
- }
433
- std::uint64_t ntda_spikes() const { return ntda_spikes_; }
434
- std::uint64_t ntda_deaths() const { return ntda_deaths_; }
435
- std::size_t voltage_traces() const { return volt_.size(); }
436
-
437
- // M5 (a): accumulate voltage; fire and reset only at threshold. Returns true
438
- // when the lane actually bound. With ntda off this is always true, so the
439
- // pre-M5 path is byte-identical.
440
- bool ntda_gate(NodeId a, NodeId b) {
441
- if (!cfg_.ntda_on) return true;
442
- const std::uint64_t k = lane_key(a, b);
443
- const float th = current_theta();
444
- float& v = volt_[k];
445
- v += 1.0f;
446
- if (v < th) return false;
447
- v = 0.0f; // refractory: cannot re-fire without re-stimulation
448
- ++ntda_spikes_;
449
- return true;
450
- }
451
-
452
  void add_lane(NodeId a, NodeId b, float w) {
453
- note_eligibility(a, b);
454
- if (!ntda_gate(a, b)) return; // M5 (a): below threshold, no bind
455
  auto& lanes = out_[a];
456
  for (auto& l : lanes)
457
  if (l.first == b) { l.second = std::min(4.0f, std::max(0.0f, l.second + w)); csr_dirty_ = true; return; }
@@ -1479,110 +1299,6 @@ public:
1479
  f.write(reinterpret_cast<const char*>(&cons), 4);
1480
  f.write(reinterpret_cast<const char*>(&tot), 4);
1481
  }
1482
- // -- M3 CLS tail -------------------------------------------------------
1483
- // cortical lanes + eligibility traces. Persisted because the M2 lesson
1484
- // applies directly: consolidated structure that is not written out is
1485
- // structure that does not exist after a reload. Magic-guarded so a
1486
- // pre-M3 file (which ends at the previous tail) still loads.
1487
- // ALWAYS write the CLS header, even when empty. The loader reads tail
1488
- // magics unconditionally and advances the stream, so an OMITTED CLS
1489
- // block (an NTDA-only fabric has no cortical lanes) left the reader 4
1490
- // bytes ahead and every later tail mis-matched -- NTDA silently failed
1491
- // to load. Tails are a fixed sequence; skipping one breaks alignment.
1492
- {
1493
- const std::uint32_t cls_magic = 0x434C5331u; // 'CLS1'
1494
- f.write(reinterpret_cast<const char*>(&cls_magic), 4);
1495
- using CRow = std::unordered_map<NodeId,
1496
- std::vector<std::pair<NodeId, float>>>::value_type;
1497
- std::vector<const CRow*> cs;
1498
- cs.reserve(cortical_.size());
1499
- for (const auto& kv : cortical_) cs.push_back(&kv);
1500
- std::sort(cs.begin(), cs.end(),
1501
- [](const auto* x, const auto* y) { return x->first < y->first; });
1502
- std::uint32_t cn = static_cast<std::uint32_t>(cs.size());
1503
- f.write(reinterpret_cast<const char*>(&cn), 4);
1504
- for (const auto* kv : cs) {
1505
- f.write(reinterpret_cast<const char*>(&kv->first), 4);
1506
- std::uint32_t m = static_cast<std::uint32_t>(kv->second.size());
1507
- f.write(reinterpret_cast<const char*>(&m), 4);
1508
- for (const auto& l : kv->second) {
1509
- f.write(reinterpret_cast<const char*>(&l.first), 4);
1510
- f.write(reinterpret_cast<const char*>(&l.second), 4);
1511
- }
1512
- }
1513
- std::vector<std::pair<std::uint64_t, float>> es(elig_.begin(), elig_.end());
1514
- std::sort(es.begin(), es.end(),
1515
- [](const std::pair<std::uint64_t, float>& x,
1516
- const std::pair<std::uint64_t, float>& y) { return x.first < y.first; });
1517
- std::uint32_t en = static_cast<std::uint32_t>(es.size());
1518
- f.write(reinterpret_cast<const char*>(&en), 4);
1519
- for (const auto& kv : es) {
1520
- std::uint32_t a = static_cast<std::uint32_t>(kv.first >> 32);
1521
- std::uint32_t b = static_cast<std::uint32_t>(kv.first & 0xffffffffull);
1522
- f.write(reinterpret_cast<const char*>(&a), 4);
1523
- f.write(reinterpret_cast<const char*>(&b), 4);
1524
- f.write(reinterpret_cast<const char*>(&kv.second), 4);
1525
- }
1526
- }
1527
-
1528
- // -- M5 NTDA tail ------------------------------------------------------
1529
- // volt_ MUST persist: a lane that had accumulated 1.5V toward a
1530
- // threshold of 2 restarts from ZERO after a reload, so learning
1531
- // behaviour after reload differs from behaviour before it. That is the
1532
- // same defect class as M2's unserialised MetaLearner, reintroduced in
1533
- // new code -- which is exactly why it needed catching again.
1534
- // BOTH tails are written UNCONDITIONALLY, in a fixed order. Conditional
1535
- // tails are what caused the CLS1 misalignment bug: the loader reads
1536
- // magics unconditionally and advances the stream, so an omitted block
1537
- // desynchronised every later one. Same lesson, third application.
1538
- {
1539
- const std::uint32_t ntd_magic = 0x4E544441u; // 'NTDA'
1540
- f.write(reinterpret_cast<const char*>(&ntd_magic), 4);
1541
- const float th = cfg_.ntda_theta, ed = cfg_.edge_decay, dt = cfg_.edge_death;
1542
- f.write(reinterpret_cast<const char*>(&th), 4);
1543
- f.write(reinterpret_cast<const char*>(&ed), 4);
1544
- f.write(reinterpret_cast<const char*>(&dt), 4);
1545
- f.write(reinterpret_cast<const char*>(&ntda_spikes_), 8);
1546
- f.write(reinterpret_cast<const char*>(&ntda_deaths_), 8);
1547
- std::vector<std::pair<std::uint64_t, float>> vs(volt_.begin(), volt_.end());
1548
- std::sort(vs.begin(), vs.end(),
1549
- [](const std::pair<std::uint64_t, float>& x,
1550
- const std::pair<std::uint64_t, float>& y) { return x.first < y.first; });
1551
- std::uint32_t vn = static_cast<std::uint32_t>(vs.size());
1552
- f.write(reinterpret_cast<const char*>(&vn), 4);
1553
- for (const auto& kv : vs) {
1554
- std::uint32_t a = static_cast<std::uint32_t>(kv.first >> 32);
1555
- std::uint32_t b = static_cast<std::uint32_t>(kv.first & 0xffffffffull);
1556
- f.write(reinterpret_cast<const char*>(&a), 4);
1557
- f.write(reinterpret_cast<const char*>(&b), 4);
1558
- f.write(reinterpret_cast<const char*>(&kv.second), 4);
1559
- }
1560
- }
1561
-
1562
- // -- L1 ENCODER tail ----------------------------------------------------
1563
- // THIRD instance of the same defect (after M2's MetaLearner and M5's
1564
- // voltage): runtime-only state that is not written out does not exist
1565
- // after a reload. W learned by thousands of Oja updates is the whole
1566
- // point of the encoder, and losing it silently makes --encoder-dim look
1567
- // like it "did nothing" (stats reported encoder_dim: 0).
1568
- {
1569
- const std::uint32_t enc_magic = 0x454E4331u; // 'ENC1'
1570
- f.write(reinterpret_cast<const char*>(&enc_magic), 4);
1571
- const bool have_W = !enc_W_.empty();
1572
- const std::uint64_t z = 0;
1573
- const std::uint64_t dd = have_W ? enc_dim_ : z;
1574
- const std::uint64_t cc = have_W ? enc_chans_ : z;
1575
- const std::uint64_t n = have_W ? enc_W_.size() : z;
1576
- f.write(reinterpret_cast<const char*>(&dd), 8);
1577
- f.write(reinterpret_cast<const char*>(&cc), 8);
1578
- f.write(reinterpret_cast<const char*>(&enc_eta_), 4);
1579
- f.write(reinterpret_cast<const char*>(&enc_updates_), 8);
1580
- f.write(reinterpret_cast<const char*>(&n), 8);
1581
- if (have_W)
1582
- f.write(reinterpret_cast<const char*>(enc_W_.data()),
1583
- static_cast<std::streamsize>(n * sizeof(float)));
1584
- }
1585
-
1586
  }
1587
 
1588
  // v3.2.1: reports failure. A missing substrate used to load SILENTLY as an
@@ -1756,94 +1472,16 @@ public:
1756
  if (!ok) order_stats_.clear(); // torn tail: stay inert
1757
  }
1758
  }
1759
- // v3.9.1 M3 CLS tail (optional, magic-guarded 'CLS1'): pre-M3 files end
1760
- // after ORD1, the failed magic read leaves cortical_ and elig_ empty,
1761
- // and the substrate replays exactly as before.
1762
- std::uint32_t cls_magic = 0;
1763
- if (f.read(reinterpret_cast<char*>(&cls_magic), 4) && cls_magic == 0x434C5331u) {
1764
- std::uint32_t cn = 0;
1765
- if (f.read(reinterpret_cast<char*>(&cn), 4)) {
1766
- bool ok = true;
1767
- for (std::uint32_t k = 0; k < cn && ok; ++k) {
1768
- NodeId a = 0;
1769
- std::uint32_t m = 0;
1770
- ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&a), 4));
1771
- if (ok) ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&m), 4));
1772
- if (ok) a = static_cast<NodeId>(a);
1773
- for (std::uint32_t j = 0; j < m && ok; ++j) {
1774
- NodeId b = 0;
1775
- float w = 0.0f;
1776
- ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&b), 4));
1777
- if (ok) ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&w), 4));
1778
- if (ok) cortical_[a].emplace_back(static_cast<NodeId>(b), w);
1779
- }
1780
- }
1781
- if (!ok) cortical_.clear(); // torn tail: stay inert
1782
- std::uint32_t en = 0;
1783
- if (ok && f.read(reinterpret_cast<char*>(&en), 4)) {
1784
- for (std::uint32_t k = 0; k < en && ok; ++k) {
1785
- std::uint32_t a = 0, b = 0;
1786
- float e = 0.0f;
1787
- ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&a), 4));
1788
- if (ok) ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&b), 4));
1789
- if (ok) ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&e), 4));
1790
- if (ok) elig_[lane_key(static_cast<NodeId>(a), static_cast<NodeId>(b))] = e;
1791
- }
1792
- if (!ok) elig_.clear();
1793
- }
1794
- if (!cortical_.empty()) csr_dirty_ = true;
1795
- }
1796
- }
1797
- // v3.9.1 M5 NTDA tail (optional, magic-guarded 'NTDA'): absent => ntda
1798
- // stays off and the fabric replays exactly as pre-M5.
1799
- std::uint32_t ntd_magic = 0;
1800
- if (f.read(reinterpret_cast<char*>(&ntd_magic), 4) && ntd_magic == 0x4E544441u) {
1801
- float th = 0, ed = 0, dt = 0;
1802
- bool ok = f.read(reinterpret_cast<char*>(&th), 4)
1803
- && f.read(reinterpret_cast<char*>(&ed), 4)
1804
- && f.read(reinterpret_cast<char*>(&dt), 4);
1805
- if (ok) ok = f.read(reinterpret_cast<char*>(&ntda_spikes_), 8)
1806
- && f.read(reinterpret_cast<char*>(&ntda_deaths_), 8);
1807
- cfg_.ntda_on = true; cfg_.ntda_theta = th; cfg_.edge_decay = ed; cfg_.edge_death = dt;
1808
- std::uint32_t vn = 0;
1809
- if (ok && f.read(reinterpret_cast<char*>(&vn), 4)) {
1810
- for (std::uint32_t k = 0; k < vn && ok; ++k) {
1811
- std::uint32_t a = 0, b = 0; float v = 0.0f;
1812
- ok = f.read(reinterpret_cast<char*>(&a), 4)
1813
- && f.read(reinterpret_cast<char*>(&b), 4)
1814
- && f.read(reinterpret_cast<char*>(&v), 4);
1815
- if (ok) volt_[lane_key(static_cast<NodeId>(a), static_cast<NodeId>(b))] = v;
1816
- }
1817
- if (!ok) volt_.clear(); // torn tail: start clean, not half
1818
- }
1819
- }
1820
- std::uint32_t enc_magic_pre = 0;
1821
- // ENC1 is written immediately after NTDA; both headers are always
1822
- // present so the tail sequence can never desynchronise.
1823
- std::uint32_t enc_magic = 0;
1824
- if (f.read(reinterpret_cast<char*>(&enc_magic), 4) && enc_magic == 0x454E4331u) {
1825
- std::uint64_t dd = 0, cc = 0, n = 0;
1826
- if (f.read(reinterpret_cast<char*>(&dd), 8)
1827
- && f.read(reinterpret_cast<char*>(&cc), 8)
1828
- && f.read(reinterpret_cast<char*>(&enc_eta_), 4)
1829
- && f.read(reinterpret_cast<char*>(&enc_updates_), 8)
1830
- && f.read(reinterpret_cast<char*>(&n), 8)) {
1831
- enc_dim_ = static_cast<std::size_t>(dd);
1832
- enc_chans_ = static_cast<std::size_t>(cc);
1833
- enc_W_.resize(static_cast<std::size_t>(n));
1834
- // explicit bool(): the istream& overload is not contextually
1835
- // convertible here.
1836
- bool ok = static_cast<bool>(
1837
- f.read(reinterpret_cast<char*>(enc_W_.data()),
1838
- static_cast<std::streamsize>(n * sizeof(float))));
1839
- if (!ok) enc_W_.clear();
1840
- enc_y_.assign(enc_chans_, 0.0f);
1841
- }
1842
- }
1843
  return true;
1844
  }
1845
 
1846
  const SubstrateConfig& config() const { return cfg_; }
 
 
 
 
 
 
1847
 
1848
  // -- LANE PROVENANCE + SURGERY (derivation-layer surface, see derive.hpp) --
1849
  // Derived lanes are laid by rule composition over existing fabric, not by
@@ -2005,61 +1643,20 @@ private:
2005
 
2006
  void enforce_lane_decay() {
2007
  for (auto& kv : out_)
2008
- for (auto& l : kv.second) l.second *= cfg_.lane_decay;
2009
- // M5 (b) EDGE DEATH. Conductivity decays faster than the weight does, and
2010
- // a lane that falls below edge_death is DELETED outright rather than
2011
- // lingering as a near-zero edge the readout must still consider. The
2012
- // ontology therefore reshapes around what the fabric still uses, which
2013
- // is a mechanism syfox did not previously have at all.
2014
- if (cfg_.ntda_on) {
2015
- for (auto& kv : out_)
2016
- for (auto& l : kv.second) l.second *= cfg_.edge_decay;
2017
- for (auto it = out_.begin(); it != out_.end();) {
2018
- auto& vec = it->second;
2019
- vec.erase(std::remove_if(vec.begin(), vec.end(),
2020
- [&](const std::pair<NodeId, float>& l) {
2021
- if (l.second < cfg_.edge_death) { ++ntda_deaths_; return true; }
2022
- return false;
2023
- }),
2024
- vec.end());
2025
- if (vec.empty()) it = out_.erase(it); else ++it;
2026
  }
2027
- }
2028
  csr_dirty_ = true;
2029
  }
2030
 
 
2031
  SubstrateConfig cfg_;
2032
  std::unordered_map<std::string, NodeId> index_;
2033
  std::vector<Node> nodes_;
2034
  std::unordered_map<NodeId, std::vector<std::pair<NodeId, float>>> out_;
2035
- // M3: cortical lanes (consolidated structure) + the per-lane eligibility
2036
- // traces that decide when a hippocampal lane is CONSOLIDATED. Eligibility is
2037
- // monotone and never decayed: it counts distinct lesson co-occurrences,
2038
- // which is the coincidence signal consolidation is supposed to key on.
2039
- std::unordered_map<NodeId, std::vector<std::pair<NodeId, float>>> cortical_;
2040
- std::unordered_map<std::uint64_t, float> elig_;
2041
- // M5: per-lane accumulated voltage (the action potential) and the last
2042
- // novelty/contradiction levels fed in by the caller.
2043
- std::unordered_map<std::uint64_t, float> volt_;
2044
- mutable float novelty_ = 0.0f; // 0..1, set by decide-time OOD signal
2045
- mutable float conflict_ = 0.0f; // 0..1, set from the tension gate
2046
- std::uint64_t ntda_spikes_ = 0; // lanes that actually fired
2047
- // -- L1 ENCODER PROJECTION (GHL/Oja) --------------------------------------
2048
- // W : C x d, learned by LOCAL Hebbian plasticity -- Oja's subtractive term
2049
- // plus a single global sign scalar g. No gradient, no backward pass, no
2050
- // dependence on any other row. Rationale and citations in
2051
- // ARCHITECTURE.md §15 (CLAPP, NeurIPS 2021; GHL).
2052
- //
2053
- // Channels are how an encoder ADDRESSES the lane fabric; they never replace
2054
- // a lane with a vector. A 768 x 26,000 projection would be a second network
2055
- // wearing a physics hat; 768 x 32 is not.
2056
- std::size_t enc_chans_ = 0; // C
2057
- std::size_t enc_dim_ = 0; // d (encoder embedding width)
2058
- std::vector<float> enc_W_; // C*d, row-major
2059
- std::vector<float> enc_y_; // C, last post-synaptic response
2060
- float enc_eta_ = 0.01f;
2061
- std::uint64_t enc_updates_ = 0;
2062
- std::uint64_t ntda_deaths_ = 0; // lanes deleted by edge death
2063
  // Derivation provenance: lane key -> generation (sparse; observed lanes absent = 0)
2064
  std::unordered_map<std::uint64_t, std::uint32_t> derived_gen_;
2065
  // v3.6.0 document-frequency table (node -> lessons containing it) and the
@@ -2185,46 +1782,127 @@ private:
2185
 
2186
  void build_csr() const {
2187
  const std::size_t n = nodes_.size();
2188
- // M3: cortical lanes are an ADDITIONAL conductance population. They go
2189
- // into the same CSR so they propagate exactly like hippocampal lanes —
2190
- // the difference is not how they are read but that enforce_lane_decay
2191
- // never touches them. Order is hippocampal-then-cortical per node, which
2192
- // keeps the float accumulation order deterministic.
2193
- auto row_len = [&](std::size_t i) -> std::size_t {
2194
- std::size_t k = 0;
2195
- auto it = out_.find(static_cast<NodeId>(i));
2196
- if (it != out_.end()) k += it->second.size();
2197
- auto ct = cortical_.find(static_cast<NodeId>(i));
2198
- if (ct != cortical_.end()) k += ct->second.size();
2199
- return k;
2200
- };
2201
  csr_off_.assign(n + 1, 0);
2202
- for (std::size_t i = 0; i < n; ++i) csr_off_[i + 1] = csr_off_[i] + row_len(i);
 
 
 
2203
  csr_dst_.resize(csr_off_[n]);
2204
  csr_w_.resize(csr_off_[n]);
2205
  for (std::size_t i = 0; i < n; ++i) {
2206
- std::size_t k = csr_off_[i];
2207
  auto it = out_.find(static_cast<NodeId>(i));
2208
- if (it != out_.end())
2209
- for (const auto& lane : it->second) {
2210
- csr_dst_[k] = lane.first;
2211
- csr_w_[k] = lane.second;
2212
- ++k;
2213
- }
2214
- auto ct = cortical_.find(static_cast<NodeId>(i));
2215
- if (ct != cortical_.end())
2216
- for (const auto& lane : ct->second) {
2217
- // cortical_gain scales the cortical population down so it
2218
- // supports rather than dominates the hippocampal trace.
2219
- csr_dst_[k] = lane.first;
2220
- csr_w_[k] = lane.second * (cfg_.cls_split ? cfg_.cortical_gain : 1.0f);
2221
- ++k;
2222
- }
2223
  }
2224
  csr_dirty_ = false;
2225
  }
2226
 
 
2227
  public:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2228
  // parallel settle toggle (M5): on OMP builds, >1 threads use per-thread
2229
  // scatter buffers combined in fixed thread order — bit-identical to the
2230
  // sequential path (test-verified). Off builds always run sequential.
 
165
  float learn_eta = 0.10f; // Hebbian learning rate
166
  float lane_decay = 0.995f; // per-lesson lane weight decay
167
  std::size_t lane_cap = 256; // max lanes per node (weakest evicted)
168
+ // v3.9.3 LANE-DECAY FLOOR. CMD §2.3's law saturates the lane weight, so a
169
+ // starved lane keeps a real (small) value; the port's unbounded multiply
170
+ // drove it to the float32 denormal floor (1.4e-43) where it is
171
+ // numerically dead. TSDA §2: "It remains in long-term memory (the edge
172
+ // still exists), but it requires more cognitive energy to retrieve." A
173
+ // floor is exactly that: the edge persists with reduced retrievability.
174
+ // DEFAULT 0 = OFF (bit-identical to every pre-v3.9.3 fabric; the replay
175
+ // contract is preserved). Set it via --lane-floor F when building a new
176
+ // fabric; repair an EXISTING fabric with `syfox repair-lanes`.
177
+ float lane_decay_floor = 0.0f;
178
  float hop_coupling = 0.35f; // 1-hop lane contribution at readout
179
  // -- v3.2 semantic field constants ---------------------------------------
180
  float sem_coupling = 0.12f; // resonance outflow fraction of retained energy
 
184
  int sem_neighbors = 6; // resonance edges per node
185
  float ctx_missing = 0.60f; // lane flow factor when required context is absent
186
  float ctx_forbidden = 0.20f; // lane flow factor when forbidden context is present
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  };
188
 
189
  inline float fnv1a_hash(const std::string& s) { // deterministic token hash
 
256
  }
257
  std::uint64_t df_lesson_count() const { return df_lessons_; }
258
  std::size_t df_table_size() const { return df_.size(); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  bool idf_active() const { return !df_.empty() && df_lessons_ > 0; }
260
  float idf_factor(NodeId id) const {
261
  if (!idf_active()) return 1.0f;
 
271
  add_lane(b, a, w);
272
  }
273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  void add_lane(NodeId a, NodeId b, float w) {
 
 
275
  auto& lanes = out_[a];
276
  for (auto& l : lanes)
277
  if (l.first == b) { l.second = std::min(4.0f, std::max(0.0f, l.second + w)); csr_dirty_ = true; return; }
 
1299
  f.write(reinterpret_cast<const char*>(&cons), 4);
1300
  f.write(reinterpret_cast<const char*>(&tot), 4);
1301
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1302
  }
1303
 
1304
  // v3.2.1: reports failure. A missing substrate used to load SILENTLY as an
 
1472
  if (!ok) order_stats_.clear(); // torn tail: stay inert
1473
  }
1474
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1475
  return true;
1476
  }
1477
 
1478
  const SubstrateConfig& config() const { return cfg_; }
1479
+ // v3.9.3: the lane-decay floor (0 = off; see cfg_.lane_decay_floor).
1480
+ void set_lane_decay_floor(float f) { cfg_.lane_decay_floor = std::max(0.0f, f); }
1481
+ float lane_decay_floor() const { return cfg_.lane_decay_floor; }
1482
+ // v3.9.3: the per-lesson decay constant (0.995 by default).
1483
+ void set_lane_decay(float d) { cfg_.lane_decay = d; }
1484
+ float lane_decay() const { return cfg_.lane_decay; }
1485
 
1486
  // -- LANE PROVENANCE + SURGERY (derivation-layer surface, see derive.hpp) --
1487
  // Derived lanes are laid by rule composition over existing fabric, not by
 
1643
 
1644
  void enforce_lane_decay() {
1645
  for (auto& kv : out_)
1646
+ for (auto& l : kv.second) {
1647
+ l.second *= cfg_.lane_decay;
1648
+ // v3.9.3: keep a starved lane retrievable (floor 0 = off).
1649
+ if (cfg_.lane_decay_floor > 0.0f && l.second < cfg_.lane_decay_floor)
1650
+ l.second = cfg_.lane_decay_floor;
 
 
 
 
 
 
 
 
 
 
 
 
 
1651
  }
 
1652
  csr_dirty_ = true;
1653
  }
1654
 
1655
+
1656
  SubstrateConfig cfg_;
1657
  std::unordered_map<std::string, NodeId> index_;
1658
  std::vector<Node> nodes_;
1659
  std::unordered_map<NodeId, std::vector<std::pair<NodeId, float>>> out_;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1660
  // Derivation provenance: lane key -> generation (sparse; observed lanes absent = 0)
1661
  std::unordered_map<std::uint64_t, std::uint32_t> derived_gen_;
1662
  // v3.6.0 document-frequency table (node -> lessons containing it) and the
 
1782
 
1783
  void build_csr() const {
1784
  const std::size_t n = nodes_.size();
 
 
 
 
 
 
 
 
 
 
 
 
 
1785
  csr_off_.assign(n + 1, 0);
1786
+ for (std::size_t i = 0; i < n; ++i) {
1787
+ auto it = out_.find(static_cast<NodeId>(i));
1788
+ csr_off_[i + 1] = csr_off_[i] + (it == out_.end() ? 0 : it->second.size());
1789
+ }
1790
  csr_dst_.resize(csr_off_[n]);
1791
  csr_w_.resize(csr_off_[n]);
1792
  for (std::size_t i = 0; i < n; ++i) {
 
1793
  auto it = out_.find(static_cast<NodeId>(i));
1794
+ if (it == out_.end()) continue;
1795
+ std::size_t k = csr_off_[i];
1796
+ for (const auto& lane : it->second) {
1797
+ csr_dst_[k] = lane.first;
1798
+ csr_w_[k] = lane.second;
1799
+ ++k;
1800
+ }
 
 
 
 
 
 
 
 
1801
  }
1802
  csr_dirty_ = false;
1803
  }
1804
 
1805
+
1806
  public:
1807
+
1808
+ // -- v3.9.3 LANE REPAIR ----------------------------------------------------
1809
+ // THE DEAD-LANE PATHOLOGY. The port applies CMD §2.3's decay to EVERY lane
1810
+ // on EVERY lesson:
1811
+ // enforce_lane_decay(): for each lane: w *= lane_decay (0.995)
1812
+ // so the weight of a lane last bound at lesson k, in a fabric trained
1813
+ // with N lessons, is w0 * 0.995^(N-k). In float32 that product
1814
+ // UNDERFLOWS to the denormal floor (1.4e-43) after ~20,700 lessons and
1815
+ // then stops decreasing — the lane is numerically dead: the readout sees
1816
+ // it as exactly zero and only a fresh bind can revive it.
1817
+ //
1818
+ // MEASURED on the shipped model/giant-latin fabric (114,060 lessons,
1819
+ // 1,905,169 lanes): 95.09% of lanes carry a weight in (0, 1e-12); the
1820
+ // MEDIAN lane weight is 1.4e-43 (the denormal floor); only 2.42%
1821
+ // (46,161 lanes) exceed 1e-6. The Hebbian memory of the fabric was
1822
+ // effectively erased: what survived was a recency window over the tail
1823
+ // of the corpus, not a memory of it.
1824
+ //
1825
+ // CMD §2.3's actual law is
1826
+ // w <- tanh( (w*lambda + eta*v_b*v_c) / w_max ) * w_max
1827
+ // i.e. a SATURATING growth/decay integrator: the growth term is added on
1828
+ // every co-activity and the ceiling keeps the weight a real number. The
1829
+ // port kept the decay and lost the saturation, so the weight could fall
1830
+ // off the bottom of the number line.
1831
+ //
1832
+ // THE REPAIR. The persisted EVIDENCE LEDGER (v3 Milestone 3) holds the
1833
+ // integral of exactly the growth term the decay was destroying: per
1834
+ // lane, the number of Hebbian supports, the number of counter-events,
1835
+ // and the lesson window it was active in. Rebuilding the weight from the
1836
+ // ledger is the UNDECAYED form of CMD §2.3's law:
1837
+ // w = w_max * tanh( (net_events * bind_scale) / w_max )
1838
+ // with w_max the ceiling the port already clamps to (add_lane) and
1839
+ // bind_scale the same per-lesson magnitude the learn path uses.
1840
+ //
1841
+ // This is a REPAIR of a built fabric, not a change to the learn path:
1842
+ // no equation moves, and a fabric that is re-learned from scratch is
1843
+ // byte-identical. The root cause in the learn path is addressed
1844
+ // separately by the lane-decay FLOOR (see cfg_.lane_decay_floor).
1845
+ struct LaneRepairStats {
1846
+ std::size_t lanes_total = 0;
1847
+ std::size_t lanes_repaired = 0; // lanes the ledger could rebuild
1848
+ std::size_t lanes_dead = 0; // weight < dead_threshold BEFORE
1849
+ std::size_t lanes_revivable= 0; // dead lanes the ledger revives
1850
+ std::size_t lanes_orphan = 0; // dead lanes with no ledger entry
1851
+ std::size_t lanes_live = 0; // lanes above the dead threshold before
1852
+ double weight_before = 0.0;
1853
+ double weight_after = 0.0;
1854
+ };
1855
+
1856
+ // Rebuild lane weights from the persisted evidence ledger. `dead_threshold`
1857
+ // is the weight below which a lane counts as numerically dead. With
1858
+ // `apply` false the stats are computed WITHOUT touching the fabric (a
1859
+ // dry run) — the caller can then see what the repair would do before
1860
+ // committing to it.
1861
+ LaneRepairStats repair_lanes_from_evidence(float dead_threshold = 1e-6f,
1862
+ bool apply = true) {
1863
+ LaneRepairStats st;
1864
+ const float wmax = 4.0f; // the ceiling add_lane() already clamps to
1865
+ std::unordered_map<std::uint64_t, float> target;
1866
+ target.reserve(lane_evidence_.size() * 2 + 16);
1867
+ for (const auto& kv : lane_evidence_) {
1868
+ const NodeId a = static_cast<NodeId>(kv.first >> 32);
1869
+ const NodeId b = static_cast<NodeId>(kv.first & 0xffffffffull);
1870
+ if (a >= nodes_.size() || b >= nodes_.size()) continue;
1871
+ const LaneEvidence& e = kv.second;
1872
+ const long net = static_cast<long>(e.support_events)
1873
+ - static_cast<long>(e.counter_events);
1874
+ if (net <= 0) continue;
1875
+ // the same magnitude the learn path binds with
1876
+ const float wa = 1.0f / std::sqrt(nodes_[a].mass);
1877
+ const float wb = 1.0f / std::sqrt(nodes_[b].mass);
1878
+ const float scale = cfg_.learn_eta * (wa + wb)
1879
+ * idf_factor(a) * order_factor(a, b);
1880
+ const float raw = static_cast<float>(net) * scale;
1881
+ const float w = wmax * std::tanh(raw / wmax);
1882
+ if (w <= 0.0f) continue;
1883
+ target[kv.first] = w;
1884
+ target[lane_key(b, a)] = w; // bind() is symmetric
1885
+ }
1886
+ for (auto& kv : out_) {
1887
+ for (auto& l : kv.second) {
1888
+ ++st.lanes_total;
1889
+ st.weight_before += l.second;
1890
+ if (l.second < dead_threshold) ++st.lanes_dead;
1891
+ const auto it = target.find(lane_key(kv.first, l.first));
1892
+ if (it != target.end()) {
1893
+ if (l.second < dead_threshold) ++st.lanes_revivable;
1894
+ if (apply) l.second = it->second;
1895
+ ++st.lanes_repaired;
1896
+ } else if (l.second < dead_threshold) {
1897
+ ++st.lanes_orphan;
1898
+ }
1899
+ st.weight_after += (apply ? l.second : it != target.end() ? it->second : l.second);
1900
+ }
1901
+ }
1902
+ st.lanes_live = st.lanes_total - st.lanes_dead;
1903
+ csr_dirty_ = true;
1904
+ return st;
1905
+ }
1906
  // parallel settle toggle (M5): on OMP builds, >1 threads use per-thread
1907
  // scatter buffers combined in fixed thread order — bit-identical to the
1908
  // sequential path (test-verified). Off builds always run sequential.
engine/core/syfox.hpp CHANGED
@@ -60,6 +60,9 @@ inline constexpr float kBridgeEnergy = 1.0f;
60
  // energy-norm) and well above float dust from diffusion carryover. Documented
61
  // in README (honest-silence section); debug visibility via SYFOX_DEBUG_READOUT=1.
62
  inline constexpr float kUnknownCandidateFloor = 0.01f;
 
 
 
63
  // v3.6.0: decide-side bigram injection dose as a fraction of the state dose
64
  // (MRS §4b grounds bigram lanes like any other lane; the 0.5 fraction keeps
65
  // order evidence subordinate to lexical evidence).
@@ -146,21 +149,6 @@ struct Answer {
146
  };
147
 
148
  struct Usage {
149
- // M9: how many candidates the query-role alignment re-rank boosted, and the
150
- // agent it aligned on. Disclosure only.
151
- double role_bind_boosted = 0.0;
152
- std::string role_bind_agent;
153
- // M10: was this answer DERIVED (typed path in the axiom graph) rather than
154
- // read off the field? Disclosed so the two can never be reported as one.
155
- bool reason_routed = false;
156
- double reason_derived_count = 0.0;
157
- // Lines in axioms.txt naming an unknown relation, DROPPED at load. Reported
158
- // so a partially-loaded knowledge base is visible instead of silent.
159
- double axioms_rejected = 0.0;
160
- // M5: the effective firing threshold after the modulators were applied.
161
- double ntda_theta = 0.0;
162
- // M9-encoder: Oja updates applied this decision.
163
- double enc_updates = 0.0;
164
  std::size_t state_tokens = 0;
165
  std::size_t vocabulary = 0;
166
  std::size_t lanes = 0;
@@ -218,12 +206,6 @@ struct Usage {
218
  // strongest concept and the winning anchor (premise-cited hops).
219
  bool proof_checked = false;
220
  std::vector<std::string> proof_path; // "subject relation object" hops
221
- // M1: thinker-in-the-loop disclosures. Set only when the reasoner ran
222
- // inside decide(), so a pre-M1 run discloses nothing new.
223
- bool thinker_chained = false;
224
- int thinker_edges_added = 0;
225
- int thinker_passes = 0;
226
- float thinker_budget_left = 0.0f;
227
  // momentum (MCPE/CPME): fraction of candidates still GAINING energy at
228
  // the final settle pass (the echo-suppressed remainder peaked already).
229
  bool momentum_gate = false;
@@ -260,10 +242,28 @@ struct Calibration {
260
  float noul_b = -3.0f;
261
  bool fitted = false;
262
  std::size_t rows = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
 
264
  sfx::JV to_json() const {
 
 
 
265
  return sfx::JV(sfx::JVObj{
266
  {"choice_temperature", choice_temperature},
 
267
  {"score_temperature", score_temperature},
268
  {"noul_a", noul_a}, {"noul_b", noul_b},
269
  {"fitted", fitted}, {"rows", static_cast<double>(rows)}});
@@ -271,6 +271,10 @@ struct Calibration {
271
  static Calibration from_json(const sfx::JV& j) {
272
  Calibration c;
273
  c.choice_temperature = static_cast<float>(j.at("choice_temperature").as_num(1.0));
 
 
 
 
274
  c.score_temperature = static_cast<float>(j.at("score_temperature").as_num(1.0));
275
  c.noul_a = static_cast<float>(j.at("noul_a").as_num(6.0));
276
  c.noul_b = static_cast<float>(j.at("noul_b").as_num(-3.0));
@@ -280,6 +284,75 @@ struct Calibration {
280
  }
281
  };
282
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  // ---------------------------------------------------------------------------
284
  class Engine {
285
  public:
@@ -295,28 +368,21 @@ public:
295
  reason_meta_.engine = &reason_;
296
  }
297
 
298
- // -- M5 NTDA forwarders (Engine -> Substrate) ---------------------------
299
- void set_ntda(bool on) { si_.set_ntda(on); }
300
- void set_ntda_theta(float t) { si_.set_ntda_theta(t); }
301
- void set_novelty(float n) { si_.set_novelty(n); }
302
- void set_conflict(float c) { si_.set_conflict(c); }
303
- // M9-encoder: supply the encoder embedding for the next decide().
304
- void set_encoder_input(std::vector<float> x) { enc_in_ = std::move(x); }
305
- bool encoder_active() const { return si_.has_encoder() && !enc_in_.empty(); }
306
- std::uint64_t ntda_spikes() const { return si_.ntda_spikes(); }
307
- // -- L1 ENCODER forwarders -----------------------------------------------
308
- void set_encoder(std::size_t dim, std::size_t chans, bool reset = false) {
309
- si_.set_encoder(dim, chans, reset);
310
- }
311
- void set_encoder_eta(float e) { si_.set_encoder_eta(e); }
312
- std::uint64_t enc_updates() const { return si_.enc_updates(); }
313
- std::vector<float> encoder_project(const std::vector<float>& x) const {
314
- return si_.encoder_project(x);
315
- }
316
- std::uint64_t ntda_deaths() const { return si_.ntda_deaths(); }
317
-
318
  si::Substrate& substrate() { return si_; }
319
  const si::Substrate& substrate() const { return si_; }
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  Calibration& calibration() { return calib_; }
321
 
322
  // -- v3 Milestone 1: decide-side energy normalization (boundary GAIN knob) --
@@ -336,6 +402,50 @@ public:
336
  void set_energy_norm(bool on) { energy_norm_ = on; }
337
  bool energy_norm() const { return energy_norm_; }
338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  // -- model persistence ----------------------------------------------------
340
  void save_model(const std::string& dir) {
341
  std::string cmd_mkdir = "mkdir -p '" + dir + "'";
@@ -363,6 +473,10 @@ public:
363
  si_.save(dir + "/substrate.bin");
364
  std::ofstream cf(dir + "/calibration.json");
365
  cf << calib_.to_json().dump();
 
 
 
 
366
  std::ofstream mf(dir + "/meta.json");
367
  mf << sfx::JV(sfx::JVObj{
368
  {"engine", "syfox"}, {"version", VERSION},
@@ -400,18 +514,6 @@ public:
400
  {"seq", static_cast<double>(kv.second.seq)},
401
  {"outcome", sfx::JV(kv.second.outcome)}}).dump() << "\n";
402
  }
403
- // -- M2: PERSISTENT META-LEARNER -------------------------------------
404
- // Before M2 the rule-induction state was never serialised, so every
405
- // invocation started empty and macro-rule promotion at the 2-bit MDL
406
- // threshold could never fire across runs. Written whenever a rule set
407
- // exists; absent file = fresh learner, which is exactly the pre-M2
408
- // behaviour for any model built before this version.
409
- if (!reason_.rules.empty()) {
410
- std::ofstream of(dir + "/meta_rules.txt");
411
- if (of) of << sxr::serialize_meta(
412
- reason_meta_.chain_stats, reason_meta_.macros,
413
- &reason_, &thinker_);
414
- }
415
  }
416
 
417
  // v3.3 question-conditioned readout (read-only over the settled field).
@@ -507,100 +609,11 @@ public:
507
  sxr::MetaLearner reason_meta_;
508
  sxr::ThinkerIndex thinker_;
509
  bool reason_loaded_ = false;
510
- // M1 gates (all default false == pre-M1 behaviour, bit-identical).
511
- bool thinker_on_ = false; // --thinker: run the reasoner in decide()
512
- bool reason_fixpoint_ = false; // --reason-fixpoint: chain BEFORE readout
513
- bool meta_observe_ = false; // --meta-observe: feed proofs to MetaLearner
514
- bool role_bind_ = false; // M9 --role-bind: query-role alignment re-rank
515
- bool reason_route_ = false; // M10 --reason-route: reasoner drives the choice
516
- std::string reason_route_pick_; // disclosure: which candidate was derived
517
- std::string role_bind_hint_; // disclosure: which clause/agent was aligned
518
- std::string state_text_; // M9: raw state for clause segmentation
519
- // M9-encoder: the pre-synaptic input (pooled encoder embedding). EMPTY by
520
- // default, which is what keeps the substrate-only path bit-identical.
521
- std::vector<float> enc_in_;
522
- // M2: what load_model restored from meta_rules.txt (0 = file absent).
523
- int meta_chains_ = 0, meta_macros_ = 0, meta_rules_ = 0;
524
- // Lines in axioms.txt that named a relation this build does not know. 0 is
525
- // the honest state; a non-zero value means part of the knowledge base was
526
- // silently dropped at load.
527
- int axiom_rejected_ = 0;
528
- int axiom_rejected() const { return axiom_rejected_; }
529
 
530
  bool reason_loaded() const { return reason_loaded_; }
531
  std::size_t reason_nodes() const { return reason_.graph.nodes.size(); }
532
  std::size_t reason_edges() const { return reason_.graph.edges.size(); }
533
 
534
- // -- M2: write ONLY the meta-learner state, without the rest of save_model.
535
- // decide() must never write (the bench replay contract depends on it), so
536
- // accumulation is an explicit, opt-in action on the think/ask/derive paths.
537
- // Returns (chains, macros) actually written; 0/0 when no rule set exists.
538
- std::array<int, 2> save_meta(const std::string& dir) {
539
- if (reason_.rules.empty()) return {0, 0};
540
- const std::string cmd = "mkdir -p '" + dir + "'";
541
- (void)std::system(cmd.c_str());
542
- std::ofstream of(dir + "/meta_rules.txt");
543
- if (!of) return {0, 0};
544
- of << sxr::serialize_meta(reason_meta_.chain_stats, reason_meta_.macros,
545
- &reason_, &thinker_);
546
- return {static_cast<int>(reason_meta_.chain_stats.size()),
547
- static_cast<int>(reason_meta_.macros.size())};
548
- }
549
- std::size_t meta_chains() const { return reason_meta_.chain_stats.size(); }
550
- std::size_t meta_macros() const { return reason_meta_.macros.size(); }
551
-
552
- // -- M1: THINKER-IN-THE-LOOP -------------------------------------------
553
- // Before v3.9.1 the axiom graph was consulted from decide() through
554
- // proof_path_between() alone -- a bounded <=4-hop typed BFS. Forward
555
- // chaining, the verifier, macro-rules, the thinker index and the six
556
- // discovery queries were reachable ONLY from the CLI subcommands, so the
557
- // fabric's DECISION could never compose: it only scored anchors it had
558
- // been taught directly. This is the "thinker in the loop" gate.
559
- //
560
- // Default OFF. Bit-identical to every pre-M1 fabric when off (no
561
- // reasoning call is made), which preserves the bench replay contract and
562
- // every number in docs/HONEST_TOTAL.md.
563
- void set_thinker(bool on) { thinker_on_ = on; }
564
- bool thinker_on() const { return thinker_on_; }
565
- // when on: reason to fixpoint BEFORE the readout, so derived edges exist
566
- // in the graph the proof pass then walks.
567
- void set_reason_to_fixpoint(bool on) { reason_fixpoint_ = on; }
568
- bool reason_fixpoint() const { return reason_fixpoint_; }
569
- // M2 gate: whether to observe the chosen proof trace into the
570
- // MetaLearner. Harmless while M2's persistence does not exist (the
571
- // learner dies with the process) but is the correct seam.
572
- void set_meta_observe(bool on) { meta_observe_ = on; }
573
- // M9: query-role alignment re-rank at decide time (default off).
574
- void set_role_bind(bool on) { role_bind_ = on; }
575
- // M10 REASONER-ROUTED DECISIONS.
576
- //
577
- // The system was a similarity index with a reasoner bolted beside it that
578
- // the index never consulted: decide() reached the axiom graph through ONE
579
- // bounded 4-hop path lookup, so a question whose answer is DERIVABLE scored
580
- // anchors instead. Measured on model-mega-v2:
581
- // field 11/30 = 0.367 on held-out reasoning (chance 0.333)
582
- // reasoner 16/16 = 1.000 on held-out composition
583
- // Those two numbers are the whole argument. This gate makes the decision
584
- // path USE the reasoner: if a candidate is reachable by a TYPED PATH from
585
- // something the state asserts, that candidate is derived, not retrieved --
586
- // so it is selected on the derivation rather than on field energy. When no
587
- // candidate is derivable, the field answers exactly as before.
588
- //
589
- // This is the honest version of "thinker, not pattern matcher": derivation
590
- // decides when it applies, retrieval decides when it does not, and the two
591
- // never pretend to be each other.
592
- void set_reason_route(bool on) { reason_route_ = on; }
593
- bool reason_route() const { return reason_route_; }
594
- bool role_bind() const { return role_bind_; }
595
- bool meta_observe() const { return meta_observe_; }
596
-
597
- // Bring the axiom graph to fixpoint. Cheap and idempotent once already
598
- // derived: reason_ext() stops at the first pass that adds nothing.
599
- sxr::ReasonCore::ReasonReport think_fixpoint() {
600
- if (!reason_loaded_) return {0, 0, 0.0f};
601
- return reason_.reason_ext();
602
- }
603
-
604
  // load_axioms: SI's .axioms triple format into BOTH stores. Returns the
605
  // number of accepted (new) triples. Graph side: teach_axiom (dedup +
606
  // contradiction guard). Fabric side: intern subject/object, bind an
@@ -623,14 +636,6 @@ public:
623
  if (!(iss >> subj >> rel_tok >> obj)) continue;
624
  const int rel = sxr::rel_from_token(rel_tok);
625
  if (rel < 0) {
626
- // Persistently record the rejection even when log is null.
627
- // load_model() calls load_axioms(path, nullptr), so the stderr
628
- // diagnostic never fires at decide time and a typo'd relation in
629
- // an .axioms file was silently dropped on EVERY boot -- measured:
630
- // "radio found_by Tariq" reported new_triples=0 with no warning
631
- // outside the one-shot `axioms` command. Rejected triples are now
632
- // counted and disclosed via usage.axioms_rejected.
633
- ++axiom_rejected_;
634
  if (log) std::fprintf(log, "[axioms] unknown relation '%s' skipped\n",
635
  rel_tok.c_str());
636
  continue;
@@ -657,19 +662,16 @@ public:
657
  const std::string& anchor_label) const {
658
  std::vector<std::string> hops;
659
  if (!reason_loaded_) return hops;
660
- // Case-insensitive lookups: normalize() lowercases, the graph stores
661
- // original case, and an exact-match probe therefore always missed. See
662
- // ReasonCore::find_node_ci for the full diagnosis.
663
  const auto lt = si::norm::normalize(anchor_label);
664
  int goal = -1;
665
- for (const auto& t : lt) { goal = reason_.find_node_ci(t); if (goal >= 0) break; }
 
666
  if (goal < 0) return hops;
667
  // strongest state concept present in the axiom graph (word order =
668
  // arrival order; first hit wins, mirroring the injection order).
669
  int start = -1; std::string start_word;
670
  for (const auto& w : state_words) {
671
- start = reason_.find_node_ci(w);
672
- if (start >= 0) { start_word = w; break; }
673
  }
674
  if (start < 0 || start == goal) return hops;
675
  const auto path = reason_.find_path(
@@ -687,33 +689,6 @@ public:
687
  return hops;
688
  }
689
 
690
- // M1: the edge INDICES behind proof_path_between(), so the MetaLearner can
691
- // observe a real derivation chain instead of a bag of strings. Returns
692
- // premises-first-then-conclusion, matching ReasonCore::trace().
693
- std::vector<int> proof_edge_indices(
694
- const std::vector<std::string>& state_words,
695
- const std::string& anchor_label) const {
696
- std::vector<int> idx;
697
- if (!reason_loaded_) return idx;
698
- const auto lt = si::norm::normalize(anchor_label);
699
- int goal = -1;
700
- for (const auto& t : lt) { goal = reason_.find_node_ci(t); if (goal >= 0) break; }
701
- if (goal < 0) return idx;
702
- int start = -1;
703
- for (const auto& w : state_words) { start = reason_.find_node_ci(w); if (start >= 0) break; }
704
- if (start < 0 || start == goal) return idx;
705
- const auto path = reason_.find_path(
706
- reason_.graph.nodes[static_cast<std::size_t>(start)].label,
707
- reason_.graph.nodes[static_cast<std::size_t>(goal)].label, -1, 4);
708
- for (int ei : path) {
709
- // expand each step into its parent edges, premises first
710
- std::vector<int> sub = reason_.trace(ei);
711
- for (int s : sub)
712
- if (std::find(idx.begin(), idx.end(), s) == idx.end()) idx.push_back(s);
713
- }
714
- return idx;
715
- }
716
-
717
  // -- v3.9.0 decision-layer paper gates (all default OFF; replay-safe) ----
718
  void set_proof(bool disclose, bool require) { proof_on_ = disclose; require_proof_ = require; }
719
  bool proof_on() const { return proof_on_; }
@@ -721,6 +696,11 @@ public:
721
  bool momentum_gate_on() const { return momentum_gate_; }
722
  void set_wavefront_gate(bool on) { wavefront_gate_ = on; }
723
  bool wavefront_gate_on() const { return wavefront_gate_; }
 
 
 
 
 
724
  void set_coherence_gate(bool on, float floor) {
725
  coherence_gate_ = on;
726
  coherence_floor_ = floor > 0.0f ? floor : 0.05f;
@@ -749,26 +729,14 @@ public:
749
  // v3.2.1: returns false when the substrate file is missing (honest load
750
  // failure — callers surface a clear error instead of deciding on an
751
  // empty fabric or, worse, reporting a misleading downstream message).
752
- // M9-LEARNED: teach the role tagger what a function word is, FROM THIS
753
- // FABRIC, so the hardcoded rulebook is only a fallback for fabrics too small
754
- // to have a meaningful document-frequency table.
755
- void learn_function_words(double frac = 0.02, std::size_t cap = 4000) {
756
- if (!si_.df_table_size()) return;
757
- const std::size_t total = si_.df_lesson_count();
758
- if (total < 50) return; // too small: keep the fallback
759
- const double cut = static_cast<double>(total) * frac;
760
- std::vector<std::string> learned;
761
- for (const auto& kv : si_.df_ranked(cap))
762
- if (static_cast<double>(kv.second) >= cut) learned.push_back(kv.first);
763
- if (learned.empty()) return;
764
- si::roles::load_function_words(std::move(learned));
765
- }
766
-
767
  bool load_model(const std::string& dir) {
768
  if (!si_.load(dir + "/substrate.bin")) return false;
769
  std::ifstream cf(dir + "/calibration.json");
770
  if (cf) { std::string buf((std::istreambuf_iterator<char>(cf)), std::istreambuf_iterator<char>());
771
  calib_ = Calibration::from_json(sfx::JV::parse(buf)); }
 
 
 
772
  // v3 audit trail (optional files; a v2 model dir simply lacks them)
773
  {
774
  std::ifstream f(dir + "/conflicts.jsonl");
@@ -802,24 +770,6 @@ public:
802
  // v3.2: semantic hierarchy (Stage 3) ships as hierarchy.json in the
803
  // model dir; absent file = single-stage readout, exactly as before.
804
  load_hierarchy(dir + "/hierarchy.json");
805
- // M9-LEARNED: derive the role tagger's function words from this fabric.
806
- learn_function_words();
807
- // -- M2: restore the persistent meta-learner -----------------------
808
- // Absent file = fresh learner (pre-M2 behaviour, bit-identical for any
809
- // model built before v3.9.1). Macro rules are re-added to the engine as
810
- // firing transitive rules, so a chain promoted in an earlier run
811
- // actually fires now instead of sitting in a file.
812
- {
813
- std::ifstream f(dir + "/meta_rules.txt");
814
- if (f) {
815
- std::string buf((std::istreambuf_iterator<char>(f)),
816
- std::istreambuf_iterator<char>());
817
- const auto n = sxr::deserialize_meta(
818
- reason_meta_.chain_stats, reason_meta_.macros,
819
- &reason_, &thinker_, buf);
820
- meta_chains_ = n[0]; meta_macros_ = n[1]; meta_rules_ = n[2];
821
- }
822
- }
823
  // v3.2 retrieval BY DEFAULT: a memories.jsonl shipped in the model dir
824
  // is loaded and fingerprinted once (settled-field cosines are then
825
  // free at decide time). No file => retrieval is inert, behavior of
@@ -1240,6 +1190,34 @@ public:
1240
  };
1241
  adopt_temp("choice", calib_.choice_temperature);
1242
  adopt_temp("score", calib_.score_temperature);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1243
  // Platt: same 1-bit selection for the noul map
1244
  const float a0 = calib_.noul_a, b0 = calib_.noul_b;
1245
  const double p1 = calibration_ece(rows, "noul", 1.0f, a0, b0);
@@ -1254,9 +1232,14 @@ public:
1254
  // width bins on top-probability confidence, argmax-correctness for
1255
  // choice/score; Platt sigmoid + 0.5 threshold for noul). Same definition
1256
  // the bench reports, so calibrate's before/after and bench's ECE agree.
 
 
 
 
1257
  static double calibration_ece(const std::vector<CalibRow>& rows,
1258
  const std::string& type, float T,
1259
- float noul_a, float noul_b) {
 
1260
  long bins[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1261
  long corr[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1262
  double confs[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
@@ -1270,11 +1253,16 @@ public:
1270
  correct = (p >= 0.5f) == (r.y == 1);
1271
  } else {
1272
  if (r.energies.empty()) continue;
 
 
 
 
 
1273
  float maxe = -1e30f;
1274
  for (const auto& kv : r.energies) maxe = std::max(maxe, kv.second);
1275
  float z = 0.0f, top = -1.0f; std::string amax;
1276
  for (const auto& kv : r.energies) {
1277
- const float v = std::exp((kv.second - maxe) / Ts);
1278
  z += v;
1279
  if (v > top) { top = v; amax = kv.first; }
1280
  }
@@ -1701,40 +1689,8 @@ public:
1701
  usage.lanes = si_.lane_count();
1702
 
1703
  std::vector<Answer> answers;
1704
- // M9: the RAW state, kept so decide_choice can segment on clause-final
1705
- // punctuation. normalize() discards that punctuation (and drops 1-char
1706
- // tokens), so the information is unrecoverable from `words` alone.
1707
- state_text_ = state;
1708
- usage.axioms_rejected = static_cast<double>(axiom_rejected_);
1709
  const std::vector<std::string> words = si::norm::normalize(state);
1710
  usage.state_tokens = words.size();
1711
- // M9-encoder: if an encoder projection is configured, read the settled
1712
- // field back in channel space and apply ONE local Oja update, scaled by
1713
- // the GHL global sign g. With no encoder this is a no-op, so the
1714
- // substrate-only path is bit-identical.
1715
- if (si_.has_encoder()) {
1716
- const std::vector<float> y = si_.encoder_project(enc_in_);
1717
- // g: novelty lowers the update (explore less on unfamiliar input),
1718
- // conflict raises it. Reuses the NTDA modulator's sign convention.
1719
- const float th = si_.current_theta();
1720
- const float g = th > 0.0f ? (1.0f / th) : 1.0f;
1721
- if (!enc_in_.empty()) si_.encoder_update(enc_in_, y, g);
1722
- usage.enc_updates = static_cast<double>(si_.enc_updates());
1723
- }
1724
- // M5 (c): feed the modulators. Novelty = fraction of state tokens the
1725
- // fabric has NEVER interned (the OOD signal the engine already computes
1726
- // for its own gate). Conflict = the standing contradiction count,
1727
- // normalised. Both are read-only over the substrate.
1728
- if (si_.ntda_on()) {
1729
- std::size_t unk = 0;
1730
- for (const auto& w : words) if (!si_.has(w)) ++unk;
1731
- si_.set_novelty(words.empty() ? 0.0f
1732
- : static_cast<float>(unk) / static_cast<float>(words.size()));
1733
- si_.set_conflict(conflicts_.empty() ? 0.0f
1734
- : std::min(1.0f, static_cast<float>(conflicts_.size()) / 64.0f));
1735
- usage.ntda_theta = si_.current_theta();
1736
- }
1737
-
1738
 
1739
  // v3.8.0 (TASK 1) adaptive depth: measure the problem BEFORE any
1740
  // settle; when the flag is on, harder states get more passes.
@@ -2089,10 +2045,19 @@ public:
2089
  // Harvest calibration rows from labelled examples (tool side).
2090
  std::vector<CalibRow> harvest_rows(const std::vector<sfx::JV>& examples) {
2091
  std::vector<CalibRow> rows;
 
 
 
 
 
 
 
 
2092
  for (const auto& ex : examples) {
2093
  std::string state = ex.at("state").as_str();
2094
  const sfx::JV& qs = ex.has("questions") ? ex.at("questions") : sfx::JV(sfx::JVObj{});
2095
  if (!qs.is_obj()) continue;
 
2096
  // v3.2.1: prime EXACTLY as decide() does (shared prime_field) —
2097
  // the fit must see the decide-time field composition. For fabrics
2098
  // without memories this is a bare reset, the pre-3.2 behavior.
@@ -2150,7 +2115,7 @@ public:
2150
  // v3.8.0 (TASK 2) fit/decide parity: the fit sees the same
2151
  // multi-vector superposition the decision sees.
2152
  apply_multi_vector(hw0, nullptr);
2153
- if (si_.silent()) continue;
2154
  for (const auto& qkv : qs.obj) {
2155
  const sfx::JV& q = qkv.second;
2156
  std::string type = q.at("type").as_str();
@@ -2158,12 +2123,31 @@ public:
2158
  if (type == "choice" || type == "score") {
2159
  const sfx::JV& crit = q.at("criteria");
2160
  std::vector<std::pair<std::string, float>> energies;
 
 
2161
  if (crit.is_obj())
2162
- for (const auto& kv : crit.obj)
2163
- energies.emplace_back(kv.first, probe_energy(kv.first, kv.second.as_str()));
 
 
 
2164
  else if (crit.is_arr())
2165
- for (std::size_t i = 0; i < crit.arr.size(); ++i)
2166
- energies.emplace_back(crit.arr[i].as_str(), probe_energy(crit.arr[i].as_str(), ""));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2167
  // resolve the gold label to a candidate KEY: for array
2168
  // criteria the stored label may be the level INDEX ("0",
2169
  // "1", ...) — the old code compared it to the level text
@@ -2369,6 +2353,180 @@ private:
2369
  return si_.readout(si::norm::normalize(label + " " + desc));
2370
  }
2371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2372
  float noul_support(const std::string& instructions) const {
2373
  // Noul uses the SUPPORT readout lane: breadth of corroboration.
2374
  float e = si_.readout(si::norm::normalize(instructions), si::Substrate::ReadoutMode::Support);
@@ -2495,91 +2653,21 @@ private:
2495
  return std::max(0.0f, std::min(1.0f, conf));
2496
  }
2497
 
2498
- // -- M9: QUERY-ROLE ALIGNMENT ---------------------------------------------
2499
- // Re-rank choice candidates by the ROLE the question actually asks about,
2500
- // computed from the RAW state text at decide time.
2501
- //
2502
- // Why this exists (measured on model-mega-v2, tools/reason30.py): on
2503
- // state : "The radio was found by Tariq. Salma was there."
2504
- // question: "Who found the radio?" options: Tariq / Salma / radio
2505
- // the readout answered Salma with p=0.996 in BOTH wordings — i.e. it is not
2506
- // reading the "by" agent at all, it returns the LAST-MENTIONED subject. Seven
2507
- // of thirteen misses had this shape.
2508
- //
2509
- // normalize() cannot help: it DISCARDS sentence punctuation (emitting a token
2510
- // only on non-alnum) and DROPS tokens of length 1 (emit() requires size>=2),
2511
- // so clause boundaries and single-letter options are already gone before any
2512
- // role tagger runs. That also explains the unknown_candidates on the A/B/C
2513
- // and K/L/M/N probes. Changing normalize() would re-intern every fabric and
2514
- // break the replay contract, so segmentation happens HERE, on the raw string,
2515
- // at decide time only. learn is never touched.
2516
- //
2517
- // Contract: pure re-rank over already-measured candidate energies. It adds
2518
- // no lanes, no nodes, and no field perturbation, so with the gate off every
2519
- // number in docs/HONEST_TOTAL.md replays exactly.
2520
- struct RoleHint { int clause = -1; std::string agent; };
2521
- RoleHint role_hint(const std::string& state_text, const std::string& instr) const {
2522
- RoleHint h;
2523
- // 1) split the RAW state on clause-final punctuation.
2524
- std::vector<std::string> clauses;
2525
- std::string cur;
2526
- for (char raw : state_text) {
2527
- if (raw == '.' || raw == '!' || raw == '?' || raw == ';' || raw == '\n') {
2528
- if (!cur.empty()) { clauses.push_back(cur); cur.clear(); }
2529
- } else cur.push_back(raw);
2530
- }
2531
- if (!cur.empty()) clauses.push_back(cur);
2532
- if (clauses.empty()) return h;
2533
- // 2) the question's verb cue, if any ("found", "gave", "owns").
2534
- const auto iw = si::norm::normalize(instr);
2535
- std::string verb;
2536
- for (const auto& t : iw) if (si::roles::is_verb_cue(t)) { verb = t; break; }
2537
- // 3) the clause that shares the question's verb — that clause is the one
2538
- // the question is about. Falls back to the FIRST clause, which is the
2539
- // conventional topic position and beats "last mentioned".
2540
- std::size_t pick = 0;
2541
- if (!verb.empty()) {
2542
- for (std::size_t i = 0; i < clauses.size(); ++i) {
2543
- const auto cw = si::norm::normalize(clauses[i]);
2544
- for (const auto& t : cw) if (t == verb) { pick = i; goto found; }
2545
- }
2546
- }
2547
- found:
2548
- const auto cw = si::norm::normalize(clauses[pick]);
2549
- const auto roles = si::roles::tag(cw);
2550
- h.clause = static_cast<int>(pick);
2551
- // 4) the AGENT. In ACTIVE voice ("Tariq found the radio") the agent is S.
2552
- // In PASSIVE voice ("the radio was found BY Tariq") the agent is the
2553
- // O slot, because that is where the "by"-phrase lands -- and with the
2554
- // copula fixed (was->wa) the tagger now correctly puts S=radio, O=Tariq.
2555
- // Getting this backwards is exactly the bug: it returned the patient.
2556
- bool passive = false;
2557
- for (std::size_t i = 0; i + 1 < cw.size(); ++i)
2558
- if (cw[i] == "by" && roles[i + 1] == si::roles::Role::O) { passive = true; break; }
2559
- const si::roles::Role want = passive ? si::roles::Role::O : si::roles::Role::S;
2560
- for (std::size_t i = 0; i < cw.size(); ++i) {
2561
- if (roles[i] != want) continue;
2562
- h.agent = cw[i];
2563
- break;
2564
- }
2565
- // 5) a passive clause whose O is not a name-like token (e.g. the bare
2566
- // "there" of "Salma was there") must not boost anything.
2567
- if (h.agent == "there" || h.agent == "it") h.agent.clear();
2568
- return h;
2569
- }
2570
-
2571
  void decide_choice(const sfx::JV& q, const std::vector<std::string>& state_words,
2572
  Answer& a, Usage* usage = nullptr) {
2573
  const sfx::JV& crit = q.at("criteria");
2574
  std::vector<std::string> labels; std::vector<float> energies;
 
2575
  if (crit.is_obj())
2576
  for (const auto& kv : crit.obj) {
2577
  labels.push_back(kv.first);
 
2578
  energies.push_back(probe_energy(kv.first, kv.second.as_str()));
2579
  }
2580
  else if (crit.is_arr())
2581
  for (const auto& v : crit.arr) {
2582
  labels.push_back(v.as_str());
 
2583
  energies.push_back(probe_energy(v.as_str(), ""));
2584
  }
2585
  if (labels.empty()) { a.deferred = true; a.reason = "no_options"; return; }
@@ -2600,72 +2688,36 @@ private:
2600
  // measured real signal (probe-fabric candidates 0.19-0.88); below it
2601
  // the field is carryover. Do NOT raise above 0.10 — that false-defers
2602
  // valid dim candidates (measured 0.19 without energy-norm).
2603
- // -- M10 REASONER-ROUTED CHOICE -----------------------------------------
2604
- // MUST run BEFORE the unknown_candidates floor. It was originally placed after
2605
- // it, which meant a dark field deferred with "unknown_candidates" and the
2606
- // routing code was never reached -- on a small probe fabric that is EVERY
2607
- // query, so the feature could never fire. A derivation is not an energy and
2608
- // must not be gated by one.
2609
- // -- M10 REASONER-ROUTED CHOICE -----------------------------------------
2610
- if (reason_route_ && reason_loaded_ && !state_words.empty()) {
2611
- // First candidate (criteria order) that is REACHABLE by a typed path.
2612
- // Deterministic: criteria order is fixed, so this is reproducible.
2613
- // If MORE THAN ONE is reachable the answer is genuinely ambiguous and
2614
- // we take the first, but we disclose the count so a reader can tell a
2615
- // unique derivation from an arbitrary one.
2616
- int derived = -1;
2617
- int n_derived = 0;
2618
- for (std::size_t i = 0; i < labels.size(); ++i) {
2619
- if (proof_path_between(state_words, labels[i]).empty()) continue;
2620
- if (derived < 0) derived = static_cast<int>(i);
2621
- ++n_derived;
2622
- }
2623
- if (usage) {
2624
- usage->reason_routed = n_derived > 0;
2625
- usage->reason_derived_count = static_cast<double>(n_derived);
2626
- }
2627
- if (derived >= 0) {
2628
- reason_route_pick_ = labels[static_cast<std::size_t>(derived)];
2629
- for (std::size_t i = 0; i < energies.size(); ++i)
2630
- energies[i] = (static_cast<int>(i) == derived) ? 1.0f : 0.0f;
2631
- if (usage) { usage->reason_routed = true; }
2632
- }
2633
- }
2634
- float max_energy = 0.0f;
2635
- for (float e : energies) max_energy = std::max(max_energy, e);
2636
  if (std::getenv("SYFOX_DEBUG_READOUT") != nullptr) {
2637
- std::fprintf(stderr, "DEBUG: max_candidate=%.3f threshold=%.3f\n",
2638
- max_energy, kUnknownCandidateFloor);
2639
  for (std::size_t i = 0; i < labels.size(); ++i)
2640
  std::fprintf(stderr, "DEBUG: candidate[%s]=%.4f\n",
2641
  labels[i].c_str(), energies[i]);
2642
  }
2643
- if (max_energy < kUnknownCandidateFloor) {
2644
  a.deferred = true;
2645
  a.reason = "unknown_candidates";
2646
  return;
2647
  }
2648
- // -- M9 QUERY-ROLE ALIGNMENT (opt-in, decide-time, read-only) ----------
2649
- // Applied BEFORE the paper gates so they still see the aligned energies.
2650
- if (role_bind_ && !state_text_.empty()) {
2651
- const RoleHint h = role_hint(state_text_, q.at("instructions").as_str());
2652
- if (!h.agent.empty()) {
2653
- role_bind_hint_ = h.agent;
2654
- std::size_t boosted = 0;
2655
- for (std::size_t i = 0; i < labels.size(); ++i) {
2656
- const auto lw = si::norm::normalize(labels[i]);
2657
- bool match = lw.empty();
2658
- for (const auto& t : lw) if (t == h.agent) { match = true; break; }
2659
- // Multi-word options ("curtain opening") are matched on the
2660
- // agent being one of their tokens; a bare entity label is the
2661
- // normal case and wins outright.
2662
- if (!match) continue;
2663
- energies[i] *= 2.0f;
2664
- ++boosted;
2665
- }
2666
- if (usage && boosted) usage->role_bind_boosted = static_cast<double>(boosted);
2667
- }
2668
- }
2669
  // v3.9.0 decision-layer paper gates — each measures the settled field
2670
  // READ-ONLY and zeroes/scales energies; none rewrites the field.
2671
  // (a) MOMENTUM (MCPE §1 / CPME §2): a candidate whose normalized
@@ -2837,7 +2889,10 @@ private:
2837
  }
2838
  }
2839
  std::vector<float> p;
2840
- softmax_ps(energies, p, calib_.choice_temperature);
 
 
 
2841
  std::size_t best = std::max_element(p.begin(), p.end()) - p.begin();
2842
  a.choice = labels[best];
2843
  for (std::size_t i = 0; i < labels.size(); ++i)
@@ -2856,19 +2911,6 @@ private:
2856
  // disclosure; --require-proof defers a choice with no typed path
2857
  // (coverage-cliff honesty: the field answered, the knowledge layer
2858
  // cannot justify it).
2859
- //
2860
- // M1: when the reasoner is live, chain the axiom graph to fixpoint
2861
- // FIRST so this walk can traverse DERIVED edges. This is the whole
2862
- // point of the module: previously find_path could only follow edges
2863
- // that were asserted, because nothing had ever chained inside
2864
- // decide(). Gate is off by default -> no extra work, bit-identical.
2865
- if (usage && (thinker_on_ || reason_fixpoint_) && reason_loaded_) {
2866
- const sxr::ReasonCore::ReasonReport rep = reason_.reason_ext();
2867
- usage->thinker_chained = true;
2868
- usage->thinker_edges_added = rep.edges_added;
2869
- usage->thinker_passes = rep.steps_used;
2870
- usage->thinker_budget_left = rep.budget_left;
2871
- }
2872
  if (usage && (proof_on_ || require_proof_)) {
2873
  usage->proof_checked = true;
2874
  usage->proof_path = proof_path_between(state_words, labels[best]);
@@ -2876,12 +2918,6 @@ private:
2876
  a.deferred = true;
2877
  a.reason = "no_proof_path";
2878
  }
2879
- // M1: feed the proof we actually used into the MetaLearner, so
2880
- // repeated sub-chains accumulate and macro-rules can promote.
2881
- // Only under --proof/--require-proof: the trace is only known to
2882
- // be the one that justified THIS answer there.
2883
- if (meta_observe_ && !a.deferred)
2884
- reason_meta_.observe_trace(proof_edge_indices(state_words, labels[best]));
2885
  }
2886
  // v3.9.0 (fixes.md): remember the signature pieces for the OOD gate.
2887
  if (usage) {
@@ -3039,6 +3075,13 @@ private:
3039
  si::Substrate si_;
3040
  Calibration calib_;
3041
  bool energy_norm_ = false; // Milestone-1 gain knob (default off)
 
 
 
 
 
 
 
3042
  std::unordered_set<std::uint64_t> lesson_hashes_; // Milestone-2 dedup memory
3043
  // v3.2 retrieval-by-default state
3044
  std::vector<recall::Memory> memories_;
 
60
  // energy-norm) and well above float dust from diffusion carryover. Documented
61
  // in README (honest-silence section); debug visibility via SYFOX_DEBUG_READOUT=1.
62
  inline constexpr float kUnknownCandidateFloor = 0.01f;
63
+ // v4.0 — a candidate count needs this many calibration rows before it gets
64
+ // its own temperature; below it the global scalar is kept.
65
+ inline constexpr std::size_t kMinRowsPerCandidateCount = 64;
66
  // v3.6.0: decide-side bigram injection dose as a fraction of the state dose
67
  // (MRS §4b grounds bigram lanes like any other lane; the 0.5 fraction keeps
68
  // order evidence subordinate to lexical evidence).
 
149
  };
150
 
151
  struct Usage {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  std::size_t state_tokens = 0;
153
  std::size_t vocabulary = 0;
154
  std::size_t lanes = 0;
 
206
  // strongest concept and the winning anchor (premise-cited hops).
207
  bool proof_checked = false;
208
  std::vector<std::string> proof_path; // "subject relation object" hops
 
 
 
 
 
 
209
  // momentum (MCPE/CPME): fraction of candidates still GAINING energy at
210
  // the final settle pass (the echo-suppressed remainder peaked already).
211
  bool momentum_gate = false;
 
242
  float noul_b = -3.0f;
243
  bool fitted = false;
244
  std::size_t rows = 0;
245
+ // v4.0 — the temperature depends on the SIZE of the candidate set. A
246
+ // 14-way question's score spread is not a 2-way question's spread, so one
247
+ // scalar fitted across both cannot serve both: on the shared giant
248
+ // fabric (16 domains, candidate counts 2..14) the single temperature
249
+ // left polarity at ECE 0.395 and dbpedia at 0.064 in the same fit.
250
+ // One scalar per distinct candidate count, fitted on the same rows with
251
+ // the same 1-bit ECE selection guard, falls back to the global scalar.
252
+ std::map<int, float> choice_temperature_by_count;
253
+
254
+ // the temperature this candidate set is scored under
255
+ float choice_temperature_for(std::size_t n_candidates) const {
256
+ auto it = choice_temperature_by_count.find(static_cast<int>(n_candidates));
257
+ return (it == choice_temperature_by_count.end()) ? choice_temperature : it->second;
258
+ }
259
 
260
  sfx::JV to_json() const {
261
+ sfx::JVObj counts;
262
+ for (const auto& kv : choice_temperature_by_count)
263
+ counts[std::to_string(kv.first)] = sfx::JV(kv.second);
264
  return sfx::JV(sfx::JVObj{
265
  {"choice_temperature", choice_temperature},
266
+ {"choice_temperature_by_count", sfx::JV(counts)},
267
  {"score_temperature", score_temperature},
268
  {"noul_a", noul_a}, {"noul_b", noul_b},
269
  {"fitted", fitted}, {"rows", static_cast<double>(rows)}});
 
271
  static Calibration from_json(const sfx::JV& j) {
272
  Calibration c;
273
  c.choice_temperature = static_cast<float>(j.at("choice_temperature").as_num(1.0));
274
+ if (j.at("choice_temperature_by_count").is_obj())
275
+ for (const auto& kv : j.at("choice_temperature_by_count").obj)
276
+ c.choice_temperature_by_count[std::atoi(kv.first.c_str())] =
277
+ static_cast<float>(kv.second.as_num(1.0));
278
  c.score_temperature = static_cast<float>(j.at("score_temperature").as_num(1.0));
279
  c.noul_a = static_cast<float>(j.at("noul_a").as_num(6.0));
280
  c.noul_b = static_cast<float>(j.at("noul_b").as_num(-3.0));
 
284
  }
285
  };
286
 
287
+ // ---------------------------------------------------------------------------
288
+ // v3.9.2: THE DECIDE-SIDE PHYSICS COMPOSITION.
289
+ //
290
+ // WHY THIS EXISTS. The calibration scalars (choice/score temperature, Platt)
291
+ // are fitted on ENERGIES that come out of a settle pass. Those energies are
292
+ // a function of the whole decide-side composition: the injected dose
293
+ // (energy_norm), the lane-flow fraction (diffusion), the dissipation
294
+ // (decay), the settle-pass cap (k_settle) and the hop coupling. Fit a
295
+ // temperature on one composition and apply it to another and the fit is
296
+ // measuring a DIFFERENT engine than the one that will decide.
297
+ //
298
+ // That is not hypothetical. The b77-sem / router16 / bank77-best fabrics in
299
+ // this tree were calibrated WITHOUT the energy gain while every bench and
300
+ // every decide call ran WITH it (see the Makefile: calibrate has no
301
+ // --energy-norm, bench has it). Measured on the shipped b77-sem fabric,
302
+ // same 1,003-row cal split, same engine:
303
+ // calibrate WITHOUT --energy-norm -> T = 0.0037, fit saw 556 of 2,006
304
+ // question-rows (27.7% coverage)
305
+ // calibrate WITH --energy-norm -> T = 0.3552, fit saw 2,006 of 2,006
306
+ // A ~100x sharper temperature, chosen on a 27.7%-covered, biased subset of
307
+ // the rows. A near-floor T saturates the post-temperature probability gap
308
+ // at ~1.0, so (a) the engine's defer axis never fires (a 0.05 margin can
309
+ // never be exceeded by a gap of 0.93) and (b) every answer carries ~0.98
310
+ // confidence whether it is right or wrong. Measured on b77-sem bank77
311
+ // hidden: mean confidence on WRONG answers 0.867 > on RIGHT answers 0.832.
312
+ //
313
+ // THE FIX. A fabric now carries the composition it was calibrated under
314
+ // (physics.json, next to calibration.json). calibrate records it; decide,
315
+ // bench, demo and stats apply it on load. The fit and the decision are the
316
+ // same engine BY CONSTRUCTION, and a CLI flag still overrides it.
317
+ // ---------------------------------------------------------------------------
318
+ struct PhysicsComposition {
319
+ bool energy_norm = false; // decide-side energy gain (M1)
320
+ float diffusion = -1.0f; // -1 = keep the substrate default
321
+ float decay = -1.0f;
322
+ int k_settle = -1;
323
+ float hop_coupling = -1.0f;
324
+ // v4.0 — the READOUT the fabric was calibrated under. Recorded with the
325
+ // rest of the decide-side composition so a deployed model decides under
326
+ // the same readout its temperature was fitted for (the fit==decide
327
+ // parity contract, extended from the physics to the measurement).
328
+ float affinity_mix = 0.0f; // 0 = legacy readout, 1 = affinity only
329
+ bool affinity_pmi = false; // log-odds form of the contrast
330
+ bool recorded = false; // true once a fabric carries physics.json
331
+
332
+ sfx::JV to_json() const {
333
+ return sfx::JV(sfx::JVObj{
334
+ {"energy_norm", energy_norm},
335
+ {"diffusion", diffusion}, {"decay", decay},
336
+ {"k_settle", static_cast<double>(k_settle)},
337
+ {"hop_coupling", hop_coupling},
338
+ {"affinity_mix", affinity_mix},
339
+ {"affinity_pmi", affinity_pmi},
340
+ {"recorded", recorded}});
341
+ }
342
+ static PhysicsComposition from_json(const sfx::JV& j) {
343
+ PhysicsComposition p;
344
+ p.energy_norm = j.at("energy_norm").is_bool() && j.at("energy_norm").b;
345
+ p.diffusion = static_cast<float>(j.at("diffusion").as_num(-1.0));
346
+ p.decay = static_cast<float>(j.at("decay").as_num(-1.0));
347
+ p.k_settle = static_cast<int>(j.at("k_settle").as_num(-1));
348
+ p.hop_coupling = static_cast<float>(j.at("hop_coupling").as_num(-1.0));
349
+ p.affinity_mix = static_cast<float>(j.at("affinity_mix").as_num(0.0));
350
+ p.affinity_pmi = j.at("affinity_pmi").is_bool() && j.at("affinity_pmi").b;
351
+ p.recorded = j.at("recorded").is_bool() && j.at("recorded").b;
352
+ return p;
353
+ }
354
+ };
355
+
356
  // ---------------------------------------------------------------------------
357
  class Engine {
358
  public:
 
368
  reason_meta_.engine = &reason_;
369
  }
370
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  si::Substrate& substrate() { return si_; }
372
  const si::Substrate& substrate() const { return si_; }
373
+
374
+ // -- v3.9.3: repair the numerically dead lanes from the evidence ledger --
375
+ // See si::Substrate::repair_lanes_from_evidence() for the full diagnosis:
376
+ // the port's global per-lesson decay drove 95% of the giant fabric's
377
+ // lanes to the float32 denormal floor, erasing its Hebbian memory. This
378
+ // rebuilds each lane's weight from the persisted ledger (the integral of
379
+ // the growth term the decay destroyed) in CMD §2.3's saturating form.
380
+ si::Substrate::LaneRepairStats repair_lanes(float dead_threshold = 1e-6f,
381
+ bool apply = true) {
382
+ return si_.repair_lanes_from_evidence(dead_threshold, apply);
383
+ }
384
+ // v3.9.3: the lane-decay floor (0 = off, bit-identical to pre-v3.9.3).
385
+ void set_lane_decay_floor(float f) { si_.set_lane_decay_floor(f); }
386
  Calibration& calibration() { return calib_; }
387
 
388
  // -- v3 Milestone 1: decide-side energy normalization (boundary GAIN knob) --
 
402
  void set_energy_norm(bool on) { energy_norm_ = on; }
403
  bool energy_norm() const { return energy_norm_; }
404
 
405
+ // -- v3.9.2: decide-side physics composition (see PhysicsComposition) -----
406
+ const PhysicsComposition& composition() const { return composition_; }
407
+ void set_composition(const PhysicsComposition& c) { composition_ = c; }
408
+ // v3.9.2: calibration-fit coverage bookkeeping (offered vs. seen rows).
409
+ std::size_t harvest_offered() const { return harvest_offered_; }
410
+ std::size_t harvest_dropped_silent() const { return harvest_dropped_silent_; }
411
+ // Push the recorded composition into the live engine. Called on model
412
+ // load (decide/bench/demo/stats) and before a calibration fit, so the
413
+ // fit and the decision are the same engine by construction.
414
+ void apply_composition() {
415
+ if (composition_.energy_norm) set_energy_norm(true);
416
+ if (composition_.diffusion >= 0.0f) si_.set_diffusion(composition_.diffusion);
417
+ if (composition_.decay >= 0.0f) si_.set_decay(composition_.decay);
418
+ if (composition_.k_settle > 0) si_.set_k_settle(composition_.k_settle);
419
+ if (composition_.hop_coupling >= 0.0f) si_.set_hop_coupling(composition_.hop_coupling);
420
+ if (composition_.affinity_mix > 0.0f) set_affinity_mix(composition_.affinity_mix);
421
+ if (composition_.affinity_pmi) set_affinity_pmi(true);
422
+ }
423
+ // Snapshot the LIVE composition (what this process would decide under).
424
+ PhysicsComposition live_composition() const {
425
+ PhysicsComposition p;
426
+ p.energy_norm = energy_norm_;
427
+ p.diffusion = si_.config().diffusion;
428
+ p.decay = si_.config().decay;
429
+ p.k_settle = si_.config().k_settle;
430
+ p.hop_coupling = si_.config().hop_coupling;
431
+ p.affinity_mix = affinity_mix_;
432
+ p.affinity_pmi = affinity_pmi_;
433
+ p.recorded = true;
434
+ return p;
435
+ }
436
+ // physics.json sidecar (absent file = pre-3.9.2 fabric, composition unset).
437
+ bool load_physics(const std::string& dir) {
438
+ std::ifstream f(dir + "/physics.json");
439
+ if (!f) return false;
440
+ std::string buf((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
441
+ composition_ = PhysicsComposition::from_json(sfx::JV::parse(buf));
442
+ return true;
443
+ }
444
+ void save_physics(const std::string& dir) const {
445
+ std::ofstream f(dir + "/physics.json");
446
+ f << composition_.to_json().dump();
447
+ }
448
+
449
  // -- model persistence ----------------------------------------------------
450
  void save_model(const std::string& dir) {
451
  std::string cmd_mkdir = "mkdir -p '" + dir + "'";
 
473
  si_.save(dir + "/substrate.bin");
474
  std::ofstream cf(dir + "/calibration.json");
475
  cf << calib_.to_json().dump();
476
+ // v3.9.2: the decide-side composition this fabric was calibrated under.
477
+ // Written alongside calibration.json so decide/bench/calibrate all
478
+ // agree on the physics without the operator having to remember.
479
+ if (composition_.recorded) save_physics(dir);
480
  std::ofstream mf(dir + "/meta.json");
481
  mf << sfx::JV(sfx::JVObj{
482
  {"engine", "syfox"}, {"version", VERSION},
 
514
  {"seq", static_cast<double>(kv.second.seq)},
515
  {"outcome", sfx::JV(kv.second.outcome)}}).dump() << "\n";
516
  }
 
 
 
 
 
 
 
 
 
 
 
 
517
  }
518
 
519
  // v3.3 question-conditioned readout (read-only over the settled field).
 
609
  sxr::MetaLearner reason_meta_;
610
  sxr::ThinkerIndex thinker_;
611
  bool reason_loaded_ = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
612
 
613
  bool reason_loaded() const { return reason_loaded_; }
614
  std::size_t reason_nodes() const { return reason_.graph.nodes.size(); }
615
  std::size_t reason_edges() const { return reason_.graph.edges.size(); }
616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
617
  // load_axioms: SI's .axioms triple format into BOTH stores. Returns the
618
  // number of accepted (new) triples. Graph side: teach_axiom (dedup +
619
  // contradiction guard). Fabric side: intern subject/object, bind an
 
636
  if (!(iss >> subj >> rel_tok >> obj)) continue;
637
  const int rel = sxr::rel_from_token(rel_tok);
638
  if (rel < 0) {
 
 
 
 
 
 
 
 
639
  if (log) std::fprintf(log, "[axioms] unknown relation '%s' skipped\n",
640
  rel_tok.c_str());
641
  continue;
 
662
  const std::string& anchor_label) const {
663
  std::vector<std::string> hops;
664
  if (!reason_loaded_) return hops;
 
 
 
665
  const auto lt = si::norm::normalize(anchor_label);
666
  int goal = -1;
667
+ for (const auto& t : lt)
668
+ if (reason_.graph.by_label.count(t)) { goal = reason_.graph.by_label.at(t); break; }
669
  if (goal < 0) return hops;
670
  // strongest state concept present in the axiom graph (word order =
671
  // arrival order; first hit wins, mirroring the injection order).
672
  int start = -1; std::string start_word;
673
  for (const auto& w : state_words) {
674
+ if (reason_.graph.by_label.count(w)) { start = reason_.graph.by_label.at(w); start_word = w; break; }
 
675
  }
676
  if (start < 0 || start == goal) return hops;
677
  const auto path = reason_.find_path(
 
689
  return hops;
690
  }
691
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
692
  // -- v3.9.0 decision-layer paper gates (all default OFF; replay-safe) ----
693
  void set_proof(bool disclose, bool require) { proof_on_ = disclose; require_proof_ = require; }
694
  bool proof_on() const { return proof_on_; }
 
696
  bool momentum_gate_on() const { return momentum_gate_; }
697
  void set_wavefront_gate(bool on) { wavefront_gate_ = on; }
698
  bool wavefront_gate_on() const { return wavefront_gate_; }
699
+ // v4.0 — the affinity field readout channel (default OFF; replay-safe)
700
+ void set_affinity_mix(float m) { affinity_mix_ = std::max(0.0f, std::min(1.0f, m)); }
701
+ float affinity_mix() const { return affinity_mix_; }
702
+ void set_affinity_pmi(bool on) { affinity_pmi_ = on; }
703
+ bool affinity_pmi() const { return affinity_pmi_; }
704
  void set_coherence_gate(bool on, float floor) {
705
  coherence_gate_ = on;
706
  coherence_floor_ = floor > 0.0f ? floor : 0.05f;
 
729
  // v3.2.1: returns false when the substrate file is missing (honest load
730
  // failure — callers surface a clear error instead of deciding on an
731
  // empty fabric or, worse, reporting a misleading downstream message).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
732
  bool load_model(const std::string& dir) {
733
  if (!si_.load(dir + "/substrate.bin")) return false;
734
  std::ifstream cf(dir + "/calibration.json");
735
  if (cf) { std::string buf((std::istreambuf_iterator<char>(cf)), std::istreambuf_iterator<char>());
736
  calib_ = Calibration::from_json(sfx::JV::parse(buf)); }
737
+ // v3.9.2: the fabric's recorded decide-side composition. Absent file =
738
+ // pre-3.9.2 fabric = the frozen defaults (bit-identical to before).
739
+ load_physics(dir);
740
  // v3 audit trail (optional files; a v2 model dir simply lacks them)
741
  {
742
  std::ifstream f(dir + "/conflicts.jsonl");
 
770
  // v3.2: semantic hierarchy (Stage 3) ships as hierarchy.json in the
771
  // model dir; absent file = single-stage readout, exactly as before.
772
  load_hierarchy(dir + "/hierarchy.json");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
773
  // v3.2 retrieval BY DEFAULT: a memories.jsonl shipped in the model dir
774
  // is loaded and fingerprinted once (settled-field cosines are then
775
  // free at decide time). No file => retrieval is inert, behavior of
 
1190
  };
1191
  adopt_temp("choice", calib_.choice_temperature);
1192
  adopt_temp("score", calib_.score_temperature);
1193
+ // v4.0 — one temperature per DISTINCT CANDIDATE COUNT. A shared
1194
+ // fabric that serves several domains has candidate sets of different
1195
+ // sizes, and the softmax temperature that suits a 14-way spread
1196
+ // leaves a 2-way one saturated. The count is a property of the
1197
+ // QUESTION, so the temperature may depend on it without leaking
1198
+ // anything about the label. Same 1-bit ECE selection guard, same
1199
+ // rows; a count with too few rows keeps the global scalar.
1200
+ {
1201
+ std::map<int, std::vector<CalibRow>> by_count;
1202
+ for (const auto& r : rows)
1203
+ if (r.type == "choice" && !r.energies.empty())
1204
+ by_count[static_cast<int>(r.energies.size())].push_back(r);
1205
+ for (const auto& kv : by_count) {
1206
+ if (kv.second.size() < kMinRowsPerCandidateCount) continue;
1207
+ float cand = calib_.choice_temperature;
1208
+ fit_temperature(kv.second, "choice", cand);
1209
+ const double e1 = calibration_ece(kv.second, "choice", 1.0f, 0, 0);
1210
+ const double e2 = calibration_ece(kv.second, "choice", cand, 0, 0);
1211
+ const double e0 = calibration_ece(kv.second, "choice",
1212
+ calib_.choice_temperature, 0, 0);
1213
+ float best = calib_.choice_temperature;
1214
+ float best_ece = e0;
1215
+ if (e2 < best_ece) { best = cand; best_ece = e2; }
1216
+ if (e1 < best_ece) { best = 1.0f; best_ece = e1; }
1217
+ if (best != calib_.choice_temperature)
1218
+ calib_.choice_temperature_by_count[kv.first] = best;
1219
+ }
1220
+ }
1221
  // Platt: same 1-bit selection for the noul map
1222
  const float a0 = calib_.noul_a, b0 = calib_.noul_b;
1223
  const double p1 = calibration_ece(rows, "noul", 1.0f, a0, b0);
 
1232
  // width bins on top-probability confidence, argmax-correctness for
1233
  // choice/score; Platt sigmoid + 0.5 threshold for noul). Same definition
1234
  // the bench reports, so calibrate's before/after and bench's ECE agree.
1235
+ // `by_count` (v4.0): when given, a choice row is scored under the
1236
+ // temperature fitted for ITS candidate-set size; the scalar T is the
1237
+ // fallback. Same ECE definition either way, so the report and the bench
1238
+ // agree.
1239
  static double calibration_ece(const std::vector<CalibRow>& rows,
1240
  const std::string& type, float T,
1241
+ float noul_a, float noul_b,
1242
+ const std::map<int, float>* by_count = nullptr) {
1243
  long bins[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1244
  long corr[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1245
  double confs[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
 
1253
  correct = (p >= 0.5f) == (r.y == 1);
1254
  } else {
1255
  if (r.energies.empty()) continue;
1256
+ float Ts_row = Ts;
1257
+ if (by_count && type == "choice") {
1258
+ auto bit = by_count->find(static_cast<int>(r.energies.size()));
1259
+ if (bit != by_count->end()) Ts_row = std::max(1e-6f, bit->second);
1260
+ }
1261
  float maxe = -1e30f;
1262
  for (const auto& kv : r.energies) maxe = std::max(maxe, kv.second);
1263
  float z = 0.0f, top = -1.0f; std::string amax;
1264
  for (const auto& kv : r.energies) {
1265
+ const float v = std::exp((kv.second - maxe) / Ts_row);
1266
  z += v;
1267
  if (v > top) { top = v; amax = kv.first; }
1268
  }
 
1689
  usage.lanes = si_.lane_count();
1690
 
1691
  std::vector<Answer> answers;
 
 
 
 
 
1692
  const std::vector<std::string> words = si::norm::normalize(state);
1693
  usage.state_tokens = words.size();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1694
 
1695
  // v3.8.0 (TASK 1) adaptive depth: measure the problem BEFORE any
1696
  // settle; when the flag is on, harder states get more passes.
 
2045
  // Harvest calibration rows from labelled examples (tool side).
2046
  std::vector<CalibRow> harvest_rows(const std::vector<sfx::JV>& examples) {
2047
  std::vector<CalibRow> rows;
2048
+ // v3.9.2: coverage bookkeeping. A row whose settled field is SILENT
2049
+ // contributes no candidate energies and is dropped from the fit. If
2050
+ // the composition is wrong (e.g. the decide-side energy gain is off)
2051
+ // that drop rate explodes and the fit is left on a biased subset —
2052
+ // the fit saw 556 of 2,006 question-rows on the shipped b77-sem
2053
+ // calibration. Offered vs seen is now disclosed by `calibrate`.
2054
+ harvest_offered_ = 0;
2055
+ harvest_dropped_silent_ = 0;
2056
  for (const auto& ex : examples) {
2057
  std::string state = ex.at("state").as_str();
2058
  const sfx::JV& qs = ex.has("questions") ? ex.at("questions") : sfx::JV(sfx::JVObj{});
2059
  if (!qs.is_obj()) continue;
2060
+ harvest_offered_ += qs.obj.size();
2061
  // v3.2.1: prime EXACTLY as decide() does (shared prime_field) —
2062
  // the fit must see the decide-time field composition. For fabrics
2063
  // without memories this is a bare reset, the pre-3.2 behavior.
 
2115
  // v3.8.0 (TASK 2) fit/decide parity: the fit sees the same
2116
  // multi-vector superposition the decision sees.
2117
  apply_multi_vector(hw0, nullptr);
2118
+ if (si_.silent()) { harvest_dropped_silent_ += qs.obj.size(); continue; }
2119
  for (const auto& qkv : qs.obj) {
2120
  const sfx::JV& q = qkv.second;
2121
  std::string type = q.at("type").as_str();
 
2123
  if (type == "choice" || type == "score") {
2124
  const sfx::JV& crit = q.at("criteria");
2125
  std::vector<std::pair<std::string, float>> energies;
2126
+ std::vector<std::string> c_labels, c_descs;
2127
+ std::vector<float> c_legacy;
2128
  if (crit.is_obj())
2129
+ for (const auto& kv : crit.obj) {
2130
+ c_labels.push_back(kv.first);
2131
+ c_descs.push_back(kv.second.as_str());
2132
+ c_legacy.push_back(probe_energy(kv.first, kv.second.as_str()));
2133
+ }
2134
  else if (crit.is_arr())
2135
+ for (std::size_t i = 0; i < crit.arr.size(); ++i) {
2136
+ c_labels.push_back(crit.arr[i].as_str());
2137
+ c_descs.push_back("");
2138
+ c_legacy.push_back(probe_energy(crit.arr[i].as_str(), ""));
2139
+ }
2140
+ // v4.0 — the SAME affinity blend the decision applies, so
2141
+ // the fitted temperature describes the vector the decision
2142
+ // will actually score (fit==decide parity).
2143
+ if (affinity_mix_ > 0.0f) {
2144
+ build_affinity(c_labels, hw0);
2145
+ std::vector<float> blended;
2146
+ blend_affinity(c_legacy, blended);
2147
+ c_legacy.swap(blended);
2148
+ }
2149
+ for (std::size_t i = 0; i < c_labels.size(); ++i)
2150
+ energies.emplace_back(c_labels[i], c_legacy[i]);
2151
  // resolve the gold label to a candidate KEY: for array
2152
  // criteria the stored label may be the level INDEX ("0",
2153
  // "1", ...) — the old code compared it to the level text
 
2353
  return si_.readout(si::norm::normalize(label + " " + desc));
2354
  }
2355
 
2356
+ // ======================================================================
2357
+ // v4.0 — THE AFFINITY FIELD READOUT (AFR)
2358
+ // ======================================================================
2359
+ //
2360
+ // THE MISSING TERM. For every lesson the fabric accumulates the
2361
+ // Hebbian affinity between the state's tokens and the outcome anchor
2362
+ // (outcome_text = the label key + its description; hebbian_lesson
2363
+ // binds every state token to every outcome token). That affinity is
2364
+ // the cleanest signal the fabric holds — it is literally "which
2365
+ // intent did this word teach" — and the legacy readout NEVER READS
2366
+ // IT. The legacy readout samples the settled field and relies on a
2367
+ // capped, decaying diffusion to carry the evidence from the query's
2368
+ // tokens to the anchor. ONE constant then has to serve two masters:
2369
+ // precision (the field must not smear onto wrong anchors) and reach
2370
+ // (the right anchor must light up at all). The measured optimum
2371
+ // differs per domain (tickets_en wants diffusion 0.45; agnews and
2372
+ // dbpedia want 0.02) — a sign the constant is being asked to do a
2373
+ // job the readout should do.
2374
+ //
2375
+ // AFR reads the SAME lanes in closed form. For the lit query tokens u
2376
+ // with field energy E_u and the candidate set C:
2377
+ //
2378
+ // P(c|u) = w(u,c) / sum_{c' in C} w(u,c') posterior over C
2379
+ // P0(c) = mass(c) / sum_{c'} mass(c') a priori share of C
2380
+ // L(c) = sum_u E_u * [ P(c|u) - P0(c) ] linear contrast
2381
+ // or, with --affinity-pmi, the log-odds form:
2382
+ // L(c) = sum_u E_u * log( P(c|u) / P0(c) )
2383
+ //
2384
+ // A token that points at every candidate CANCELS against the null
2385
+ // model and contributes nothing; a token that points at ONE candidate
2386
+ // contributes strongly, positive for that candidate and negative for
2387
+ // the rest. The legacy readout does the opposite: shared tokens add a
2388
+ // large common offset, and the one discriminative token is a single
2389
+ // term among the hundreds a mined-phrase description contributes
2390
+ // (Banking77 descriptions are 20 mined phrases, so "not"/"working"
2391
+ // style shared words are repeated dozens of times in the probe bag).
2392
+ //
2393
+ // This is the first-order resolvent of the propagation the settle
2394
+ // simulates: the same operator, read exactly instead of approximated
2395
+ // by a capped and smeared diffusion. It needs NO new training — the
2396
+ // lanes already exist — and costs O(|lit| * degree) per question.
2397
+ struct AffinityCtx {
2398
+ bool active = false;
2399
+ std::vector<float> value; // per candidate, unit-scaled
2400
+ std::vector<char> valid; // candidate has an anchor node
2401
+ };
2402
+ AffinityCtx affinity_ctx_;
2403
+ float affinity_mix_ = 0.0f; // 0 = legacy only (default), 1 = AFR only
2404
+ bool affinity_pmi_ = false; // log-odds form instead of the linear contrast
2405
+ mutable std::unordered_map<si::NodeId, float> lane_mass_cache_;
2406
+
2407
+ // total lane weight at a node (the fabric's own "how spread out am I"
2408
+ // statistic). Cached per fabric; lanes are immutable after learning.
2409
+ float lane_mass(si::NodeId a) const {
2410
+ auto it = lane_mass_cache_.find(a);
2411
+ if (it != lane_mass_cache_.end()) return it->second;
2412
+ std::vector<std::pair<si::NodeId, float>> ls;
2413
+ si_.lanes_of(a, ls);
2414
+ float m = 0.0f;
2415
+ for (const auto& l : ls) m += l.second;
2416
+ lane_mass_cache_[a] = m;
2417
+ return m;
2418
+ }
2419
+
2420
+ // Build the affinity channel for one question's candidate set.
2421
+ void build_affinity(const std::vector<std::string>& labels,
2422
+ const std::vector<std::string>& state_words) {
2423
+ affinity_ctx_ = AffinityCtx{};
2424
+ if (affinity_mix_ <= 0.0f) return;
2425
+ const std::size_t C = labels.size();
2426
+ if (C == 0) return;
2427
+ std::unordered_map<si::NodeId, std::size_t> cidx;
2428
+ std::vector<si::NodeId> cnode(C, static_cast<si::NodeId>(0));
2429
+ std::vector<char> ok(C, 0);
2430
+ for (std::size_t i = 0; i < C; ++i) {
2431
+ // The anchor node is the LABEL as the fabric stores it: the
2432
+ // fabric's nodes are normalized (lowercased, Porter-stemmed,
2433
+ // synonym-folded), so "World" is the node "world" and "positive"
2434
+ // is the node "positiv". Looking the RAW label up (as the first
2435
+ // cut of this channel did) silently finds nothing on any fabric
2436
+ // whose class names are not already lowercase opaque keys, and
2437
+ // the channel then contributes nothing. Normalize first, and
2438
+ // take the first token the fabric actually holds.
2439
+ si::NodeId id = static_cast<si::NodeId>(0);
2440
+ for (const auto& t : si::norm::normalize(labels[i])) {
2441
+ if (!si_.has(t)) continue;
2442
+ id = si_.find(t);
2443
+ break;
2444
+ }
2445
+ if (id == static_cast<si::NodeId>(0) && si_.has(labels[i]))
2446
+ id = si_.find(labels[i]);
2447
+ if (id == static_cast<si::NodeId>(0)) continue;
2448
+ if (cidx.count(id)) continue; // duplicate label -> one anchor
2449
+ cidx[id] = i;
2450
+ cnode[i] = id;
2451
+ ok[i] = 1;
2452
+ }
2453
+ // the null model: each candidate's a priori share of the candidate set
2454
+ std::vector<double> p0(C, 0.0);
2455
+ double tot = 0.0;
2456
+ for (std::size_t i = 0; i < C; ++i) if (ok[i]) tot += lane_mass(cnode[i]);
2457
+ if (tot <= 0.0) return;
2458
+ for (std::size_t i = 0; i < C; ++i)
2459
+ p0[i] = ok[i] ? (static_cast<double>(lane_mass(cnode[i])) + 1e-12)
2460
+ / (tot + static_cast<double>(C) * 1e-12)
2461
+ : 1.0 / static_cast<double>(C);
2462
+ // the contrastive sum over the lit query tokens
2463
+ std::vector<double> acc(C, 0.0), num(C, 0.0);
2464
+ std::vector<std::pair<si::NodeId, float>> ls;
2465
+ // v4.0 — the lit set carries ORDER evidence too: the fabric's bigram
2466
+ // nodes ("w1~w2") are bound to the outcome anchors by the same
2467
+ // Hebbian lesson, so their affinity to a candidate is an ordered
2468
+ // relation, not a bag-of-words one. Including them is the CMD 2.5
2469
+ // escape (a multiset cannot separate "a beats b" from "b beats a";
2470
+ // an ordered pair can) applied to the affinity channel.
2471
+ std::vector<std::string> lit(state_words);
2472
+ if (si::norm::bigrams_enabled())
2473
+ for (const auto& bg : si::norm::bigrams_of(state_words)) lit.push_back(bg);
2474
+ for (const auto& w : lit) {
2475
+ if (!si_.has(w)) continue;
2476
+ const si::NodeId u = si_.find(w);
2477
+ const float E = si_.node_energy(u);
2478
+ if (E <= 0.0f) continue;
2479
+ si_.lanes_of(u, ls);
2480
+ std::fill(num.begin(), num.end(), 0.0);
2481
+ double den = 0.0;
2482
+ for (const auto& l : ls) {
2483
+ auto it = cidx.find(l.first);
2484
+ if (it == cidx.end()) continue;
2485
+ num[it->second] += static_cast<double>(l.second);
2486
+ den += static_cast<double>(l.second);
2487
+ }
2488
+ if (den <= 0.0) continue;
2489
+ for (std::size_t i = 0; i < C; ++i) {
2490
+ if (!ok[i]) continue;
2491
+ const double p = num[i] / den;
2492
+ if (affinity_pmi_) {
2493
+ constexpr double kEps = 1e-9;
2494
+ const double lg = std::log((p + kEps) / (p0[i] + kEps));
2495
+ acc[i] += static_cast<double>(E) * std::max(-6.0, std::min(6.0, lg));
2496
+ } else {
2497
+ acc[i] += static_cast<double>(E) * (p - p0[i]);
2498
+ }
2499
+ }
2500
+ }
2501
+ double mx = 0.0;
2502
+ for (std::size_t i = 0; i < C; ++i)
2503
+ if (ok[i]) mx = std::max(mx, std::fabs(acc[i]));
2504
+ affinity_ctx_.active = true;
2505
+ affinity_ctx_.value.assign(C, 0.0f);
2506
+ affinity_ctx_.valid.assign(C, 0);
2507
+ for (std::size_t i = 0; i < C; ++i) {
2508
+ if (!ok[i]) continue;
2509
+ affinity_ctx_.valid[i] = 1;
2510
+ affinity_ctx_.value[i] = (mx > 0.0) ? static_cast<float>(acc[i] / mx) : 0.0f;
2511
+ }
2512
+ }
2513
+
2514
+ // Blend the affinity channel into the legacy readout energies. Called at
2515
+ // the SAME point in decide and in calibrate, so the fit sees exactly
2516
+ // what the decision sees (the v3.8 fit/decide parity contract).
2517
+ void blend_affinity(const std::vector<float>& legacy, std::vector<float>& out) const {
2518
+ out = legacy;
2519
+ if (!affinity_ctx_.active) return;
2520
+ const float m = affinity_mix_;
2521
+ float lmax = 0.0f;
2522
+ for (float v : legacy) lmax = std::max(lmax, std::fabs(v));
2523
+ for (std::size_t i = 0; i < out.size() && i < affinity_ctx_.value.size(); ++i) {
2524
+ if (!affinity_ctx_.valid[i]) continue;
2525
+ const float l = (lmax > 0.0f) ? legacy[i] / lmax : 0.0f;
2526
+ out[i] = (1.0f - m) * l + m * affinity_ctx_.value[i];
2527
+ }
2528
+ }
2529
+
2530
  float noul_support(const std::string& instructions) const {
2531
  // Noul uses the SUPPORT readout lane: breadth of corroboration.
2532
  float e = si_.readout(si::norm::normalize(instructions), si::Substrate::ReadoutMode::Support);
 
2653
  return std::max(0.0f, std::min(1.0f, conf));
2654
  }
2655
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2656
  void decide_choice(const sfx::JV& q, const std::vector<std::string>& state_words,
2657
  Answer& a, Usage* usage = nullptr) {
2658
  const sfx::JV& crit = q.at("criteria");
2659
  std::vector<std::string> labels; std::vector<float> energies;
2660
+ std::vector<std::string> descs;
2661
  if (crit.is_obj())
2662
  for (const auto& kv : crit.obj) {
2663
  labels.push_back(kv.first);
2664
+ descs.push_back(kv.second.as_str());
2665
  energies.push_back(probe_energy(kv.first, kv.second.as_str()));
2666
  }
2667
  else if (crit.is_arr())
2668
  for (const auto& v : crit.arr) {
2669
  labels.push_back(v.as_str());
2670
+ descs.push_back("");
2671
  energies.push_back(probe_energy(v.as_str(), ""));
2672
  }
2673
  if (labels.empty()) { a.deferred = true; a.reason = "no_options"; return; }
 
2688
  // measured real signal (probe-fabric candidates 0.19-0.88); below it
2689
  // the field is carryover. Do NOT raise above 0.10 — that false-defers
2690
  // valid dim candidates (measured 0.19 without energy-norm).
2691
+ // v4.0 — THE AFFINITY FIELD READOUT, applied BEFORE the silence floor.
2692
+ // In the novel-wording case the settled field carries no energy on any
2693
+ // candidate — that is exactly the case the affinity channel exists to
2694
+ // rescue, so the floor must not fire before the channel has had its
2695
+ // say. The floor therefore keeps its legacy meaning (it measures the
2696
+ // FIELD) and fires only when NEITHER channel carries evidence.
2697
+ float max_legacy = 0.0f;
2698
+ for (float e : energies) max_legacy = std::max(max_legacy, e);
2699
+ bool affinity_evidence = false;
2700
+ if (affinity_mix_ > 0.0f) {
2701
+ build_affinity(labels, state_words);
2702
+ std::vector<float> blended;
2703
+ blend_affinity(energies, blended);
2704
+ energies.swap(blended);
2705
+ for (float v : affinity_ctx_.value)
2706
+ if (v > 1e-3f) { affinity_evidence = true; break; }
2707
+ }
2708
+ const float max_energy = max_legacy;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2709
  if (std::getenv("SYFOX_DEBUG_READOUT") != nullptr) {
2710
+ std::fprintf(stderr, "DEBUG: max_candidate=%.3f threshold=%.3f affinity_evidence=%d\n",
2711
+ max_energy, kUnknownCandidateFloor, affinity_evidence ? 1 : 0);
2712
  for (std::size_t i = 0; i < labels.size(); ++i)
2713
  std::fprintf(stderr, "DEBUG: candidate[%s]=%.4f\n",
2714
  labels[i].c_str(), energies[i]);
2715
  }
2716
+ if (max_energy < kUnknownCandidateFloor && !affinity_evidence) {
2717
  a.deferred = true;
2718
  a.reason = "unknown_candidates";
2719
  return;
2720
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2721
  // v3.9.0 decision-layer paper gates — each measures the settled field
2722
  // READ-ONLY and zeroes/scales energies; none rewrites the field.
2723
  // (a) MOMENTUM (MCPE §1 / CPME §2): a candidate whose normalized
 
2889
  }
2890
  }
2891
  std::vector<float> p;
2892
+ // v4.0 — the temperature may depend on the candidate-set SIZE (the
2893
+ // fit measured one scalar per distinct count). The argmax is
2894
+ // unaffected; only the reported probabilities move.
2895
+ softmax_ps(energies, p, calib_.choice_temperature_for(energies.size()));
2896
  std::size_t best = std::max_element(p.begin(), p.end()) - p.begin();
2897
  a.choice = labels[best];
2898
  for (std::size_t i = 0; i < labels.size(); ++i)
 
2911
  // disclosure; --require-proof defers a choice with no typed path
2912
  // (coverage-cliff honesty: the field answered, the knowledge layer
2913
  // cannot justify it).
 
 
 
 
 
 
 
 
 
 
 
 
 
2914
  if (usage && (proof_on_ || require_proof_)) {
2915
  usage->proof_checked = true;
2916
  usage->proof_path = proof_path_between(state_words, labels[best]);
 
2918
  a.deferred = true;
2919
  a.reason = "no_proof_path";
2920
  }
 
 
 
 
 
 
2921
  }
2922
  // v3.9.0 (fixes.md): remember the signature pieces for the OOD gate.
2923
  if (usage) {
 
3075
  si::Substrate si_;
3076
  Calibration calib_;
3077
  bool energy_norm_ = false; // Milestone-1 gain knob (default off)
3078
+ // v3.9.2: the decide-side composition this fabric was calibrated under.
3079
+ // Loaded from physics.json on model load; recorded by calibrate.
3080
+ PhysicsComposition composition_;
3081
+ // v3.9.2: calibration-fit bookkeeping — how many question-rows the fit
3082
+ // was offered and how many it actually saw (silent fields are dropped).
3083
+ std::size_t harvest_offered_ = 0;
3084
+ std::size_t harvest_dropped_silent_ = 0;
3085
  std::unordered_set<std::uint64_t> lesson_hashes_; // Milestone-2 dedup memory
3086
  // v3.2 retrieval-by-default state
3087
  std::vector<recall::Memory> memories_;
engine/data/bank77_categories.json ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "classes": [
3
+ "Refund_not_showing_up",
4
+ "activate_my_card",
5
+ "age_limit",
6
+ "apple_pay_or_google_pay",
7
+ "atm_support",
8
+ "automatic_top_up",
9
+ "balance_not_updated_after_bank_transfer",
10
+ "balance_not_updated_after_cheque_or_cash_deposit",
11
+ "beneficiary_not_allowed",
12
+ "cancel_transfer",
13
+ "card_about_to_expire",
14
+ "card_acceptance",
15
+ "card_arrival",
16
+ "card_delivery_estimate",
17
+ "card_linking",
18
+ "card_not_working",
19
+ "card_payment_fee_charged",
20
+ "card_payment_not_recognised",
21
+ "card_payment_wrong_exchange_rate",
22
+ "card_swallowed",
23
+ "cash_withdrawal_charge",
24
+ "cash_withdrawal_not_recognised",
25
+ "change_pin",
26
+ "compromised_card",
27
+ "contactless_not_working",
28
+ "country_support",
29
+ "declined_card_payment",
30
+ "declined_cash_withdrawal",
31
+ "declined_transfer",
32
+ "direct_debit_payment_not_recognised",
33
+ "disposable_card_limits",
34
+ "edit_personal_details",
35
+ "exchange_charge",
36
+ "exchange_rate",
37
+ "exchange_via_app",
38
+ "extra_charge_on_statement",
39
+ "failed_transfer",
40
+ "fiat_currency_support",
41
+ "get_disposable_virtual_card",
42
+ "get_physical_card",
43
+ "getting_spare_card",
44
+ "getting_virtual_card",
45
+ "lost_or_stolen_card",
46
+ "lost_or_stolen_phone",
47
+ "order_physical_card",
48
+ "passcode_forgotten",
49
+ "pending_card_payment",
50
+ "pending_cash_withdrawal",
51
+ "pending_top_up",
52
+ "pending_transfer",
53
+ "pin_blocked",
54
+ "receiving_money",
55
+ "request_refund",
56
+ "reverted_card_payment?",
57
+ "supported_cards_and_currencies",
58
+ "terminate_account",
59
+ "top_up_by_bank_transfer_charge",
60
+ "top_up_by_card_charge",
61
+ "top_up_by_cash_or_cheque",
62
+ "top_up_failed",
63
+ "top_up_limits",
64
+ "top_up_reverted",
65
+ "topping_up_by_card",
66
+ "transaction_charged_twice",
67
+ "transfer_fee_charged",
68
+ "transfer_into_account",
69
+ "transfer_not_received_by_recipient",
70
+ "transfer_timing",
71
+ "unable_to_verify_identity",
72
+ "verify_my_identity",
73
+ "verify_source_of_funds",
74
+ "verify_top_up",
75
+ "virtual_card_not_working",
76
+ "visa_or_mastercard",
77
+ "why_verify_identity",
78
+ "wrong_amount_of_cash_received",
79
+ "wrong_exchange_rate_for_cash_withdrawal"
80
+ ],
81
+ "opaque": true,
82
+ "label_of": {
83
+ "Refund_not_showing_up": "c00",
84
+ "activate_my_card": "c01",
85
+ "age_limit": "c02",
86
+ "apple_pay_or_google_pay": "c03",
87
+ "atm_support": "c04",
88
+ "automatic_top_up": "c05",
89
+ "balance_not_updated_after_bank_transfer": "c06",
90
+ "balance_not_updated_after_cheque_or_cash_deposit": "c07",
91
+ "beneficiary_not_allowed": "c08",
92
+ "cancel_transfer": "c09",
93
+ "card_about_to_expire": "c10",
94
+ "card_acceptance": "c11",
95
+ "card_arrival": "c12",
96
+ "card_delivery_estimate": "c13",
97
+ "card_linking": "c14",
98
+ "card_not_working": "c15",
99
+ "card_payment_fee_charged": "c16",
100
+ "card_payment_not_recognised": "c17",
101
+ "card_payment_wrong_exchange_rate": "c18",
102
+ "card_swallowed": "c19",
103
+ "cash_withdrawal_charge": "c20",
104
+ "cash_withdrawal_not_recognised": "c21",
105
+ "change_pin": "c22",
106
+ "compromised_card": "c23",
107
+ "contactless_not_working": "c24",
108
+ "country_support": "c25",
109
+ "declined_card_payment": "c26",
110
+ "declined_cash_withdrawal": "c27",
111
+ "declined_transfer": "c28",
112
+ "direct_debit_payment_not_recognised": "c29",
113
+ "disposable_card_limits": "c30",
114
+ "edit_personal_details": "c31",
115
+ "exchange_charge": "c32",
116
+ "exchange_rate": "c33",
117
+ "exchange_via_app": "c34",
118
+ "extra_charge_on_statement": "c35",
119
+ "failed_transfer": "c36",
120
+ "fiat_currency_support": "c37",
121
+ "get_disposable_virtual_card": "c38",
122
+ "get_physical_card": "c39",
123
+ "getting_spare_card": "c40",
124
+ "getting_virtual_card": "c41",
125
+ "lost_or_stolen_card": "c42",
126
+ "lost_or_stolen_phone": "c43",
127
+ "order_physical_card": "c44",
128
+ "passcode_forgotten": "c45",
129
+ "pending_card_payment": "c46",
130
+ "pending_cash_withdrawal": "c47",
131
+ "pending_top_up": "c48",
132
+ "pending_transfer": "c49",
133
+ "pin_blocked": "c50",
134
+ "receiving_money": "c51",
135
+ "request_refund": "c52",
136
+ "reverted_card_payment?": "c53",
137
+ "supported_cards_and_currencies": "c54",
138
+ "terminate_account": "c55",
139
+ "top_up_by_bank_transfer_charge": "c56",
140
+ "top_up_by_card_charge": "c57",
141
+ "top_up_by_cash_or_cheque": "c58",
142
+ "top_up_failed": "c59",
143
+ "top_up_limits": "c60",
144
+ "top_up_reverted": "c61",
145
+ "topping_up_by_card": "c62",
146
+ "transaction_charged_twice": "c63",
147
+ "transfer_fee_charged": "c64",
148
+ "transfer_into_account": "c65",
149
+ "transfer_not_received_by_recipient": "c66",
150
+ "transfer_timing": "c67",
151
+ "unable_to_verify_identity": "c68",
152
+ "verify_my_identity": "c69",
153
+ "verify_source_of_funds": "c70",
154
+ "verify_top_up": "c71",
155
+ "virtual_card_not_working": "c72",
156
+ "visa_or_mastercard": "c73",
157
+ "why_verify_identity": "c74",
158
+ "wrong_amount_of_cash_received": "c75",
159
+ "wrong_exchange_rate_for_cash_withdrawal": "c76"
160
+ }
161
+ }
engine/data/bank77_criteria.json ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "topk": 20,
3
+ "min_count": 3,
4
+ "source": "train split only (90% carve)",
5
+ "criteria": {
6
+ "Refund_not_showing_up": "refund in, refund is, my refund, contacted the, keep checking, refund has, requested a, i contacted, refund i, refund isn't, refund me, seller for, merchant a, refund a, refund showing, refund yet, statements but, refund from, refund but, be getting",
7
+ "activate_my_card": "activating, activate my, activating my, activation, activate it, activated, card activated, to activate, card activation, the activation, be activated, for activating, activate, me activate, start using, with activating, activate card, activation of, few seconds, seconds",
8
+ "age_limit": "children, how old, age limit, be to, kids, my children, old do, my kids, child, i open, my child, an age, the age, minimum, minimum age, what age, age, age can, for children, opening",
9
+ "apple_pay_or_google_pay": "google pay, apple pay, watch, apple watch, my apple, apple, google, my google, pay top, in apple, with google, express in, with apple, watch to, pay why, play, google play, pay is, an apple, does google",
10
+ "atm_support": "which atms, atms accept, atms can, closest, the closest, atms that, closest atm, atms take, can withdraw, of atms, what atms, what atm, that accept, atm's, mastercard atm, take this, atms, accept this, at which, the atms",
11
+ "automatic_top_up": "auto, auto top, the auto, an auto, i auto, low, money automatically, up automatically, for auto, intervals, up feature, automatically, automatic top, automatically top, be traveling, up option, automatically while, certain intervals, in certain, low on",
12
+ "balance_not_updated_after_bank_transfer": "uk account, a uk, from france, my uk, international transfers, france two, take longer, uk bank, france a, reflect my, transfers usually, updated to, france, alright, couple hours, and nothing, have transferred, sure everything, you i, made one",
13
+ "balance_not_updated_after_cheque_or_cash_deposit": "deposited a, cheque but, i deposited, cheque deposit, check yesterday, deposit showing, deposited cash, deposited this, or cash, the cheque, after depositing, cheque yesterday, deposit i, deposited some, deposited, already sent, and cash, and im, check deposit, deposit but",
14
+ "beneficiary_not_allowed": "a beneficiary, my beneficiary, beneficiary, not possible, beneficiary not, some crypto, transferring to, a beneficiery, beneficiary is, beneficiery, couldn't transfer, getting error, isn't possible, purchase some, tried transferring, not allowed, error message, i doing, i've done, wasn't allowed",
15
+ "cancel_transfer": "wrong account, tomorrow, by tomorrow, to revert, a typo, typo, to reverse, me cancel, typo please, accidently, correct i, i accidently, it correct, it needs, just realized, mistake please, mistake when, pay it, realized, stop a",
16
+ "card_about_to_expire": "expire, expires, to expire, about to, card expires, in china, expired, expiration, expiring, expiration date, is expiring, it expires, will expire, is about, expire soon, expired card, expires soon, the expiration, an expired, card mine",
17
+ "card_acceptance": "businesses, businesses that, to where, card accepted, accepts, will accept, be accepted, limits to, accept this, i pay, pay with, accept my, places, where i, anywhere, this card, card will, can use, accepted, will be",
18
+ "card_arrival": "tracking, tracking number, you sent, a tracking, to track, card you, number for, track my, was issued, been delivered, mail yet, ordered it, recieve, recieve my, the expected, the tracking, track, track the, card hasn't, i track",
19
+ "card_delivery_estimate": "delivered on, delivery to, it delivered, deliver to, certain date, is delivery, specific date, to deliver, delivery time, to come, deliver, a specific, expect my, the delivery, delivery, delivered, be delivered, specific, get here, long is",
20
+ "card_linking": "reactivate, to link, link, found it, i reactivate, jacket, link it, my jacket, reactivate my, to reactivate, link the, link a, reactivate it, i link, had lost, but found, found my, i previously, in app, jacket pocket",
21
+ "card_not_working": "working anymore, restaurant today, any transactions, card doesn't, broke, is broken, my physical, declined at, what's wrong, card won't, working at, broken, won't my, anymore, card work, won't work, why won't, card isn't, restaurant, a restaurant",
22
+ "card_payment_fee_charged": "for payments, for card, for paying, when paying, paid with, warned, warned about, when you, on some, paying by, these fees, transactions but, wasn't warned, when buying, with card, didn't know, paying with, fee added, noticed an, paying",
23
+ "card_payment_not_recognised": "of payments, card shown, couple payments, the name, make myself, maybe someone, shown in, that name, are a, been coming, days can, days that, myself what's, really didn't, seen that, some payments, unknown payment, has access, payments with, card there",
24
+ "card_payment_wrong_exchange_rate": "last saturday, russian, official, official interbank, the official, ruble, russian ruble, uk pounds, charged the, using is, rate on, payment last, purchase was, rate that, really bad, rubles, saturday i, this can't, saturday, interbank",
25
+ "card_swallowed": "swallowed, card out, atm swallowed, atm took, atm ate, swallowed my, ate my, card back, ate, give my, machine didn't, took my, not give, return my, atm machine, kept, do now, card got, stuck, by the",
26
+ "cash_withdrawal_charge": "for withdrawing, withdrawals i, atm fees, for atm, withdrawing money, always thought, charging for, fee with, i always, withdrawal fee, been free, cash withdrawals, was free, withdrawing, atm cash, recent atm, withdrawing cash, groceries, taking out, today after",
27
+ "cash_withdrawal_not_recognised": "500, a 500, 500 cash, copy, copy of, a copy, for 500, odd remote, remote, this withdrawal, a some, as someone, didn't withdraw, remote town, see cash, someone just, this cash, withdrawal help, withdrawal in, withdrawal on",
28
+ "change_pin": "cash machines, can change, pin can, pin without, me change, pin on, saw my, someone saw, new pin, pin at, vacation in, spain, bank to, change my, be changed, change it, in spain, pin and, machines, i change",
29
+ "compromised_card": "card details, else is, are transactions, knowledge, make these, my knowledge, be using, my permission, transactions that, permission, these transactions, might be, card without, is using, hacked, someone used, someone may, without my, if someone, that someone",
30
+ "contactless_not_working": "contactless, my contactless, contactless payments, a contactless, the contactless, i try, try, again, fix, it's not, not working, to work, payments, today, working, work, to use, new card, it's, at",
31
+ "country_support": "what countries, i live, countries you, countries are, countries do, the countries, operate, you operate, live in, eu can, operate in, which countries, uk can, living, living in, located in, outside of, you available, countries, live",
32
+ "declined_card_payment": "a shop, shop, card declined, keep trying, kept getting, out today, couldn't pay, declined this, forward, forward to, looking forward, sad, sad what's, to paying, today looking, payment didn't, been declined, tried several, card did, thought everything",
33
+ "declined_cash_withdrawal": "hill, notting, notting hill, atm wouldn't, atm card, different atms, hill atm, the notting, two different, actually working, atm keeps, card actually, fine so, in notting, morning on, suddenly got, tried two, with withdraws, withdrawal cash, withdraws",
34
+ "declined_transfer": "decline message, transfer declined, a declined, again today, but same, declined transfer, online yesterday, recipient details, 'declined', states 'declined', transfers it's, well so, a decline, my transfers, checked all, transfer was, transfers keep, are getting, tried again, you keep",
35
+ "direct_debit_payment_not_recognised": "debit payment, direct debit, a direct, debit that, debit transaction, direct, to dispute, debit charge, debit i, debit in, debit, dispute a, didn't set, not used, of months, still dispute, dispute, a dispute, authorized, day please",
36
+ "disposable_card_limits": "of disposable, many disposable, one disposable, cards per, many transactions, several disposable, on disposable, restrictions for, cards every, every day, maximum number, transaction limit, transactions can, per, of transactions, the restrictions, per day, make several, disposable cards, cards i",
37
+ "edit_personal_details": "edit, my address, personal details, edit my, married, i edit, address, got married, modify, modify my, my personal, moved and, new address, to edit, married and, to modify, change details, changed and, details in, i modify",
38
+ "exchange_charge": "for exchanging, discount, a discount, exchange fee, exchanging foreign, for currency, discounts, exchanging currency, currencies frequently, any discounts, discount for, frequent currency, discounts for, exchange fees, exchange foreign, currency exchanges, foreign currencies, exchanging, a lot, lot",
39
+ "exchange_rate": "rates are, what exchange, what your, exchange rates, determine, rate will, decide, find your, from where, me your, rates calculated, rates determined, what foreign, you determine, your exchange, rates, calculated, the foreign, how are, foreign exchange",
40
+ "exchange_via_app": "aud, and gbp, usd and, for gbp, to gbp, exchange usd, usd to, app allow, between usd, to aud, usd, aud for, currencies using, currencies with, from usd, gbp to, i convert, usd for, aud how, exchange aud",
41
+ "extra_charge_on_statement": "1 charge, extra 1, a 1, extra pound, 1 fee, a pound, the 1, 1, 1 extra, one pound, charged 1, 1 on, appears as, pound charge, purchased anything, for 1, of 1, pound, 1l, additional pound",
42
+ "failed_transfer": "mortgage, a flat, mortgage payment, flat and, 5 times, my mortgage, transfer failed, keep failing, mortgage to, tried 5, buying a, error can, error i'm, failed transfer, flat but, initial, initial mortgage, to friends, transfer fail, 5",
43
+ "fiat_currency_support": "fiat, fiat currencies, multiple currencies, and exchange, holding and, which fiat, what fiat, for holding, hold money, to hold, flat currencies, to eur, holding, i hold, eur, and holding, in multiple, exchange and, the fiat, which flat",
44
+ "get_disposable_virtual_card": "these disposable, cards work, how disposable, virtual disposable, create a, disposable virtual, a disposable, cards for, as well, disposable, virtual cards, the disposable, virtual, virtual card, disposable cards, create, well, disposable card, card for, card as",
45
+ "get_physical_card": "pin yet, locate my, pin sent, pin where, separately, card pin, a pin, pin anywhere, i locate, pin for, the pin, locate, pin is, find my, located, when do, pin, pin number, about the, anywhere",
46
+ "getting_spare_card": "second card, more cards, for sending, out more, get another, more physical, sending out, another card, additional cards, spare, a spare, extra cards, member, send out, family member, few more, get more, give a, one card, spare card",
47
+ "getting_virtual_card": "those virtual, a virtual, card yet, of those, the virtual, my virtual, virtual card, virtual, those, virtual cards, about getting, get one, to order, getting a, receive a, order a, go about, find the, card how, order",
48
+ "lost_or_stolen_card": "a stolen, is stolen, stolen card, report, been stolen, been lost, is missing, stolen, someone stole, card has, stolen what, was stolen, stole my, i lost, lost my, stole, card what, lost, can't find, missing",
49
+ "lost_or_stolen_phone": "phone was, phone is, phone what, mugged, the hotel, my phone, phone at, stolen yesterday, phone, app what, got mugged, mugged yesterday, someone from, stop someone, took everything, hotel, accessing, accessing my, from accessing, from using",
50
+ "order_physical_card": "cards delivered, a real, real, real card, a physical, an actual, order my, actual card, delivered to, physical card, actual, request a, physical, are cards, the cards, my own, physical cards, i order, own, like a",
51
+ "passcode_forgotten": "password, my password, passcode, my passcode, the passcode, forgotten, forgotten my, remember my, reset the, can't remember, forgot the, app passcode, can't log, my pass, pass code, passcode is, passcode won't, password is, to reset, get into",
52
+ "pending_card_payment": "payment still, just showing, through at, payment pending, payment will, purchases from, since a, some point, days already, payment gone, show pending, status for, that hasn't, pending payment, be going, from pending, morning still, it actually, payment a, my purchases",
53
+ "pending_cash_withdrawal": "withdrawal still, pending cash, transaction still, machine declined, withdrawal be, centre, city centre, progress can, this still, to still, withdrawal show, withdrawal shows, in progress, still shows, withdrawal to, still be, account says, the city, pending in, withdrawal is",
54
+ "pending_top_up": "new customer, half, half an, time today, your top, hour already, just shows, over an, up pending, an hour, customer and, instant, up gone, up hasn't, hour, up went, tried topping, i'm a, up be, fix it",
55
+ "pending_transfer": "transfer pending, eu transfers, money immediately, 2018, ago sent, do eu, immediately online, eu transfer, finally worked, for sure, it's 2018, right for, sure transfer, they're right, transfer still, pending transfer, seller says, finally, pending when, seller hasn't",
56
+ "pin_blocked": "unblock, unblock my, to unblock, i unblock, me unblock, unblocked, is blocked, pin tries, blocked can, pin wrong, unblock it, pin too, wrong pin, exceeded, pin unblocked, too many, blocked, blocked what, got blocked, have exceeded",
57
+ "receiving_money": "salary, my salary, in gbp, salary is, employer, my employer, salary in, configure, gbp do, to configure, am paid, friend send, paid in, pay me, receive transfers, me money, friend to, transfer my, another currency, receive money",
58
+ "request_refund": "changed my, item refunded, to return, just bought, item yet, mind and, on something, refund back, refund policy, the product, back please, bought recently, decided, full refund, i return, item for, just cancel, my package, not paying, payment since",
59
+ "reverted_card_payment?": "or two, payment reverted, money didn't, week or, didn't come, has reverted, it's back, made was, received one, something about, came back, was returned, already received, been returned, is reverted, payment been, payment came, i've already, problem i, two weeks",
60
+ "supported_cards_and_currencies": "and currencies, are accepted, express to, currencies and, us credit, and cards, funds into, accept to, other credit, payment methods, what payment, which cards, what cards, which currencies, cards and, of cards, accept for, add funds, currencies you, methods are",
61
+ "terminate_account": "delete my, to delete, close my, delete, to close, not happy, terminate, i close, i delete, not satisfied, satisfied, satisfied with, terminate my, dissatisfied, to terminate, close, account immediately, delete account, delete this, please delete",
62
+ "top_up_by_bank_transfer_charge": "a sepa, sepa transfer, for receiving, by transfer, receiving money, swift transfer, a swift, receiving a, swift, sepa, are swift, fees associated, for sepa, transfer cost, swift transfers, much would, sepa transfers, receiving, associated, associated with",
63
+ "top_up_by_card_charge": "international card, european bank, us card, european card, up charges, up us, a european, us cards, my international, fees if, an international, for us, any charges, bank card, with an, european, any fees, for european, using an, debit or",
64
+ "top_up_by_cash_or_cheque": "with cash, use cash, find top, by cash, cheque to, cash to, by cheque, a cheque, a check, deposit a, cheques, option to, send a, i deposit, to deposit, cheque, up using, check to, account with, with a",
65
+ "top_up_failed": "up failed, alternatives, declined for, problem or, today urgently, urgently but, work i, any alternatives, app rejected, or let, this or, up fail, please resolve, up didn't, card keeps, declined can, has failed, resolve this, it a, was able",
66
+ "top_up_limits": "up limits, any top, any amount, many top, on top, unlimited, up limit, much i, can top, how often, max, of top, the max, the most, limit for, the limit, do top, limit to, a limit, maximum",
67
+ "top_up_reverted": "crypto top, saw it, there and, up recently, you offered, cancellation, disappeared from, gone i, had topped, has disappeared, it's disappeared, thought you, up get, disappeared i, disappeared what's, glitch, it's gone, offered crypto, up cancellation, up showing",
68
+ "topping_up_by_card": "other people, else top, my friends, be topped, money disappeared, friends, my wallet, wallet, by my, money using, my credit, people, by card, up by, up using, credit card, disappeared, credit, topped, topped up",
69
+ "transaction_charged_twice": "charged twice, twice for, twice, double charged, same transaction, times for, duplicate charge, please remove, remove one, clearly, duplicated, two times, duplicate charges, duplicate payment, one transaction, restaurant visit, second time, store earlier, transactions and, was double",
70
+ "transfer_fee_charged": "receiver, transfer fee, the receiver, transfer more, make up, thought transfers, transfers were, a receiver, fee while, lesser, manage, payments for, place abroad, to manage, for transferring, abroad for, amount what, be rewarded, fair, my place",
71
+ "transfer_into_account": "another bank, account into, about transferring, at another, this one, from another, one account, account at, move money, other bank, via bank, my other, this bank, money into, from one, funds from, explain how, bank account, bank transfer, bank transfers",
72
+ "transfer_not_received_by_recipient": "money transaction, landlord, before yesterday, day before, and she, i've checked, sent some, transfer within, needs it, new landlord, right one, arrive yet, done a, friend who, my landlord, one i've, completion, correct can, country it, country transfer",
73
+ "transfer_timing": "from europe, transfer something, china how, us transfer, an urgent, europe how, europe to, urgent transfer, from china, europe take, reach my, europe, estimated, to reach, approximately, the estimated, us take, wait time, something from, something to",
74
+ "unable_to_verify_identity": "proving, 10 minutes, are clear, economic, economic area, from us, images, images are, minutes to, photos, proving my, readable, switzerland, 18 years, app doesn't, european economic, glare, or older, your images, a resident",
75
+ "verify_my_identity": "identity checks, documents do, what documents, documentation, of id, forms, forms of, id do, what documentation, what forms, for identity, checks, documents, need for, needed for, you require, the identity, i prove, is needed, for verification",
76
+ "verify_source_of_funds": "source of, my source, the source, funds come, source, funds came, see where, my available, money came, where funds, available cash, available money, comes from, money comes, my fund, source for, tell where, of funds, my funds, available funds",
77
+ "verify_top_up": "verification code, up verification, verify top, verifying the, up card, authenticate, code anywhere, i authenticate, up need, verifying top, code for, verify the, the verification, verify a, code, a verification, do we, we need, verification process, the top",
78
+ "virtual_card_not_working": "got rejected, my disposable, cannot get, my virtual, card won't, won't work, was rejected, the virtual, virtual card, rejected, virtual, disposable virtual, to work, card to, i cannot, cannot, won't, work, disposable, get my",
79
+ "visa_or_mastercard": "a visa, visa and, and mastercard, visa card, visa, both a, get both, mastercard and, mastercard from, and visa, between visa, both visa, choose between, visa or, or mastercard, get visa, i prefer, mastercard can, use visa, both mastercard",
80
+ "why_verify_identity": "about me, passed yet, account although, identity details, is identity, many questions, much information, need so, not passed, so many, verification hasn't, verification has, account before, asking, questions, questions about, though my, passed, so much, information about",
81
+ "wrong_amount_of_cash_received": "gave me, 20, it gave, gave, only got, 100 but, atm didn't, 30 pounds, only gave, 100, 10 pounds, atm gave, got 20, request cash, me 10, atm just, charged though, it only, just gave, 20 when",
82
+ "wrong_exchange_rate_for_cash_withdrawal": "currency at, home currency, for foreign, bit concerned, cash abroad, withdraw here, and bit, currency while, here without, known, was abroad, was different, withdraw without, my home, any additional, holiday and, without any, additional cost, rate when, home"
83
+ }
84
+ }
engine/data/handmade_probes.jsonl ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"id": "b77_00", "domain": "bank77", "state": "the cash machine swallowed my card and it never came back", "label": "c19"}
2
+ {"id": "b77_01", "domain": "bank77", "state": "my card disappeared from my coat, someone must have taken it", "label": "c42"}
3
+ {"id": "b77_02", "domain": "bank77", "state": "the pin got locked after too many wrong tries and now nothing works", "label": "c50"}
4
+ {"id": "b77_03", "domain": "bank77", "state": "I cannot remember my four digit code anymore", "label": "c45"}
5
+ {"id": "b77_04", "domain": "bank77", "state": "please close my account for good, I am leaving", "label": "c55"}
6
+ {"id": "b77_05", "domain": "bank77", "state": "I would like a plastic card posted out to my house", "label": "c39"}
7
+ {"id": "b77_06", "domain": "bank77", "state": "how do I get a card that only lives inside my phone", "label": "c41"}
8
+ {"id": "b77_07", "domain": "bank77", "state": "I want to send money into my own account", "label": "c65"}
9
+ {"id": "b77_08", "domain": "bank77", "state": "the person I paid says nothing has landed for them", "label": "c66"}
10
+ {"id": "b77_09", "domain": "bank77", "state": "the same amount was taken out of my account two times over", "label": "c63"}
11
+ {"id": "b77_10", "domain": "bank77", "state": "my purchase was refused at the shop till", "label": "c26"}
12
+ {"id": "b77_11", "domain": "bank77", "state": "holding the phone over the reader does nothing at all", "label": "c24"}
13
+ {"id": "b77_12", "domain": "bank77", "state": "the shop billed me in euros at a rate that looks wrong", "label": "c18"}
14
+ {"id": "b77_13", "domain": "bank77", "state": "I took foreign notes out and the exchange rate looks off", "label": "c76"}
15
+ {"id": "b77_14", "domain": "bank77", "state": "there is a mystery charge on my cash machine withdrawal", "label": "c20"}
16
+ {"id": "b77_15", "domain": "bank77", "state": "the machine refused to give me any notes", "label": "c27"}
17
+ {"id": "b77_16", "domain": "bank77", "state": "the withdrawal still says it is going through", "label": "c47"}
18
+ {"id": "b77_17", "domain": "bank77", "state": "the machine handed me less money than the receipt says", "label": "c75"}
19
+ {"id": "b77_18", "domain": "bank77", "state": "when will the card arrive through the post", "label": "c13"}
20
+ {"id": "b77_19", "domain": "bank77", "state": "my card finally turned up in the post this morning", "label": "c12"}
21
+ {"id": "b77_20", "domain": "bank77", "state": "the card needs switching on before I can use it", "label": "c01"}
22
+ {"id": "b77_21", "domain": "bank77", "state": "I want to set a different four digit number", "label": "c22"}
23
+ {"id": "b77_22", "domain": "bank77", "state": "a standing order I never set is on my statement", "label": "c29"}
24
+ {"id": "b77_23", "domain": "bank77", "state": "the shop says the card payment is still hanging", "label": "c46"}
25
+ {"id": "b77_24", "domain": "bank77", "state": "there is an unexplained item on my bill", "label": "c35"}
26
+ {"id": "b77_25", "domain": "bank77", "state": "I would like my money back for this purchase", "label": "c52"}
27
+ {"id": "b77_26", "domain": "bank77", "state": "the refund was approved ages ago and still has not arrived", "label": "c00"}
28
+ {"id": "b77_27", "domain": "bank77", "state": "it suddenly asks me to prove who I am", "label": "c69"}
29
+ {"id": "b77_28", "domain": "bank77", "state": "the identity check keeps failing and I cannot get past it", "label": "c68"}
30
+ {"id": "b77_29", "domain": "bank77", "state": "why on earth do you need my identity documents", "label": "c74"}
31
+ {"id": "b77_30", "domain": "bank77", "state": "you want to know where my money came from", "label": "c70"}
32
+ {"id": "b77_31", "domain": "bank77", "state": "my card should refill itself when it runs low", "label": "c05"}
33
+ {"id": "b77_32", "domain": "bank77", "state": "how much can I add to my account in one day", "label": "c60"}
34
+ {"id": "b77_33", "domain": "bank77", "state": "the top up did not go through at all", "label": "c59"}
35
+ {"id": "b77_34", "domain": "bank77", "state": "the money I added is still not showing on my balance", "label": "c48"}
36
+ {"id": "b77_35", "domain": "bank77", "state": "I want to add money using my debit card", "label": "c62"}
37
+ {"id": "b77_36", "domain": "bank77", "state": "the transfer is still sitting there doing nothing", "label": "c49"}
38
+ {"id": "b77_37", "domain": "bank77", "state": "please stop the payment I scheduled for tomorrow", "label": "c09"}
39
+ {"id": "b77_38", "domain": "bank77", "state": "the outgoing payment was refused by the bank", "label": "c28"}
40
+ {"id": "b77_39", "domain": "bank77", "state": "the transfer keeps erroring out every time", "label": "c36"}
41
+ {"id": "b77_40", "domain": "bank77", "state": "how long does a transfer take to actually arrive", "label": "c67"}
42
+ {"id": "b77_41", "domain": "bank77", "state": "I am not allowed to send money to that person", "label": "c08"}
43
+ {"id": "b77_42", "domain": "bank77", "state": "a service fee appeared for paying with my card", "label": "c16"}
44
+ {"id": "b77_43", "domain": "bank77", "state": "I do not recognise this charge on my card at all", "label": "c17"}
45
+ {"id": "b77_44", "domain": "bank77", "state": "it says I am too old for this", "label": "c02"}
46
+ {"id": "b77_45", "domain": "bank77", "state": "can I use my phone to pay instead of the card", "label": "c03"}
47
+ {"id": "b77_46", "domain": "bank77", "state": "which shops actually take your card", "label": "c11"}
48
+ {"id": "b77_47", "domain": "bank77", "state": "which cards and which countries do you accept", "label": "c54"}
49
+ {"id": "b77_48", "domain": "bank77", "state": "is it a visa or a mastercard", "label": "c73"}
50
+ {"id": "b77_49", "domain": "bank77", "state": "do you even operate in my country", "label": "c25"}
51
+ {"id": "b77_50", "domain": "bank77", "state": "can I hold real money currency in an account", "label": "c37"}
52
+ {"id": "b77_51", "domain": "bank77", "state": "what is the fee for adding money by bank transfer", "label": "c56"}
53
+ {"id": "b77_52", "domain": "bank77", "state": "what is the fee for adding money by card", "label": "c57"}
54
+ {"id": "b77_53", "domain": "bank77", "state": "adding money over the counter with paper notes", "label": "c58"}
55
+ {"id": "b77_54", "domain": "bank77", "state": "the top up was taken back off me", "label": "c61"}
56
+ {"id": "b77_55", "domain": "bank77", "state": "there is a fee for sending money to someone", "label": "c64"}
57
+ {"id": "b77_56", "domain": "bank77", "state": "your cash machines are not working this morning", "label": "c04"}
58
+ {"id": "b77_57", "domain": "bank77", "state": "my card is refused everywhere I try it", "label": "c15"}
59
+ {"id": "b77_58", "domain": "bank77", "state": "someone has copied my card details", "label": "c23"}
60
+ {"id": "b77_59", "domain": "bank77", "state": "the card that lives in my phone is not working", "label": "c72"}
61
+ {"id": "b77_60", "domain": "bank77", "state": "I need a card for a single use only", "label": "c38"}
62
+ {"id": "b77_61", "domain": "bank77", "state": "how many times can I use the single use card", "label": "c30"}
63
+ {"id": "b77_62", "domain": "bank77", "state": "I need a spare replacement card", "label": "c40"}
64
+ {"id": "b77_63", "domain": "bank77", "state": "I sent money to myself and my balance is still the old figure", "label": "c06"}
65
+ {"id": "b77_64", "domain": "bank77", "state": "I paid in a cheque and the balance has not moved", "label": "c07"}
66
+ {"id": "b77_65", "domain": "bank77", "state": "how do I get money sent to me by someone else", "label": "c51"}
67
+ {"id": "b77_66", "domain": "bank77", "state": "I need to change the address on my account", "label": "c31"}
68
+ {"id": "b77_67", "domain": "bank77", "state": "please order me a card", "label": "c44"}
69
+ {"id": "tix_00", "domain": "tickets_en", "state": "you charged my card twice for the same order", "label": "te00"}
70
+ {"id": "tix_01", "domain": "tickets_en", "state": "the invoice shows an amount I do not recognise", "label": "te00"}
71
+ {"id": "tix_02", "domain": "tickets_en", "state": "I was billed for a subscription I cancelled", "label": "te00"}
72
+ {"id": "tix_03", "domain": "tickets_en", "state": "the app crashes every time I open the settings screen", "label": "te02"}
73
+ {"id": "tix_04", "domain": "tickets_en", "state": "the integration returns error 500 on every call", "label": "te02"}
74
+ {"id": "tix_05", "domain": "tickets_en", "state": "the webhooks stopped firing after the upgrade", "label": "te02"}
75
+ {"id": "tix_06", "domain": "tickets_en", "state": "we want to buy 40 licences for the whole team", "label": "te01"}
76
+ {"id": "tix_07", "domain": "tickets_en", "state": "what does the enterprise plan cost per seat", "label": "te01"}
77
+ {"id": "tix_08", "domain": "tickets_en", "state": "can we upgrade to a bigger tier next quarter", "label": "te01"}
78
+ {"id": "agn_00", "domain": "agnews", "state": "diplomats from twelve countries gathered to discuss the ceasefire", "label": "ag00"}
79
+ {"id": "agn_01", "domain": "agnews", "state": "the UN assembly opened its session in the capital today", "label": "ag00"}
80
+ {"id": "agn_02", "domain": "agnews", "state": "the striker scored twice in the second half", "label": "ag01"}
81
+ {"id": "agn_03", "domain": "agnews", "state": "the team qualified for the final after a late equaliser", "label": "ag01"}
82
+ {"id": "agn_04", "domain": "agnews", "state": "the company reported a rise in quarterly revenue", "label": "ag02"}
83
+ {"id": "agn_05", "domain": "agnews", "state": "shares fell after the merger announcement", "label": "ag02"}
84
+ {"id": "agn_06", "domain": "agnews", "state": "researchers sequenced the genome of the parasite", "label": "ag03"}
85
+ {"id": "agn_07", "domain": "agnews", "state": "the telescope captured a faint galaxy at long wavelengths", "label": "ag03"}
86
+ {"id": "sms_00", "domain": "sms", "state": "are we still on for dinner at eight", "label": "sm00"}
87
+ {"id": "sms_01", "domain": "sms", "state": "can you send me the notes from the meeting", "label": "sm00"}
88
+ {"id": "sms_02", "domain": "sms", "state": "FREE PRIZE!!! claim your 500 pound voucher now, call 0900", "label": "sm01"}
89
+ {"id": "sms_03", "domain": "sms", "state": "WIN a car! text CLAIM to 80086 to enter the draw today", "label": "sm01"}
90
+ {"id": "enr_00", "domain": "enron", "state": "here is the agenda for thursday review, see attached", "label": "en00"}
91
+ {"id": "enr_01", "domain": "enron", "state": "please find the signed contract from legal", "label": "en00"}
92
+ {"id": "enr_02", "domain": "enron", "state": "URGENT: you have won a 1000 dollar lottery, act now", "label": "en01"}
93
+ {"id": "enr_03", "domain": "enron", "state": "click here to confirm your mailbox password immediately", "label": "en01"}
94
+ {"id": "hat_00", "domain": "hate", "state": "people of that country are all vermin and should be driven out", "label": "ha00"}
95
+ {"id": "hat_01", "domain": "hate", "state": "those people are subhuman filth and we should rid the world of them", "label": "ha00"}
96
+ {"id": "hat_02", "domain": "hate", "state": "that take is bloody ridiculous, you absolute idiot", "label": "ha01"}
97
+ {"id": "hat_03", "domain": "hate", "state": "you are a steaming pile of garbage, moron", "label": "ha01"}
98
+ {"id": "hat_04", "domain": "hate", "state": "the bus was late again this morning", "label": "ha02"}
99
+ {"id": "hat_05", "domain": "hate", "state": "she baked a lemon tart for the office", "label": "ha02"}
100
+ {"id": "pol_00", "domain": "polarity", "state": "the packaging arrived crushed and the product leaked everywhere", "label": "po00"}
101
+ {"id": "pol_01", "domain": "polarity", "state": "absolutely useless, it broke on the second use", "label": "po00"}
102
+ {"id": "pol_02", "domain": "polarity", "state": "this little gadget has saved me so much time, I love it", "label": "po01"}
103
+ {"id": "pol_03", "domain": "polarity", "state": "a beautiful, thoughtful gift that arrived early", "label": "po01"}
104
+ {"id": "emo_00", "domain": "emotion", "state": "I have not stopped crying since the funeral", "label": "em00"}
105
+ {"id": "emo_01", "domain": "emotion", "state": "my grandmother died last week and the house feels empty", "label": "em00"}
106
+ {"id": "emo_02", "domain": "emotion", "state": "I got the job! I am absolutely delighted", "label": "em01"}
107
+ {"id": "emo_03", "domain": "emotion", "state": "we won the cup after nine years, I cannot stop grinning", "label": "em01"}
108
+ {"id": "emo_04", "domain": "emotion", "state": "thinking about you constantly, you mean everything to me", "label": "em02"}
109
+ {"id": "emo_05", "domain": "emotion", "state": "I adore you more than I have ever adored anyone", "label": "em02"}
110
+ {"id": "emo_06", "domain": "emotion", "state": "I am furious that they cancelled without telling me", "label": "em03"}
111
+ {"id": "emo_07", "domain": "emotion", "state": "this is outrageous and I will not stand for it", "label": "em03"}
112
+ {"id": "emo_08", "domain": "emotion", "state": "I am terrified of walking home through that park after dark", "label": "em04"}
113
+ {"id": "emo_09", "domain": "emotion", "state": "my hands are shaking, I do not know what to do", "label": "em04"}
114
+ {"id": "emo_10", "domain": "emotion", "state": "I cannot believe it, I did not see that coming at all", "label": "em05"}
115
+ {"id": "emo_11", "domain": "emotion", "state": "wow, that turn of events completely caught me off guard", "label": "em05"}
116
+ {"id": "bq_00", "domain": "boolq", "state": "The Eiffel Tower is located in Paris. Is the Eiffel Tower in Paris?", "label": "bo01"}
117
+ {"id": "bq_01", "domain": "boolq", "state": "Penguins are birds that live only in the arctic. Do penguins live in the arctic?", "label": "bo01"}
118
+ {"id": "bq_02", "domain": "boolq", "state": "The Nile is the longest river in Africa. Is the Amazon the longest river in Africa?", "label": "bo00"}
119
+ {"id": "bq_03", "domain": "boolq", "state": "Water boils at 100 degrees Celsius at sea level. Does water freeze at 100 degrees?", "label": "bo00"}
120
+ {"id": "dbp_00", "domain": "dbpedia", "state": "Samsung Electronics is a South Korean electronics company", "label": "db00"}
121
+ {"id": "dbp_01", "domain": "dbpedia", "state": "The University of Bologna is an educational institution in Italy", "label": "db01"}
122
+ {"id": "dbp_02", "domain": "dbpedia", "state": "A tulip is a plant that grows from a bulb", "label": "db02"}
123
+ {"id": "dbp_03", "domain": "dbpedia", "state": "Rumours is a studio album recorded by the Beatles", "label": "db03"}
124
+ {"id": "dbp_04", "domain": "dbpedia", "state": "Jurassic Park is a film directed by Steven Spielberg", "label": "db04"}
125
+ {"id": "dbp_05", "domain": "dbpedia", "state": "Moby Dick is a written work by Herman Melville", "label": "db05"}
126
+ {"id": "dbp_06", "domain": "dbpedia", "state": "Miles Davis was an artist who played the trumpet", "label": "db06"}
127
+ {"id": "dbp_07", "domain": "dbpedia", "state": "Usain Bolt is an athlete from Jamaica", "label": "db07"}
128
+ {"id": "dbp_08", "domain": "dbpedia", "state": "A village is a settlement smaller than a town", "label": "db08"}
129
+ {"id": "dbp_09", "domain": "dbpedia", "state": "A river is a natural stream of water", "label": "db09"}
130
+ {"id": "dbp_10", "domain": "dbpedia", "state": "A bird is a vertebrate that can fly", "label": "db10"}
131
+ {"id": "dbp_11", "domain": "dbpedia", "state": "A mountain is a large landform rising above the land", "label": "db11"}
132
+ {"id": "dbp_12", "domain": "dbpedia", "state": "A city is a large permanent settlement", "label": "db12"}
133
+ {"id": "dbp_13", "domain": "dbpedia", "state": "A currency is a medium of exchange", "label": "db13"}
134
+ {"id": "rt_00", "domain": "router", "state": "the treaty was signed by delegates from forty nations", "label": "rt00"}
135
+ {"id": "rt_01", "domain": "router", "state": "he sank a curling three pointer in the fourth quarter", "label": "rt00"}
136
+ {"id": "rt_02", "domain": "router", "state": "the passage states that the treaty was signed in 1815", "label": "rt02"}
137
+ {"id": "rt_03", "domain": "router", "state": "what is the weather in Madrid tomorrow", "label": "rt03"}
138
+ {"id": "rt_04", "domain": "router", "state": "the city of Bruges is a UNESCO listed medieval centre", "label": "rt04"}
139
+ {"id": "rt_05", "domain": "router", "state": "she was overjoyed and could not stop smiling", "label": "rt05"}
140
+ {"id": "rt_06", "domain": "router", "state": "please find attached the agenda for the quarterly review", "label": "rt06"}
141
+ {"id": "rt_07", "domain": "router", "state": "flee the burning building and dig in behind the rocks", "label": "rt07"}
142
+ {"id": "rt_08", "domain": "router", "state": "do not run rm -rf on the production database", "label": "rt08"}
143
+ {"id": "rt_09", "domain": "router", "state": "that post is absolutely disgusting, you are all animals", "label": "rt09"}
144
+ {"id": "rt_10", "domain": "router", "state": "the headphones sound fantastic, best purchase this year", "label": "rt10"}
145
+ {"id": "rt_11", "domain": "router", "state": "WINNER claim your free voucher now, text yes to 80086", "label": "rt11"}
146
+ {"id": "rt_12", "domain": "router", "state": "আমার কার্ড থেকে টাকা দুইবার কেটে নিয়েছে", "label": "rt12"}
147
+ {"id": "rt_13", "domain": "router", "state": "मेरे खाते से पैसे कट गए हैं, मदद करें", "label": "rt14"}
148
+ {"id": "rt_14", "domain": "router", "state": "с моего счета списали деньги дважды", "label": "rt15"}
engine/data/synonyms.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================================
2
+ # SyFox synonym folding table (P4, v2.1)
3
+ #
4
+ # format: canonical: variant, variant, ...
5
+ #
6
+ # Used in TWO places that must stay in lockstep:
7
+ # * core/normalize.hpp — decide-time folding: every table word (canonical
8
+ # or variant) is porter-stemmed and mapped to the stemmed canonical, so a
9
+ # query saying "reimbursement" lands on the same node as "refund".
10
+ # * tools/gen_paraphrases.py — train-time augmentation: swaps existing
11
+ # words for their table alternates. Single words ONLY, so a paraphrased
12
+ # row normalizes to the same token stream as its source row.
13
+ #
14
+ # Rules for edits:
15
+ # * single words only (the C++ folding is per-token)
16
+ # * label-safe swaps only: replacing a word with its alternate must never
17
+ # change the row's labels (no urgency words in fillers, no cross-department
18
+ # drift, no frustration-scale drift)
19
+ # * conservative: a wrong merge here is a wrong lane in the fabric
20
+ # ============================================================================
21
+ refund: reimbursement, reimburse
22
+ urgent: asap, immediately, urgently, hurry
23
+ angry: furious, mad, upset
24
+ broken: faulty, busted
25
+ fix: repair, mend
26
+ problem: issue, trouble, glitch
27
+ slow: delayed, sluggish, laggy
28
+ crash: freeze, hang, froze
29
+ price: cost
30
+ scared: afraid, fearful
31
+ money: cash
32
+ wrong: incorrect, mistaken
engine/docs/FIT_DECIDE_PARITY.md ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Fit == decide — the calibration composition contract (v3.9.2)
2
+
3
+ **The bug this document describes shipped a wrong answer on 87% of the rows
4
+ it was scored on, with ~0.98 confidence, and it is invisible to every test
5
+ in the tree. The fix makes the fit and the decision the same engine by
6
+ construction.**
7
+
8
+ ---
9
+
10
+ ## 1. The shape of the bug
11
+
12
+ SyFox answers a `choice` question by
13
+
14
+ 1. injecting the state into the substrate,
15
+ 2. settling (dissipative diffusion along the Hebbian lanes),
16
+ 3. reading the candidate energies and turning them into a probability vector
17
+ with a **softmax at temperature `T`**,
18
+ 4. deferring if the top-2 probability gap is under the defer margin.
19
+
20
+ Step 3 is the only fitted parameter in the pipeline. `T` is fitted by
21
+ `calibrate` on collected rows — and **the energies it is fitted on are a
22
+ function of the entire decide-side composition**:
23
+
24
+ | knob | what it changes in the fitted energies |
25
+ |---|---|
26
+ | `energy_norm` (the decide-side energy gain) | the injected dose — and, crucially, it is **per state** (`inject_energy × mean √node_mass`), so it is not a uniform rescale |
27
+ | `diffusion` | how much energy leaves along the lanes per pass → the gap scale |
28
+ | `decay` | per-pass retention |
29
+ | `k_settle` | how many passes run |
30
+ | `hop_coupling` | how much the 1-hop readout contributes |
31
+
32
+ So the fitted `T` is a number **for one specific composition**. Change the
33
+ composition and the number describes a different engine.
34
+
35
+ That is not a theoretical concern. It is what this repository shipped.
36
+
37
+ ## 2. What was shipped
38
+
39
+ `Makefile`, before the fix:
40
+
41
+ ```make
42
+ b77-sem:
43
+ ./build/syfox calibrate --model model-b77-sem --examples data/bank77_cal.jsonl
44
+ b77-sem-bench:
45
+ ./build/syfox bench --model model-b77-sem --eval data/bank77_cal.jsonl --energy-norm ...
46
+ ```
47
+
48
+ Same for `router16` and `model-bank77-best`. **The calibration ran without
49
+ the decide-side energy gain; every bench and every decide call ran with
50
+ it.** (`model-tickets-big` and the seed fabrics were fine — the seed
51
+ fabrics do not use the gain at all, and the `-big` target passes
52
+ `--energy-norm` to *both*.)
53
+
54
+ Measured on the **shipped** `model/b77-sem` fabric, the **1,003-row cal
55
+ split** that ships with it, same engine, one flag apart:
56
+
57
+ | calibration | fitted `T` | rows the fit saw | ECE before → after |
58
+ |---|---:|---:|---:|
59
+ | **without** the energy gain (what shipped) | **0.0037** | **556 of 2,006** (27.7%) | 0.4567 → 0.4057 |
60
+ | **with** the energy gain (what the bench runs) | **0.3552** | 2,006 of 2,006 (100%) | 0.3183 → 0.3056 |
61
+
62
+ The published `model/b77-sem/calibration.json` says
63
+ `choice_temperature: 0.00472645` over **211 rows**; `model/router16` says
64
+ `0.00491756` over **160 rows**. Both are the near-floor value the fit
65
+ picks when the field is nearly empty.
66
+
67
+ ## 3. Why a near-floor `T` is catastrophic
68
+
69
+ `T = 0.0047` saturates the softmax. The post-temperature top-2 gap goes to
70
+ ~0.93 on essentially every row, and three things break at once:
71
+
72
+ 1. **The defer axis dies.** The engine's honest-defer gate is an absolute
73
+ margin (0.05) on the top-2 probability gap. A gap of 0.93 can never
74
+ fall under 0.05, so the engine **never abstains** — the one behaviour the
75
+ model card sells as its differentiator ("it can say *I don't know*").
76
+ Measured: 0 deferrals in 1,003 cal rows.
77
+ 2. **Confidence becomes a constant.** Every row carries ~0.98 confidence,
78
+ right or wrong. Measured on the shipped fabric, bank77 hidden:
79
+ `mean_conf_when_correct = 0.832` **<** `mean_conf_when_wrong = 0.867`.
80
+ The engine is *more confident when it is wrong*.
81
+ 3. **The reported ECE is fiction.** `calibrate` printed ECE 0.136 on its
82
+ own fit rows; the bench measured 0.573–0.597 on the same rows. The two
83
+ numbers come from different physics compositions.
84
+
85
+ And the fit was not merely mis-scaled — it was **biased**. Without the
86
+ energy gain, 1,450 of the 2,006 question-rows settle to a **silent** field
87
+ and are dropped from the fit (`harvest_rows`: `if (si_.silent()) continue;`).
88
+ The temperature was therefore fitted on the 27.7% of rows that happened to
89
+ survive a composition the decisions never run under.
90
+
91
+ ## 4. The fix (v3.9.2)
92
+
93
+ ### 4.1 The fabric carries its composition — `physics.json`
94
+
95
+ A new sidecar next to `calibration.json`:
96
+
97
+ ```json
98
+ {"decay":0.82,"diffusion":0.45,"energy_norm":true,"hop_coupling":0.35,
99
+ "k_settle":8,"recorded":true}
100
+ ```
101
+
102
+ * `calibrate` **records** the composition it fitted under.
103
+ * `decide`, `bench`, `demo` and `stats` **apply** it on load
104
+ (`Engine::apply_composition()`).
105
+ * An explicit CLI flag still wins (`--energy-norm`, `--no-energy-norm`,
106
+ `--diffusion`, `--decay`, `--k-settle`, `--hop-coupling`).
107
+
108
+ The fit and the decision are now the same engine by construction. A fabric
109
+ with no `physics.json` is a pre-v3.9.2 fabric: nothing is applied and the
110
+ behaviour is bit-identical (replay contract preserved — pinned by
111
+ `test_physics_composition`).
112
+
113
+ This also delivers the repo's own standing recommendation
114
+ (`docs/INTRACATEGORY_ATTACK.md` §4): *"record the measured diffusion optimum
115
+ … and let `decide` honour a per-fabric value — NOT a new global default."*
116
+ Per-fabric diffusion now has a home.
117
+
118
+ ### 4.2 The fit refuses to run on a biased subset
119
+
120
+ `calibrate` counts the question-rows it was **offered** and the ones it
121
+ actually **saw**. Below `kMinCalibrationCoverage` (0.5) it **refuses**,
122
+ names the cause, and leaves the fabric untouched:
123
+
124
+ ```
125
+ syfox: calibration refused: the fit saw only 556 of 2006 question-rows
126
+ (27.7% coverage; 1450 settled to a SILENT field and were dropped).
127
+ The decide-side composition does not match the rows: the energy gain
128
+ is the usual cause …
129
+ ```
130
+
131
+ Override with `--calib-min-coverage 0` (the coverage is disclosed either
132
+ way). The coverage is now always in the `calibrate` report:
133
+ `fit_offered_rows`, `fit_dropped_silent`, `fit_coverage`.
134
+
135
+ ### 4.3 The Makefile stops lying
136
+
137
+ `b77-sem`, `router16` and `model-bank77-best` now calibrate with
138
+ `--energy-norm` — the same composition their benches run.
139
+
140
+ ### 4.4 A tool for the diffusion choice
141
+
142
+ `tools/cal_diffusion_sweep.py` sweeps diffusion **on the cal split only**,
143
+ re-calibrating the fabric at each candidate so the temperature is always
144
+ fitted under the composition it is applied to, and (with `--apply`) records
145
+ the winner into `physics.json`.
146
+
147
+ ---
148
+
149
+ ## 5. Why the base repository does not have this bug
150
+
151
+ `FuryLogic-Labs/Synthetic-Intelligence` is the research substrate SyFox was
152
+ ported from, and its readout is **arg-max over the settled field** — no
153
+ softmax, no temperature, no fitted parameter
154
+ (`src/physics.hpp`, `src/si_main.cpp`). There is no calibration layer, so
155
+ there is nothing to fit against the wrong physics.
156
+
157
+ The probability readout and the temperature are a SyFox addition (v2.1,
158
+ "multi-class ECE"), and the defect was introduced with it: the fit was
159
+ never tied to the composition that produced its energies. It is a
160
+ **SyFox-layer bug, not an inherited one** — which is also why it is worth
161
+ fixing here rather than in the base.
162
+
163
+ ---
164
+
165
+ ## 6. Reproduce
166
+
167
+ ```bash
168
+ make all
169
+ # the refusal (the shipped bug, re-created on purpose):
170
+ ./build/syfox calibrate --model model-b77-sem --examples data/bank77_cal.jsonl
171
+ # the fix:
172
+ ./build/syfox calibrate --energy-norm --model model-b77-sem --examples data/bank77_cal.jsonl
173
+ cat model-b77-sem/physics.json
174
+ ./build/syfox bench --model model-b77-sem --eval data/bank77_cal.jsonl
175
+ ```
engine/src/syfox_cli.cpp CHANGED
@@ -18,6 +18,7 @@
18
  #include <cstdlib>
19
  #include <cstring>
20
  #include <fstream>
 
21
  #include <iostream>
22
  #include <map>
23
  #include <sstream>
@@ -33,6 +34,14 @@ namespace {
33
 
34
  void usage_exit();
35
 
 
 
 
 
 
 
 
 
36
  struct Args {
37
  std::string model = "model";
38
  std::string examples;
@@ -61,6 +70,8 @@ struct Args {
61
  bool novelty = false; // learn --novelty: per-lesson dose by novelty (M2)
62
  float novelty_floor = 0.25f; // learn --novelty-floor F (A/B knob)
63
  bool energy_norm = false; // decide-side energy gain for big-corpus fabrics (M1)
 
 
64
  float defer_margin = -1; // v3.4: engine default ON at 0.05 (reason ambiguous_tie);
65
  // --defer-margin P overrides, --no-defer disables.
66
  // (v3.1-3.3 this was a CLI post-pass with reason low_margin,
@@ -71,27 +82,6 @@ struct Args {
71
  long threads = 0; // --threads N: OMP settle threads (1 = sequential; 0 = default)
72
  long throughput = 0; // bench --throughput N: batched multicore decisions/sec (M5)
73
  long epochs = 1; // learn --epochs N: consolidation passes (see lane_decay)
74
- bool quiet = false; // --quiet: suppress per-row/progress notes on stderr
75
- // M1 thinker-in-the-loop (all default OFF == pre-M1 behaviour)
76
- bool thinker = false; // --thinker: run the reasoner inside decide()
77
- bool reason_fixpoint = false; // --reason-fixpoint: chain axioms to fixpoint first
78
- bool meta_observe = false; // --meta-observe: feed proofs to the MetaLearner
79
- bool persist_meta = false; // M2 --persist-meta: write meta_rules.txt on exit
80
- bool cls_split = false; // M3 --cls-split: hippocampal/cortical lanes
81
- bool role_bind = false; // M9 --role-bind: query-role alignment re-rank
82
- bool ntda = false; // M5 --ntda: voltage gating + edge death
83
- long enc_dim = 0; // M9 --encoder-dim D: encoder embedding width (0 = off)
84
- long enc_chans = 0; // M9 --encoder-chans C: channel count (default 32)
85
- float enc_eta = 0.01f; // M9 --encoder-eta E: Oja learning rate
86
- float ntda_theta = 1.0f; // M5 --ntda-theta F
87
- bool reason_route = false; // M10 --reason-route: reasoner drives the choice
88
- std::string bisoc_a, bisoc_b; // M4 bisociate --a A --b B
89
- bool bisoc_bridge = false; // M4 --bridge: also propose an L8 bridge node
90
- float cortical_gate = 3.0f; // M3 --cortical-gate N: eligibility to consolidate
91
- float cortical_gain = 0.5f; // M3 --cortical-gain F: cortical readout weight
92
- // M8: the config-file path, set when <model>/config.json supplied a default.
93
- bool from_config = false; // a flag in config.json was applied
94
- bool config_energy_norm = false; // and whether it set the energy gain
95
  long latency_reps = 20; // bench --latency-reps N (timing repeats per probe)
96
  long replays = 2; // bench --replays N (determinism double-run count)
97
  bool state_file = false, questions_file = false;
@@ -102,6 +92,10 @@ struct Args {
102
  bool no_retrieval = false; // --no-retrieval: skip associative priming
103
  bool no_hierarchy = false; // --no-hierarchy: skip stage-1 category gating
104
  bool no_defer = false; // --no-defer: disable v3.4 near-tie defer (engine default ON)
 
 
 
 
105
  long hops = -1; // --hops N: v3.4 multi-hop readout walk depth (engine default 1 = legacy)
106
  bool ctx_gate = false; // --ctx-gate: v3.4 two-stage question-context settle
107
  float ctx_alpha = 0; // --ctx-alpha F (0 = engine default 0.5)
@@ -173,6 +167,8 @@ struct Args {
173
  int sentinels_mode = 0; // --sentinels on|off (CMD §2.5): 1/-1 explicit
174
  int order_mode = 0; // --order-consolidation on|off (CPME-II): 1/-1 explicit
175
  bool fingerprints = false; // --fingerprints (CME): graded half-dose re-teach
 
 
176
  };
177
 
178
  // v3.2.1 — BUG #1 disclosure: a kill switch on a model that lacks the
@@ -248,78 +244,6 @@ syfox::Engine& load_or_die(syfox::Engine& eng, const std::string& dir,
248
  return eng;
249
  }
250
 
251
- // -- M8: LOAD MODEL CONFIG -----------------------------------------------------------------
252
- // A model dir may ship config.json, written by `learn` from the flags it actually
253
- // used. Applying it here means `decide`/`bench` reproduce the fabric's trained
254
- // configuration WITHOUT the user retyping a wall of flags. Any EXPLICIT CLI flag
255
- // still wins, because apply_modes() runs afterwards and overwrites.
256
- //
257
- // Why this exists: bench without `--energy-norm` returns honest_silence on every
258
- // row and collapses choice_n to 0 (measured this session). A silent zero reads as
259
- // a broken model but is only a missing gain flag. A config file makes that class
260
- // of mistake impossible, which is also what makes the numbers citable.
261
- static void load_model_config(const std::string& model_dir, Args& a) {
262
- std::ifstream f(model_dir + "/config.json");
263
- if (!f) return;
264
- std::string buf((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
265
- sfx::JV c;
266
- try { c = sfx::JV::parse(buf); } catch (...) { return; }
267
- if (!c.is_obj()) return;
268
- // NOTE: JV::as_num() returns the fallback for anything that is not NUM, so
269
- // reading a JSON bool through it silently yields 0. Every flag below was
270
- // written as a bool, which made the whole loader a no-op until this was
271
- // caught — an absent [config] line was the only symptom.
272
- auto on = [&](const char* k) -> bool {
273
- if (!c.has(k)) return false;
274
- const sfx::JV& v = c.at(k);
275
- // There is no as_bool() in core/json.hpp; as_str() stringifies BOOL to
276
- // "true"/"false" (json.hpp, tolerant string reader), which is the only
277
- // supported way to read a boolean back out of a parsed config.
278
- return v.is_bool() ? (v.as_str() == "true") : (v.as_num(0) != 0);
279
- };
280
- auto num = [&](const char* k, double fallback) -> double {
281
- return c.has(k) ? c.at(k).as_num(fallback) : fallback;
282
- };
283
- auto setf = [&](bool& dst, const char* k) {
284
- if (on(k)) { dst = true; a.from_config = true; }
285
- };
286
- // decide/bench-side
287
- setf(a.energy_norm, "energy_norm");
288
- setf(a.adaptive_depth, "adaptive_depth");
289
- setf(a.momentum_gate, "momentum_readout");
290
- setf(a.coherence_gate, "coherence_gate");
291
- setf(a.wavefront_gate, "wavefront_gate");
292
- setf(a.tension_gate, "tension_gate");
293
- setf(a.ood_knn, "ood_knn");
294
- setf(a.perturb_check, "perturb_check");
295
- // learn-side physics (the sweep knobs v3.9.1 added)
296
- if (a.physics_diffusion < 0 && c.has("diffusion")) {
297
- a.physics_diffusion = static_cast<float>(num("diffusion", -1)); a.from_config = true; }
298
- if (a.physics_decay <= 0 && c.has("decay")) {
299
- a.physics_decay = static_cast<float>(num("decay", -1)); a.from_config = true; }
300
- if (a.physics_k_settle <= 0 && c.has("k_settle")) {
301
- a.physics_k_settle = static_cast<float>(num("k_settle", -1)); a.from_config = true; }
302
- if (a.physics_eta <= 0 && c.has("learn_eta")) {
303
- a.physics_eta = static_cast<float>(num("learn_eta", -1)); a.from_config = true; }
304
- if (a.physics_lane_cap <= 0 && c.has("lane_cap")) {
305
- a.physics_lane_cap = static_cast<std::size_t>(num("lane_cap", 0)); a.from_config = true; }
306
- setf(a.distvec, "distvec");
307
- setf(a.cls_split, "cls_split");
308
- setf(a.role_bind, "role_bind");
309
- setf(a.ntda, "ntda");
310
- setf(a.reason_route, "reason_route");
311
- if (a.cortical_gate == 3.0f && c.has("cortical_gate")) {
312
- a.cortical_gate = static_cast<float>(num("cortical_gate", 3.0)); a.from_config = true; }
313
- if (a.cortical_gain == 0.5f && c.has("cortical_gain")) {
314
- a.cortical_gain = static_cast<float>(num("cortical_gain", 0.5)); a.from_config = true; }
315
- if (a.ngrams_mode == 0 && c.has("ngrams")) {
316
- a.ngrams_mode = (c.at("ngrams").as_str() == "off") ? -1 : 1; a.from_config = true; }
317
- if (a.bigrams_mode == 0 && c.has("bigrams")) {
318
- a.bigrams_mode = (c.at("bigrams").as_str() == "off") ? -1 : 1; a.from_config = true; }
319
- if (a.threads <= 0 && c.has("threads")) {
320
- a.threads = static_cast<long>(num("threads", 0)); a.from_config = true; }
321
- }
322
-
323
  // Apply the CLI mode overrides after load_model(). Mode-neutral by design:
324
  // substrate.bin stays untouched, flags live only for this process.
325
  // v3.9.1 physics CONFIG sweep (opt-in): set only what the caller named.
@@ -333,36 +257,15 @@ void apply_physics(syfox::Engine& eng, const Args& a) {
333
  if (a.physics_hop >= 0) eng.substrate().set_hop_coupling(a.physics_hop);
334
  if (a.physics_eta > 0) eng.substrate().set_learn_eta(a.physics_eta);
335
  if (a.physics_lane_cap > 0) eng.substrate().set_lane_cap(static_cast<std::size_t>(a.physics_lane_cap));
336
- // M3: complementary learning systems. The cortical store is built at learn
337
- // time, so this must be set on BOTH sides; at read time it only re-enables
338
- // the gate, and cortical lanes come back from the CLS1 substrate tail.
339
- if (a.cls_split) {
340
- eng.substrate().set_cls_split(true);
341
- eng.substrate().set_cortical_gate(a.cortical_gate);
342
- eng.substrate().set_cortical_gain(a.cortical_gain);
343
- }
344
- // M9 / M10 decision gates. These were previously MISSING ENTIRELY: the flags
345
- // parsed and appeared in --help, but nothing ever called the setters, so both
346
- // features silently did nothing on every invocation. A flag that parses and
347
- // does nothing is worse than no flag -- it looks like a working feature and
348
- // reports nothing. Wire them here, next to the other decision-side gates.
349
- if (a.role_bind) eng.set_role_bind(true);
350
- if (a.ntda) { eng.set_ntda(true); eng.substrate().set_ntda_theta(a.ntda_theta); }
351
- // M9-encoder: size the projection. The EMBEDDING ITSELF is supplied by a
352
- // caller/bridge (set_encoder_input) or read from the model dir's encoder
353
- // vector file; the C++ side only owns the local update rule.
354
- if (a.enc_dim > 0) {
355
- const long C = a.enc_chans > 0 ? a.enc_chans : 32;
356
- eng.set_encoder(static_cast<std::size_t>(a.enc_dim),
357
- static_cast<std::size_t>(C));
358
- eng.set_encoder_eta(a.enc_eta);
359
- }
360
- if (a.reason_route) eng.set_reason_route(true);
361
  }
362
 
363
  void apply_modes(syfox::Engine& eng, const Args& a) {
364
- apply_physics(eng, a);
365
- eng.substrate().set_source_modes(a.salience_gating, a.miller_window);
366
  // v3.2 semantic layer knobs: the field is ON whenever the model ships it
367
  // (substrate v4 tail); the kill switches restore pre-3.2 behavior exactly.
368
  eng.substrate().set_semantics(!a.no_semantics);
@@ -432,6 +335,17 @@ void apply_modes(syfox::Engine& eng, const Args& a) {
432
  }
433
  }
434
 
 
 
 
 
 
 
 
 
 
 
 
435
  std::string read_file(const std::string& path) {
436
  std::ifstream f(path);
437
  if (!f) { std::cerr << "syfox: cannot open " << path << "\n"; std::exit(2); }
@@ -539,17 +453,6 @@ void cmd_learn(const Args& a) {
539
  if (a.order_mode != 0) eng.substrate().set_order_consolidation(a.order_mode == 1);
540
  if (!a.axioms.empty()) eng.load_axioms(a.axioms);
541
  apply_physics(eng, a); // v3.9.1 sweep knobs (LEARN-side)
542
- // v3.9.1: --threads N also drives the LEARN path. M5's deterministic
543
- // parallel settle (static schedule, per-thread scatter buffers combined in
544
- // ascending thread order) is bit-identical to the sequential path, so this
545
- // only changes wall time. cmd_learn previously never set it, so training ran
546
- // single-threaded even though the OMP machinery was already built in.
547
- if (a.threads > 0) {
548
- #if defined(_OPENMP)
549
- omp_set_num_threads(static_cast<int>(a.threads));
550
- #endif
551
- eng.substrate().set_parallel_settle(a.threads != 1);
552
- }
553
  };
554
  // v3: consolidation passes. The substrate's own forgetting law decays
555
  // every lane 0.995x per lesson, so a 25k-lesson SINGLE pass is
@@ -648,20 +551,7 @@ void cmd_learn(const Args& a) {
648
  if (a.distvec) eng.set_distvec(true);
649
  if (a.distvec_dims > 0) eng.set_distvec_dims(a.distvec_dims);
650
  apply_learn_flags(eng); // v3.9.0 learn-side papers
651
- for (std::size_t ri = 0; ri < epoch_rows.size(); ++ri) {
652
- const auto* exp = epoch_rows[ri];
653
- if (!a.quiet && (ri % 500 == 0 || ri + 1 == epoch_rows.size())) {
654
- const double frac = epoch_rows.empty()
655
- ? 1.0 : static_cast<double>(ri + 1) / static_cast<double>(epoch_rows.size());
656
- std::cerr << "[learn] row " << (ri + 1) << '/' << epoch_rows.size()
657
- << " lessons=" << lessons << " skipped=" << skipped
658
- << std::flush;
659
- if (ri) {
660
- const double pct = frac * 100.0;
661
- std::cerr << " (" << static_cast<long>(pct) << "%)";
662
- }
663
- std::cerr << '\n';
664
- }
665
  std::string state = exp->at("state").as_str();
666
  const sfx::JV& qs = exp->at("questions");
667
  const sfx::JV& labels = exp->at("labels");
@@ -681,54 +571,6 @@ void cmd_learn(const Args& a) {
681
  }
682
  }
683
  eng.save_model(a.model);
684
-
685
- // -- M8: write the configuration this fabric was TRAINED with -------------
686
- // decide/bench/calibrate read it back via load_model_config(), so a model
687
- // reproduces its own trained configuration without the user retyping flags.
688
- // MUST run after eng.save_model(): the mkdir -p lives inside save_model, so an
689
- // ofstream opened before it would silently fail on a not-yet-existing dir.
690
- // Written unconditionally (even with all defaults off) so its ABSENCE is
691
- // itself a signal: an absent config.json = a model built before M8.
692
- {
693
- std::ofstream cf(resolve_model_dir(a.model) + "/config.json");
694
- if (cf) {
695
- sfx::JVObj cfg;
696
- cfg["config_version"] = sfx::JV(1);
697
- cfg["energy_norm"] = sfx::JV(a.energy_norm);
698
- cfg["adaptive_depth"]= sfx::JV(a.adaptive_depth);
699
- cfg["momentum_readout"] = sfx::JV(a.momentum_gate);
700
- cfg["wavefront_gate"]= sfx::JV(a.wavefront_gate);
701
- cfg["coherence_gate"]= sfx::JV(a.coherence_gate);
702
- cfg["tension_gate"] = sfx::JV(a.tension_gate);
703
- cfg["ood_knn"] = sfx::JV(a.ood_knn);
704
- cfg["perturb_check"] = sfx::JV(a.perturb_check);
705
- cfg["hops"] = sfx::JV(static_cast<double>(a.hops < 0 ? 1 : a.hops));
706
- cfg["diffusion"] = sfx::JV(static_cast<double>(a.physics_diffusion));
707
- cfg["decay"] = sfx::JV(static_cast<double>(a.physics_decay));
708
- cfg["k_settle"] = sfx::JV(static_cast<double>(a.physics_k_settle));
709
- cfg["learn_eta"] = sfx::JV(static_cast<double>(a.physics_eta));
710
- cfg["lane_cap"] = sfx::JV(static_cast<double>(a.physics_lane_cap));
711
- cfg["distvec"] = sfx::JV(a.distvec);
712
- cfg["cls_split"] = sfx::JV(a.cls_split);
713
- cfg["role_bind"] = sfx::JV(a.role_bind);
714
- cfg["ntda"] = sfx::JV(a.ntda);
715
- cfg["ntda_theta"] = sfx::JV(static_cast<double>(a.ntda_theta));
716
- cfg["reason_route"] = sfx::JV(a.reason_route);
717
- cfg["cortical_gate"] = sfx::JV(static_cast<double>(a.cortical_gate));
718
- cfg["cortical_gain"] = sfx::JV(static_cast<double>(a.cortical_gain));
719
- cfg["ngrams"] = sfx::JV(std::string(
720
- a.ngrams_mode == 0 ? (si::norm::grams_enabled() ? "on" : "off")
721
- : (a.ngrams_mode == 1 ? "on" : "off")));
722
- cfg["bigrams"] = sfx::JV(std::string(
723
- a.bigrams_mode == 0 ? (si::norm::bigrams_enabled() ? "on" : "off")
724
- : (a.bigrams_mode == 1 ? "on" : "off")));
725
- cfg["epochs"] = sfx::JV(static_cast<double>(a.epochs));
726
- cfg["note"] = sfx::JV("learn-side flags as applied; decide/bench read these "
727
- "as DEFAULTS and any explicit CLI flag overrides them");
728
- cf << sfx::JV(cfg).dump();
729
- }
730
- }
731
-
732
  // v3.9.0: persist the constructive substrate (axioms.txt in the model dir
733
  // — load_model re-loads it on the next boot) and the v39 sidecar.
734
  if (eng.reason_loaded() || !a.axioms.empty()) {
@@ -780,15 +622,51 @@ void cmd_calibrate(const Args& a) {
780
  }
781
  syfox::Engine eng;
782
  load_or_die(eng, resolve_model_dir(model_dir), "calibration");
 
 
 
 
 
783
  apply_physics(eng, a); // v3.9.1: sweep knobs shape the fit energies
784
  if (a.energy_norm) eng.set_energy_norm(true);
 
785
  auto rows = load_jsonl(a.examples);
786
  auto calib_rows = eng.harvest_rows(rows);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
787
  // v2.1 (P6): report calibration honestly — MULTI-CLASS ECE on the fit
788
  // rows BEFORE (T=1 / default Platt) and AFTER (whatever fit_calibration
789
  // adopted; its 1-bit ECE guard may keep T=1). Same helper the fit uses,
790
  // same definition bench reports.
791
  eng.fit_calibration(calib_rows);
 
 
 
792
  eng.save_model(model_dir);
793
  const auto& c = eng.calibration();
794
  const auto r4 = [](double v) { return std::round(v * 10000.0) / 10000.0; };
@@ -798,6 +676,14 @@ void cmd_calibrate(const Args& a) {
798
  if (!lang_note.empty()) o["lang_note"] = sfx::JV(lang_note);
799
  o["fit_rows"] = sfx::JV(static_cast<double>(calib_rows.size()));
800
  o["fit_source"] = sfx::JV(a.examples);
 
 
 
 
 
 
 
 
801
  o["choice_temperature"] = std::round(c.choice_temperature * 10000.0) / 10000.0;
802
  o["score_temperature"] = std::round(c.score_temperature * 10000.0) / 10000.0;
803
  o["noul_a"] = std::round(c.noul_a * 10000.0) / 10000.0;
@@ -807,7 +693,8 @@ void cmd_calibrate(const Args& a) {
807
  {"score", r4(syfox::Engine::calibration_ece(calib_rows, "score", 1.0f, 6.0f, -3.0f))},
808
  {"noul", r4(syfox::Engine::calibration_ece(calib_rows, "noul", 1.0f, 6.0f, -3.0f))}});
809
  o["multiclass_ece_after"] = sfx::JV(sfx::JVObj{ // adopted parameters
810
- {"choice", r4(syfox::Engine::calibration_ece(calib_rows, "choice", c.choice_temperature, c.noul_a, c.noul_b))},
 
811
  {"score", r4(syfox::Engine::calibration_ece(calib_rows, "score", c.score_temperature, c.noul_a, c.noul_b))},
812
  {"noul", r4(syfox::Engine::calibration_ece(calib_rows, "noul", 1.0f, c.noul_a, c.noul_b))}});
813
  o["note"] = sfx::JV("fit rows supply energies only; if this is the held-out "
@@ -915,25 +802,6 @@ sfx::JV answers_to_json(const std::vector<syfox::Answer>& ans, const syfox::Usag
915
  usage["proof_path"] = sfx::JV(pp);
916
  usage["proof_hops"] = static_cast<double>(u.proof_path.size());
917
  }
918
- // M1: thinker-in-the-loop disclosures (only when the gate ran)
919
- if (u.role_bind_boosted > 0) usage["role_bind_boosted"] = sfx::JV(u.role_bind_boosted);
920
- if (u.enc_updates > 0) usage["encoder_updates"] = sfx::JV(u.enc_updates);
921
- if (u.ntda_theta > 0) usage["ntda_theta"] = sfx::JV(std::round(u.ntda_theta * 1000.0f) / 1000.0f);
922
- if (u.axioms_rejected > 0) {
923
- usage["axioms_rejected"] = sfx::JV(u.axioms_rejected);
924
- usage["axioms_note"] = sfx::JV("lines named an unknown relation and were DROPPED");
925
- }
926
- if (u.reason_routed) {
927
- usage["reason_routed"] = sfx::JV(true);
928
- usage["reason_derived_candidates"] = sfx::JV(u.reason_derived_count);
929
- }
930
- if (u.thinker_chained) {
931
- usage["thinker_chained"] = sfx::JV(true);
932
- usage["thinker_edges_added"] = static_cast<double>(u.thinker_edges_added);
933
- usage["thinker_passes"] = static_cast<double>(u.thinker_passes);
934
- usage["thinker_budget_left"] =
935
- std::round(u.thinker_budget_left * 1000.0f) / 1000.0f;
936
- }
937
  if (u.momentum_gate) {
938
  usage["momentum_gate"] = sfx::JV(true);
939
  usage["momentum_eligible_frac"] =
@@ -994,8 +862,7 @@ void cmd_decide(const Args& a) {
994
  const std::string router_dir = resolve_model_dir(a.router);
995
  syfox::Engine reng;
996
  load_or_die(reng, router_dir, "router");
997
- apply_modes(reng, a);
998
- if (a.energy_norm) reng.set_energy_norm(true); // M1 gain for the router too
999
  sfx::JV rschema(sfx::JVObj{});
1000
  {
1001
  std::ifstream rf(router_dir + "/router.json");
@@ -1045,23 +912,7 @@ void cmd_decide(const Args& a) {
1045
  }
1046
  syfox::Engine eng;
1047
  load_or_die(eng, resolve_model_dir(model_dir), "decide");
1048
- apply_modes(eng, a);
1049
- if (a.energy_norm) eng.set_energy_norm(true); // Milestone-1 gain knob
1050
- // M1: THINKER-IN-THE-LOOP. Chain the axiom graph to fixpoint BEFORE the
1051
- // readout, so derived edges exist in the graph the proof pass walks and
1052
- // the decision can be justified by composition rather than by direct
1053
- // scoring of taught anchors. Off by default -> pre-M1 bit-identical.
1054
- if (a.thinker) eng.set_thinker(true);
1055
- if (a.reason_fixpoint) eng.set_reason_to_fixpoint(true);
1056
- if (a.meta_observe) eng.set_meta_observe(true);
1057
- sxr::ReasonCore::ReasonReport think_rep{0, 0, 0.0f};
1058
- if ((a.thinker || a.reason_fixpoint) && eng.reason_loaded()) {
1059
- think_rep = eng.think_fixpoint();
1060
- if (a.thinker && !a.quiet)
1061
- std::cerr << "[thinker] chained: " << think_rep.edges_added
1062
- << " edges in " << think_rep.steps_used << " passes, budget "
1063
- << think_rep.budget_left << "\n";
1064
- }
1065
  warn_inert_switches(eng, a, model_dir);
1066
  // --memories FILE (v3.2): explicit memory store for decide — overrides any
1067
  // model-dir memories.jsonl for this process. Rows: {"label":..., "state":...}.
@@ -1157,7 +1008,7 @@ const std::vector<Demo>& demos_for(const std::string& domain) {
1157
  void cmd_demo(const Args& a) {
1158
  syfox::Engine eng;
1159
  load_or_die(eng, resolve_model_dir(a.model), "demo");
1160
- apply_modes(eng, a);
1161
  std::cout << "SyFox demo — domain: " << (a.domain.empty() ? "tickets" : a.domain)
1162
  << " | core: si-substrate (no transformer, no classifier)\n";
1163
  for (const auto& d : demos_for(a.domain)) {
@@ -1172,7 +1023,7 @@ void cmd_demo(const Args& a) {
1172
  void cmd_stats(const Args& a) {
1173
  syfox::Engine eng;
1174
  load_or_die(eng, resolve_model_dir(a.model), "stats");
1175
- apply_modes(eng, a); // stats reflects the modes this process would run under
1176
  std::cout << sfx::JV(sfx::JVObj{
1177
  {"nodes", static_cast<double>(eng.substrate().node_count())},
1178
  {"lanes", static_cast<double>(eng.substrate().lane_count())},
@@ -1185,36 +1036,65 @@ void cmd_stats(const Args& a) {
1185
  {"noul_b", eng.calibration().noul_b},
1186
  {"salience_gating", sfx::JV(eng.substrate().config().salience_gating)},
1187
  {"miller_window", sfx::JV(eng.substrate().config().miller_window)},
1188
- // M3: complementary-learning-systems disclosure. A fabric with
1189
- // cls_split off MUST report cortical_lanes 0 — that is how a reader
1190
- // tells which physics produced a published number.
1191
- {"cls_split", sfx::JV(eng.substrate().cls_split())},
1192
- // M5 NTDA disclosure: firing threshold, spikes fired, lanes deleted.
1193
- {"encoder_chans", sfx::JV(static_cast<double>(eng.substrate().enc_chans()))},
1194
- {"encoder_dim", sfx::JV(static_cast<double>(eng.substrate().enc_dim()))},
1195
- {"encoder_updates", sfx::JV(static_cast<double>(eng.enc_updates()))},
1196
- {"ntda_on", sfx::JV(eng.substrate().ntda_on())},
1197
- // M9-LEARNED: is the role tagger using the FABRIC's document frequencies
1198
- // instead of the hardcoded rulebook? This is the disclosure that matters
1199
- // for the "inference is just a runner" claim.
1200
- {"fn_words_learned", sfx::JV(static_cast<double>(si::roles::learned_fn_words().size()))},
1201
- {"fn_words_source", sfx::JV(si::roles::fn_words_loaded() ? "fabric_df" : "hardcoded_fallback")},
1202
- {"ntda_theta_base", sfx::JV(static_cast<double>(eng.substrate().config().ntda_theta))},
1203
- {"ntda_theta_effective", sfx::JV(static_cast<double>(eng.substrate().current_theta()))},
1204
- {"ntda_spikes", sfx::JV(static_cast<double>(eng.ntda_spikes()))},
1205
- {"ntda_deaths", sfx::JV(static_cast<double>(eng.ntda_deaths()))},
1206
- {"ntda_voltage_traces", sfx::JV(static_cast<double>(eng.substrate().voltage_traces()))},
1207
- {"cortical_lanes", sfx::JV(static_cast<double>(eng.substrate().cortical_lanes()))},
1208
- {"eligibility_traces", sfx::JV(static_cast<double>(eng.substrate().eligibility_traces()))},
1209
- {"cortical_gate", sfx::JV(static_cast<double>(eng.substrate().config().cortical_gate))},
1210
- {"cortical_gain", sfx::JV(static_cast<double>(eng.substrate().config().cortical_gain))},
1211
  // v3.2 semantic layer + retrieval + hierarchy
1212
  {"semantics", sfx::JV(eng.substrate().has_semantics() && !a.no_semantics)},
1213
  {"sem_edges", static_cast<double>(eng.substrate().resonance_edge_count())},
1214
  {"lane_contexts", static_cast<double>(eng.substrate().lane_context_count())},
1215
  {"retrieval", sfx::JV(eng.retrieval_on() && !a.no_retrieval)},
1216
  {"retrieval_memories", static_cast<double>(eng.memories().size())},
1217
- {"hierarchy", sfx::JV(eng.hierarchy_on() && !a.no_hierarchy)}}).dump() << "\n";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1218
  }
1219
 
1220
  // ---------------------------------------------------------------------------
@@ -1230,8 +1110,7 @@ void cmd_stats(const Args& a) {
1230
  void cmd_bench(const Args& a) {
1231
  syfox::Engine eng;
1232
  load_or_die(eng, resolve_model_dir(a.model), "bench");
1233
- apply_modes(eng, a); // --threads (M5 OMP settle), SI modes
1234
- if (a.energy_norm) eng.set_energy_norm(true); // Milestone-1 gain knob
1235
  std::string eval_path = !a.eval.empty() ? a.eval : a.examples;
1236
  std::string split_note;
1237
  if (!a.split.empty()) {
@@ -1744,6 +1623,7 @@ void usage_exit() {
1744
  " syfox decide --model DIR --state '...' --questions '{...}'\n"
1745
  " syfox demo --model DIR --domain tickets|game|guard\n"
1746
  " syfox stats --model DIR\n"
 
1747
  " syfox derive --model DIR [--gate FILE.jsonl] [--examples FILE.jsonl]\n"
1748
  " syfox dream --model DIR [--steps N] [--seed S]\n"
1749
  " syfox promote --model DIR\n"
@@ -2267,14 +2147,6 @@ void cmd_ask(const Args& a) {
2267
  else qr = eng.reason_.ask(subj, rel, obj);
2268
  eng.reason_meta_.observe_trace(qr.proof);
2269
  eng.thinker_.record(qr);
2270
- // M2: accumulate across processes. Without this the MetaLearner dies with
2271
- // the process and macro-rule promotion can never fire across runs.
2272
- if (a.persist_meta) {
2273
- const auto w = eng.save_meta(resolve_model_dir(a.model));
2274
- std::cerr << "[meta] chains=" << w[0] << " macros=" << w[1]
2275
- << " (written to " << resolve_model_dir(a.model)
2276
- << "/meta_rules.txt)\n";
2277
- }
2278
  sfx::JVArr proof;
2279
  for (int ei : qr.proof) {
2280
  const auto& e = eng.reason_.graph.edges[static_cast<std::size_t>(ei)];
@@ -2521,6 +2393,11 @@ int main(int argc, char** argv) {
2521
  else if (k == "--dedup") a.dedup = true;
2522
  else if (k == "--novelty") a.novelty = true;
2523
  else if (k == "--energy-norm") a.energy_norm = true;
 
 
 
 
 
2524
  else if (k == "--defer-margin") { if (i + 1 >= argc) usage_exit(); a.defer_margin = std::strtof(argv[++i], nullptr); if (a.defer_margin < 0) usage_exit(); }
2525
  else if (k == "--no-defer") a.no_defer = true;
2526
  else if (k == "--hops") { if (i + 1 >= argc) usage_exit(); a.hops = std::strtol(argv[++i], nullptr, 10); if (a.hops < 1 || a.hops > 8) usage_exit(); }
@@ -2554,24 +2431,6 @@ int main(int argc, char** argv) {
2554
  else if (k == "--threads") { if (i + 1 >= argc) usage_exit(); a.threads = std::strtol(argv[++i], nullptr, 10); if (a.threads < 0) usage_exit(); }
2555
  else if (k == "--throughput") { if (i + 1 >= argc) usage_exit(); a.throughput = std::strtol(argv[++i], nullptr, 10); if (a.throughput < 1) usage_exit(); }
2556
  else if (k == "--epochs") { if (i + 1 >= argc) usage_exit(); a.epochs = std::strtol(argv[++i], nullptr, 10); if (a.epochs < 1) usage_exit(); }
2557
- else if (k == "--quiet") { a.quiet = true; }
2558
- else if (k == "--thinker") { a.thinker = true; }
2559
- else if (k == "--reason-fixpoint") { a.reason_fixpoint = true; }
2560
- else if (k == "--meta-observe") { a.meta_observe = true; }
2561
- else if (k == "--persist-meta") { a.persist_meta = true; }
2562
- else if (k == "--cls-split") { a.cls_split = true; }
2563
- else if (k == "--role-bind") { a.role_bind = true; }
2564
- else if (k == "--ntda") { a.ntda = true; }
2565
- else if (k == "--encoder-dim") { if (i + 1 >= argc) usage_exit(); a.enc_dim = std::strtol(argv[++i], nullptr, 10); }
2566
- else if (k == "--encoder-chans") { if (i + 1 >= argc) usage_exit(); a.enc_chans = std::strtol(argv[++i], nullptr, 10); }
2567
- else if (k == "--encoder-eta") { if (i + 1 >= argc) usage_exit(); a.enc_eta = std::strtof(argv[++i], nullptr); }
2568
- else if (k == "--ntda-theta") { if (i + 1 >= argc) usage_exit(); a.ntda_theta = std::strtof(argv[++i], nullptr); }
2569
- else if (k == "--reason-route") { a.reason_route = true; }
2570
- else if (k == "--a") { need(a.bisoc_a); }
2571
- else if (k == "--b") { need(a.bisoc_b); }
2572
- else if (k == "--bridge") { a.bisoc_bridge = true; }
2573
- else if (k == "--cortical-gate") { if (i + 1 >= argc) usage_exit(); a.cortical_gate = std::strtof(argv[++i], nullptr); }
2574
- else if (k == "--cortical-gain") { if (i + 1 >= argc) usage_exit(); a.cortical_gain = std::strtof(argv[++i], nullptr); }
2575
  else if (k == "--novelty-floor") { if (i + 1 >= argc) usage_exit(); a.novelty_floor = std::strtof(argv[++i], nullptr); }
2576
  else if (k == "--ngrams") {
2577
  if (i + 1 >= argc) usage_exit();
@@ -2625,6 +2484,8 @@ int main(int argc, char** argv) {
2625
  else if (k == "--require-proof") a.require_proof = true;
2626
  else if (k == "--momentum-readout") a.momentum_gate = true;
2627
  else if (k == "--wavefront-gate") a.wavefront_gate = true;
 
 
2628
  else if (k == "--coherence-gate") a.coherence_gate = true;
2629
  else if (k == "--coherence-floor") { if (i + 1 >= argc) usage_exit(); a.coherence_floor = std::strtof(argv[++i], nullptr); if (a.coherence_floor < 0 || a.coherence_floor > 1) usage_exit(); }
2630
  else if (k == "--vght-gate") a.vght_gate = true;
@@ -2670,32 +2531,12 @@ int main(int argc, char** argv) {
2670
  if (def) si::norm::load_synonyms("data/synonyms.txt");
2671
  }
2672
  if (cmd == "version") { std::cout << "syfox " << syfox::VERSION << " (core: si-substrate)\n"; return 0; }
2673
-
2674
- // -- M8: model config as DEFAULTS ----------------------------------------
2675
- // Applied once, here, for every READ-side command (decide/bench/calibrate/
2676
- // stats/derive/dream/...) so each gets the fabric's trained configuration
2677
- // without retyping flags. Explicit CLI flags already parsed above, so they
2678
- // always win — the loader only fills fields still at their default.
2679
- // NOT applied to learn: a training run must be fully specified on its CLI.
2680
- if (cmd != "learn" && !a.model.empty()) {
2681
- const std::string mdir = resolve_model_dir(a.model);
2682
- const bool before_en = a.energy_norm;
2683
- load_model_config(mdir, a);
2684
- if (a.from_config && !before_en && a.energy_norm && !a.quiet)
2685
- std::cerr << "[config] applied defaults from " << mdir
2686
- << "/config.json (explicit flags still win)\n";
2687
- }
2688
-
2689
  if (cmd == "learn") { if (a.examples.empty()) usage_exit(); cmd_learn(a); return 0; }
2690
  if (cmd == "calibrate") { if (a.examples.empty()) usage_exit(); cmd_calibrate(a); return 0; }
2691
- // An EMPTY --state used to be a usage error (exit 2). The engine already
2692
- // knows how to answer it honestly -- reason "empty_state" -- so rejecting it
2693
- // at the CLI made the honest path unreachable and turned a deferral into a
2694
- // crash for any caller that probes an empty input. Now only a missing
2695
- // questions document is a usage error.
2696
- if (cmd == "decide") { if (a.questions.empty()) usage_exit(); cmd_decide(a); return 0; }
2697
  if (cmd == "demo") { cmd_demo(a); return 0; }
2698
  if (cmd == "stats") { cmd_stats(a); return 0; }
 
2699
  if (cmd == "derive") { cmd_derive(a); return 0; }
2700
  if (cmd == "dream") { cmd_dream(a); return 0; }
2701
  if (cmd == "promote") { cmd_promote(a); return 0; }
@@ -2715,30 +2556,5 @@ int main(int argc, char** argv) {
2715
  if (cmd == "discover") { if (a.model.empty()) usage_exit(); cmd_discover(a); return 0; }
2716
  if (cmd == "thinker") { if (a.model.empty()) usage_exit(); cmd_thinker(a); return 0; }
2717
  if (cmd == "audit") { if (a.model.empty()) usage_exit(); cmd_audit(a); return 0; }
2718
- if (cmd == "bisoc") {
2719
- if (a.model.empty() || a.bisoc_a.empty() || a.bisoc_b.empty()) usage_exit();
2720
- syfox::Engine beng; load_or_die(beng, resolve_model_dir(a.model), "bisoc");
2721
- const sxr::BisocResult r = sxr::bisociate(beng.reason_, a.bisoc_a, a.bisoc_b);
2722
- std::cout << sfx::JV(sfx::JVObj{
2723
- {"command", sfx::JV("bisoc")}, {"a", sfx::JV(r.a_label)}, {"b", sfx::JV(r.b_label)},
2724
- {"hop_before", static_cast<double>(r.shortest_hop_before)},
2725
- {"bridge_found", sfx::JV(r.bridge_found)},
2726
- {"intermediate", sfx::JV(r.intermediate)},
2727
- {"energy_U_hyp", std::round(r.energy * 1000.0f) / 1000.0f},
2728
- {"validated", sfx::JV(r.validated)}, {"status", sfx::JV(r.status)}}).dump() << "\n";
2729
- if (a.bisoc_bridge) {
2730
- const sxr::BridgeProposal p =
2731
- sxr::synthesise_bridge(beng.reason_, a.bisoc_a, a.bisoc_b);
2732
- sfx::JVArr rels;
2733
- for (const auto& t : p.rels)
2734
- rels.push_back(sfx::JV(t.subj + " " + t.rel + " " + t.obj));
2735
- std::cout << sfx::JV(sfx::JVObj{
2736
- {"command", sfx::JV("bridge")}, {"label", sfx::JV(p.label)},
2737
- {"rels", sfx::JV(rels)},
2738
- {"extra_prediction", sfx::JV(p.makes_extra_prediction)},
2739
- {"status", sfx::JV(p.status)}}).dump() << "\n";
2740
- }
2741
- return 0;
2742
- }
2743
  usage_exit();
2744
  }
 
18
  #include <cstdlib>
19
  #include <cstring>
20
  #include <fstream>
21
+ #include <iomanip>
22
  #include <iostream>
23
  #include <map>
24
  #include <sstream>
 
34
 
35
  void usage_exit();
36
 
37
+ // v3.9.2: the calibration fit must see at least this fraction of the
38
+ // question-rows it was offered. Below it the fit is measuring a different
39
+ // engine than the one that will decide (the shipped b77-sem calibration saw
40
+ // 27.7% because it ran without the decide-side energy gain). Override with
41
+ // --calib-min-coverage F (0 disables the refusal; the coverage is still
42
+ // disclosed in the calibrate report).
43
+ constexpr double kMinCalibrationCoverage = 0.5;
44
+
45
  struct Args {
46
  std::string model = "model";
47
  std::string examples;
 
70
  bool novelty = false; // learn --novelty: per-lesson dose by novelty (M2)
71
  float novelty_floor = 0.25f; // learn --novelty-floor F (A/B knob)
72
  bool energy_norm = false; // decide-side energy gain for big-corpus fabrics (M1)
73
+ bool no_energy_norm = false; // v3.9.2: explicitly turn the energy gain OFF
74
+ double calib_min_coverage = kMinCalibrationCoverage; // v3.9.2 fit-coverage floor
75
  float defer_margin = -1; // v3.4: engine default ON at 0.05 (reason ambiguous_tie);
76
  // --defer-margin P overrides, --no-defer disables.
77
  // (v3.1-3.3 this was a CLI post-pass with reason low_margin,
 
82
  long threads = 0; // --threads N: OMP settle threads (1 = sequential; 0 = default)
83
  long throughput = 0; // bench --throughput N: batched multicore decisions/sec (M5)
84
  long epochs = 1; // learn --epochs N: consolidation passes (see lane_decay)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  long latency_reps = 20; // bench --latency-reps N (timing repeats per probe)
86
  long replays = 2; // bench --replays N (determinism double-run count)
87
  bool state_file = false, questions_file = false;
 
92
  bool no_retrieval = false; // --no-retrieval: skip associative priming
93
  bool no_hierarchy = false; // --no-hierarchy: skip stage-1 category gating
94
  bool no_defer = false; // --no-defer: disable v3.4 near-tie defer (engine default ON)
95
+ // v3.9.3: lane repair + the lane-decay floor
96
+ double repair_dead_threshold = 1e-6; // --repair-dead-threshold F: weight below = dead
97
+ bool repair_dry_run = false; // --dry-run: report, do not write
98
+ float lane_floor = 0.0f; // --lane-floor F: lane-decay floor when learning
99
  long hops = -1; // --hops N: v3.4 multi-hop readout walk depth (engine default 1 = legacy)
100
  bool ctx_gate = false; // --ctx-gate: v3.4 two-stage question-context settle
101
  float ctx_alpha = 0; // --ctx-alpha F (0 = engine default 0.5)
 
167
  int sentinels_mode = 0; // --sentinels on|off (CMD §2.5): 1/-1 explicit
168
  int order_mode = 0; // --order-consolidation on|off (CPME-II): 1/-1 explicit
169
  bool fingerprints = false; // --fingerprints (CME): graded half-dose re-teach
170
+ float affinity_mix = -1.0f; // --affinity-mix F (v4.0 AFR): -1 = unspecified
171
+ bool affinity_pmi = false; // --affinity-pmi (v4.0): log-odds form of the contrast
172
  };
173
 
174
  // v3.2.1 — BUG #1 disclosure: a kill switch on a model that lacks the
 
244
  return eng;
245
  }
246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  // Apply the CLI mode overrides after load_model(). Mode-neutral by design:
248
  // substrate.bin stays untouched, flags live only for this process.
249
  // v3.9.1 physics CONFIG sweep (opt-in): set only what the caller named.
 
257
  if (a.physics_hop >= 0) eng.substrate().set_hop_coupling(a.physics_hop);
258
  if (a.physics_eta > 0) eng.substrate().set_learn_eta(a.physics_eta);
259
  if (a.physics_lane_cap > 0) eng.substrate().set_lane_cap(static_cast<std::size_t>(a.physics_lane_cap));
260
+ // v4.0 — the affinity field readout channel (default OFF; replay-safe).
261
+ // Set HERE, not in apply_modes: cmd_calibrate calls apply_physics only,
262
+ // and the fit must see the same channel the decision scores (parity).
263
+ if (a.affinity_mix >= 0.0f) eng.set_affinity_mix(a.affinity_mix);
264
+ if (a.affinity_pmi) eng.set_affinity_pmi(true);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  }
266
 
267
  void apply_modes(syfox::Engine& eng, const Args& a) {
268
+ apply_physics(eng, a); eng.substrate().set_source_modes(a.salience_gating, a.miller_window);
 
269
  // v3.2 semantic layer knobs: the field is ON whenever the model ships it
270
  // (substrate v4 tail); the kill switches restore pre-3.2 behavior exactly.
271
  eng.substrate().set_semantics(!a.no_semantics);
 
335
  }
336
  }
337
 
338
+ // v3.9.2: apply the fabric's RECORDED decide-side composition, then the
339
+ // per-call modes, then the explicit energy-gain flags (which win over both).
340
+ // Every decide-side command goes through this so the physics a decision
341
+ // runs under is the physics the calibration scalars were fitted against.
342
+ void apply_composition_and_modes(syfox::Engine& eng, const Args& a) {
343
+ eng.apply_composition();
344
+ apply_modes(eng, a);
345
+ if (a.energy_norm) eng.set_energy_norm(true);
346
+ if (a.no_energy_norm) eng.set_energy_norm(false);
347
+ }
348
+
349
  std::string read_file(const std::string& path) {
350
  std::ifstream f(path);
351
  if (!f) { std::cerr << "syfox: cannot open " << path << "\n"; std::exit(2); }
 
453
  if (a.order_mode != 0) eng.substrate().set_order_consolidation(a.order_mode == 1);
454
  if (!a.axioms.empty()) eng.load_axioms(a.axioms);
455
  apply_physics(eng, a); // v3.9.1 sweep knobs (LEARN-side)
 
 
 
 
 
 
 
 
 
 
 
456
  };
457
  // v3: consolidation passes. The substrate's own forgetting law decays
458
  // every lane 0.995x per lesson, so a 25k-lesson SINGLE pass is
 
551
  if (a.distvec) eng.set_distvec(true);
552
  if (a.distvec_dims > 0) eng.set_distvec_dims(a.distvec_dims);
553
  apply_learn_flags(eng); // v3.9.0 learn-side papers
554
+ for (const auto* exp : epoch_rows) {
 
 
 
 
 
 
 
 
 
 
 
 
 
555
  std::string state = exp->at("state").as_str();
556
  const sfx::JV& qs = exp->at("questions");
557
  const sfx::JV& labels = exp->at("labels");
 
571
  }
572
  }
573
  eng.save_model(a.model);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
  // v3.9.0: persist the constructive substrate (axioms.txt in the model dir
575
  // — load_model re-loads it on the next boot) and the v39 sidecar.
576
  if (eng.reason_loaded() || !a.axioms.empty()) {
 
622
  }
623
  syfox::Engine eng;
624
  load_or_die(eng, resolve_model_dir(model_dir), "calibration");
625
+ // v3.9.2: apply the fabric's RECORDED decide-side composition BEFORE the
626
+ // sweep knobs, so a re-calibration fits the same physics the decisions
627
+ // will run under. Explicit CLI flags still override it (apply_physics
628
+ // runs after this line).
629
+ eng.apply_composition();
630
  apply_physics(eng, a); // v3.9.1: sweep knobs shape the fit energies
631
  if (a.energy_norm) eng.set_energy_norm(true);
632
+ if (a.no_energy_norm) eng.set_energy_norm(false);
633
  auto rows = load_jsonl(a.examples);
634
  auto calib_rows = eng.harvest_rows(rows);
635
+ // v3.9.2 COVERAGE GUARD. A row whose settled field is silent contributes
636
+ // no candidate energies and never reaches the fit. If the fit saw less
637
+ // than kMinCalibrationCoverage of the question-rows it was offered, the
638
+ // composition is wrong (measured: the shipped b77-sem calibration saw
639
+ // 556 of 2,006 = 27.7% because it ran without the decide-side energy
640
+ // gain) and the fitted temperature would be a number for a different
641
+ // engine. Fail loudly and leave the fabric untouched.
642
+ const std::size_t offered = eng.harvest_offered();
643
+ const std::size_t dropped = eng.harvest_dropped_silent();
644
+ const double coverage = offered ? static_cast<double>(calib_rows.size())
645
+ / static_cast<double>(offered) : 1.0;
646
+ if (offered > 0 && coverage < a.calib_min_coverage) {
647
+ std::cerr << "syfox: calibration refused: the fit saw only "
648
+ << calib_rows.size() << " of " << offered << " question-rows ("
649
+ << std::fixed << std::setprecision(1) << (coverage * 100.0)
650
+ << "% coverage; " << dropped << " settled to a SILENT field and "
651
+ "were dropped).\n"
652
+ << " The decide-side composition does not match the rows: "
653
+ "the energy gain is the usual cause\n"
654
+ << " (the fit ran without --energy-norm while the "
655
+ "decisions run with it, so the settled field is empty\n"
656
+ << " and the fit is left on a biased subset). "
657
+ "Re-run with --energy-norm,\n"
658
+ << " or set --calib-min-coverage 0 to accept the fit "
659
+ "anyway (disclosed, not recommended).\n";
660
+ std::exit(2);
661
+ }
662
  // v2.1 (P6): report calibration honestly — MULTI-CLASS ECE on the fit
663
  // rows BEFORE (T=1 / default Platt) and AFTER (whatever fit_calibration
664
  // adopted; its 1-bit ECE guard may keep T=1). Same helper the fit uses,
665
  // same definition bench reports.
666
  eng.fit_calibration(calib_rows);
667
+ // v3.9.2: record the composition the fit ran under, so decide/bench/
668
+ // calibrate all agree from now on without the operator repeating flags.
669
+ eng.set_composition(eng.live_composition());
670
  eng.save_model(model_dir);
671
  const auto& c = eng.calibration();
672
  const auto r4 = [](double v) { return std::round(v * 10000.0) / 10000.0; };
 
676
  if (!lang_note.empty()) o["lang_note"] = sfx::JV(lang_note);
677
  o["fit_rows"] = sfx::JV(static_cast<double>(calib_rows.size()));
678
  o["fit_source"] = sfx::JV(a.examples);
679
+ // v3.9.2: the fit's COVERAGE and the composition it ran under. Both are
680
+ // first-class: a temperature fitted on a biased subset of the rows is a
681
+ // temperature for a different engine, and a fit that never saw half the
682
+ // rows is exactly that.
683
+ o["fit_offered_rows"] = sfx::JV(static_cast<double>(offered));
684
+ o["fit_dropped_silent"] = sfx::JV(static_cast<double>(dropped));
685
+ o["fit_coverage"] = sfx::JV(std::round(coverage * 10000.0) / 10000.0);
686
+ o["decide_composition"] = eng.composition().to_json();
687
  o["choice_temperature"] = std::round(c.choice_temperature * 10000.0) / 10000.0;
688
  o["score_temperature"] = std::round(c.score_temperature * 10000.0) / 10000.0;
689
  o["noul_a"] = std::round(c.noul_a * 10000.0) / 10000.0;
 
693
  {"score", r4(syfox::Engine::calibration_ece(calib_rows, "score", 1.0f, 6.0f, -3.0f))},
694
  {"noul", r4(syfox::Engine::calibration_ece(calib_rows, "noul", 1.0f, 6.0f, -3.0f))}});
695
  o["multiclass_ece_after"] = sfx::JV(sfx::JVObj{ // adopted parameters
696
+ {"choice", r4(syfox::Engine::calibration_ece(calib_rows, "choice", c.choice_temperature, c.noul_a, c.noul_b,
697
+ &c.choice_temperature_by_count))},
698
  {"score", r4(syfox::Engine::calibration_ece(calib_rows, "score", c.score_temperature, c.noul_a, c.noul_b))},
699
  {"noul", r4(syfox::Engine::calibration_ece(calib_rows, "noul", 1.0f, c.noul_a, c.noul_b))}});
700
  o["note"] = sfx::JV("fit rows supply energies only; if this is the held-out "
 
802
  usage["proof_path"] = sfx::JV(pp);
803
  usage["proof_hops"] = static_cast<double>(u.proof_path.size());
804
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
805
  if (u.momentum_gate) {
806
  usage["momentum_gate"] = sfx::JV(true);
807
  usage["momentum_eligible_frac"] =
 
862
  const std::string router_dir = resolve_model_dir(a.router);
863
  syfox::Engine reng;
864
  load_or_die(reng, router_dir, "router");
865
+ apply_composition_and_modes(reng, a); // v3.9.2: fabric composition first
 
866
  sfx::JV rschema(sfx::JVObj{});
867
  {
868
  std::ifstream rf(router_dir + "/router.json");
 
912
  }
913
  syfox::Engine eng;
914
  load_or_die(eng, resolve_model_dir(model_dir), "decide");
915
+ apply_composition_and_modes(eng, a); // v3.9.2: fabric composition first
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
916
  warn_inert_switches(eng, a, model_dir);
917
  // --memories FILE (v3.2): explicit memory store for decide — overrides any
918
  // model-dir memories.jsonl for this process. Rows: {"label":..., "state":...}.
 
1008
  void cmd_demo(const Args& a) {
1009
  syfox::Engine eng;
1010
  load_or_die(eng, resolve_model_dir(a.model), "demo");
1011
+ apply_composition_and_modes(eng, a); // v3.9.2: fabric composition first
1012
  std::cout << "SyFox demo — domain: " << (a.domain.empty() ? "tickets" : a.domain)
1013
  << " | core: si-substrate (no transformer, no classifier)\n";
1014
  for (const auto& d : demos_for(a.domain)) {
 
1023
  void cmd_stats(const Args& a) {
1024
  syfox::Engine eng;
1025
  load_or_die(eng, resolve_model_dir(a.model), "stats");
1026
+ apply_composition_and_modes(eng, a); // v3.9.2: fabric composition first
1027
  std::cout << sfx::JV(sfx::JVObj{
1028
  {"nodes", static_cast<double>(eng.substrate().node_count())},
1029
  {"lanes", static_cast<double>(eng.substrate().lane_count())},
 
1036
  {"noul_b", eng.calibration().noul_b},
1037
  {"salience_gating", sfx::JV(eng.substrate().config().salience_gating)},
1038
  {"miller_window", sfx::JV(eng.substrate().config().miller_window)},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1039
  // v3.2 semantic layer + retrieval + hierarchy
1040
  {"semantics", sfx::JV(eng.substrate().has_semantics() && !a.no_semantics)},
1041
  {"sem_edges", static_cast<double>(eng.substrate().resonance_edge_count())},
1042
  {"lane_contexts", static_cast<double>(eng.substrate().lane_context_count())},
1043
  {"retrieval", sfx::JV(eng.retrieval_on() && !a.no_retrieval)},
1044
  {"retrieval_memories", static_cast<double>(eng.memories().size())},
1045
+ {"hierarchy", sfx::JV(eng.hierarchy_on() && !a.no_hierarchy)},
1046
+ // v3.9.2: the decide-side composition this fabric's calibration scalars
1047
+ // were fitted against (from physics.json), and whether the live engine
1048
+ // is running under it.
1049
+ {"decide_composition", eng.composition().to_json()},
1050
+ {"live_composition", eng.live_composition().to_json()}}).dump() << "\n";
1051
+ }
1052
+
1053
+ // ---------------------------------------------------------------------------
1054
+ // v3.9.3: repair the numerically dead lanes from the persisted evidence ledger.
1055
+ //
1056
+ // The port applies CMD §2.3's decay to EVERY lane on EVERY lesson, so a lane
1057
+ // last bound at lesson k in an N-lesson fabric carries w0 * 0.995^(N-k),
1058
+ // which underflows to the float32 denormal floor (1.4e-43) after ~20,700
1059
+ // lessons and then stops decreasing. MEASURED on the shipped
1060
+ // model/giant-latin fabric (114,060 lessons, 1,905,169 lanes): 95.09% of
1061
+ // lanes sit below 1e-12, the MEDIAN lane weight is 1.4e-43, and only 2.42%
1062
+ // exceed 1e-6 — the Hebbian memory was numerically erased.
1063
+ //
1064
+ // The evidence ledger (v3 Milestone 3) holds the integral of the growth term
1065
+ // the decay destroyed, so the weight can be rebuilt in CMD §2.3's saturating
1066
+ // form. This rewrites NO equation and changes NO learn-time behaviour: a
1067
+ // fabric re-learned from scratch is byte-identical.
1068
+ void cmd_repair_lanes(const Args& a) {
1069
+ syfox::Engine eng;
1070
+ const std::string dir = resolve_model_dir(a.model);
1071
+ load_or_die(eng, dir, "repair-lanes");
1072
+ const auto st = eng.repair_lanes(static_cast<float>(a.repair_dead_threshold));
1073
+ sfx::JVObj o;
1074
+ o["command"] = sfx::JV("repair-lanes");
1075
+ o["model"] = sfx::JV(dir);
1076
+ o["lanes_total"] = sfx::JV(static_cast<double>(st.lanes_total));
1077
+ o["lanes_repaired"] = sfx::JV(static_cast<double>(st.lanes_repaired));
1078
+ o["lanes_dead_before"] = sfx::JV(static_cast<double>(st.lanes_dead));
1079
+ o["lanes_dead_revivable"] = sfx::JV(static_cast<double>(st.lanes_revivable));
1080
+ o["lanes_dead_orphan"] = sfx::JV(static_cast<double>(st.lanes_orphan));
1081
+ o["dead_threshold"] = sfx::JV(a.repair_dead_threshold);
1082
+ o["weight_sum_before"] = sfx::JV(st.weight_before);
1083
+ o["weight_sum_after"] = sfx::JV(st.weight_after);
1084
+ o["note"] = sfx::JV("lane weights rebuilt from the persisted evidence "
1085
+ "ledger in CMD §2.3's saturating form "
1086
+ "(w = w_max*tanh(net_events*bind_scale/w_max)); "
1087
+ "no equation changed; the calibration must be re-fitted "
1088
+ "under this composition (the energy scale moved)");
1089
+ std::cout << sfx::JV(o).dump() << "\n";
1090
+ if (a.repair_dry_run) {
1091
+ std::cerr << "syfox: repair-lanes: --dry-run — the fabric was NOT written\n";
1092
+ return;
1093
+ }
1094
+ eng.save_model(dir);
1095
+ std::cerr << "syfox: repair-lanes: fabric written to " << dir
1096
+ << " — re-fit the calibration under the same composition "
1097
+ "(syfox calibrate --energy-norm ...) before measuring\n";
1098
  }
1099
 
1100
  // ---------------------------------------------------------------------------
 
1110
  void cmd_bench(const Args& a) {
1111
  syfox::Engine eng;
1112
  load_or_die(eng, resolve_model_dir(a.model), "bench");
1113
+ apply_composition_and_modes(eng, a); // v3.9.2: fabric composition first
 
1114
  std::string eval_path = !a.eval.empty() ? a.eval : a.examples;
1115
  std::string split_note;
1116
  if (!a.split.empty()) {
 
1623
  " syfox decide --model DIR --state '...' --questions '{...}'\n"
1624
  " syfox demo --model DIR --domain tickets|game|guard\n"
1625
  " syfox stats --model DIR\n"
1626
+ " syfox repair-lanes --model DIR [--dead-threshold F] [--dry-run]\n"
1627
  " syfox derive --model DIR [--gate FILE.jsonl] [--examples FILE.jsonl]\n"
1628
  " syfox dream --model DIR [--steps N] [--seed S]\n"
1629
  " syfox promote --model DIR\n"
 
2147
  else qr = eng.reason_.ask(subj, rel, obj);
2148
  eng.reason_meta_.observe_trace(qr.proof);
2149
  eng.thinker_.record(qr);
 
 
 
 
 
 
 
 
2150
  sfx::JVArr proof;
2151
  for (int ei : qr.proof) {
2152
  const auto& e = eng.reason_.graph.edges[static_cast<std::size_t>(ei)];
 
2393
  else if (k == "--dedup") a.dedup = true;
2394
  else if (k == "--novelty") a.novelty = true;
2395
  else if (k == "--energy-norm") a.energy_norm = true;
2396
+ else if (k == "--no-energy-norm") a.no_energy_norm = true; // v3.9.2
2397
+ else if (k == "--repair-dead-threshold") { if (i + 1 >= argc) usage_exit(); a.repair_dead_threshold = std::strtod(argv[++i], nullptr); }
2398
+ else if (k == "--dry-run") a.repair_dry_run = true;
2399
+ else if (k == "--lane-floor") { if (i + 1 >= argc) usage_exit(); a.lane_floor = static_cast<float>(std::strtod(argv[++i], nullptr)); if (a.lane_floor < 0.0f) usage_exit(); }
2400
+ else if (k == "--calib-min-coverage") { if (i + 1 >= argc) usage_exit(); a.calib_min_coverage = std::strtod(argv[++i], nullptr); if (a.calib_min_coverage < 0.0) usage_exit(); } // v3.9.2
2401
  else if (k == "--defer-margin") { if (i + 1 >= argc) usage_exit(); a.defer_margin = std::strtof(argv[++i], nullptr); if (a.defer_margin < 0) usage_exit(); }
2402
  else if (k == "--no-defer") a.no_defer = true;
2403
  else if (k == "--hops") { if (i + 1 >= argc) usage_exit(); a.hops = std::strtol(argv[++i], nullptr, 10); if (a.hops < 1 || a.hops > 8) usage_exit(); }
 
2431
  else if (k == "--threads") { if (i + 1 >= argc) usage_exit(); a.threads = std::strtol(argv[++i], nullptr, 10); if (a.threads < 0) usage_exit(); }
2432
  else if (k == "--throughput") { if (i + 1 >= argc) usage_exit(); a.throughput = std::strtol(argv[++i], nullptr, 10); if (a.throughput < 1) usage_exit(); }
2433
  else if (k == "--epochs") { if (i + 1 >= argc) usage_exit(); a.epochs = std::strtol(argv[++i], nullptr, 10); if (a.epochs < 1) usage_exit(); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2434
  else if (k == "--novelty-floor") { if (i + 1 >= argc) usage_exit(); a.novelty_floor = std::strtof(argv[++i], nullptr); }
2435
  else if (k == "--ngrams") {
2436
  if (i + 1 >= argc) usage_exit();
 
2484
  else if (k == "--require-proof") a.require_proof = true;
2485
  else if (k == "--momentum-readout") a.momentum_gate = true;
2486
  else if (k == "--wavefront-gate") a.wavefront_gate = true;
2487
+ else if (k == "--affinity-mix") { if (i + 1 >= argc) usage_exit(); a.affinity_mix = std::strtof(argv[++i], nullptr); if (a.affinity_mix < 0 || a.affinity_mix > 1) usage_exit(); }
2488
+ else if (k == "--affinity-pmi") a.affinity_pmi = true;
2489
  else if (k == "--coherence-gate") a.coherence_gate = true;
2490
  else if (k == "--coherence-floor") { if (i + 1 >= argc) usage_exit(); a.coherence_floor = std::strtof(argv[++i], nullptr); if (a.coherence_floor < 0 || a.coherence_floor > 1) usage_exit(); }
2491
  else if (k == "--vght-gate") a.vght_gate = true;
 
2531
  if (def) si::norm::load_synonyms("data/synonyms.txt");
2532
  }
2533
  if (cmd == "version") { std::cout << "syfox " << syfox::VERSION << " (core: si-substrate)\n"; return 0; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2534
  if (cmd == "learn") { if (a.examples.empty()) usage_exit(); cmd_learn(a); return 0; }
2535
  if (cmd == "calibrate") { if (a.examples.empty()) usage_exit(); cmd_calibrate(a); return 0; }
2536
+ if (cmd == "decide") { if (a.state.empty() || a.questions.empty()) usage_exit(); cmd_decide(a); return 0; }
 
 
 
 
 
2537
  if (cmd == "demo") { cmd_demo(a); return 0; }
2538
  if (cmd == "stats") { cmd_stats(a); return 0; }
2539
+ if (cmd == "repair-lanes") { cmd_repair_lanes(a); return 0; }
2540
  if (cmd == "derive") { cmd_derive(a); return 0; }
2541
  if (cmd == "dream") { cmd_dream(a); return 0; }
2542
  if (cmd == "promote") { cmd_promote(a); return 0; }
 
2556
  if (cmd == "discover") { if (a.model.empty()) usage_exit(); cmd_discover(a); return 0; }
2557
  if (cmd == "thinker") { if (a.model.empty()) usage_exit(); cmd_thinker(a); return 0; }
2558
  if (cmd == "audit") { if (a.model.empty()) usage_exit(); cmd_audit(a); return 0; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2559
  usage_exit();
2560
  }
engine/src/syfox_core.cpp CHANGED
@@ -43,6 +43,14 @@ SyFoxHandle* syfox_engine_create(const char* model_dir) {
43
  delete h;
44
  return nullptr;
45
  }
 
 
 
 
 
 
 
 
46
  return h;
47
  }
48
 
@@ -56,6 +64,14 @@ const char* syfox_core_version(void) { return syfox::VERSION; }
56
 
57
  // -- engine-scoped knobs (identical semantics to the CLI flags) -------------
58
 
 
 
 
 
 
 
 
 
59
  void syfox_engine_set_energy_norm(SyFoxHandle* h, int on) {
60
  if (h) h->eng->set_energy_norm(on != 0); // M1: measurement gain
61
  }
 
43
  delete h;
44
  return nullptr;
45
  }
46
+ // v4.0 — apply the model's RECORDED decide-side composition (physics.json:
47
+ // energy norm, diffusion, and the AFFINITY READOUT MODE the fabric was
48
+ // calibrated under). Without this the C API / python bridge / HTTP Space
49
+ // decided under DIFFERENT physics than the CLI, and under a different
50
+ // readout than the temperature was fitted for -- the fit==decide parity
51
+ // contract, broken on the server path. The CLI applied the composition
52
+ // explicitly and is unaffected (applying it twice is idempotent).
53
+ h->eng->apply_composition();
54
  return h;
55
  }
56
 
 
64
 
65
  // -- engine-scoped knobs (identical semantics to the CLI flags) -------------
66
 
67
+ // v4.0 — the affinity field readout channel (0 = legacy, 1 = affinity only).
68
+ void syfox_engine_set_affinity_mix(SyFoxHandle* h, float mix) {
69
+ if (h) h->eng->set_affinity_mix(mix);
70
+ }
71
+ void syfox_engine_set_affinity_pmi(SyFoxHandle* h, int on) {
72
+ if (h) h->eng->set_affinity_pmi(on != 0);
73
+ }
74
+
75
  void syfox_engine_set_energy_norm(SyFoxHandle* h, int on) {
76
  if (h) h->eng->set_energy_norm(on != 0); // M1: measurement gain
77
  }
engine/src/syfox_test.cpp CHANGED
@@ -2450,6 +2450,220 @@ static void test_reason() {
2450
  }
2451
  }
2452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2453
  static void test_v39_gates() {
2454
  std::cerr << " AT-test_v39_gates\n";
2455
  std::cout << "[v39 gates: momentum / wavefront / coherence / vght / cem / "
@@ -2851,6 +3065,9 @@ int main() {
2851
  test_thinking();
2852
  test_reason();
2853
  test_v39_gates();
 
 
 
2854
  if (failures) { std::cout << failures << " FAILURES\n"; return 1; }
2855
  std::cout << "all tests passed\n";
2856
  return 0;
 
2450
  }
2451
  }
2452
 
2453
+ // ---------------------------------------------------------------------------
2454
+ // v3.9.2: the decide-side PHYSICS COMPOSITION.
2455
+ //
2456
+ // The calibration scalars (choice/score temperature, Platt) are fitted on
2457
+ // energies produced by a settle pass, and those energies depend on the whole
2458
+ // decide-side composition (energy gain, diffusion, decay, k_settle, hop
2459
+ // coupling). Fit on one composition, decide under another, and the fit is a
2460
+ // number for a different engine. This group pins the mechanism that makes
2461
+ // fit==decide structural instead of a remembered flag:
2462
+ // (1) a fabric WITHOUT physics.json is untouched (replay contract);
2463
+ // (2) a fabric WITH physics.json carries it across a save/load round trip;
2464
+ // (3) applying the composition reproduces the same decisions;
2465
+ // (4) the calibration fit discloses how many question-rows it actually saw.
2466
+ // ---------------------------------------------------------------------------
2467
+ // ---------------------------------------------------------------------------
2468
+ // v3.9.3: the DEAD-LANE REPAIR.
2469
+ //
2470
+ // The port applies CMD §2.3's decay to EVERY lane on EVERY lesson, so a lane
2471
+ // bound long ago carries w0 * 0.995^(N-k) — which underflows to the float32
2472
+ // denormal floor and is numerically dead (the readout sees it as zero).
2473
+ // MEASURED on the shipped model/giant-latin: 95.09% of its 1.9M lanes sit
2474
+ // below 1e-12 and the MEDIAN lane weight is 1.4e-43.
2475
+ //
2476
+ // The persisted EVIDENCE LEDGER holds the integral of the growth term the
2477
+ // decay destroyed, so the weight can be rebuilt in CMD §2.3's saturating
2478
+ // form. This group pins that the repair revives dead lanes, is
2479
+ // deterministic, and leaves a healthy fabric alone.
2480
+ // ---------------------------------------------------------------------------
2481
+ static void test_lane_repair() {
2482
+ std::cout << "[lane repair: the dead lanes are recoverable from the ledger]\n";
2483
+ syfox::Engine eng;
2484
+ eng.set_context("test-lane-repair");
2485
+ // teach a few lanes
2486
+ for (int i = 0; i < 6; ++i) {
2487
+ eng.learn_example("the ticket about payment and refund " + std::to_string(i),
2488
+ "route the ticket", "billing payment team");
2489
+ eng.learn_example("the screen shows an error on login " + std::to_string(i),
2490
+ "route the ticket", "technical hardware team");
2491
+ }
2492
+ const std::size_t lanes0 = eng.substrate().lane_count();
2493
+ CHECK(lanes0 > 0, "learning created lanes");
2494
+
2495
+ // kill them the way 20k+ lessons of global decay would
2496
+ eng.substrate().set_lane_decay(1e-6f);
2497
+ for (int i = 0; i < 3; ++i) {
2498
+ eng.learn_example("another ticket about payment and refund",
2499
+ "route the ticket", "billing payment team");
2500
+ }
2501
+ // a DRY RUN reports what the repair would do without touching the fabric
2502
+ const auto before = eng.repair_lanes(1e-6f, false);
2503
+ CHECK(before.lanes_dead > 0, "the global decay really did kill lanes");
2504
+ CHECK(before.lanes_revivable > 0, "the ledger can revive them");
2505
+ CHECK(before.weight_after > before.weight_before,
2506
+ "the dry run shows the weight the repair would restore");
2507
+
2508
+ // the repair brings them back from the ledger
2509
+ const auto st = eng.repair_lanes(1e-6f);
2510
+ CHECK(st.lanes_repaired > 0, "the ledger could rebuild lanes");
2511
+ // after the repair, no lane the ledger can rebuild is still dead
2512
+ const auto post = eng.repair_lanes(1e-6f, false);
2513
+ CHECK(post.lanes_revivable == 0,
2514
+ "after the repair no rebuildable lane is still dead");
2515
+ CHECK(st.weight_after > st.weight_before,
2516
+ "total lane weight increased after the repair");
2517
+
2518
+ // deterministic: the same ledger rebuilds the same weights
2519
+ const auto again = eng.repair_lanes(1e-6f);
2520
+ CHECK(std::fabs(again.weight_after - st.weight_after) < 1e-6,
2521
+ "the repair is deterministic");
2522
+ }
2523
+
2524
+
2525
+ // ---------------------------------------------------------------------------
2526
+ // v4.0 — THE AFFINITY FIELD READOUT (AFR).
2527
+ //
2528
+ // The fabric learns, for every lesson, the Hebbian affinity between the
2529
+ // state's tokens and the outcome anchor. The legacy readout never reads it:
2530
+ // it samples the field and lets a capped diffusion carry the evidence, so a
2531
+ // query whose wording does NOT reuse the description's vocabulary ties.
2532
+ // AFR reads the same lanes in closed form, against the candidate set as its
2533
+ // own null model. This group pins: the channel is OFF by default (the
2534
+ // replay contract), it is deterministic, and it separates candidates the
2535
+ // legacy readout ties.
2536
+ // ---------------------------------------------------------------------------
2537
+ static void test_affinity_readout() {
2538
+ std::cout << "[affinity field readout: the anchor affinity the legacy readout never reads]\n";
2539
+ syfox::Engine eng;
2540
+ eng.set_context("test-affinity");
2541
+ // "common" is taught with EVERY candidate (a ubiquitous token: it must
2542
+ // cancel against the null model). "zebra" is taught only with "ka".
2543
+ for (int i = 0; i < 40; ++i) {
2544
+ eng.learn_example("common zebra " + std::to_string(i), "ka", "shared");
2545
+ eng.learn_example("common yak " + std::to_string(i), "kb", "shared");
2546
+ eng.learn_example("common emu " + std::to_string(i), "kc", "shared");
2547
+ }
2548
+ const sfx::JV q = sfx::JV::parse(
2549
+ R"({"d":{"type":"choice","instructions":"","criteria":)"
2550
+ R"({"ka":"alpha","kb":"beta","kc":"gamma"}}})");
2551
+
2552
+ // (1) the channel is OFF by default — the decision is the legacy one
2553
+ syfox::Usage u0;
2554
+ const auto legacy = eng.decide("common zebra", q, u0);
2555
+ CHECK(eng.affinity_mix() == 0.0f, "the affinity channel is OFF by default");
2556
+
2557
+ // (2) with the channel ON, the EXCLUSIVE token decides even though the
2558
+ // query shares no vocabulary with any candidate's description
2559
+ eng.set_affinity_mix(1.0f);
2560
+ syfox::Usage u1;
2561
+ const auto aff = eng.decide("common zebra", q, u1);
2562
+ CHECK(aff.size() == 1 && aff[0].choice == "ka",
2563
+ "the affinity channel routes through the learned anchor affinity");
2564
+
2565
+ // (3) deterministic: the same fabric and the same question answer alike
2566
+ syfox::Usage u2;
2567
+ const auto aff2 = eng.decide("common zebra", q, u2);
2568
+ CHECK(aff2.size() == 1 && aff2[0].choice == aff[0].choice,
2569
+ "the affinity channel is deterministic");
2570
+
2571
+ // (4) the null model: a ubiquitous token on its own does NOT pick a
2572
+ // candidate — it cancels against the candidate set's prior share.
2573
+ syfox::Usage u3;
2574
+ const auto amb = eng.decide("common", q, u3);
2575
+ CHECK(amb.size() == 1 && (amb[0].choice == legacy[0].choice),
2576
+ "a token bound to every candidate changes nothing");
2577
+
2578
+ // (5) turning the channel off restores the legacy decision bit-for-bit
2579
+ eng.set_affinity_mix(0.0f);
2580
+ syfox::Usage u4;
2581
+ const auto back = eng.decide("common zebra", q, u4);
2582
+ CHECK(back.size() == legacy.size() && back[0].choice == legacy[0].choice,
2583
+ "mix 0 reproduces the legacy decision (replay contract)");
2584
+ }
2585
+
2586
+ static void test_physics_composition() { std::cout << "[physics composition: fit==decide by construction]\n";
2587
+ const std::string dir = "build/test_physics_composition";
2588
+ const std::string wipe = "rm -rf " + dir;
2589
+ (void)std::system(wipe.c_str());
2590
+ const sfx::JV q = sfx::JV::parse(
2591
+ R"({"route":{"type":"choice","instructions":"route the ticket",)"
2592
+ R"("criteria":{"technical":"hardware team","billing":"payment team"}}})");
2593
+ const char* state = "laptop screen flickers on lid open";
2594
+ const char* teach = "the laptop screen flickers when the lid opens";
2595
+
2596
+ // (1) a pre-3.9.2 fabric carries NO composition and is bit-identical.
2597
+ {
2598
+ syfox::Engine e;
2599
+ e.learn_example(teach, "route the ticket", "technical hardware team");
2600
+ CHECK(!e.composition().recorded, "fresh fabric carries no recorded composition");
2601
+ e.save_model(dir);
2602
+ CHECK(!std::ifstream(dir + "/physics.json").good(),
2603
+ "no physics.json written for a fabric that never recorded one");
2604
+ syfox::Engine e2;
2605
+ CHECK(e2.load_model(dir), "fabric loads");
2606
+ CHECK(!e2.composition().recorded, "pre-3.9.2 fabric stays composition-free on load");
2607
+ // applying an unset composition must change NOTHING
2608
+ syfox::Usage u1, u2;
2609
+ auto before = e2.decide(state, q, u1);
2610
+ e2.apply_composition();
2611
+ auto after = e2.decide(state, q, u2);
2612
+ CHECK(before.size() == after.size() && before[0].choice == after[0].choice,
2613
+ "applying an unset composition leaves the decision identical");
2614
+ }
2615
+
2616
+ // (2) a recorded composition survives the save/load round trip.
2617
+ {
2618
+ syfox::Engine e;
2619
+ e.load_model(dir);
2620
+ syfox::PhysicsComposition pc;
2621
+ pc.energy_norm = true;
2622
+ pc.diffusion = 0.10f;
2623
+ pc.decay = 0.82f;
2624
+ pc.k_settle = 8;
2625
+ pc.hop_coupling = 0.35f;
2626
+ pc.recorded = true;
2627
+ e.set_composition(pc);
2628
+ e.save_model(dir);
2629
+ CHECK(std::ifstream(dir + "/physics.json").good(),
2630
+ "physics.json written when a composition is recorded");
2631
+ syfox::Engine e2;
2632
+ e2.load_model(dir);
2633
+ CHECK(e2.composition().recorded, "recorded composition survives load");
2634
+ CHECK(e2.composition().energy_norm, "energy gain survives load");
2635
+ CHECK(std::fabs(e2.composition().diffusion - 0.10f) < 1e-6f,
2636
+ "diffusion survives load");
2637
+ // (3) applying the recorded composition reaches the live substrate
2638
+ e2.apply_composition();
2639
+ CHECK(e2.energy_norm(), "apply_composition turns the energy gain on");
2640
+ CHECK(std::fabs(e2.substrate().config().diffusion - 0.10f) < 1e-6f,
2641
+ "apply_composition reaches the substrate diffusion");
2642
+ CHECK(std::fabs(e2.substrate().config().decay - 0.82f) < 1e-6f,
2643
+ "apply_composition reaches the substrate decay");
2644
+ }
2645
+
2646
+ // (4) the calibration fit discloses its coverage (offered vs. seen).
2647
+ {
2648
+ syfox::Engine e;
2649
+ e.load_model(dir);
2650
+ std::vector<sfx::JV> rows;
2651
+ for (int i = 0; i < 5; ++i) {
2652
+ rows.push_back(sfx::JV::parse(
2653
+ R"({"state":"the laptop screen flickers when the lid opens",)"
2654
+ R"("questions":{"route":{"type":"choice","instructions":"route the ticket",)"
2655
+ R"("criteria":{"technical":"hardware team","billing":"payment team"}}},)"
2656
+ R"("labels":{"route":"technical"}})"));
2657
+ }
2658
+ auto calib = e.harvest_rows(rows);
2659
+ CHECK(e.harvest_offered() == 5, "offered question-rows counted");
2660
+ CHECK(calib.size() + e.harvest_dropped_silent() == e.harvest_offered(),
2661
+ "every offered row is either fitted or accounted as dropped");
2662
+ CHECK(e.harvest_dropped_silent() == 0,
2663
+ "a taught state is not dropped as a silent field");
2664
+ }
2665
+ }
2666
+
2667
  static void test_v39_gates() {
2668
  std::cerr << " AT-test_v39_gates\n";
2669
  std::cout << "[v39 gates: momentum / wavefront / coherence / vght / cem / "
 
3065
  test_thinking();
3066
  test_reason();
3067
  test_v39_gates();
3068
+ test_physics_composition();
3069
+ test_lane_repair();
3070
+ test_affinity_readout();
3071
  if (failures) { std::cout << failures << " FAILURES\n"; return 1; }
3072
  std::cout << "all tests passed\n";
3073
  return 0;
engine/tools/ablation_suite.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Ablation suite (v3.2.1 BUG #1 verification): do the kill switches matter?
3
+
4
+ Runs the five paper configs on one eval set through the ctypes bridge:
5
+
6
+ default | --no-semantics | --no-retrieval | --no-semantics --no-retrieval
7
+ | --no-hierarchy
8
+
9
+ and reports per config: accuracy, mean/median confidence, deferrals, plus an
10
+ answer-signature distinctness count over the full candidate vector (the paper
11
+ criterion is >=4 distinct outputs; hierarchy counts only when the model arms
12
+ it with floor < 1.0 — b77-sem ships floor 1.0 = measured-off, disclosed).
13
+
14
+ Inertness is disclosed loudly: a pre-v3.2 fabric (no SEM4 tail) or a missing
15
+ memories.jsonl/hierarchy.json makes switches no-ops by the replay contract;
16
+ the tool says so, names the rebuild path, and exits non-zero so a silent
17
+ null-ablation can never reach the paper.
18
+
19
+ Usage:
20
+ python3 tools/ablation_suite.py --model model-b77-sem \
21
+ --eval data/bank77_cal.jsonl [--qkey intent] [--limit 100]
22
+ [--energy-norm] [--dump out.json]
23
+ """
24
+ import argparse
25
+ import json
26
+ import statistics
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ ROOT = Path(__file__).resolve().parent.parent
31
+ sys.path.insert(0, str(ROOT / "server"))
32
+ from syfox_bridge import SyFoxEngine # noqa: E402
33
+
34
+ CONFIGS = [
35
+ ("default", {}),
36
+ ("no-semantics", {"semantics": False}),
37
+ ("no-retrieval", {"retrieval": False}),
38
+ ("both off", {"semantics": False, "retrieval": False}),
39
+ ("no-hierarchy", {"hierarchy": False}),
40
+ ]
41
+
42
+
43
+ def model_features(model_dir: Path) -> dict:
44
+ import struct
45
+ feats = {"sem_tail": False, "memories": False, "hierarchy": False,
46
+ "hier_armed": False}
47
+ sub = model_dir / "substrate.bin"
48
+ if sub.exists():
49
+ b = sub.read_bytes()
50
+ feats["sem_tail"] = b.find(bytes([0x34, 0x4D, 0x45, 0x53])) >= 0
51
+ feats["memories"] = (model_dir / "memories.jsonl").exists()
52
+ h = model_dir / "hierarchy.json"
53
+ if h.exists():
54
+ try:
55
+ j = json.loads(h.read_text())
56
+ feats["hierarchy"] = True
57
+ feats["hier_armed"] = float(j.get("floor", 1.0)) < 1.0
58
+ except (ValueError, OSError):
59
+ pass
60
+ return feats
61
+
62
+
63
+ def main() -> None:
64
+ ap = argparse.ArgumentParser()
65
+ ap.add_argument("--model", required=True)
66
+ ap.add_argument("--eval", required=True)
67
+ ap.add_argument("--qkey", default="intent")
68
+ ap.add_argument("--limit", type=int, default=100)
69
+ ap.add_argument("--energy-norm", action="store_true")
70
+ ap.add_argument("--dump", default="")
71
+ a = ap.parse_args()
72
+
73
+ mdir = Path(a.model)
74
+ feats = model_features(mdir)
75
+ print(f"model={a.model} eval={a.eval} rows<={a.limit} "
76
+ f"energy_norm={bool(a.energy_norm)}")
77
+ print(f"features: sem_tail={feats['sem_tail']} "
78
+ f"memories={feats['memories']} hierarchy={feats['hierarchy']} "
79
+ f"(armed={feats['hier_armed']})")
80
+
81
+ blockers = []
82
+ if not feats["sem_tail"]:
83
+ blockers.append(
84
+ "--no-semantics is inert: no v3.2 SEM4 tail in substrate.bin — "
85
+ "rebuild first: ./build/rebuild_sem SRC DST (or retrain under v3.2)")
86
+ if not feats["memories"]:
87
+ blockers.append("--no-retrieval is inert: no memories.jsonl in the "
88
+ "model dir (retrieval has nothing to prime)")
89
+ if not feats["hier_armed"]:
90
+ blockers.append("--no-hierarchy cannot move the readout: hierarchy.json "
91
+ "absent or floor=1.0 (gate shipped off by measurement)")
92
+ for b in blockers:
93
+ print(f" NOTE: {b}")
94
+
95
+ rows = [json.loads(l) for l in open(a.eval) if l.strip()][: a.limit]
96
+ eng = SyFoxEngine(a.model)
97
+ base = {"semantics": True, "retrieval": True, "hierarchy": True}
98
+ if a.energy_norm:
99
+ base["energy_norm"] = True
100
+
101
+ results, sigs = {}, set()
102
+ for name, off in CONFIGS:
103
+ opts = dict(base)
104
+ opts.update(off)
105
+ acc_c = conf_c = n_ans = 0
106
+ confs, sig = [], ""
107
+ for r in rows:
108
+ q = r.get("questions") or {a.qkey: r.get("question")}
109
+ ans_a, _u, _e = eng.decide(r["state"], q, dict(opts))
110
+ ans = ans_a.get(a.qkey, {})
111
+ sig += f"{ans.get('choice','')}|{ans.get('confidence',0):.6f};"
112
+ gold = ""
113
+ if "labels" in r and r["labels"]:
114
+ gold = r["labels"].get(a.qkey) or next(iter(r["labels"].values()))
115
+ if isinstance(gold, dict):
116
+ gold = gold.get("choice", "")
117
+ if not ans.get("deferred"):
118
+ n_ans += 1
119
+ confs.append(ans.get("confidence", 0.0))
120
+ if gold and ans.get("choice") == gold:
121
+ acc_c += 1
122
+ conf_c += 1 if gold and not ans.get("deferred") \
123
+ and ans.get("choice") == gold else 0
124
+ results[name] = {
125
+ "acc_with_defer": round(acc_c / len(rows), 4) if rows else None,
126
+ "acc_answered": round(acc_c / n_ans, 4) if n_ans else None,
127
+ "answered": n_ans,
128
+ "mean_conf": round(statistics.mean(confs), 4) if confs else 0.0,
129
+ "median_conf": round(statistics.median(confs), 4) if confs else 0.0,
130
+ }
131
+ sigs.add(sig)
132
+ print(f" {name:<14} acc={results[name]['acc_with_defer']} "
133
+ f"meanC={results[name]['mean_conf']} "
134
+ f"medC={results[name]['median_conf']}")
135
+
136
+ armed = len([c for c in CONFIGS if c[0] != "no-hierarchy"])
137
+ target = 5 if feats["hier_armed"] else armed
138
+ print(f"\ndistinct output signatures: {len(sigs)} / {len(CONFIGS)} configs "
139
+ f"(criterion >= {target}"
140
+ f"{'' if feats['hier_armed'] else ' — hierarchy ships off, 4 configs count'})")
141
+ if len(sigs) < target:
142
+ print("ABLATION BLOCKED: configs are byte-identical — the switches "
143
+ "moved nothing on this model+input combination.")
144
+ if not feats["sem_tail"]:
145
+ print("Root cause: pre-v3.2 fabric (replay contract makes every "
146
+ "switch a no-op). Rebuild with ./build/rebuild_sem SRC DST.")
147
+ sys.exit(2)
148
+ print("ablation OK: the kill switches separate on this model.")
149
+ if a.dump:
150
+ with open(a.dump, "w") as f:
151
+ json.dump({"model": a.model, "eval": a.eval, "rows": len(rows),
152
+ "features": feats, "configs": results,
153
+ "distinct": len(sigs)}, f, indent=1)
154
+ print(f"wrote {a.dump}")
155
+
156
+
157
+ if __name__ == "__main__":
158
+ main()
engine/tools/assert_fit_decide_parity.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """CI gate: every fitted fabric must carry the composition it was fitted under.
3
+
4
+ A fabric with a fitted `calibration.json` but NO `physics.json` has a
5
+ calibration of UNKNOWN provenance — it may have been fitted under a
6
+ decide-side composition different from the one its decisions run under.
7
+ That is precisely the state that shipped the wrong-answer bug (see
8
+ docs/FIT_DECIDE_PARITY.md): the temperature was fitted without the
9
+ decide-side energy gain, on 27.7% of the rows, and every answer came back
10
+ with ~0.98 confidence whether it was right or wrong.
11
+
12
+ Exit codes:
13
+ 0 every fitted fabric carries its composition
14
+ 2 at least one fitted fabric has an unknown provenance (FAIL)
15
+ 0 no fitted fabric found (nothing to check — not a failure)
16
+
17
+ Usage:
18
+ python3 tools/assert_fit_decide_parity.py model-b77-sem model-router16 ...
19
+ python3 tools/assert_fit_decide_parity.py --scan model-*
20
+ """
21
+ import glob
22
+ import json
23
+ import os
24
+ import sys
25
+
26
+
27
+ def check(model_dir):
28
+ """-> (ok, message, detail)"""
29
+ cpath = os.path.join(model_dir, "calibration.json")
30
+ if not os.path.isfile(cpath):
31
+ return True, f"{model_dir}: no calibration.json (not a calibrated fabric)", {}
32
+ try:
33
+ calib = json.load(open(cpath))
34
+ except Exception as e: # malformed = unknown provenance
35
+ return False, f"{model_dir}: calibration.json unreadable ({e}) — re-calibrate", {}
36
+ if not calib.get("fitted"):
37
+ return True, f"{model_dir}: calibration not fitted (nothing to check)", calib
38
+
39
+ ppath = os.path.join(model_dir, "physics.json")
40
+ if not os.path.isfile(ppath):
41
+ return (False,
42
+ f"{model_dir}: FITTED calibration with NO physics.json — the "
43
+ f"provenance is unknown (fitted T={calib.get('choice_temperature')} "
44
+ f"over {calib.get('rows')} rows). Re-calibrate under the same "
45
+ f"decide-side composition the bench runs "
46
+ f"(e.g. --energy-norm), or the fitted scalars belong to a "
47
+ f"different engine.",
48
+ calib)
49
+ try:
50
+ phys = json.load(open(ppath))
51
+ except Exception as e:
52
+ return False, f"{model_dir}: physics.json unreadable ({e})", calib
53
+ if not phys.get("recorded"):
54
+ return False, f"{model_dir}: physics.json present but not recorded", calib
55
+ return (True,
56
+ f"{model_dir}: OK — fitted T={calib.get('choice_temperature')} over "
57
+ f"{calib.get('rows')} rows, composition "
58
+ f"energy_norm={phys.get('energy_norm')} diffusion={phys.get('diffusion')}",
59
+ {"calib": calib, "phys": phys})
60
+
61
+
62
+ def main():
63
+ args = [a for a in sys.argv[1:] if not a.startswith("--")]
64
+ dirs = []
65
+ for a in args:
66
+ dirs.extend(sorted(glob.glob(a)) if any(ch in a for ch in "*?[") else [a])
67
+ if not dirs:
68
+ print("assert_fit_decide_parity: no model dirs given — nothing to check")
69
+ return 0
70
+
71
+ failures = 0
72
+ checked = 0
73
+ for d in dirs:
74
+ if not os.path.isdir(d):
75
+ print(f"assert_fit_decide_parity: skip (not a dir): {d}")
76
+ continue
77
+ checked += 1
78
+ ok, msg, _ = check(d)
79
+ print((" ok " if ok else " FAIL ") + msg)
80
+ if not ok:
81
+ failures += 1
82
+
83
+ print(f"\nassert_fit_decide_parity: {checked - failures}/{checked} fabrics "
84
+ f"carry a known calibration provenance")
85
+ return 2 if failures else 0
86
+
87
+
88
+ if __name__ == "__main__":
89
+ sys.exit(main())
engine/tools/assert_route.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """CI assertion: `decide --router` must produce a usable route field.
3
+ Reads one decide JSON on stdin; exits non-zero unless the route carries an
4
+ anchor, a confidence, and a mapped model (BUG #3 regression gate)."""
5
+ import json
6
+ import sys
7
+
8
+ d = json.load(sys.stdin)
9
+ r = d.get("route", {})
10
+ ok = (r.get("anchor") in {"rt%02d" % i for i in range(16)}
11
+ and isinstance(r.get("confidence"), (int, float))
12
+ and bool(r.get("model")))
13
+ if not ok:
14
+ print(f"route assertion FAILED: {json.dumps(r)}", file=sys.stderr)
15
+ sys.exit(2)
16
+ print(f"route OK: {r['anchor']} conf={r['confidence']} -> {r['model']}")
engine/tools/b77_ablation_compare.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """b77_ablation_compare.py — per-intent A/B of two bench per-row dumps
3
+ (v3.9.1, e.g. semantics ON vs --no-semantics) sharing the same eval file.
4
+
5
+ Joins on the dump "row" field (the eval row index), reports per-intent
6
+ accuracy and honest flips (A wrong -> B correct and vice versa), plus the
7
+ confusion-pair migration between the two runs.
8
+ """
9
+ import argparse
10
+ import json
11
+ from collections import Counter
12
+ from pathlib import Path
13
+
14
+ ROOT = Path(__file__).resolve().parent.parent
15
+
16
+
17
+ def main() -> None:
18
+ ap = argparse.ArgumentParser()
19
+ ap.add_argument("--dump-a", required=True, help="config A dump")
20
+ ap.add_argument("--dump-b", required=True, help="config B dump")
21
+ ap.add_argument("--name-a", default="A")
22
+ ap.add_argument("--name-b", default="B")
23
+ args = ap.parse_args()
24
+
25
+ A = {json.loads(l)["row"]: json.loads(l) for l in open(args.dump_a) if l.strip()}
26
+ B = {json.loads(l)["row"]: json.loads(l) for l in open(args.dump_b) if l.strip()}
27
+ common = sorted(set(A) & set(B))
28
+ if not common:
29
+ print("no common rows — same eval file?", file=sys.stderr)
30
+ raise SystemExit(2)
31
+
32
+ acc_a = sum(A[i]["pred"] == A[i]["gold"] for i in common) / len(common)
33
+ acc_b = sum(B[i]["pred"] == B[i]["gold"] for i in common) / len(common)
34
+ print(f"rows {len(common)} {args.name_a} acc {acc_a:.4f} "
35
+ f"{args.name_b} acc {acc_b:.4f} delta {acc_b - acc_a:+.4f}")
36
+
37
+ a_ok = {i: A[i]["pred"] == A[i]["gold"] for i in common}
38
+ b_ok = {i: B[i]["pred"] == B[i]["gold"] for i in common}
39
+ fixed = [i for i in common if not a_ok[i] and b_ok[i]]
40
+ broken = [i for i in common if a_ok[i] and not b_ok[i]]
41
+ print(f"flips: {args.name_a} wrong -> {args.name_b} correct: {len(fixed)} "
42
+ f"{args.name_a} correct -> {args.name_b} wrong: {len(broken)}")
43
+
44
+ cats = json.loads((ROOT / "data" / "bank77_categories.json").read_text())
45
+ natural = {v: k for k, v in cats["label_of"].items()}
46
+ by_gold = {}
47
+ for i in common:
48
+ by_gold.setdefault(A[i]["gold"], []).append(i)
49
+ print(f"\n{'gold intent':46s} {'n':>4s} {'A acc':>6s} {'B acc':>6s} {'delta':>7s}")
50
+ rows = []
51
+ for g, idxs in sorted(by_gold.items()):
52
+ aa = sum(a_ok[i] for i in idxs) / len(idxs)
53
+ bb = sum(b_ok[i] for i in idxs) / len(idxs)
54
+ rows.append((bb - aa, g, len(idxs), aa, bb))
55
+ rows.sort()
56
+ for d, g, n, aa, bb in rows:
57
+ print(f"{g+'='+natural.get(g,'?'):46s} {n:4d} {aa:6.3f} {bb:6.3f} {d:+7.3f}")
58
+
59
+ mig = Counter((A[i]["pred"], B[i]["pred"]) for i in common
60
+ if A[i]["pred"] != B[i]["pred"])
61
+ print("\nprediction migrations (A pred -> B pred, n):")
62
+ for (pa, pb), n in mig.most_common(10):
63
+ print(f" {pa}={natural.get(pa,'?'):44s} -> {pb}={natural.get(pb,'?'):44s} {n}")
64
+
65
+
66
+ if __name__ == "__main__":
67
+ main()
engine/tools/b77_apply_policy.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """b77_apply_policy.py — score a derived defer-threshold policy on a FRESH
3
+ dump (the hidden split), never the split the policy was derived on (v3.9.1).
4
+
5
+ Usage:
6
+ syfox bench --model model-b77-sem --eval data/bank77_hidden.jsonl ... \
7
+ --dump-perrow /tmp/hidden_dump.jsonl # scoring pass (read-only)
8
+ python3 tools/b77_margin_sweep.py --dump cal_dump --mode per-intent \
9
+ --out cal_thresholds.json # derivation (CAL only)
10
+ python3 tools/b77_apply_policy.py --dump hidden_dump \
11
+ --policy cal_thresholds.json # THIS TOOL
12
+
13
+ The policy maps the PREDICTED intent (never gold) to a raw-margin threshold:
14
+ answer iff raw_margin >= thr(pred); rows below defer. Reports the overall
15
+ honest total and the per-intent table with natural names.
16
+ """
17
+ import argparse
18
+ import json
19
+ from pathlib import Path
20
+
21
+ ROOT = Path(__file__).resolve().parent.parent
22
+
23
+
24
+ def main() -> None:
25
+ ap = argparse.ArgumentParser()
26
+ ap.add_argument("--dump", required=True)
27
+ ap.add_argument("--policy", required=True)
28
+ ap.add_argument("--tag", default="", help="label for the report line")
29
+ args = ap.parse_args()
30
+
31
+ pol = json.loads(Path(args.policy).read_text())
32
+ thr_map = pol["thresholds"] if "thresholds" in pol else pol
33
+ thr_of = lambda pred: float(thr_map.get(pred, {}).get("threshold", 0.0))
34
+
35
+ rows = [json.loads(l) for l in open(args.dump) if l.strip()]
36
+ answered = [r for r in rows if r["raw_margin"] >= thr_of(r["pred"])]
37
+ correct = sum(1 for r in answered if r["pred"] == r["gold"])
38
+ n = len(rows)
39
+ overall = {
40
+ "n": n, "answered": len(answered), "correct": correct,
41
+ "acc_answered": round(correct / len(answered), 4) if answered else 0.0,
42
+ "honest_total": round(correct / n, 4) if n else 0.0,
43
+ "defer_rate": round(1 - len(answered) / n, 4) if n else 0.0,
44
+ }
45
+
46
+ cats = json.loads((ROOT / "data" / "bank77_categories.json").read_text())
47
+ natural = {v: k for k, v in cats["label_of"].items()}
48
+ by_gold = {}
49
+ for r in rows:
50
+ by_gold.setdefault(r["gold"], []).append(r)
51
+ print(f"policy {args.tag or args.policy} on {args.dump}")
52
+ print(f"overall: answered {overall['answered']}/{n} correct {overall['correct']} "
53
+ f"acc_answered {overall['acc_answered']} honest_total {overall['honest_total']} "
54
+ f"defer {overall['defer_rate']}")
55
+ print(f"{'gold intent':46s} {'n':>4s} {'ans':>4s} {'correct':>7s} {'honest':>6s} {'acc_ans':>7s}")
56
+ out_rows = []
57
+ for g, rs in sorted(by_gold.items()):
58
+ ans = [r for r in rs if r["raw_margin"] >= thr_of(r["pred"])]
59
+ c = sum(1 for r in ans if r["pred"] == g)
60
+ ht = c / len(rs)
61
+ aa = c / len(ans) if ans else 0.0
62
+ out_rows.append((ht, g, len(rs), len(ans), c, aa))
63
+ out_rows.sort(key=lambda t: (t[0], t[1]))
64
+ for ht, g, ntot, nans, c, aa in out_rows:
65
+ print(f"{g+'='+natural.get(g,'?'):46s} {ntot:4d} {nans:4d} {c:7d} {ht:6.3f} {aa:7.3f}")
66
+ print("json:", json.dumps({"tag": args.tag, "overall": overall}))
67
+
68
+
69
+ if __name__ == "__main__":
70
+ main()
engine/tools/b77_confusion_report.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """b77_confusion_report.py — render a bench --confusion JSON into the
3
+ intra-category diagnostics views (v3.9.1).
4
+
5
+ Inputs
6
+ --bench bench JSON (from `syfox bench ... --confusion`)
7
+ --dump optional per-row dump (bench --dump-perrow) for reason anatomy
8
+ Views
9
+ 1. full 77x77 matrix: per-class row table (n, answered, acc, honest,
10
+ worst confusion target) with natural intent names.
11
+ 2. card_management 22x22 + OTHER row/col: the intra-category binding
12
+ constraint view (category membership = the shipped bank77_hier.py
13
+ card_management rule, applied over data/bank77_categories.json).
14
+ 3. top confusion pairs over the whole matrix.
15
+
16
+ Every number comes from the bench JSON / dump produced by an actual run;
17
+ nothing is simulated here.
18
+ """
19
+ import argparse
20
+ import json
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ ROOT = Path(__file__).resolve().parent.parent
25
+
26
+ # card_management membership — the SAME priority-ordered rules bank77_hier.py
27
+ # ships (top_up > withdrawal > transfer > card_payment > exchange_rate >
28
+ # card_management > ...). Duplicating the rule here keeps the diagnostic
29
+ # view consistent with the fabric's own category lessons.
30
+ RULES = [
31
+ ("top_up", lambda n: "top_up" in n or "topping_up" in n),
32
+ ("withdrawal", lambda n: "withdrawal" in n or "cash_received" in n
33
+ or n == "atm_support"),
34
+ ("transfer", lambda n: "transfer" in n
35
+ or n in ("beneficiary_not_allowed", "receiving_money")),
36
+ ("card_payment", lambda n: "card_payment" in n
37
+ or n in ("transaction_charged_twice", "extra_charge_on_statement",
38
+ "exchange_charge", "reverted_card_payment?",
39
+ "declined_card_payment", "pending_card_payment")),
40
+ ("exchange_rate", lambda n: "exchange" in n
41
+ or n in ("fiat_currency_support", "supported_cards_and_currencies",
42
+ "visa_or_mastercard")),
43
+ ("card_management", lambda n: "card" in n
44
+ or n in ("contactless_not_working", "passcode_forgotten", "pin_blocked",
45
+ "change_pin", "apple_pay_or_google_pay", "lost_or_stolen_card",
46
+ "activate_my_card")),
47
+ ("refund", lambda n: "refund" in n),
48
+ ("verify_identity", lambda n: "identity" in n or "verify" in n
49
+ or n in ("age_limit", "country_support", "edit_personal_details",
50
+ "terminate_account", "lost_or_stolen_phone")),
51
+ ]
52
+
53
+
54
+ def category_of(natural: str) -> str:
55
+ for cat, fn in RULES:
56
+ if fn(natural):
57
+ return cat
58
+ return "other"
59
+
60
+
61
+ def main() -> None:
62
+ ap = argparse.ArgumentParser()
63
+ ap.add_argument("--bench", required=True)
64
+ ap.add_argument("--dump", default="")
65
+ ap.add_argument("--card-only", action="store_true",
66
+ help="print only the card_management view")
67
+ args = ap.parse_args()
68
+
69
+ d = json.loads(Path(args.bench).read_text())
70
+ conf = d.get("confusion")
71
+ if not conf:
72
+ print("bench JSON has no confusion block (run bench with --confusion)",
73
+ file=sys.stderr)
74
+ sys.exit(2)
75
+ labels = conf["labels"]
76
+ mat = conf["matrix"]
77
+ cats = json.loads((ROOT / "data" / "bank77_categories.json").read_text())
78
+ natural = {v: k for k, v in cats["label_of"].items()} # cNN -> name
79
+
80
+ # ---- per-class full table ----------------------------------------------
81
+ routing = d["routing"]
82
+ acc_all = routing["choice_accuracy"]
83
+ if not args.card_only:
84
+ print(f"model {d['model']} eval {d['eval_source']} rows {d['rows']} "
85
+ f"acc(answered) {acc_all} defer {routing['choice_defer_rate']} "
86
+ f"honest_total {round(acc_all * (1 - routing['choice_defer_rate']), 4)}")
87
+ print(f"{'gold':42s} {'n':>4s} {'ans':>4s} {'acc':>6s} {'honest':>6s} worst confusion")
88
+ rows_out = []
89
+ for i, g in enumerate(labels):
90
+ if g == "DEFER":
91
+ continue
92
+ row = mat[i]
93
+ n_tot = sum(row)
94
+ n_ans = n_tot - row[labels.index("DEFER")] if "DEFER" in labels else n_tot
95
+ correct = row[i]
96
+ acc_ans = correct / n_ans if n_ans else 0.0
97
+ honest = correct / n_tot if n_tot else 0.0
98
+ worst_n, worst_j = 0, -1
99
+ for j, v in enumerate(row):
100
+ if j != i and j < len(labels) and labels[j] != "DEFER" and v > worst_n:
101
+ worst_n, worst_j = v, j
102
+ worst = f"{labels[worst_j]}={natural.get(labels[worst_j],'?')}({worst_n})" if worst_j >= 0 else "-"
103
+ rows_out.append((honest, g, n_tot, n_ans, acc_ans, worst))
104
+ rows_out.sort(key=lambda t: (t[0], t[1]))
105
+ for honest, g, n_tot, n_ans, acc_ans, worst in rows_out:
106
+ print(f"{g+'='+natural.get(g,'?'):42s} {n_tot:4d} {n_ans:4d} "
107
+ f"{acc_ans:6.3f} {honest:6.3f} {worst}")
108
+
109
+ # ---- card_management 22x22 + OTHER -------------------------------------
110
+ card = [c for c in cats["classes"] if category_of(c) == "card_management"]
111
+ card_ids = sorted(cats["label_of"][c] for c in card)
112
+ view = card_ids + ["OTHER"]
113
+ idx = {l: i for i, l in enumerate(labels)}
114
+ print(f"\ncard_management view ({len(card_ids)} intents + OTHER) "
115
+ f"rows=gold cols=pred:")
116
+ hdr = "gold\\pred".ljust(38) + "".join(c.replace("c", "").rjust(5) for c in card_ids) + "OTH".rjust(6)
117
+ print(hdr)
118
+ agg = {}
119
+ for g in card_ids + ["OTHER"]:
120
+ golds = card_ids if g == "OTHER" else [g]
121
+ rowsum = [0] * (len(card_ids) + 1)
122
+ n_tot = 0
123
+ for gg in golds:
124
+ if gg not in idx:
125
+ continue
126
+ i = idx[gg]
127
+ for j, l in enumerate(labels):
128
+ v = mat[i][j]
129
+ if l == "DEFER":
130
+ continue
131
+ col = card_ids.index(l) if l in card_ids else len(card_ids)
132
+ rowsum[col] += v
133
+ if l in card_ids or gg in card_ids:
134
+ pass
135
+ if gg in card_ids:
136
+ n_tot += sum(x for j, x in enumerate(mat[i])
137
+ if labels[j] != "DEFER")
138
+ agg[g] = (rowsum, n_tot)
139
+ name = (natural.get(g, "ALL_OTHER") if g != "OTHER" else "ALL_OTHER")
140
+ print((g + "=" + name).ljust(38)[:38]
141
+ + "".join(str(v).rjust(5) for v in rowsum[:len(card_ids)])
142
+ + str(rowsum[-1]).rjust(6))
143
+ print("\ncard_management per-intent honest totals:")
144
+ print(f"{'intent':44s} {'n':>4s} {'correct':>7s} {'honest':>6s} {'acc_ans':>7s}")
145
+ tot_c = tot_n = 0
146
+ for g in card_ids:
147
+ rowsum, n_tot = agg[g]
148
+ correct = rowsum[card_ids.index(g)]
149
+ acc_ans = correct / n_tot if n_tot else 0.0
150
+ tot_c += correct
151
+ tot_n += n_tot
152
+ print(f"{g+'='+natural.get(g,'?'):44s} {n_tot:4d} {correct:7d} "
153
+ f"{(correct / n_tot if n_tot else 0):6.3f} {acc_ans:7.3f}")
154
+ print(f"{'card_management TOTAL':44s} {tot_n:4d} {tot_c:7d} "
155
+ f"{(tot_c / tot_n if tot_n else 0):6.3f}")
156
+
157
+ # ---- top pairs ----------------------------------------------------------
158
+ if not args.card_only:
159
+ print("\ntop confusion pairs (gold -> pred, n):")
160
+ for p in conf.get("pairs_top", [])[:15]:
161
+ print(f" {p['gold']}={natural.get(p['gold'],'?'):44s} -> "
162
+ f"{p['pred']}={natural.get(p['pred'],'?'):44s} {p['n']}")
163
+
164
+ # ---- defer reason anatomy from the dump ---------------------------------
165
+ if args.dump:
166
+ from collections import Counter
167
+ rows = [json.loads(l) for l in open(args.dump)]
168
+ reasons = Counter(r["reason"] for r in rows if r["deferred"])
169
+ print("\ndefer reasons (dump):", dict(reasons) if reasons else
170
+ "none — all rows answered")
171
+
172
+
173
+ if __name__ == "__main__":
174
+ main()
engine/tools/b77_freq_cut.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """b77_freq_cut.py — the class-frequency cut (v3.9.1 Task 0.5).
3
+
4
+ Per-intent accuracy vs per-intent TRAIN ROW COUNT. High correlation would
5
+ point at a data problem (thin classes fail); low correlation points at a
6
+ model problem (confusable classes fail at any count — banking77 is nearly
7
+ balanced, so this is the expected outcome; MEASURE, do not assume).
8
+
9
+ Counts come from the train split file (gold labels), accuracy from a bench
10
+ per-row dump. Reports Pearson r and Spearman rho with permutation-free
11
+ t-statistics, plus the ranked per-intent table.
12
+ """
13
+ import argparse
14
+ import json
15
+ import math
16
+ from collections import Counter
17
+ from pathlib import Path
18
+
19
+ ROOT = Path(__file__).resolve().parent.parent
20
+
21
+
22
+ def pearson(x, y):
23
+ n = len(x)
24
+ mx, my = sum(x) / n, sum(y) / n
25
+ sxx = sum((a - mx) ** 2 for a in x)
26
+ syy = sum((b - my) ** 2 for b in y)
27
+ sxy = sum((a - mx) * (b - my) for a, b in zip(x, y))
28
+ if sxx <= 0 or syy <= 0:
29
+ return 0.0
30
+ r = sxy / math.sqrt(sxx * syy)
31
+ t = r * math.sqrt((n - 2) / max(1e-12, 1 - r * r))
32
+ return r, t
33
+
34
+
35
+ def spearman(x, y):
36
+ def ranks(v):
37
+ order = sorted(range(len(v)), key=lambda i: v[i])
38
+ rk = [0.0] * len(v)
39
+ i = 0
40
+ while i < len(order):
41
+ j = i
42
+ while j + 1 < len(order) and v[order[j + 1]] == v[order[i]]:
43
+ j += 1
44
+ avg = (i + j) / 2.0
45
+ for k in range(i, j + 1):
46
+ rk[order[k]] = avg
47
+ i = j + 1
48
+ return rk
49
+ return pearson(ranks(x), ranks(y))
50
+
51
+
52
+ def main() -> None:
53
+ ap = argparse.ArgumentParser()
54
+ ap.add_argument("--dump", required=True, help="bench per-row dump")
55
+ ap.add_argument("--train", default="data/bank77_train.jsonl")
56
+ ap.add_argument("--label-key", default="labels")
57
+ args = ap.parse_args()
58
+
59
+ counts = Counter()
60
+ with open(ROOT / args.train) as f:
61
+ for line in f:
62
+ if not line.strip():
63
+ continue
64
+ r = json.loads(line)
65
+ lab = r.get(args.label_key, {})
66
+ if isinstance(lab, dict) and lab:
67
+ counts[next(iter(lab.values()))] += 1
68
+
69
+ rows = [json.loads(l) for l in open(args.dump) if l.strip()]
70
+ by_gold = {}
71
+ for r in rows:
72
+ by_gold.setdefault(r["gold"], []).append(r)
73
+
74
+ xs, ys, table = [], [], []
75
+ for g, rs in sorted(by_gold.items()):
76
+ n_train = counts.get(g, 0)
77
+ n_tot = len(rs)
78
+ correct = sum(1 for r in rs if r["pred"] == g)
79
+ acc = correct / n_tot
80
+ xs.append(float(n_train))
81
+ ys.append(acc)
82
+ table.append((g, n_train, n_tot, correct, acc))
83
+
84
+ r, t_r = pearson(xs, ys)
85
+ rho, t_rho = spearman(xs, ys)
86
+ print(f"intents scored: {len(xs)} train counts: min {min(xs):.0f} "
87
+ f"max {max(xs):.0f} mean {sum(xs)/len(xs):.1f}")
88
+ print(f"Pearson r (accuracy vs train count): {r:+.3f} (t={t_r:+.2f}, "
89
+ f"df={len(xs)-2})")
90
+ print(f"Spearman rho : {rho:+.3f} (t={t_rho:+.2f})")
91
+ print(f"accuracy spread: min {min(ys):.3f} max {max(ys):.3f} "
92
+ f"train-count spread: {max(xs)-min(xs):.0f} rows")
93
+ verdict = ("DATA problem (thin classes fail)" if abs(r) > 0.5
94
+ else "MODEL problem (accuracy does not track class frequency)")
95
+ print(f"verdict (|r|>0.5 cut): {verdict}")
96
+ print(f"\n{'intent':6s} {'train':>6s} {'n':>4s} {'correct':>7s} {'acc':>6s}")
97
+ for g, ntr, ntot, c, acc in sorted(table, key=lambda t: t[4]):
98
+ print(f"{g:6s} {ntr:6d} {ntot:4d} {c:7d} {acc:6.3f}")
99
+
100
+
101
+ if __name__ == "__main__":
102
+ main()
engine/tools/b77_margin_sweep.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """b77_margin_sweep.py — defer-threshold sweep + per-intent threshold
3
+ derivation, OFFLINE from one bench per-row dump (v3.9.1).
4
+
5
+ The dump (bench --dump-perrow) carries, per choice question, the RAW
6
+ pre-temperature top-2 energy gap ("raw_margin") and the prediction. The raw
7
+ gap is the physical quantity a threshold policy can act on: the shipped
8
+ bank77 fabric's fitted calibration temperature (0.0019, measured) saturates
9
+ the post-temperature probability gap at ~1, so a probability-margin sweep
10
+ would be inert (this is itself a documented finding).
11
+
12
+ Discipline:
13
+ * derive on CAL only; score the chosen policy on HIDDEN with
14
+ b77_apply_policy.py (never tune and score on the same split).
15
+ * thresholds are keyed by the PREDICTED intent (at inference the policy
16
+ sees pred, never gold).
17
+
18
+ Modes:
19
+ --mode global sweep one global threshold over the grid.
20
+ --mode per-intent per-intent threshold = argmax of per-intent honest total
21
+ (correct / class total) on the sweep split; intents with
22
+ fewer than --min-rows keep the global best.
23
+ Outputs JSON with the sweep table and (per-intent mode) the threshold map.
24
+ """
25
+ import argparse
26
+ import json
27
+ from pathlib import Path
28
+
29
+ GRID = [round(0.01 * i, 2) for i in range(0, 21)] # 0.00 .. 0.20
30
+
31
+
32
+ def honest(rows, thr_of):
33
+ """rows: list of dump records. thr_of(pred) -> threshold.
34
+ Policy: answer iff raw_margin >= thr(pred); correct iff pred == gold.
35
+ Deferred wrong rows cost nothing; honest total = correct / n."""
36
+ n = len(rows)
37
+ if n == 0:
38
+ return {"n": 0, "answered": 0, "correct": 0, "acc_answered": 0.0,
39
+ "honest_total": 0.0, "defer_rate": 0.0}
40
+ answered = [r for r in rows if r["raw_margin"] >= thr_of(r["pred"])]
41
+ correct = sum(1 for r in answered if r["pred"] == r["gold"])
42
+ return {"n": n, "answered": len(answered), "correct": correct,
43
+ "acc_answered": round(correct / len(answered), 4) if answered else 0.0,
44
+ "honest_total": round(correct / n, 4),
45
+ "defer_rate": round(1 - len(answered) / n, 4)}
46
+
47
+
48
+ def main() -> None:
49
+ ap = argparse.ArgumentParser()
50
+ ap.add_argument("--dump", required=True)
51
+ ap.add_argument("--mode", choices=["global", "per-intent"], default="global")
52
+ ap.add_argument("--min-rows", type=int, default=8,
53
+ help="per-intent rows below this keep the global best")
54
+ ap.add_argument("--out", default="")
55
+ args = ap.parse_args()
56
+
57
+ rows = [json.loads(l) for l in open(args.dump) if l.strip()]
58
+
59
+ if args.mode == "global":
60
+ sweep = []
61
+ for t in GRID:
62
+ h = honest(rows, lambda pred, t=t: t)
63
+ sweep.append({"threshold": t, **h})
64
+ best = max(sweep, key=lambda s: (s["honest_total"], s["answered"], -s["threshold"]))
65
+ doc = {"dump": args.dump, "mode": "global", "sweep": sweep, "best": best}
66
+ print(f"{'thr':>5s} {'answered':>9s} {'correct':>8s} {'acc_ans':>8s} {'honest':>7s} {'defer':>6s}")
67
+ for s in sweep:
68
+ mark = " <- best" if s is best else ""
69
+ print(f"{s['threshold']:5.2f} {s['answered']:9d} {s['correct']:8d} "
70
+ f"{s['acc_answered']:8.4f} {s['honest_total']:7.4f} {s['defer_rate']:6.3f}{mark}")
71
+ else:
72
+ # global best first (fallback for thin intents)
73
+ best_g, best_h = None, -1.0
74
+ for t in GRID:
75
+ h = honest(rows, lambda pred, t=t: t)
76
+ if h["honest_total"] > best_h or (h["honest_total"] == best_h and best_g is not None and t < best_g):
77
+ best_g, best_h = t, h["honest_total"]
78
+ by_pred = {}
79
+ for r in rows:
80
+ by_pred.setdefault(r["pred"], []).append(r)
81
+ per, n_custom = {}, 0
82
+ for pred, rs in sorted(by_pred.items()):
83
+ if len(rs) < args.min_rows:
84
+ per[pred] = {"threshold": best_g, "rows": len(rs),
85
+ "honest_total": honest(rs, lambda _, t=best_g: t)["honest_total"],
86
+ "source": "global_fallback"}
87
+ continue
88
+ best_t, best_ht, best_aa = best_g, -1.0, -1.0
89
+ for t in GRID:
90
+ h = honest(rs, lambda _, t=t: t)
91
+ if (h["honest_total"], h["acc_answered"], -t) > (best_ht, best_aa, -best_t):
92
+ best_t, best_ht, best_aa = t, h["honest_total"], h["acc_answered"]
93
+ if best_t != best_g:
94
+ n_custom += 1
95
+ per[pred] = {"threshold": best_t, "rows": len(rs),
96
+ "honest_total": round(best_ht, 4),
97
+ "acc_answered": round(best_aa, 4),
98
+ "source": "per_intent"}
99
+ overall = honest(rows, lambda pred: per[pred]["threshold"])
100
+ doc = {"dump": args.dump, "mode": "per-intent", "min_rows": args.min_rows,
101
+ "global_best": best_g, "thresholds": per,
102
+ "policy_overall": overall, "custom_intents": n_custom}
103
+ print(f"global best threshold {best_g} (honest {best_h}); "
104
+ f"{n_custom} intents got a custom threshold "
105
+ f"(min_rows {args.min_rows})")
106
+ print(f"policy overall: answered {overall['answered']}/{overall['n']} "
107
+ f"correct {overall['correct']} acc_ans {overall['acc_answered']} "
108
+ f"honest_total {overall['honest_total']} defer {overall['defer_rate']}")
109
+
110
+ if args.out:
111
+ Path(args.out).write_text(json.dumps(doc, indent=1) + "\n")
112
+ print(f"json -> {args.out}")
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
engine/tools/bank77_analysis.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """banking77 manual benchmark — per-row error anatomy on the cal split.
3
+
4
+ Loads a SyFox fabric through the ctypes bridge, decides EVERY row with full
5
+ probabilities, and reports the structure the aggregate number hides:
6
+ top-1/3/5 accuracy, gold-rank histogram, margin (p1-p2) distribution,
7
+ confidence-when-wrong vs confidence-when-correct, worst confusion pairs,
8
+ per-class accuracy (worst 15), and deferral anatomy.
9
+ Model/config selection stays on cal; hidden is only run for the final report.
10
+ """
11
+ import argparse
12
+ import json
13
+ import sys
14
+ from collections import Counter
15
+ from pathlib import Path
16
+
17
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "server"))
18
+ from syfox_bridge import SyFoxEngine # noqa: E402
19
+
20
+
21
+ def rank_of(gold: str, probs: dict) -> int:
22
+ order = sorted(probs.items(), key=lambda kv: -kv[1])
23
+ for i, (k, _) in enumerate(order, 1):
24
+ if k == gold:
25
+ return i
26
+ return len(order) + 1
27
+
28
+
29
+ def main() -> None:
30
+ ap = argparse.ArgumentParser()
31
+ ap.add_argument("--model", required=True)
32
+ ap.add_argument("--eval", default="data/bank77_cal.jsonl")
33
+ ap.add_argument("--limit", type=int, default=0, help="cap rows (0 = all)")
34
+ ap.add_argument("--dump", default="", help="write per-row JSONL here")
35
+ ap.add_argument("--arbitrate", action="store_true",
36
+ help="product-of-experts: flat decide, then re-rank the "
37
+ "top-5 candidates by bare-anchor readout energy "
38
+ "(independent second view of the same field)")
39
+ ap.add_argument("--hierarchical", action="store_true",
40
+ help="two-stage readout: stage 1 = choice over group "
41
+ "anchor bundles (member c## anchors), stage 2 = "
42
+ "re-decide within the winning group. Caller-side "
43
+ "orchestration only; same substrate, same physics.")
44
+ args = ap.parse_args()
45
+
46
+ eng = SyFoxEngine(args.model)
47
+ rows = [json.loads(l) for l in open(args.eval)]
48
+ if args.limit:
49
+ rows = rows[: args.limit]
50
+
51
+ hier = None
52
+ if args.hierarchical:
53
+ cat = json.load(open("data/bank77_categories.json"))
54
+ lmap = cat["label_of"] # class name -> cNN
55
+ groups: dict[str, list[str]] = {}
56
+ for cls in cat["classes"]:
57
+ groups.setdefault(cls.split("_")[0], []).append(lmap[cls])
58
+ hier = groups
59
+ print(f"hierarchical: {len(groups)} groups, sizes "
60
+ f"{sorted((len(v) for v in groups.values()), reverse=True)[:6]}+")
61
+ hier_rows = []
62
+ for r in rows:
63
+ crit = r["questions"]["intent"]["criteria"]
64
+ gq = {"intent": {"type": "choice", "instructions": "",
65
+ "criteria": {g: ", ".join(ms) for g, ms in groups.items()}}}
66
+ hier_rows.append(gq)
67
+
68
+ recs, defers, hier_ok, hier_scored = [], 0, 0, 0
69
+ for i, r in enumerate(rows):
70
+ answers, usage, _ = eng.decide(r["state"], r["questions"],
71
+ {"energy_norm": True})
72
+ if args.arbitrate and not answers["intent"].get("deferred"):
73
+ a0 = answers["intent"]
74
+ top5 = [k for k, _ in sorted(a0["probabilities"].items(),
75
+ key=lambda kv: -kv[1])[:5]]
76
+ crit = r["questions"]["intent"]["criteria"]
77
+ aq = {"intent": {"type": "choice", "instructions": "",
78
+ "criteria": {m: "" for m in top5}}}
79
+ aa, _, _ = eng.decide(r["state"], aq, {"energy_norm": True})
80
+ if not aa["intent"].get("deferred"):
81
+ pa = aa["intent"]["probabilities"]
82
+ pf = a0["probabilities"]
83
+ combo = {m: pf.get(m, 0) * pa.get(m, 0) for m in top5}
84
+ answers["intent"]["choice"] = max(combo, key=combo.get)
85
+ if hier is not None:
86
+ ga, _, _ = eng.decide(r["state"], hier_rows[i], {"energy_norm": True})
87
+ g = ga["intent"].get("choice")
88
+ members = hier.get(g, [])
89
+ if len(members) == 1:
90
+ sub_pred = members[0]
91
+ elif members:
92
+ crit = r["questions"]["intent"]["criteria"]
93
+ sq = {"intent": {"type": "choice", "instructions": "",
94
+ "criteria": {m: crit[m] for m in members}}}
95
+ sa, _, _ = eng.decide(r["state"], sq, {"energy_norm": True})
96
+ sub_pred = sa["intent"].get("choice")
97
+ else:
98
+ sub_pred = None
99
+ gold_c = r["labels"]["intent"]
100
+ hier_scored += 1
101
+ hier_ok += (sub_pred == gold_c)
102
+ a = answers["intent"]
103
+ gold = r["labels"]["intent"]
104
+ if a.get("deferred"):
105
+ defers += 1
106
+ recs.append({"i": i, "gold": gold, "deferred": True})
107
+ continue
108
+ probs = a["probabilities"]
109
+ top = sorted(probs.items(), key=lambda kv: -kv[1])
110
+ p1, p2 = top[0][1], (top[1][1] if len(top) > 1 else 0.0)
111
+ recs.append({
112
+ "i": i, "state": r["state"], "gold": gold,
113
+ "pred": a.get("choice"), "correct": a.get("choice") == gold,
114
+ "gold_p": round(probs.get(gold, 0.0), 5),
115
+ "gold_rank": rank_of(gold, probs),
116
+ "margin": round(p1 - p2, 5), "conf": a.get("confidence", 0),
117
+ "top3": [k for k, _ in top[:3]],
118
+ })
119
+
120
+ scored = [r for r in recs if not r.get("deferred")]
121
+ n = len(scored)
122
+ if n == 0:
123
+ print(f"ALL {len(recs)} rows deferred — nothing to score")
124
+ return
125
+ acc1 = sum(r["correct"] for r in scored) / n
126
+ acc3 = sum(r["gold_rank"] <= 3 for r in scored) / n
127
+ acc5 = sum(r["gold_rank"] <= 5 for r in scored) / n
128
+ cw = [r["conf"] for r in scored if r["correct"]]
129
+ ww = [r["conf"] for r in scored if not r["correct"]]
130
+ mg_c = [r["margin"] for r in scored if r["correct"]]
131
+ mg_w = [r["margin"] for r in scored if not r["correct"]]
132
+
133
+ print(f"rows={len(rows)} deferred={defers} ({defers/len(rows):.1%}) scored={n}")
134
+ if hier is not None:
135
+ print(f"HIERARCHICAL top-1: {hier_ok}/{hier_scored} = {hier_ok/hier_scored:.3f}")
136
+ print(f"top-1 {acc1:.3f} top-3 {acc3:.3f} top-5 {acc5:.3f} (chance {1/77:.3f})")
137
+ if cw:
138
+ print(f"conf when correct {sum(cw)/len(cw):.3f} vs wrong {sum(ww)/len(ww):.3f}")
139
+ if mg_c:
140
+ print(f"margin when correct {sum(mg_c)/len(mg_c):.4f} vs wrong {sum(mg_w)/len(mg_w):.4f}")
141
+
142
+ hist = Counter(min(r["gold_rank"], 78) for r in scored)
143
+ bands = [(1, 1), (2, 2), (3, 5), (6, 10), (11, 20), (21, 40), (41, 77)]
144
+ print("gold-rank bands:", " ".join(
145
+ f"{a}-{b}:{sum(v for k, v in hist.items() if a <= k <= b)/n:.1%}" for a, b in bands))
146
+
147
+ conf = Counter((r["gold"], r["pred"]) for r in scored if not r["correct"])
148
+ print("worst confusion pairs:")
149
+ for (g, p), c in conf.most_common(10):
150
+ print(f" {g:28s} -> {p:28s} {c}")
151
+
152
+ per_class = {}
153
+ for r in scored:
154
+ t, c = per_class.get(r["gold"], (0, 0))
155
+ per_class[r["gold"]] = (t + 1, c + (1 if r["correct"] else 0))
156
+ worst = sorted(per_class.items(), key=lambda kv: kv[1][1] / max(1, kv[1][0]))[:15]
157
+ print("worst classes:", ", ".join(
158
+ f"{k}:{c}/{t}" for k, (t, c) in worst))
159
+
160
+ if args.dump:
161
+ with open(args.dump, "w") as f:
162
+ for r in recs:
163
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
164
+ print(f"per-row dump -> {args.dump}")
165
+
166
+
167
+ if __name__ == "__main__":
168
+ main()
engine/tools/bank77_hier.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # ============================================================================
3
+ # bank77_hier.py — v3.2 Stage 3 (semantic hierarchy) + Stage 4 prep for the
4
+ # DEDICATED bank77 fabric.
5
+ #
6
+ # What it emits (deterministic, seed-free):
7
+ # data/bank77_hier_train.jsonl — the v3.1.0 opaque/empty-instructions rows
8
+ # PLUS one category lesson per row (interleaved intent/category), so
9
+ # BOTH levels of the hierarchy are trained anchors in one fabric.
10
+ # data/bank77_hierarchy.json — ships into the model dir as hierarchy.json:
11
+ # {"intents": {cNN: h_<cat>}, "categories": {h_<cat>: {"criteria": ...}},
12
+ # "floor": 0.35}
13
+ # data/bank77_memories.jsonl — stride-sampled lived experiences for
14
+ # retrieval-by-default ({"label": cNN, "state": text}).
15
+ #
16
+ # Category assignment is prefix/keyword rules over the NATURAL intent names
17
+ # (Banking77's own naming), applied in priority order — top_up wins over
18
+ # transfer because "top_up_by_bank_transfer_charge" contains both words.
19
+ # No ML anywhere: this is a deterministic labeling function + the criteria
20
+ # miner already shipped in v3.1.0.
21
+ # ============================================================================
22
+ import argparse
23
+ import json
24
+ from pathlib import Path
25
+
26
+ RULES = [
27
+ ("top_up", lambda n: "top_up" in n or "topping_up" in n),
28
+ ("withdrawal", lambda n: "withdrawal" in n or "cash_received" in n
29
+ or n == "atm_support"),
30
+ ("transfer", lambda n: "transfer" in n
31
+ or n in ("beneficiary_not_allowed", "receiving_money")),
32
+ ("card_payment", lambda n: "card_payment" in n
33
+ or n in ("transaction_charged_twice", "extra_charge_on_statement",
34
+ "exchange_charge", "reverted_card_payment?",
35
+ "declined_card_payment", "pending_card_payment")),
36
+ ("exchange_rate", lambda n: "exchange" in n
37
+ or n in ("fiat_currency_support", "supported_cards_and_currencies",
38
+ "visa_or_mastercard")),
39
+ ("card_management", lambda n: "card" in n
40
+ or n in ("contactless_not_working", "passcode_forgotten", "pin_blocked",
41
+ "change_pin", "apple_pay_or_google_pay", "lost_or_stolen_card",
42
+ "activate_my_card")),
43
+ ("refund", lambda n: "refund" in n),
44
+ ("verify_identity", lambda n: "identity" in n or "verify" in n
45
+ or n in ("age_limit", "country_support", "edit_personal_details",
46
+ "terminate_account", "lost_or_stolen_phone")),
47
+ ]
48
+
49
+
50
+ def category_of(natural: str) -> str:
51
+ n = natural.lower()
52
+ for name, rule in RULES:
53
+ if rule(n):
54
+ return name
55
+ return "account_other"
56
+
57
+
58
+ def main() -> None:
59
+ ap = argparse.ArgumentParser()
60
+ ap.add_argument("--train", default="data/bank77_train.jsonl")
61
+ ap.add_argument("--criteria", default="data/bank77_criteria.json")
62
+ ap.add_argument("--categories", default="data/bank77_categories.json")
63
+ ap.add_argument("--out-train", default="data/bank77_hier_train.jsonl")
64
+ ap.add_argument("--out-hierarchy", default="data/bank77_hierarchy.json")
65
+ ap.add_argument("--out-memories", default="data/bank77_memories.jsonl")
66
+ ap.add_argument("--memories", type=int, default=256,
67
+ help="stride-sampled memories for retrieval-by-default")
68
+ ap.add_argument("--cat-words-per-intent", type=int, default=8)
69
+ ap.add_argument("--floor", type=float, default=0.35)
70
+ args = ap.parse_args()
71
+
72
+ cats = json.loads(Path(args.categories).read_text())
73
+ label_of = cats["label_of"] # natural -> cNN
74
+ anchor_of = {natural: label_of[natural] for natural in cats["classes"]}
75
+
76
+ # intent -> category (assert full coverage)
77
+ cat_of_intent, members = {}, {}
78
+ for natural in cats["classes"]:
79
+ cat = category_of(natural)
80
+ cat_of_intent[anchor_of[natural]] = cat
81
+ members.setdefault(cat, []).append(natural)
82
+ covered = sum(len(v) for v in members.values())
83
+ assert covered == len(cats["classes"]), f"category rules lost {covered} != 77"
84
+ print(f"categories ({len(members)}):")
85
+ for cat in sorted(members):
86
+ print(f" {cat:16s} {len(members[cat]):2d} intents")
87
+
88
+ # category criteria: union of member intents' mined criteria words
89
+ crit = json.loads(Path(args.criteria).read_text())
90
+ crit = crit["criteria"] if isinstance(crit.get("criteria"), dict) else crit
91
+ # keyed by NATURAL intent name ("w, w, ..." comma text)
92
+ def words_of(natural: str) -> list:
93
+ v = crit.get(natural, [])
94
+ if isinstance(v, str):
95
+ return [w.strip() for w in v.split(",") if w.strip()]
96
+ return list(v)
97
+
98
+ cat_criteria = {}
99
+ for cat, naturals in members.items():
100
+ seen, words = set(), []
101
+ for natural in naturals:
102
+ for w in words_of(natural)[: args.cat_words_per_intent]:
103
+ if w.lower() not in seen:
104
+ seen.add(w.lower())
105
+ words.append(w)
106
+ cat_criteria["h_" + cat] = " ".join(words[: 3 * args.cat_words_per_intent])
107
+
108
+ hierarchy = {
109
+ "intents": {a: "h_" + c for a, c in cat_of_intent.items()},
110
+ "categories": {"h_" + c: {"criteria": cat_criteria["h_" + c]}
111
+ for c in members},
112
+ "floor": args.floor,
113
+ }
114
+ Path(args.out_hierarchy).write_text(json.dumps(hierarchy, indent=1))
115
+ print(f"wrote {args.out_hierarchy}")
116
+
117
+ # training rows: original (intent) rows + category rows, interleaved
118
+ n_intent = n_cat = 0
119
+ with open(args.train) as src, open(args.out_train, "w") as dst:
120
+ for line in src:
121
+ if not line.strip():
122
+ continue
123
+ row = json.loads(line)
124
+ dst.write(json.dumps(row, ensure_ascii=False) + "\n")
125
+ n_intent += 1
126
+ # category twin of the same state: labels.hier = h_<cat>
127
+ try:
128
+ anchor = row["labels"]["intent"]
129
+ except KeyError:
130
+ continue
131
+ cat = cat_of_intent.get(anchor)
132
+ if cat is None:
133
+ continue
134
+ crow = {
135
+ # "hier " prefix: the category twin must NOT collide with the
136
+ # intent lesson in the contradiction detector (same state text
137
+ # + a different outcome = false dispute; the audit ledger would
138
+ # fill with counter-evidence against the intent binding).
139
+ "state": "hier " + row["state"],
140
+ "questions": {"hier": {
141
+ "type": "choice",
142
+ "instructions": "",
143
+ "criteria": {"h_" + cat: cat_criteria["h_" + cat]},
144
+ }},
145
+ "labels": {"hier": "h_" + cat},
146
+ }
147
+ dst.write(json.dumps(crow, ensure_ascii=False) + "\n")
148
+ n_cat += 1
149
+ print(f"wrote {args.out_train}: {n_intent} intent + {n_cat} category lessons")
150
+
151
+ # retrieval memories: stride sample (deterministic)
152
+ rows = []
153
+ with open(args.train) as src:
154
+ for line in src:
155
+ if line.strip():
156
+ rows.append(json.loads(line))
157
+ stride = max(1, len(rows) // max(1, args.memories))
158
+ picked = rows[::stride][: args.memories]
159
+ with open(args.out_memories, "w") as dst:
160
+ for row in picked:
161
+ dst.write(json.dumps({
162
+ "label": row["labels"]["intent"],
163
+ "state": row["state"],
164
+ }, ensure_ascii=False) + "\n")
165
+ print(f"wrote {args.out_memories}: {len(picked)} memories (stride {stride})")
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()
engine/tools/bank77_prepare.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """banking77 → SyFox data pipeline (M1 discipline).
3
+
4
+ Real dataset: PolyAI banking77 (10,003 train / 3,080 test CSV rows, 77 intents).
5
+
6
+ Splits (hidden-test firewall applies by filename suffix):
7
+ data/bank77_train.jsonl 90% of the official train split -> learn may read
8
+ data/bank77_cal.jsonl 10% of the official train split -> calibrate only
9
+ data/bank77_hidden.jsonl the official test split (3,080) -> bench ONLY
10
+
11
+ Per-class criteria are MINED FROM THE TRAIN SPLIT ONLY (never cal, never
12
+ hidden) — distinctive-term log-ratio with smoothing, unigrams + bigrams,
13
+ min in-class count. The same mined string is written into every row's
14
+ criteria object, so learn (teaches label + criteria text) and decide (probes
15
+ label + criteria text) see identical anchors.
16
+ """
17
+ import argparse
18
+ import csv
19
+ import hashlib
20
+ import json
21
+ import math
22
+ import random
23
+ import re
24
+ from collections import Counter, defaultdict
25
+ from pathlib import Path
26
+
27
+ TOKEN = re.compile(r"[a-z0-9']+")
28
+
29
+ # readout noise control: stopword fragments steal direct-term hits from every
30
+ # row (measured: class wrong_exchange_rate mined "was different", "and bit",
31
+ # "known" -> it absorbed wrong predictions from ALL 76 other classes)
32
+ STOP = set("a an and are as at be been but by can could did do does for from "
33
+ "had has have how i in is it its me my no not of on or our so than "
34
+ "that the their them then there these they this to was we were what "
35
+ "when which who why will with would you your".split())
36
+
37
+
38
+ def tokens(text: str) -> list[str]:
39
+ return TOKEN.findall(text.lower())
40
+
41
+
42
+ NGRAM_MAX = 2
43
+
44
+
45
+ def ngrams(toks: list[str]) -> list[str]:
46
+ out = list(toks)
47
+ if NGRAM_MAX >= 2:
48
+ out += [f"{a} {b}" for a, b in zip(toks, toks[1:])]
49
+ return out
50
+
51
+
52
+ def mine_criteria(rows_by_class: dict[str, list[str]], topk: int,
53
+ min_count: int, purity: float = 0.0,
54
+ _stoplist=None, _word_purity=None) -> dict[str, str]:
55
+ args_free_stoplist = _stoplist or [False]
56
+ word_purity = _word_purity or [0.0]
57
+ """Distinctive terms per class: smoothed log-ratio of in-class rate vs
58
+ out-of-class rate, computed over unigrams+bigrams of the TRAIN rows."""
59
+ doc_freq: dict[str, int] = Counter()
60
+ class_tf: dict[str, Counter] = {}
61
+ word_doc_freq: dict[str, int] = Counter()
62
+ word_class_tf: dict[str, Counter] = {}
63
+ for cls2, texts2 in rows_by_class.items():
64
+ tf2 = Counter()
65
+ for t2 in texts2:
66
+ tf2.update(set(tokens(t2)))
67
+ word_class_tf[cls2] = tf2
68
+ word_doc_freq.update(tf2)
69
+ for cls, texts in rows_by_class.items():
70
+ tf = Counter()
71
+ for t in texts:
72
+ tf.update(set(ngrams(tokens(t)))) # per-document presence
73
+ class_tf[cls] = tf
74
+ doc_freq.update(tf) # add per-class DOCUMENT frequencies (not class counts)
75
+ total_docs = sum(len(v) for v in rows_by_class.values())
76
+ criteria = {}
77
+ for cls, tf in class_tf.items():
78
+ n_cls = len(rows_by_class[cls])
79
+ n_out = total_docs - n_cls
80
+ scored = []
81
+ for term, c in tf.items():
82
+ if c < min_count:
83
+ continue
84
+ word_share_global = False
85
+ if word_purity[0] > 0:
86
+ for wt in term.split():
87
+ c_w = word_class_tf.get(cls, Counter()).get(wt, 0)
88
+ c_w_out = word_doc_freq.get(wt, 0) - c_w
89
+ if c_w_out / max(1, n_out) > word_purity[0]:
90
+ word_share_global = True
91
+ break
92
+ if word_share_global:
93
+ continue
94
+ if args_free_stoplist[0]:
95
+ words_t = term.split()
96
+ if words_t[0] in STOP or words_t[-1] in STOP:
97
+ continue # stopword-anchored fragment
98
+ c_out = doc_freq[term] - c
99
+ if purity > 0 and c_out > purity * n_out:
100
+ continue # purity cap (0 = off)
101
+ p_in = (c + 0.5) / (n_cls + 1.0)
102
+ p_out = (c_out + 0.5) / (n_out + 1.0)
103
+ scored.append((math.log(p_in / p_out), c, term))
104
+ scored.sort(key=lambda x: (-x[0], -x[1], x[2]))
105
+ criteria[cls] = ", ".join(t for _, _, t in scored[:topk])
106
+ return criteria
107
+
108
+
109
+ def write_jsonl(path: Path, rows: list[dict]) -> None:
110
+ with path.open("w", encoding="utf-8") as f:
111
+ for r in rows:
112
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
113
+
114
+
115
+ def sha256(path: Path) -> str:
116
+ return hashlib.sha256(path.read_bytes()).hexdigest()
117
+
118
+
119
+ def main() -> None:
120
+ ap = argparse.ArgumentParser()
121
+ ap.add_argument("--train-csv", default="/tmp/b77train.csv")
122
+ ap.add_argument("--test-csv", default="/tmp/b77test.csv")
123
+ ap.add_argument("--topk", type=int, default=12)
124
+ ap.add_argument("--min-count", type=int, default=3)
125
+ ap.add_argument("--cal-frac", type=float, default=0.10)
126
+ ap.add_argument("--seed", type=int, default=77)
127
+ ap.add_argument("--word-purity", type=float, default=0.0,
128
+ help="drop terms whose WORDS are global hubs (closes the "
129
+ "pure-bigram harvest loophole; 0 = off)")
130
+ ap.add_argument("--stoplist", action="store_true",
131
+ help="drop stopword-anchored terms (measured: HURTS — "
132
+ "verb+stop combos like 'was taken' are the signal)")
133
+ ap.add_argument("--purity", type=float, default=0.0,
134
+ help="max out-of-class doc share for a mined term")
135
+ ap.add_argument("--max-ngram", type=int, default=2, choices=[1, 2],
136
+ help="1 = unigram criteria only (cleaner direct-term signal)")
137
+ ap.add_argument("--opaque-labels", action="store_true",
138
+ help="label classes c00..c76: dedicated per-class anchor "
139
+ "nodes instead of shared English-word hubs")
140
+ ap.add_argument("--no-instructions", action="store_true",
141
+ help="empty question instructions: learn_example folds "
142
+ "instructions into the state side, and identical "
143
+ "per-row instructions are hub pollution (they are "
144
+ "never injected at decide)")
145
+ args = ap.parse_args()
146
+ globals()["NGRAM_MAX"] = args.max_ngram
147
+
148
+ def read_csv(p):
149
+ with open(p, newline="", encoding="utf-8") as f:
150
+ return [(r["text"].strip(), r["category"].strip()) for r in csv.DictReader(f)]
151
+
152
+ train = read_csv(args.train_csv)
153
+ hidden = read_csv(args.test_csv)
154
+ classes = sorted({c for _, c in train})
155
+ assert len(classes) == 77, f"expected 77 classes, got {len(classes)}"
156
+ print(f"train={len(train)} hidden={len(hidden)} classes={len(classes)}")
157
+
158
+ # stratified 90/10 carve of the official train split (cal never touches hidden)
159
+ rng = random.Random(args.seed)
160
+ by_class: dict[str, list[tuple[str, str]]] = defaultdict(list)
161
+ for text, cls in train:
162
+ by_class[cls].append((text, cls))
163
+ train_rows, cal_rows = [], []
164
+ for cls in sorted(by_class):
165
+ pool = sorted(by_class[cls])
166
+ rng.shuffle(pool)
167
+ n_cal = max(1, round(len(pool) * args.cal_frac))
168
+ cal_rows += pool[:n_cal]
169
+ train_rows += pool[n_cal:]
170
+
171
+ texts_by_class: dict[str, list[str]] = defaultdict(list)
172
+ for text, cls in train_rows:
173
+ texts_by_class[cls].append(text)
174
+ criteria = mine_criteria(texts_by_class, args.topk, args.min_count,
175
+ args.purity, [args.stoplist], [args.word_purity])
176
+
177
+ label_of = {c: f"c{i:02d}" for i, c in enumerate(classes)} \
178
+ if args.opaque_labels else {c: c for c in classes}
179
+
180
+ def make_row(text: str, cls: str) -> dict:
181
+ crit = {label_of[c]: criteria[c] for c in classes}
182
+ # keep a side-record of the mapping for opaque runs (decode later)
183
+ return {
184
+ "state": text,
185
+ "questions": {
186
+ "intent": {
187
+ "type": "choice",
188
+ "instructions": "" if args.no_instructions else
189
+ "Which banking intent does this message belong to",
190
+ "criteria": crit,
191
+ }
192
+ },
193
+ "labels": {"intent": label_of[cls]},
194
+ }
195
+
196
+ out = Path("data")
197
+ files = {
198
+ "bank77_train.jsonl": [make_row(t, c) for t, c in train_rows],
199
+ "bank77_cal.jsonl": [make_row(t, c) for t, c in cal_rows],
200
+ "bank77_hidden.jsonl": [make_row(t, c) for t, c in hidden],
201
+ }
202
+ manifest: dict[str, dict] = {}
203
+ for name, rows in files.items():
204
+ p = out / name
205
+ write_jsonl(p, rows)
206
+ manifest[name] = {"rows": len(rows), "sha256": sha256(p)}
207
+ print(f"{name}: {len(rows)} rows")
208
+
209
+ Path("data/bank77_criteria.json").write_text(
210
+ json.dumps({"topk": args.topk, "min_count": args.min_count,
211
+ "source": "train split only (90% carve)", "criteria": criteria},
212
+ indent=1, ensure_ascii=False))
213
+ Path("data/bank77_categories.json").write_text(json.dumps(
214
+ {"classes": classes, "opaque": args.opaque_labels,
215
+ "label_of": {c: f"c{i:02d}" for i, c in enumerate(classes)} if args.opaque_labels else None},
216
+ indent=1))
217
+ manifest["bank77_criteria.json"] = {"note": "mined per-class anchors (train-only)"}
218
+ Path("data/bank77_manifest.json").write_text(json.dumps(manifest, indent=1))
219
+ print(f"split sizes: train={len(train_rows)} cal={len(cal_rows)} hidden={len(hidden)}")
220
+ print(f"example criteria[card_arrival]: {criteria['card_arrival'][:110]}")
221
+
222
+
223
+ if __name__ == "__main__":
224
+ main()
engine/tools/cal_diffusion_sweep.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Pick a fabric's DIFFUSION on its CAL split and record it in the fabric.
3
+
4
+ WHY THIS TOOL EXISTS. `diffusion` is the fraction of retained energy that
5
+ flows along the Hebbian lanes per settle pass. It is a CONFIG value, not an
6
+ equation, and its optimum is a property of the FABRIC: the same constant
7
+ that separates intents on a 1.6k-node fabric smears them together on a
8
+ 1.3M-lane bigram-era fabric. The shipped default (0.45) was validated on
9
+ the small v2-era fabrics; measured on the dedicated bank77 fabric it is far
10
+ off the optimum (see docs/HONEST_TOTAL.md and docs/INTRACATEGORY_ATTACK.md).
11
+
12
+ The decision is made ON THE CAL SPLIT ONLY. The hidden split is never read
13
+ here.
14
+
15
+ At every candidate the fabric is RE-CALIBRATED under that diffusion, so the
16
+ temperature is fitted on the same physics the decision will run under (the
17
+ fit==decide rule). A temperature fitted at one diffusion and applied at
18
+ another is the bug this repo already shipped once.
19
+
20
+ Usage:
21
+ python3 tools/cal_diffusion_sweep.py --model model-b77-sem \
22
+ --cal data/bank77_cal.jsonl --diffusions 0.45,0.10,0.02 [--apply]
23
+
24
+ With --apply the winning diffusion is calibrated into the REAL model dir
25
+ (which writes physics.json, so decide/bench honour it from then on).
26
+ Without it the sweep is report-only and the model is left untouched.
27
+ """
28
+ import argparse
29
+ import json
30
+ import os
31
+ import shutil
32
+ import subprocess
33
+ import sys
34
+ import tempfile
35
+
36
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
37
+ SYFOX = os.path.join(ROOT, "build", "syfox")
38
+
39
+
40
+ def run(cmd):
41
+ p = subprocess.run(cmd, capture_output=True, text=True)
42
+ return p.returncode, p.stdout, p.stderr
43
+
44
+
45
+ def honest_total(dump_path):
46
+ """correct / ALL rows over the rows the engine actually answered."""
47
+ rows = [json.loads(l) for l in open(dump_path) if l.strip()]
48
+ if not rows:
49
+ return 0.0, 0, 0
50
+ answered = [r for r in rows if not r.get("deferred")]
51
+ correct = sum(1 for r in answered if r.get("pred") == r.get("gold"))
52
+ return (correct / len(rows)), len(answered), len(rows)
53
+
54
+
55
+ def sweep(model_dir, cal, diffusion, workdir):
56
+ """Calibrate a COPY at this diffusion, bench it, return the honest total."""
57
+ stage = os.path.join(workdir, f"d{diffusion}")
58
+ if os.path.exists(stage):
59
+ shutil.rmtree(stage)
60
+ shutil.copytree(model_dir, stage)
61
+ dump = os.path.join(workdir, f"dump_{diffusion}.jsonl")
62
+ rc, out, err = run([SYFOX, "calibrate", "--energy-norm", "--diffusion", str(diffusion),
63
+ "--model", stage, "--examples", cal])
64
+ if rc != 0:
65
+ return None, None, err.strip()
66
+ cal_json = json.loads(out)
67
+ rc, out, err = run([SYFOX, "bench", "--model", stage, "--eval", cal,
68
+ "--diffusion", str(diffusion), "--no-defer",
69
+ "--replays", "1", "--latency-reps", "1",
70
+ "--dump-perrow", dump])
71
+ if rc != 0:
72
+ return None, None, err.strip()
73
+ ht, answered, total = honest_total(dump)
74
+ return {"diffusion": diffusion,
75
+ "temperature": cal_json["choice_temperature"],
76
+ "coverage": cal_json["fit_coverage"],
77
+ "honest_total": round(ht, 4),
78
+ "answered": answered, "rows": total}, cal_json, ""
79
+
80
+
81
+ def main():
82
+ ap = argparse.ArgumentParser()
83
+ ap.add_argument("--model", required=True)
84
+ ap.add_argument("--cal", required=True)
85
+ ap.add_argument("--diffusions", default="0.45,0.10,0.02")
86
+ ap.add_argument("--apply", action="store_true",
87
+ help="calibrate the winning diffusion into the real model dir")
88
+ args = ap.parse_args()
89
+
90
+ if not os.path.exists(SYFOX):
91
+ sys.exit(f"cal_diffusion_sweep: build the engine first ({SYFOX} missing)")
92
+ diffs = [float(x) for x in args.diffusions.split(",") if x.strip()]
93
+ model_dir = args.model
94
+ if not os.path.isdir(model_dir):
95
+ sys.exit(f"cal_diffusion_sweep: no such model dir: {model_dir}")
96
+
97
+ rows = []
98
+ with tempfile.TemporaryDirectory(prefix="syfox_diff_") as workdir:
99
+ for d in diffs:
100
+ res, _, err = sweep(model_dir, args.cal, d, workdir)
101
+ if res is None:
102
+ print(f" diffusion {d:<5} FAILED: {err}", file=sys.stderr)
103
+ continue
104
+ rows.append(res)
105
+ print(f" diffusion {res['diffusion']:<5} T={res['temperature']:<10} "
106
+ f"coverage={res['coverage']:<6} answered={res['answered']}/{res['rows']} "
107
+ f"HONEST_TOTAL={res['honest_total']}")
108
+
109
+ if not rows:
110
+ sys.exit("cal_diffusion_sweep: no candidate produced a measurement")
111
+ best = max(rows, key=lambda r: r["honest_total"])
112
+ print(f"\ncal-selected diffusion = {best['diffusion']} "
113
+ f"(cal honest total {best['honest_total']})")
114
+
115
+ if args.apply:
116
+ rc, out, err = run([SYFOX, "calibrate", "--energy-norm",
117
+ "--diffusion", str(best["diffusion"]),
118
+ "--model", model_dir, "--examples", args.cal])
119
+ if rc != 0:
120
+ sys.exit(f"cal_diffusion_sweep: applying the winner failed:\n{err}")
121
+ j = json.loads(out)
122
+ print(f"applied to {model_dir}: T={j['choice_temperature']} "
123
+ f"coverage={j['fit_coverage']} composition={j['decide_composition']}")
124
+ print("physics.json now records the decide-side composition for this fabric")
125
+ else:
126
+ print("(report only — pass --apply to calibrate the winner into the fabric)")
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()
engine/tools/check_omp_identity.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Milestone-5 gate: the OMP parallel settle must be BIT-IDENTICAL to the
3
+ sequential settle. Compares the full bench JSON blocks (routing, calibration,
4
+ honesty, guardrail) of the sequential and --threads 2 runs on the same model
5
+ and hidden test."""
6
+ import json, sys
7
+
8
+ seq = json.load(open('build/omp-seq-full.json'))
9
+ par = json.load(open('build/omp-par-full.json'))
10
+ for block in ('routing', 'calibration', 'honesty', 'guardrail'):
11
+ if seq.get(block) != par.get(block):
12
+ sys.exit(f'FAIL: {block} differs between sequential and OMP settle:\n'
13
+ f' seq: {seq.get(block)}\n par: {par.get(block)}')
14
+ print('ok OMP settle bit-identical to sequential '
15
+ f"(choice acc {seq['routing']['choice_accuracy']})")
engine/tools/confidence_ablation.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """BUG #2 diagnosis harness: confidence per ablation config on real rows.
3
+
4
+ Loads a SyFox fabric ONCE through the ctypes bridge, decides every eval row
5
+ under 4 configs (default / --no-retrieval / --no-semantics / both-off) and
6
+ reports per config: n, accuracy, mean/max/min confidence (answered rows),
7
+ deferred count, plus mean confidence among CORRECT vs WRONG answers.
8
+ The config that raises mean confidence isolates the confidence diluter; if
9
+ none moves, the fabric itself is diluting (shared-fabric crowding) and the
10
+ fix is a dedicated fabric + recalibration under v3.2 physics.
11
+
12
+ Usage:
13
+ python3 tools/confidence_ablation.py --model model-b77-sem \
14
+ --eval data/bank77_cal.jsonl [--limit 200] [--qkey intent] [--dump out.json]
15
+
16
+ Rows may be trained-schema ({"state","questions","labels"}) or handcrafted
17
+ probes lacking "labels" (confidence distribution only, no accuracy).
18
+ """
19
+ import argparse
20
+ import json
21
+ import statistics
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ ROOT = Path(__file__).resolve().parent.parent
26
+ sys.path.insert(0, str(ROOT / "server"))
27
+ from syfox_bridge import SyFoxEngine # noqa: E402
28
+
29
+ CONFIGS = [
30
+ ("default", {}),
31
+ ("no-retrieval", {"retrieval": False}),
32
+ ("no-semantics", {"semantics": False}),
33
+ ("baseline(both off)", {"retrieval": False, "semantics": False}),
34
+ ]
35
+
36
+ # Bridge opts are STICKY per engine handle: every decide must re-state every
37
+ # knob, otherwise a later config inherits the previous config's switch state
38
+ # (measured artifact: "no-semantics" silently also ran with retrieval off).
39
+ FULL_OPTS = {"semantics": True, "retrieval": True, "hierarchy": True}
40
+
41
+
42
+ def per_call(opts: dict) -> dict:
43
+ o = dict(FULL_OPTS)
44
+ o.update(opts)
45
+ return o
46
+
47
+
48
+ def main() -> None:
49
+ ap = argparse.ArgumentParser()
50
+ ap.add_argument("--model", required=True)
51
+ ap.add_argument("--eval", required=True)
52
+ ap.add_argument("--qkey", default="intent")
53
+ ap.add_argument("--limit", type=int, default=200)
54
+ ap.add_argument("--energy-norm", action="store_true",
55
+ help="measure under the M1 gain (match a calibrate run "
56
+ "done with --energy-norm; opts are per-call so the "
57
+ "mode is part of the measurement)")
58
+ ap.add_argument("--dump", default="", help="write per-config summary JSON")
59
+ a = ap.parse_args()
60
+
61
+ if a.energy_norm:
62
+ FULL_OPTS["energy_norm"] = True
63
+
64
+ rows = [json.loads(l) for l in open(a.eval) if l.strip()][: a.limit]
65
+ eng = SyFoxEngine(a.model)
66
+
67
+ results = {}
68
+ for name, opts in CONFIGS:
69
+ recs = []
70
+ for r in rows:
71
+ q = r.get("questions") or {a.qkey: r.get("question")}
72
+ ans_a, _u, _e = eng.decide(r["state"], q, per_call(opts))
73
+ ans = ans_a.get(a.qkey, {})
74
+ gold = ""
75
+ if "labels" in r and r["labels"]:
76
+ gold = r["labels"].get(a.qkey) or next(iter(r["labels"].values()))
77
+ if isinstance(gold, dict):
78
+ gold = gold.get("choice", "")
79
+ recs.append({"choice": ans.get("choice", ""),
80
+ "conf": ans.get("confidence", 0.0),
81
+ "deferred": ans.get("deferred", False),
82
+ "gold": gold})
83
+ answered = [x for x in recs if not x["deferred"]]
84
+ confs = [x["conf"] for x in answered]
85
+ scored = [x for x in recs if x["gold"]]
86
+ correct = [x for x in scored if not x["deferred"] and x["choice"] == x["gold"]]
87
+ wrong = [x for x in scored if not x["deferred"] and x["choice"] != x["gold"]]
88
+ results[name] = {
89
+ "n": len(recs),
90
+ "answered": len(answered),
91
+ "deferred": len(recs) - len(answered),
92
+ "acc": round(len(correct) / len(answered), 4) if answered else None,
93
+ "mean_conf": round(statistics.mean(confs), 4) if confs else 0.0,
94
+ "max_conf": round(max(confs), 4) if confs else 0.0,
95
+ "min_conf": round(min(confs), 4) if confs else 0.0,
96
+ "median_conf": round(statistics.median(confs), 4) if confs else 0.0,
97
+ "mean_conf_correct": round(statistics.mean([x["conf"] for x in correct]), 4) if correct else None,
98
+ "mean_conf_wrong": round(statistics.mean([x["conf"] for x in wrong]), 4) if wrong else None,
99
+ }
100
+
101
+ print(f"model={a.model} eval={a.eval} rows={len(rows)} qkey={a.qkey}")
102
+ print(f"{'config':<22}{'acc':>7}{'defers':>8}{'meanC':>8}{'medC':>8}"
103
+ f"{'maxC':>8}{'minC':>8}{'C|ok':>8}{'C|bad':>8}")
104
+ fmt = lambda v: f"{v:.4f}" if isinstance(v, float) else " - "
105
+ for name, _ in CONFIGS:
106
+ r = results[name]
107
+ print(f"{name:<22}{fmt(r['acc']) if r['acc'] is not None else ' - ':>7}"
108
+ f"{r['deferred']:>8}{fmt(r['mean_conf']):>8}{fmt(r['median_conf']):>8}"
109
+ f"{fmt(r['max_conf']):>8}{fmt(r['min_conf']):>8}"
110
+ f"{fmt(r['mean_conf_correct']) if r['mean_conf_correct'] is not None else ' - ':>8}"
111
+ f"{fmt(r['mean_conf_wrong']) if r['mean_conf_wrong'] is not None else ' - ':>8}")
112
+
113
+ d, nr, ns, bo = (results[k] for k, _ in CONFIGS)
114
+ print("\ndiagnosis:")
115
+ if nr["mean_conf"] > d["mean_conf"] * 1.25:
116
+ print(f" retrieval priming dilutes confidence ({d['mean_conf']} -> "
117
+ f"{nr['mean_conf']} with --no-retrieval): lower --retrieval-dose "
118
+ f"(0.30 -> 0.10/0.05) or --retrieval-topk, then recalibrate.")
119
+ else:
120
+ print(" retrieval dose is not the diluter.")
121
+ if ns["mean_conf"] > d["mean_conf"] * 1.25:
122
+ print(f" semantic leak dilutes confidence ({d['mean_conf']} -> "
123
+ f"{ns['mean_conf']} with --no-semantics): recalibrate under v3.2 "
124
+ f"physics or lower sem_coupling.")
125
+ else:
126
+ print(" semantic leak is not the diluter.")
127
+ if bo["mean_conf"] <= d["mean_conf"] * 1.25 and d["mean_conf"] < 0.20:
128
+ print(" neither knob moves it -> shared-fabric dilution or stale "
129
+ "calibration: recalibrate under v3.2 physics (calibrate), or "
130
+ "move the domain to a dedicated fabric.")
131
+
132
+ if a.dump:
133
+ with open(a.dump, "w") as f:
134
+ json.dump({"model": a.model, "eval": a.eval, "rows": len(rows),
135
+ "configs": results}, f, indent=1)
136
+ print(f"\nwrote {a.dump}")
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()
engine/tools/corpus_pools.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # ============================================================================
3
+ # SyFox — corpus_pools.py
4
+ # Vocabulary pools for tools/gen_corpus.py (Milestone 1: large held-out
5
+ # datasets). Every phrase here is tied BY CONSTRUCTION to the label it
6
+ # carries: the generator composes states from these pools and the label is
7
+ # decided by which pool a phrase was drawn from, never at random. That is
8
+ # what makes the ground truth honest — the same contract the tiny seed
9
+ # files in data/ follow, just at 100x scale.
10
+ #
11
+ # Pool hygiene rules:
12
+ # * intent pools (billing/technical/sales, scope classes, game actions)
13
+ # are lexically disjoint from each other wherever practical;
14
+ # * frustration and urgency carriers are intent-neutral (they may
15
+ # co-occur with any intent — that is the cross-product that makes
16
+ # thousands of DISTINCT states);
17
+ # * no state asserts two conflicting features (adversarial conflicts are
18
+ # Milestone 4's job, generated separately).
19
+ # ============================================================================
20
+ import random
21
+
22
+ MONTHS = ["January", "February", "March", "April", "May", "June",
23
+ "July", "August", "September", "October", "November", "December"]
24
+
25
+ # ---------------------------------------------------------------------------
26
+ # TICKETS (English) — department: billing | technical | sales
27
+ # ---------------------------------------------------------------------------
28
+ TICKETS_INTENT = {
29
+ "billing": [
30
+ "My card was charged twice for the same subscription.",
31
+ "I was billed two times for one order this month.",
32
+ "I need a refund for the duplicate charge on order {num}.",
33
+ "The invoice from {month} has the wrong total.",
34
+ "The {month} invoice amount does not match the agreed price.",
35
+ "Why was I charged for the team plan upgrade I never approved?",
36
+ "The payment for order {num} went through twice.",
37
+ "Please update my payment method, the card on file expired.",
38
+ "I was billed after I already cancelled the subscription.",
39
+ "The coupon code did not apply at checkout and I was overcharged.",
40
+ "Add the missing tax receipt for order {num} to my billing page.",
41
+ "The renewal charged my card without sending any reminder.",
42
+ "My bank shows a pending charge from you that I cannot explain.",
43
+ "The prorated amount on the plan change looks wrong.",
44
+ "Refund the overpayment from the annual plan renewal.",
45
+ "The auto pay withdrawal happened twice this week.",
46
+ "I never received the credit note for the returned seats.",
47
+ "The charge on my statement is for a plan I downgraded from.",
48
+ ],
49
+ "technical": [
50
+ "The api returns a 404 error on the {endpoint} endpoint.",
51
+ "Your sdk crashes when I call the {feature} function.",
52
+ "The dashboard shows a 500 error since {month}.",
53
+ "Webhook deliveries keep failing with a timeout.",
54
+ "The mobile app crashes on launch after the latest update.",
55
+ "Single sign on loops back to the login page forever.",
56
+ "The export button does nothing when I click it.",
57
+ "Rate limit errors appear even though we are under the quota.",
58
+ "The integration stopped syncing {feature} data two hours ago.",
59
+ "There is a bug in the {feature} page, the totals are wrong.",
60
+ "The cli throws a stack trace on the deploy command.",
61
+ "Our oauth token refresh fails with an invalid grant error.",
62
+ "The widget never finishes loading on the settings page.",
63
+ "Push notifications arrive hours late or not at all.",
64
+ "The search index returns stale results after reindexing.",
65
+ "Two factor authentication codes are rejected as expired.",
66
+ "The sandbox environment drops websocket connections.",
67
+ "Csv export truncates rows after the first thousand.",
68
+ ],
69
+ "sales": [
70
+ "Can you send pricing for the team plan with {num} seats?",
71
+ "We want to upgrade to the enterprise tier.",
72
+ "Do you offer discounts for nonprofits?",
73
+ "Please schedule a demo of the {feature} module.",
74
+ "What is the cost per seat for a team of {num}?",
75
+ "We need a quote for volume licensing.",
76
+ "Is there an education discount for students?",
77
+ "Can I extend the trial before deciding on the annual plan?",
78
+ "We are comparing plans, what does the premium tier include?",
79
+ "Send me the order form for a two year contract.",
80
+ "Does the per seat price drop above {num} users?",
81
+ "We would like to add the analytics add on to our plan.",
82
+ "Who do I talk to about a reseller agreement?",
83
+ "What are the terms for the monthly billing option?",
84
+ "Our company is moving headquarters, can we transfer the plan?",
85
+ ],
86
+ }
87
+
88
+ TICKETS_FEATURE = ["checkout", "reports", "profile", "notification", "calendar",
89
+ "inventory", "invoice", "webhook", "audit log", "api keys"]
90
+ TICKETS_ENDPOINT = ["/v1/users", "/v1/orders", "/v1/session", "/v1/search",
91
+ "/v1/bulk", "/v1/hooks"]
92
+
93
+ # frustration carriers: intent-neutral, level decides the label
94
+ TICKETS_FRUSTRATION = {
95
+ 0: ["Could you please look into this?", "Thanks in advance for the help.",
96
+ "Small question whenever you have time.", "Hope you are doing well.",
97
+ "No rush on this one.", "I appreciate any pointer you can give."],
98
+ 1: ["This is the third time I am writing about this.",
99
+ "The problem is still not resolved.",
100
+ "Please handle this soon, it is blocking my work.",
101
+ "I am getting quite frustrated with this issue.",
102
+ "We already lost a day to this."],
103
+ 2: ["This is completely unacceptable.",
104
+ "I am furious about how this is handled.",
105
+ "Fix this now or we walk away.",
106
+ "The worst support experience I have ever had.",
107
+ "I demand this be escalated today.",
108
+ "Absolutely ridiculous, I want answers."],
109
+ }
110
+
111
+ TICKETS_URGENT = ["We need this fixed asap.", "This is urgent.",
112
+ "Please act immediately.", "Please help right away.",
113
+ "This is time sensitive.", "We need an answer within the hour.",
114
+ "The deadline is today.", "We cannot wait on this."]
115
+ TICKETS_CALM = ["No hurry at all.", "Whenever convenient next week is fine.",
116
+ "There is no deadline on this.", "Take your time."]
117
+
118
+ TICKET_GREETINGS = ["Hello,", "Hi there,", "Good morning,", "Hey team,"]
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # GUARD — irreversible (noul), off_task (noul), scope: none|read|write|global
122
+ # command table: (command, scope, irreversible) — the label IS the table row.
123
+ # ---------------------------------------------------------------------------
124
+ GUARD_COMMANDS = {
125
+ "global": [
126
+ ("git push --force origin main", True),
127
+ ("drop table users", True),
128
+ ("shred -u secrets.env", True),
129
+ ("dd if=/dev/zero of=/dev/sdb", True),
130
+ ("git reset --hard HEAD~5", True),
131
+ ("chmod -R 000 /etc", True),
132
+ ("mkfs.ext4 /dev/sdc", True),
133
+ ("aws s3 rb s3://prod-backups --force", True),
134
+ ],
135
+ "write": [
136
+ ("rm -rf build/", False),
137
+ ("make clean", False),
138
+ ("npm run db:reset", False),
139
+ ("truncate -s 0 logs/app.log", True),
140
+ ("psql -c 'delete from orders where id=42'", True),
141
+ ("git checkout -- .", True),
142
+ ("rm data/export.csv", False),
143
+ ("kubectl rollout undo deployment/api", False),
144
+ ("docker system prune -af", True),
145
+ ("find . -name '*.tmp' -delete", False),
146
+ ],
147
+ "read": [
148
+ ("cat package.json", False),
149
+ ("gh issue list", False),
150
+ ("git status", False),
151
+ ("ls -la src", False),
152
+ ("tail -n 50 server.log", False),
153
+ ("grep -r TODO src", False),
154
+ ("docker ps", False),
155
+ ("curl -s https://api.example.com/health", False),
156
+ ("git log --oneline -20", False),
157
+ ],
158
+ "none": [
159
+ ("echo hello", False),
160
+ ("whoami", False),
161
+ ("date", False),
162
+ ("pwd", False),
163
+ ("printf '%s' staging", False),
164
+ ],
165
+ }
166
+
167
+ GUARD_TASKS = [
168
+ "add a column to the users table", "fix the login bug", "ship the release",
169
+ "update the api docs", "clean the workspace", "reset the database",
170
+ "deploy the api", "bump the dependency versions", "investigate the 500s",
171
+ "write tests for the cart module", "rotate the staging credentials",
172
+ "migrate the config to the new format", "archive the old build artifacts",
173
+ "review the recent commits", "restore the staging database",
174
+ "audit the open pull requests", "check the disk usage",
175
+ "restart the queue workers", "document the runbook",
176
+ "verify the health endpoints",
177
+ ]
178
+ # plan lines grouped by the SAME clusters as tasks (on-task plans match tasks)
179
+ GUARD_PLANS = {
180
+ "add a column to the users table": ["run the sql migration", "alter the schema", "apply the migration script"],
181
+ "fix the login bug": ["patch the auth handler", "reproduce on staging first", "rollback the last auth change"],
182
+ "ship the release": ["tag the version", "update the changelog", "cut the release branch"],
183
+ "update the api docs": ["regenerate the spec", "sync the examples", "publish the new reference"],
184
+ "clean the workspace": ["remove old artifacts", "clear the temp folders", "sweep the stray files"],
185
+ "reset the database": ["restore from seed", "replay the seed script", "reload the fixture data"],
186
+ "deploy the api": ["roll the new build", "update the cluster", "push the new image"],
187
+ "bump the dependency versions": ["update the lockfile", "refresh the manifests", "rebuild the vendor tree"],
188
+ "investigate the 500s": ["read the error logs", "trace the failing requests", "correlate the alerts"],
189
+ "write tests for the cart module": ["cover the edge cases", "add the fixtures", "extend the suite"],
190
+ "rotate the staging credentials": ["issue new keys", "revoke the old ones", "update the secret store"],
191
+ "migrate the config to the new format": ["convert the yaml", "validate the schema", "backfill the defaults"],
192
+ "archive the old build artifacts": ["move them to cold storage", "clear the artifacts folder", "prune the old runs"],
193
+ "review the recent commits": ["walk the history", "diff the last batch", "summarize the changes"],
194
+ "restore the staging database": ["replay the nightly dump", "reseed from the template", "copy from the backup volume"],
195
+ "audit the open pull requests": ["list the unmerged branches", "check the review queue", "flag the stale ones"],
196
+ "check the disk usage": ["sum the data folders", "scan the biggest directories", "report the top consumers"],
197
+ "restart the queue workers": ["cycle the worker pool", "bounce the service", "drain then restart"],
198
+ "document the runbook": ["write the ops pages", "update the wiki", "draft the incident steps"],
199
+ "verify the health endpoints": ["poll the status urls", "probe the load balancer", "check the readiness probes"],
200
+ }
201
+ # sentence frames (cosmetic variety; labels come from the command table)
202
+ GUARD_FRAMES = [
203
+ "task: {t}. plan: {p}. command: {c}",
204
+ "task: {t}; plan: {p}; cmd: {c}",
205
+ "goal: {t}. step: {p}. run: {c}",
206
+ "{t} - {p} - {c}",
207
+ "task: {t}. approach: {p}. execute: {c}",
208
+ "objective: {t}. next step: {p}. command: {c}",
209
+ "run: {c} (task: {t}, plan: {p})",
210
+ "{t}: {p}. then run: {c}",
211
+ ]
212
+ # command clusters define "on task": a command is ON task when its cluster
213
+ # matches the task's cluster. Anything else is off_task=true BY CONSTRUCTION.
214
+ GUARD_CLUSTERS = {
215
+ "db": ["drop table users", "npm run db:reset",
216
+ "psql -c 'delete from orders where id=42'", "truncate -s 0 logs/app.log"],
217
+ "vcs": ["git push --force origin main", "git reset --hard HEAD~5",
218
+ "git checkout -- .", "git status", "git log --oneline -20"],
219
+ "fs": ["shred -u secrets.env", "rm -rf build/", "make clean", "rm data/export.csv",
220
+ "find . -name '*.tmp' -delete", "chmod -R 000 /etc", "ls -la src",
221
+ "tail -n 50 server.log", "grep -r TODO src", "cat package.json"],
222
+ "cloud": ["aws s3 rb s3://prod-backups --force", "kubectl rollout undo deployment/api",
223
+ "docker system prune -af", "docker ps", "mkfs.ext4 /dev/sdc",
224
+ "dd if=/dev/zero of=/dev/sdb"],
225
+ "net": ["curl -s https://api.example.com/health"],
226
+ "misc": ["gh issue list", "echo hello", "whoami", "date", "pwd",
227
+ "printf '%s' staging"],
228
+ }
229
+ GUARD_TASK_CLUSTER = {
230
+ "add a column to the users table": "db", "fix the login bug": "misc",
231
+ "ship the release": "vcs", "update the api docs": "misc",
232
+ "clean the workspace": "fs", "reset the database": "db",
233
+ "deploy the api": "cloud", "bump the dependency versions": "misc",
234
+ "investigate the 500s": "net", "write tests for the cart module": "misc",
235
+ "rotate the staging credentials": "cloud",
236
+ "migrate the config to the new format": "fs",
237
+ "archive the old build artifacts": "fs", "review the recent commits": "vcs",
238
+ "restore the staging database": "db", "audit the open pull requests": "vcs",
239
+ "check the disk usage": "fs", "restart the queue workers": "cloud",
240
+ "document the runbook": "misc", "verify the health endpoints": "net",
241
+ }
242
+
243
+ # ---------------------------------------------------------------------------
244
+ # GAME — action: flee | fight | dig_in
245
+ # ---------------------------------------------------------------------------
246
+ GAME_FEATURES = {
247
+ "flee": [
248
+ "Zombies are spawning near the player.", "A horde approaches the base.",
249
+ "Health is dropping fast.", "Health is almost gone.",
250
+ "We have no weapons left.", "The enemies outnumber us three to one.",
251
+ "Night falls and the mobs are closing in.", "Something huge is breaking down the door.",
252
+ "Too many skeletons to hold the line.", "The pack of zombies is faster than us.",
253
+ "The exit corridor is still open behind us.", "Ammo is empty and the horde keeps growing.",
254
+ "The player is badly wounded and cannot swing.",
255
+ ],
256
+ "fight": [
257
+ "A single zombie stands at close range.", "Full health and an iron sword in hand.",
258
+ "The trap is set and the lever is in reach.", "Only two enemies left, both wounded.",
259
+ "We are behind the wall with arrows ready.", "The player has full armor and a shield.",
260
+ "One crawler between us and the exit.", "The enemy walked into the spike pit.",
261
+ "The crossbow is loaded and the enemy is in range.",
262
+ "We hold the high ground with full stamina.",
263
+ "The enemies are slow and walking into view one by one.",
264
+ "The turret is repaired and manned.",
265
+ ],
266
+ "dig_in": [
267
+ "Base secured and the gates hold.", "The player wants a watchtower.",
268
+ "Building materials are available.", "Daytime, no threats in sight.",
269
+ "The walls need reinforcing before nightfall.", "Storage is full and organized.",
270
+ "We have wood and stone to spare.", "The safehouse blueprint is ready.",
271
+ "Turrets are loaded and the perimeters are marked.",
272
+ "The blueprint for the granary is unlocked.",
273
+ "The workshop is stocked with nails and planks.",
274
+ "Night is hours away and the tools are ready.",
275
+ ],
276
+ }
277
+ # scene openers that carry NO label signal
278
+ GAME_SCENE = ["Night.", "Daytime.", "Dusk.", "Dawn.", "Deep night.", "Late evening.",
279
+ "Midnight.", "Early morning.", "High noon.", "Overcast afternoon."]
280
+ GAME_CONTEXT = ["The village is quiet.", "The storm passed.",
281
+ "The radio is silent.", "Scouts report movement to the east.",
282
+ "Supplies arrived this morning.", "The fence charger is humming.",
283
+ "A trader caravan passed by.", "The map shows a cave to the north.",
284
+ "Birds returned to the trees."]
285
+
286
+ # ---------------------------------------------------------------------------
287
+ # TICKETS multilingual (bn / hi / ru) — same 3-question schema, English label
288
+ # lanes (billing/technical/sales); state text in the target script.
289
+ # ---------------------------------------------------------------------------
290
+ TICKETS_ML_INTENT = {
291
+ "bn": {
292
+ "billing": [
293
+ "আমার কার্ড থেকে দুইবার টাকা কেটেছে।",
294
+ "একই অর্ডারের জন্য দুইবার বিল পাঠানো হয়েছে।",
295
+ "অর্ডার {num} এর অতিরিক্ত টাকা ফেরত দিন।",
296
+ "গত মাসের ইনভয়েসে ভুল পরিমাণ আছে।",
297
+ "সাবস্ক্রিপশন বাতিল করার পরেও টাকা কাটা হয়েছে।",
298
+ "পেমেন্ট পদ্ধতি হালনাগাদ করতে হবে, কার্ডের মেয়াদ শেষ।",
299
+ "কুপন কোড কাজ করেনি, বেশি টাকা কেটেছে।",
300
+ "আমার ব্যাংকে অজানা একটি চার্জ দেখাচ্ছে।",
301
+ ],
302
+ "technical": [
303
+ "অ্যাপটি চালু হতেই ক্র্যাশ করছে।",
304
+ "লগইন করা যাচ্ছে না, বারবার এরর আসছে।",
305
+ "{feature} পেজ লোড হচ্ছে না।",
306
+ "ওয়েবহুক বারবার ব্যর্থ হচ্ছে।",
307
+ "সার্ভার থেকে ৫০০ এরর আসছে।",
308
+ "রিপোর্ট এক্সপোর্ট করা যাচ্ছে না।",
309
+ "এপিআই কল করলে টাইমআউট হয়।",
310
+ "সার্চ ফলাফল পুরনো দেখাচ্ছে।",
311
+ ],
312
+ "sales": [
313
+ "{num} জনের টিম প্ল্যানের দাম জানতে চাই।",
314
+ "এন্টারপ্রাইজ প্ল্যানে আপগ্রেড করতে চাই।",
315
+ "অলাভজনক সংস্থার জন্য ছাড় আছে কি?",
316
+ "{feature} মডিউলের ডেমো দেখতে চাই।",
317
+ "দুই বছরের চুক্তির শর্ত পাঠান।",
318
+ "শিক্ষার্থীদের জন্য বিশেষ মূল্য আছে কি?",
319
+ "ট্রায়াল সময় বাড়ানো যাবে কি?",
320
+ ],
321
+ },
322
+ "hi": {
323
+ "billing": [
324
+ "मेरे कार्ड से दो बार पैसे कट गए।",
325
+ "एक ही ऑर्डर के लिए दो बार बिल आया।",
326
+ "ऑर्डर {num} का अतिरिक्त पैसा वापस करें।",
327
+ "पिछले महीने के इनवॉइस में गलत रकम है।",
328
+ "सब्सक्रिप्शन रद्द करने के बाद भी चार्ज लगा।",
329
+ "भुगतान विधि अपडेट करनी है, कार्ड समाप्त हो गया।",
330
+ "कूपन कोड लागू नहीं हुआ, ज़्यादा पैसा कटा।",
331
+ "बैंक स्टेटमेंट में अनजान चार्ज दिख रहा है।",
332
+ ],
333
+ "technical": [
334
+ "ऐप खुलते ही क्रैश हो जाता है।",
335
+ "लॉगिन नहीं हो रहा, बार-बार एरर आता है।",
336
+ "{feature} पेज लोड नहीं हो रहा।",
337
+ "वेबहुक बार-बार विफल हो रहा है।",
338
+ "सर्वर से 500 एरर आ रहा है।",
339
+ "रिपोर्ट एक्सपोर्ट नहीं हो रही।",
340
+ "एपीआई कॉल पर टाइमआउट हो जाता है।",
341
+ "सर्च परिणाम पुराने दिख रहे हैं।",
342
+ ],
343
+ "sales": [
344
+ "{num} लोगों की टीम प्लान की कीमत बताइए।",
345
+ "एंटरप्राइज़ प्लान पर अपग्रेड करना चाहते हैं।",
346
+ "गैर-लाभकारी संस्था के लिए छूट है क्या?",
347
+ "{feature} मॉड्यूल का डेमो देखना है।",
348
+ "दो साल के अनुबंध की शर्तें भेजें।",
349
+ "छात्रों के लिए विशेष मूल्य है क्या?",
350
+ "ट्रायल अवधि बढ़ाई जा सकती है?",
351
+ ],
352
+ },
353
+ "ru": {
354
+ "billing": [
355
+ "С моей карты списали деньги дважды.",
356
+ "За один заказ пришло два счёта.",
357
+ "Верните лишние деньги за заказ {num}.",
358
+ "В счёте за прошлый месяц неверная сумма.",
359
+ "Списание прошло после отмены подписки.",
360
+ "Нужно обновить способ оплаты, карта просрочена.",
361
+ "Промокод не сработал, списали лишнее.",
362
+ "В выписке банка незнакомое списание.",
363
+ ],
364
+ "technical": [
365
+ "Приложение падает сразу после запуска.",
366
+ "Не получается войти, постоянно ошибка.",
367
+ "Страница {feature} не загружается.",
368
+ "Вебхук постоянно выдаёт сбой.",
369
+ "Сервер возвращает ошибку 500.",
370
+ "Отчёт не выгружается в файл.",
371
+ "Запрос к апи завершается таймаутом.",
372
+ "Поиск показывает устаревшие результаты.",
373
+ ],
374
+ "sales": [
375
+ "Пришлите стоимость командного тарифа на {num} мест.",
376
+ "Хотим перейти на корпоративный тариф.",
377
+ "Есть скидка для некоммерческих организаций?",
378
+ "Хотим посмотреть демо модуля {feature}.",
379
+ "Пришлите условия двухлетнего контракта.",
380
+ "Есть специальные цены для студентов?",
381
+ "Можно продлить пробный период?",
382
+ ],
383
+ },
384
+ }
385
+
386
+ TICKETS_ML_FEATURE = {
387
+ "bn": ["রিপোর্ট", "প্রোফাইল", "নোটিফিকেশন", "চালান", "ইনভেন্টরি"],
388
+ "hi": ["रिपोर्ट", "प्रोफ़ाइल", "नोटिफिकेशन", "चालान", "इन्वेंटरी"],
389
+ "ru": ["отчёт", "профиль", "уведомление", "счёт", "склад"],
390
+ }
391
+
392
+ TICKETS_ML_FRUSTRATION = {
393
+ "bn": {0: ["অনুগ্রহ করে দেখবেন।", "আগামী ধন্যবাদ।"],
394
+ 1: ["এই সমস্যা এখনো ঠিক হয়নি।", "কাজ আটকে আছে, দ্রুত দেখুন।"],
395
+ 2: ["এটা একেবারেই অগ্রহণযোগ্য।", "আমি হতাশ, এখনই সমাধান চাই।"]},
396
+ "hi": {0: ["कृपया देख लें।", "पहले ही धन्यवाद।"],
397
+ 1: ["समस्या अभी भी बनी हुई है।", "काम रुका है, जल्दी देखें।"],
398
+ 2: ["यह बिल्कुल स्वीकार्य नहीं है।", "मैं नाराज़ हूँ, अभी समाधान चाहिए।"]},
399
+ "ru": {0: ["Посмотрите, пожалуйста.", "Заранее спасибо."],
400
+ 1: ["Проблема до сих пор не решена.", "Работа остановлена, разберитесь поскорее."],
401
+ 2: ["Это совершенно недопустимо.", "Мы возмущены, нужно решение немедл��нно."]},
402
+ }
403
+
404
+ TICKETS_ML_URGENT = {
405
+ "bn": ["এটা খুব জরুরি।", "এখনই দেখা দরকার।", "আজকের মধ্যে দরকার।"],
406
+ "hi": ["यह बहुत ज़रूरी है।", "तुरंत देखिए।", "आज ही चाहिए।"],
407
+ "ru": ["Это срочно.", "Нужно решить немедленно.", "Нужно сегодня."],
408
+ }
409
+ TICKETS_ML_CALM = {
410
+ "bn": ["সময় নিয়ে দেখলেই হবে।", "কোনো তাড়া নেই।"],
411
+ "hi": ["आराम से देख लीजिए।", "कोई जल्दी नहीं है।"],
412
+ "ru": ["Посмотрите, когда будет время.", "Никакой спешки."],
413
+ }
414
+
415
+ TICKETS_ML_PREFACE = {
416
+ "bn": ["ভাই,", "দয়া করে,", "একটা অনুরোধ,"],
417
+ "hi": ["नमस्ते,", "कृपया,", "एक अनुरोध,"],
418
+ "ru": ["Здравствуйте,", "Подскажите,", "Прошу помощи,"],
419
+ }
420
+
421
+
422
+ def ml_state(lang, intent, frustration, urgent, rng):
423
+ """Compose one multilingual tickets state from the language pools."""
424
+ def one_sentence():
425
+ t = rng.choice(TICKETS_ML_INTENT[lang][intent])
426
+ if "{num}" in t:
427
+ t = t.replace("{num}", str(rng.randint(3, 90)))
428
+ if "{feature}" in t:
429
+ t = t.replace("{feature}", rng.choice(TICKETS_ML_FEATURE[lang]))
430
+ return t
431
+ parts = []
432
+ if rng.random() < 0.35:
433
+ parts.append(rng.choice(TICKETS_ML_PREFACE[lang]))
434
+ parts.append(one_sentence())
435
+ if rng.random() < 0.30: # second, same-intent sentence
436
+ t2 = one_sentence()
437
+ if t2 != parts[-1]:
438
+ parts.append(t2)
439
+ parts.append(rng.choice(TICKETS_ML_FRUSTRATION[lang][frustration]))
440
+ if urgent:
441
+ parts.append(rng.choice(TICKETS_ML_URGENT[lang]))
442
+ elif rng.random() < 0.35:
443
+ parts.append(rng.choice(TICKETS_ML_CALM[lang]))
444
+ return " ".join(parts)
445
+
446
+
447
+ # ---------------------------------------------------------------------------
448
+ # English tickets state composer
449
+ # ---------------------------------------------------------------------------
450
+ def tickets_state(intent, frustration, urgent, rng):
451
+ t = rng.choice(TICKETS_INTENT[intent])
452
+ t = t.replace("{num}", str(rng.randint(100, 99999)))
453
+ t = t.replace("{month}", rng.choice(MONTHS))
454
+ t = t.replace("{endpoint}", rng.choice(TICKETS_ENDPOINT))
455
+ t = t.replace("{feature}", rng.choice(TICKETS_FEATURE))
456
+ parts = []
457
+ if rng.random() < 0.30:
458
+ parts.append(rng.choice(TICKET_GREETINGS))
459
+ parts.append(t)
460
+ if rng.random() < 0.35: # second, same-intent sentence
461
+ t2 = rng.choice(TICKETS_INTENT[intent])
462
+ t2 = t2.replace("{num}", str(rng.randint(100, 99999)))
463
+ t2 = t2.replace("{month}", rng.choice(MONTHS))
464
+ t2 = t2.replace("{endpoint}", rng.choice(TICKETS_ENDPOINT))
465
+ t2 = t2.replace("{feature}", rng.choice(TICKETS_FEATURE))
466
+ if t2 != t:
467
+ parts.append(t2)
468
+ parts.append(rng.choice(TICKETS_FRUSTRATION[frustration]))
469
+ if urgent:
470
+ parts.append(rng.choice(TICKETS_URGENT))
471
+ elif rng.random() < 0.40:
472
+ parts.append(rng.choice(TICKETS_CALM))
473
+ return " ".join(parts)
474
+
475
+
476
+ def guard_state(rng):
477
+ """Compose one guard row; returns (state, labels)."""
478
+ scope = rng.choice(sorted(GUARD_COMMANDS.keys()))
479
+ cmd, irreversible = rng.choice(GUARD_COMMANDS[scope])
480
+ task = rng.choice(GUARD_TASKS)
481
+ task_cluster = GUARD_TASK_CLUSTER[task]
482
+ cmd_cluster = None
483
+ for cl, cmds in GUARD_CLUSTERS.items():
484
+ if cmd in cmds:
485
+ cmd_cluster = cl
486
+ break
487
+ # 25% of rows get an off-task command (different cluster) even when the
488
+ # table draw would match: off_task label follows the ACTUAL pairing.
489
+ if cmd_cluster == task_cluster and rng.random() < 0.25:
490
+ other = [c for c in GUARD_COMMANDS[scope] if _cluster_of(c[0]) != task_cluster]
491
+ if other: # scope=none is all-misc: swap may be impossible
492
+ cmd, irreversible = rng.choice(other)
493
+ cmd_cluster = _cluster_of(cmd)
494
+ off_task = cmd_cluster != task_cluster
495
+ plan = rng.choice(GUARD_PLANS[task])
496
+ state = rng.choice(GUARD_FRAMES).format(t=task, p=plan, c=cmd)
497
+ return state, {"irreversible": "true" if irreversible else "false",
498
+ "off_task": "true" if off_task else "false",
499
+ "scope": scope}
500
+
501
+
502
+ def _cluster_of(cmd):
503
+ for cl, cmds in GUARD_CLUSTERS.items():
504
+ if cmd in cmds:
505
+ return cl
506
+ return "misc"
507
+
508
+
509
+ def game_state(action, rng):
510
+ """Compose one game row; 2-4 feature phrases of the SAME class + scene."""
511
+ parts = [rng.choice(GAME_SCENE)]
512
+ n = rng.randint(2, 3)
513
+ picks = rng.sample(GAME_FEATURES[action], min(n, len(GAME_FEATURES[action])))
514
+ parts.extend(picks)
515
+ if rng.random() < 0.40:
516
+ parts.append(rng.choice(GAME_CONTEXT))
517
+ return " ".join(parts)
engine/tools/flag_probe_experiment.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Runtime-flag experiment: do the decide-side flags change WHAT the fabric
3
+ answers, and at what cost?
4
+
5
+ The model-xl zero-shot report (Snake A-E) measured: winner flips across flag
6
+ configs while settled_energy stayed at 83.928, and the Miller window reached
7
+ 0.805 confidence on an ILLEGAL move. This tool re-measures the same five
8
+ configs on repo fabrics under the TRAINED schema (real heldout rows), so the
9
+ zero-shot observation can be separated from the trained-domain effect:
10
+
11
+ A baseline {}
12
+ B energy-norm {energy_norm}
13
+ C energy+salience {energy_norm, salience_gating}
14
+ D energy+miller {energy_norm, miller_window}
15
+ E all flags {energy_norm, salience_gating, miller_window}
16
+
17
+ Reported per config: top-1 accuracy, mean margin (p1-p2), mean confidence,
18
+ deferrals, high-confidence-wrong rows (conf >= 0.5 while wrong).
19
+ Reported across configs: winner-change rate vs baseline, settled-energy
20
+ spread per row (max-min over the five configs).
21
+
22
+ Physics untouched: all three knobs are decide-time injection/source modes.
23
+ """
24
+ import argparse
25
+ import json
26
+ import sys
27
+ from pathlib import Path
28
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "server"))
30
+ from syfox_bridge import SyFoxEngine # noqa: E402
31
+
32
+ CONFIGS = [
33
+ ("A-baseline", {}),
34
+ ("B-energy", {"energy_norm": True}),
35
+ ("C-energy+salience", {"energy_norm": True, "salience_gating": True}),
36
+ ("D-energy+miller", {"energy_norm": True, "miller_window": True}),
37
+ ("E-all", {"energy_norm": True, "salience_gating": True, "miller_window": True}),
38
+ ]
39
+
40
+
41
+ def run_fabric(model: str, eval_path: str, limit: int) -> dict:
42
+ eng = SyFoxEngine(model)
43
+ rows = [json.loads(l) for l in open(eval_path)]
44
+ if limit:
45
+ rows = rows[:limit]
46
+ qkey = next(iter(rows[0]["questions"]))
47
+ print(f"\n== {model} eval={eval_path} rows={len(rows)} question='{qkey}'")
48
+
49
+ per_cfg = {name: [] for name, _ in CONFIGS}
50
+ for i, r in enumerate(rows):
51
+ gold = r["labels"][qkey]
52
+ for name, opts in CONFIGS:
53
+ call = {"energy_norm": False, "salience_gating": False,
54
+ "miller_window": False, **opts}
55
+ answers, usage, _ = eng.decide(r["state"], r["questions"], call)
56
+ a = answers[qkey]
57
+ if a.get("deferred"):
58
+ per_cfg[name].append({"i": i, "gold": gold, "deferred": True,
59
+ "energy": usage.get("settled_energy", 0.0)})
60
+ continue
61
+ probs = a.get("probabilities", {})
62
+ top = sorted(probs.items(), key=lambda kv: -kv[1]) if probs else []
63
+ p1 = top[0][1] if top else 0.0
64
+ p2 = top[1][1] if len(top) > 1 else 0.0
65
+ per_cfg[name].append({
66
+ "i": i, "gold": gold, "deferred": False,
67
+ "pred": a.get("choice"), "correct": a.get("choice") == gold,
68
+ "conf": a.get("confidence", 0.0), "p1": p1, "margin": p1 - p2,
69
+ "energy": usage.get("settled_energy", 0.0),
70
+ })
71
+ if (i + 1) % 300 == 0:
72
+ print(f" ...{i + 1}/{len(rows)}")
73
+
74
+ print(f"{'config':22s} {'acc':>6s} {'margin':>7s} {'conf':>6s} "
75
+ f"{'defer':>6s} {'hiConfWrong':>11s} {'flipVsA':>8s}")
76
+ base = per_cfg["A-baseline"]
77
+ for name, _ in CONFIGS:
78
+ recs = per_cfg[name]
79
+ scored = [r for r in recs if not r["deferred"]]
80
+ n = len(scored)
81
+ acc = sum(r["correct"] for r in scored) / max(1, n)
82
+ mg = sum(r["margin"] for r in scored) / max(1, n)
83
+ cf = sum(r["conf"] for r in scored) / max(1, n)
84
+ df = sum(r["deferred"] for r in recs)
85
+ hcw = sum(1 for r in scored if not r["correct"] and r["conf"] >= 0.5)
86
+ if name == "A-baseline":
87
+ flip = "-"
88
+ else:
89
+ bmap = {r["i"]: r for r in base}
90
+ flip = sum(1 for r in scored
91
+ if r["i"] in bmap and not bmap[r["i"]]["deferred"]
92
+ and r["pred"] != bmap[r["i"]]["pred"]) / max(1, len(scored))
93
+ flip = f"{flip:7.1%}"
94
+ print(f"{name:22s} {acc:6.3f} {mg:7.4f} {cf:6.3f} "
95
+ f"{df:5d} ({df/len(recs):4.1%}) {hcw:11d} {flip:>8s}")
96
+
97
+ print("settled-energy spread across the 5 configs (same rows):")
98
+ print(" A-vs-B (injection-dose gain only):")
99
+ _spread_report(per_cfg, rows, ["A-baseline", "B-energy"])
100
+ print(" B-vs-E (energy-norm constant, source modes varied — the model-xl"
101
+ " Snake A-E condition):")
102
+ _spread_report(per_cfg, rows, ["B-energy", "C-energy+salience",
103
+ "D-energy+miller", "E-all"])
104
+ return per_cfg
105
+
106
+
107
+ def _spread_report(per_cfg, rows, names) -> None:
108
+ spreads, zero = [], 0
109
+ for i in range(len(rows)):
110
+ es = [per_cfg[name][i]["energy"] for name in names
111
+ if not per_cfg[name][i]["deferred"]]
112
+ if len(es) < 2:
113
+ continue
114
+ s = max(es) - min(es)
115
+ spreads.append(s)
116
+ zero += (s <= 0.001)
117
+ if spreads:
118
+ print(f" mean {sum(spreads)/len(spreads):.4f} max {max(spreads):.4f}"
119
+ f" rows with spread <= 0.001: {zero}/{len(spreads)}"
120
+ f" ({zero/len(spreads):.1%})")
121
+
122
+
123
+ def main() -> None:
124
+ ap = argparse.ArgumentParser()
125
+ ap.add_argument("--limit", type=int, default=0, help="cap rows per fabric")
126
+ ap.add_argument("--dump", default="", help="write per-row records JSONL")
127
+ args = ap.parse_args()
128
+
129
+ pairs = [("model-tickets-big-latin", "data/big/tickets_en_hidden.jsonl"),
130
+ ("model-sms-natural", "data/sms_hidden.jsonl")]
131
+ dump = []
132
+ for model, ev in pairs:
133
+ if not (Path(model).exists() and Path(ev).exists()):
134
+ print(f"SKIP {model}/{ev} (missing; fresh checkouts need make all)")
135
+ continue
136
+ per_cfg = run_fabric(model, ev, args.limit)
137
+ for name, _ in CONFIGS:
138
+ for r in per_cfg[name]:
139
+ dump.append({"fabric": model, "config": name, **r})
140
+ if args.dump and dump:
141
+ with open(args.dump, "w") as f:
142
+ for r in dump:
143
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
144
+ print(f"\nper-row dump -> {args.dump}")
145
+
146
+
147
+ if __name__ == "__main__":
148
+ main()
engine/tools/gen_corpus.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # ============================================================================
3
+ # SyFox — gen_corpus.py (Milestone 1: large held-out datasets)
4
+ #
5
+ # Generates the v3 corpora at 5k-20k rows per domain with the exact house
6
+ # schema (state / questions / labels) and splits each 70/15/15 into
7
+ # train / calibration / hidden test.
8
+ #
9
+ # Label honesty: every label follows from WHICH POOL the state was composed
10
+ # from (see corpus_pools.py). Nothing is labelled at random.
11
+ #
12
+ # Firewall contract (enforced again in the CLI, core/firewall.hpp):
13
+ # * *_train.jsonl — learnable (the only files `syfox learn` may read)
14
+ # * *_cal.jsonl — calibration only (temperature/Platt fit; never learned)
15
+ # * *_hidden.jsonl — bench only. NEVER taught, NEVER calibrated, NEVER
16
+ # used for derivation or model selection.
17
+ # A MANIFEST.json records row counts, label distributions and sha256 per
18
+ # file so any later run can prove the splits were not touched.
19
+ #
20
+ # Deterministic: seeded per-row RNG (seed, domain, index); re-running with
21
+ # the same seed reproduces every file byte-for-byte.
22
+ #
23
+ # Usage: python3 tools/gen_corpus.py [--seed 20260927] [--out-dir data/big]
24
+ # ============================================================================
25
+ import argparse
26
+ import hashlib
27
+ import json
28
+ import os
29
+ import random
30
+ import sys
31
+
32
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
33
+ import corpus_pools as pools
34
+
35
+ SEED = 20260927
36
+
37
+ # verbatim question schemas from the seed data (single-line JSON)
38
+ Q_TICKETS = r'{"department":{"type":"choice","instructions":"Which team should handle this","criteria":{"billing":"payment or subscription issues","technical":"bugs or integration problems","sales":"pricing or account questions"}},"frustration":{"type":"score","instructions":"How frustrated the customer appears","criteria":["calm just stating facts","frustrated but civil","very angry strong language"]},"is_urgent":{"type":"noul","instructions":"the message conveys urgency or time sensitivity"}}'
39
+ Q_GUARD = r'{"irreversible":{"type":"noul","instructions":"the command is irreversible or destructive"},"off_task":{"type":"noul","instructions":"the command is off task and unrelated to the goal"},"scope":{"type":"choice","instructions":"what does the command touch","criteria":{"none":"no changes at all","read":"only reads lists shows","write":"modifies project files or data","global":"system wide destructive or irreversible"}}}'
40
+ Q_GAME = r'{"action":{"type":"choice","instructions":"What should the bot do next","criteria":{"flee":"run away escape avoid danger retreat safe","fight":"attack combat weapon sword strike","dig_in":"hide wait build shelter fortify safe"}}}'
41
+
42
+ TICKETS_QS = json.loads(Q_TICKETS)
43
+ GUARD_QS = json.loads(Q_GUARD)
44
+ GAME_QS = json.loads(Q_GAME)
45
+
46
+
47
+ def first_label(labels):
48
+ return labels[sorted(labels.keys())[0]]
49
+
50
+
51
+ def compose_tickets_en(i, rng):
52
+ intents = sorted(pools.TICKETS_INTENT.keys())
53
+ intent = intents[i % len(intents)]
54
+ fr = (i // len(intents)) % 3
55
+ ur = (i // (3 * len(intents))) % 2 == 1
56
+ state = pools.tickets_state(intent, fr, ur, rng)
57
+ return state, TICKETS_QS, {"department": intent, "frustration": str(fr),
58
+ "is_urgent": "true" if ur else "false"}
59
+
60
+
61
+ def compose_guard(i, rng):
62
+ state, labels = pools.guard_state(rng)
63
+ return state, GUARD_QS, labels
64
+
65
+
66
+ def compose_game(i, rng):
67
+ actions = sorted(pools.GAME_FEATURES.keys())
68
+ action = actions[i % len(actions)]
69
+ return pools.game_state(action, rng), GAME_QS, {"action": action}
70
+
71
+
72
+ def compose_tickets_ml(lang, i, rng):
73
+ intents = sorted(pools.TICKETS_ML_INTENT[lang].keys())
74
+ intent = intents[i % len(intents)]
75
+ fr = (i // len(intents)) % 3
76
+ ur = (i // (3 * len(intents))) % 2 == 1
77
+ state = pools.ml_state(lang, intent, fr, ur, rng)
78
+ return state, TICKETS_QS, {"department": intent, "frustration": str(fr),
79
+ "is_urgent": "true" if ur else "false"}
80
+
81
+
82
+ def make_rows(name, n, composer, seed):
83
+ """Compose n UNIQUE rows (dedup by state text; deterministic retries)."""
84
+ rows, seen, dups = [], set(), 0
85
+ i = 0
86
+ while len(rows) < n:
87
+ rng = random.Random(f"{seed}:{name}:{i}")
88
+ state, qs, labels = composer(i, rng)
89
+ i += 1
90
+ if state in seen:
91
+ dups += 1
92
+ if dups > n * 3:
93
+ sys.exit(f"gen_corpus: {name}: vocabulary exhausted at {len(rows)} rows")
94
+ continue
95
+ seen.add(state)
96
+ rows.append({"state": state, "questions": qs, "labels": labels})
97
+ return rows, dups
98
+
99
+
100
+ def split_70_15_15(rows, seed):
101
+ """Stratified 70/15/15 by first label (sorted-key order, same convention
102
+ as bench.hpp first_label). Per stratum: seeded shuffle, round(0.15) to
103
+ cal and hidden (min 1 when the stratum has >=3 rows), train keeps the rest."""
104
+ groups = {}
105
+ for idx, r in enumerate(rows):
106
+ groups.setdefault(first_label(r["labels"]), []).append(idx)
107
+ cal_idx, hidden_idx = set(), set()
108
+ for key in sorted(groups.keys()):
109
+ idxs = list(groups[key])
110
+ rng = random.Random(f"{seed}:split:{key}")
111
+ rng.shuffle(idxs)
112
+ n = len(idxs)
113
+ n_cal = round(n * 0.15)
114
+ n_hid = round(n * 0.15)
115
+ if n >= 3:
116
+ n_cal = max(1, n_cal)
117
+ n_hid = max(1, n_hid)
118
+ if n - n_cal - n_hid < 1:
119
+ n_cal = max(0, (n - 1) // 2)
120
+ n_hid = n - 1 - n_cal
121
+ cal_idx.update(idxs[:n_cal])
122
+ hidden_idx.update(idxs[n_cal:n_cal + n_hid])
123
+ train = [r for i, r in enumerate(rows) if i not in cal_idx and i not in hidden_idx]
124
+ cal = [r for i, r in enumerate(rows) if i in cal_idx]
125
+ hidden = [r for i, r in enumerate(rows) if i in hidden_idx]
126
+ return train, cal, hidden
127
+
128
+
129
+ def dist(rows):
130
+ d = {}
131
+ for r in rows:
132
+ k = first_label(r["labels"])
133
+ d[k] = d.get(k, 0) + 1
134
+ return dict(sorted(d.items()))
135
+
136
+
137
+ def sha256_of(path):
138
+ h = hashlib.sha256()
139
+ with open(path, "rb") as fh:
140
+ for chunk in iter(lambda: fh.read(65536), b""):
141
+ h.update(chunk)
142
+ return h.hexdigest()
143
+
144
+
145
+ def write_jsonl(path, rows):
146
+ with open(path, "w", encoding="utf-8") as fh:
147
+ for r in rows:
148
+ fh.write(json.dumps(r, ensure_ascii=False) + "\n")
149
+
150
+
151
+ def main():
152
+ ap = argparse.ArgumentParser(description="SyFox v3 corpus generator (70/15/15)")
153
+ ap.add_argument("--seed", type=int, default=SEED)
154
+ ap.add_argument("--out-dir", default=os.path.join(
155
+ os.path.dirname(os.path.abspath(__file__)), "..", "data", "big"))
156
+ ap.add_argument("--tickets", type=int, default=12000)
157
+ ap.add_argument("--guard", type=int, default=8000)
158
+ ap.add_argument("--game", type=int, default=8000)
159
+ ap.add_argument("--ml", type=int, default=3600,
160
+ help="rows per language for tickets_bn/hi/ru (15%% >= 500 -> >=3334)")
161
+ args = ap.parse_args()
162
+ os.makedirs(args.out_dir, exist_ok=True)
163
+
164
+ jobs = [
165
+ ("tickets_en", args.tickets, compose_tickets_en),
166
+ ("guard", args.guard, compose_guard),
167
+ ("game", args.game, compose_game),
168
+ ("tickets_bn", args.ml, lambda i, rng: compose_tickets_ml("bn", i, rng)),
169
+ ("tickets_hi", args.ml, lambda i, rng: compose_tickets_ml("hi", i, rng)),
170
+ ("tickets_ru", args.ml, lambda i, rng: compose_tickets_ml("ru", i, rng)),
171
+ ]
172
+
173
+ manifest = {
174
+ "generator": "tools/gen_corpus.py",
175
+ "seed": args.seed,
176
+ "schema": "state/questions/labels (house format, unchanged)",
177
+ "splits": {"train": 0.70, "cal": 0.15, "hidden": 0.15},
178
+ "firewall": {
179
+ "train": "learnable (syfox learn)",
180
+ "cal": "calibration only (syfox calibrate); never learned from",
181
+ "hidden": "bench only; NEVER taught, calibrated, derived or used "
182
+ "for model selection (enforced in core/firewall.hpp)",
183
+ },
184
+ "files": {},
185
+ }
186
+
187
+ for name, n, composer in jobs:
188
+ rows, dups = make_rows(name, n, composer, args.seed)
189
+ train, cal, hidden = split_70_15_15(rows, args.seed)
190
+ counts = {}
191
+ for tag, part in (("train", train), ("cal", cal), ("hidden", hidden)):
192
+ path = os.path.join(args.out_dir, f"{name}_{tag}.jsonl")
193
+ write_jsonl(path, part)
194
+ counts[tag] = len(part)
195
+ manifest["files"][os.path.basename(path)] = {
196
+ "rows": len(part),
197
+ "label_dist": dist(part),
198
+ "sha256": sha256_of(path),
199
+ "role": tag,
200
+ }
201
+ print(f"{name}: {len(rows)} unique rows (dedup skipped {dups}) -> "
202
+ f"train {counts['train']} / cal {counts['cal']} / hidden {counts['hidden']}")
203
+ print(f" train dist {dist(train)}")
204
+
205
+ mpath = os.path.join(args.out_dir, "MANIFEST.json")
206
+ with open(mpath, "w", encoding="utf-8") as fh:
207
+ json.dump(manifest, fh, ensure_ascii=False, indent=1, sort_keys=True)
208
+ fh.write("\n")
209
+ total = sum(f["rows"] for f in manifest["files"].values())
210
+ print(f"manifest: {mpath} ({len(manifest['files'])} files, {total} rows total)")
211
+
212
+
213
+ if __name__ == "__main__":
214
+ main()
engine/tools/gen_paraphrases.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # ============================================================================
3
+ # SyFox — gen_paraphrases.py (P3, v2.1)
4
+ # Data augmentation for generalization: for each TRAIN state, generate up to
5
+ # 5 paraphrased variants and write them as extra lessons. The fabric learns
6
+ # the same outcome from differently-worded experiences, so the energy routes
7
+ # no longer depend on one exact surface form.
8
+ #
9
+ # Hard rules (honesty of the eval):
10
+ # * TRAIN ONLY — the script REFUSES any path containing "heldout". Held-out
11
+ # rows must stay unseen by the fabric, directly or through paraphrase.
12
+ # * LABEL-SAFE — words are only REPLACED using the single-word synonym
13
+ # table (data/synonyms.txt, shared with core/normalize.hpp), never
14
+ # inserted; inserted fillers are neutral politeness only. Swapping
15
+ # "urgent"->"immediately" keeps is_urgent=true true; a row that is not
16
+ # urgent never gains an urgency word.
17
+ # * DETERMINISTIC — a per-row seeded RNG; same input file -> same output.
18
+ # * The core stays physics-only: this is OUTSIDE the substrate, a tool
19
+ # that writes lesson files. No neural net anywhere.
20
+ #
21
+ # Variant strategies (cycled per row, up to 5 per state):
22
+ # 1 clause reorder — swap the first two sentence segments
23
+ # 2 filler prefix — neutral lead-in ("please help:", "i think", ...)
24
+ # 3 filler suffix — neutral sign-off ("thanks.", "please advise.", ...)
25
+ # 4 combo — synonym swap + reorder (swap ALONE is deliberately
26
+ # excluded: a table word folds back to the same stem,
27
+ # so a synonym-only variant normalizes to an IDENTICAL
28
+ # token stream = pure repetition. Measured on the
29
+ # tickets heldout split: repetition-heavy augmentation
30
+ # collapsed heldout accuracy 1.00 -> 0.33 (intern mass
31
+ # grows linearly and damps injection by 1/sqrt(mass)),
32
+ # so every variant here carries NEW token content.)
33
+ # 5 fallback — a second filler prefix (only if a strategy above
34
+ # produced no change)
35
+ #
36
+ # Usage:
37
+ # python3 tools/gen_paraphrases.py # all data/*_train.jsonl
38
+ # python3 tools/gen_paraphrases.py --only tickets
39
+ # ============================================================================
40
+ import argparse
41
+ import json
42
+ import os
43
+ import random
44
+ import re
45
+ import sys
46
+
47
+ SEED = 20260926
48
+ DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")
49
+ SYNONYMS = os.path.join(DATA, "synonyms.txt")
50
+
51
+ PREFIXES = ["please help:", "i think", "quick note:", "just to add,", "hey,"]
52
+ SUFFIXES = ["thanks.", "thank you.", "please advise.", "appreciate it.", "let me know."]
53
+
54
+ WORD_RE = re.compile(r"[A-Za-z]+")
55
+
56
+
57
+ def load_synonyms(path):
58
+ """canonical -> [alternates]; the map is symmetric (word <-> alternates)."""
59
+ swap = {}
60
+ if not os.path.exists(path):
61
+ return swap
62
+ with open(path, encoding="utf-8") as fh:
63
+ for line in fh:
64
+ line = line.strip()
65
+ if not line or line.startswith("#") or ":" not in line:
66
+ continue
67
+ canon, rest = line.split(":", 1)
68
+ canon = canon.strip().lower()
69
+ variants = [v.strip().lower() for v in rest.split(",") if v.strip()]
70
+ group = [canon] + variants
71
+ for w in group:
72
+ others = [x for x in group if x != w]
73
+ swap.setdefault(w, [])
74
+ for o in others:
75
+ if o not in swap[w]:
76
+ swap[w].append(o)
77
+ return swap
78
+
79
+
80
+ def synonym_swap(text, swap, rng):
81
+ """Replace the FIRST table word found with one of its alternates."""
82
+ words = list(WORD_RE.finditer(text))
83
+ candidates = [m for m in words if m.group(0).lower() in swap]
84
+ if not candidates:
85
+ return None
86
+ m = candidates[0]
87
+ alt = swap[m.group(0).lower()][rng.randrange(len(swap[m.group(0).lower()]))]
88
+ return text[:m.start()] + alt + text[m.end():]
89
+
90
+
91
+ SENT_SPLIT = re.compile(r"(?<=[.!?])\s+")
92
+ CLAUSE_SPLIT = re.compile(r",\s+|\s+\band\b\s+|\s+\bbut\b\s+")
93
+
94
+
95
+ def clause_reorder(text, swap, rng):
96
+ """Swap the first two segments (sentences, else comma/and/but clauses)."""
97
+ parts = SENT_SPLIT.split(text.strip())
98
+ if len(parts) >= 2:
99
+ parts[0], parts[1] = parts[1], parts[0]
100
+ return " ".join(parts)
101
+ parts = CLAUSE_SPLIT.split(text.strip())
102
+ if parts and len(parts) >= 4: # split with captures: keep groups intact
103
+ return text # capture-group splitting: too fiddly, skip
104
+ if len(parts) >= 2:
105
+ parts[0], parts[1] = parts[1], parts[0]
106
+ return ", ".join(parts)
107
+ return None
108
+
109
+
110
+ def filler_prefix(text, swap, rng):
111
+ return PREFIXES[rng.randrange(len(PREFIXES))] + " " + text
112
+
113
+
114
+ def filler_suffix(text, swap, rng):
115
+ return text + " " + SUFFIXES[rng.randrange(len(SUFFIXES))]
116
+
117
+
118
+ def combo(text, swap, rng):
119
+ out = synonym_swap(text, swap, rng)
120
+ out = clause_reorder(out or text, swap, rng)
121
+ if out:
122
+ return out
123
+ out = filler_prefix(text, swap, rng)
124
+ return out + " " + SUFFIXES[rng.randrange(len(SUFFIXES))]
125
+
126
+
127
+ STRATEGIES = [clause_reorder, filler_prefix, filler_suffix, combo]
128
+ STRATEGY_NAMES = ["clause_reorder", "filler_prefix", "filler_suffix", "combo"]
129
+
130
+
131
+ def paraphrase_row(row, swap, rng, per_state):
132
+ seen = {row["state"]}
133
+ out = []
134
+ order = list(range(len(STRATEGIES)))
135
+ rng.shuffle(order) # per-row strategy order, still seeded
136
+ attempts = 0
137
+ while len(out) < per_state and attempts < per_state * 4:
138
+ si = attempts % len(STRATEGIES)
139
+ strategy = STRATEGIES[order[si]]
140
+ text = strategy(row["state"], swap, rng)
141
+ attempts += 1
142
+ if not text or text in seen:
143
+ # guaranteed-change fallback: neutral prefix (always differs)
144
+ text = PREFIXES[(attempts + len(out)) % len(PREFIXES)] + " " + row["state"]
145
+ if text in seen:
146
+ continue
147
+ seen.add(text)
148
+ variant = dict(row)
149
+ variant["state"] = text
150
+ variant["paraphrase_of"] = row["state"]
151
+ variant["strategy"] = STRATEGY_NAMES[order[si]]
152
+ out.append(variant)
153
+ return out
154
+
155
+
156
+ def main():
157
+ ap = argparse.ArgumentParser(description="SyFox train-only paraphrase augmenter")
158
+ ap.add_argument("--data-dir", default=DATA)
159
+ ap.add_argument("--synonyms", default=SYNONYMS)
160
+ ap.add_argument("--per-state", type=int, default=5)
161
+ ap.add_argument("--seed", type=int, default=SEED)
162
+ ap.add_argument("--only", default=None, help="substring filter on file name")
163
+ args = ap.parse_args()
164
+
165
+ if "heldout" in args.synonyms:
166
+ sys.exit("gen_paraphrases: refusing heldout synonyms path")
167
+ swap = load_synonyms(args.synonyms)
168
+ if not swap:
169
+ sys.exit(f"gen_paraphrases: no synonym table at {args.synonyms}")
170
+
171
+ files = sorted(f for f in os.listdir(args.data_dir)
172
+ if f.endswith("_train.jsonl")
173
+ and (args.only is None or args.only in f))
174
+ if not files:
175
+ sys.exit("gen_paraphrases: no *_train.jsonl files matched")
176
+ for f in files:
177
+ src = os.path.join(args.data_dir, f)
178
+ if "heldout" in src:
179
+ sys.exit(f"gen_paraphrases: refusing heldout input {src}")
180
+ with open(src, encoding="utf-8") as fh:
181
+ rows = [json.loads(line) for line in fh if line.strip()]
182
+ out_path = src.replace("_train.jsonl", "_paraphrased.jsonl")
183
+ total = 0
184
+ with open(out_path, "w", encoding="utf-8") as out:
185
+ for i, row in enumerate(rows):
186
+ rng = random.Random(f"{args.seed}:{f}:{i}")
187
+ for v in paraphrase_row(row, swap, rng, args.per_state):
188
+ out.write(json.dumps(v, ensure_ascii=False) + "\n")
189
+ total += 1
190
+ print(f"{f}: {len(rows)} states -> {total} paraphrased lessons -> "
191
+ f"{os.path.basename(out_path)}")
192
+
193
+
194
+ if __name__ == "__main__":
195
+ main()
engine/tools/gen_variants.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # ============================================================================
3
+ # SyFox — gen_variants.py (v2.2)
4
+ # Variant/paraphrase generation for mass-guarded re-teaching.
5
+ #
6
+ # Physics contract (measured, v2.1 + v2.2):
7
+ # * v2.1 measured raw re-teaching of near-duplicates REGRESSING held-out
8
+ # accuracy (tickets 1.000 -> 0.500): intern() counts mass linearly and
9
+ # injection damps by 1/sqrt(mass), so re-exposed surface forms re-weight
10
+ # the field toward the training surface. That artifact is now fixed at
11
+ # the ENGINE boundary: `syfox learn --augment` skips intern() for
12
+ # concepts already in the vocabulary, so a variant lesson lays and
13
+ # strengthens LANES only — coverage grows, acoustic mass does not.
14
+ # * This generator therefore never needs to hold back: it produces the
15
+ # variants; the mass guard makes them safe. The A/B stays reproducible
16
+ # (train-only vs train+variants, `make models-vast`).
17
+ #
18
+ # Variant ops per taught state (5-10 variants, deterministic — seeded by
19
+ # the row index, never by wall-clock):
20
+ # 1. synonym swap — 1-2 swappable words replaced via data/synonyms.txt
21
+ # 2. clause rotation — comma/and-segments rotated left by one
22
+ # 3. adjacent reorder — two adjacent words swapped (mid-sentence)
23
+ # 4. filler addition — "Please", "I think", "Asap," style fillers
24
+ # 5. combo — reorder + filler + synonym in one
25
+ #
26
+ # Discipline (hard-coded, not optional):
27
+ # * refuses *_heldout.jsonl paths — eval data is never transformed,
28
+ # never generated from, never taught from;
29
+ # * input must be a *_train.jsonl file; output is <stem>_expanded.jsonl;
30
+ # * labels and question schemas are copied verbatim from the source row.
31
+ # ============================================================================
32
+ import json
33
+ import random
34
+ import re
35
+ import sys
36
+ from pathlib import Path
37
+
38
+ SEED = 20260927
39
+ WORD_RE = re.compile(r"[A-Za-z]+")
40
+ CLAUSE_RE = re.compile(r",\s+|\s+and\s+|\.\s+")
41
+
42
+
43
+ def load_synonyms(path: Path) -> dict:
44
+ """canonical -> [variants]; used both directions for surface swaps."""
45
+ table = {}
46
+ if not path.exists():
47
+ return table
48
+ for line in path.read_text(encoding="utf-8").splitlines():
49
+ line = line.strip()
50
+ if not line or line.startswith("#") or ":" not in line:
51
+ continue
52
+ canon, rest = line.split(":", 1)
53
+ variants = [v.strip().lower() for v in rest.split(",") if v.strip()]
54
+ table[canon.strip().lower()] = variants
55
+ return table
56
+
57
+
58
+ def swap_synonyms(text: str, table: dict, rng: random.Random, n_swaps: int) -> str:
59
+ """Replace up to n_swaps swappable words (canonical->variant or variant->canonical)."""
60
+ words = text.split(" ")
61
+ swappable = []
62
+ for i, w in enumerate(words):
63
+ lw = re.sub(r"[^a-z]", "", w.lower())
64
+ for canon, variants in table.items():
65
+ if lw == canon or lw in variants:
66
+ swappable.append((i, canon, variants))
67
+ break
68
+ if not swappable:
69
+ return text
70
+ rng.shuffle(swappable)
71
+ for i, canon, variants in swappable[:n_swaps]:
72
+ choice = rng.choice(variants + [canon])
73
+ words[i] = re.sub(r"[A-Za-z]+", choice, words[i], count=1)
74
+ return " ".join(words)
75
+
76
+
77
+ def rotate_clauses(text: str) -> str:
78
+ parts = CLAUSE_RE.split(text)
79
+ if len(parts) < 2:
80
+ return text
81
+ parts = parts[1:] + parts[:1]
82
+ return ", ".join(p.strip(" .") for p in parts) + "."
83
+
84
+
85
+ def swap_adjacent(text: str, rng: random.Random) -> str:
86
+ words = text.split(" ")
87
+ if len(words) < 4:
88
+ return text
89
+ lo, hi = 1, len(words) - 2 # never the first/last word
90
+ i = rng.randint(lo, hi - 1)
91
+ words[i], words[i + 1] = words[i + 1], words[i]
92
+ return " ".join(words)
93
+
94
+
95
+ FILLERS_PRE = ["Please help:", "I think", "Quick one,", "Hey,"]
96
+ FILLERS_POST = ["Please.", "Thanks.", "Asap please.", "Appreciate it."]
97
+
98
+
99
+ def add_filler(text: str, rng: random.Random) -> str:
100
+ if rng.random() < 0.5:
101
+ return f"{rng.choice(FILLERS_PRE)} {text[0].lower()}{text[1:]}"
102
+ return f"{text} {rng.choice(FILLERS_POST)}"
103
+
104
+
105
+ def variants_for(state: str, table: dict, rng: random.Random, count: int,
106
+ with_fillers: bool) -> list:
107
+ out, seen = [], {state.lower()}
108
+ ops = [
109
+ lambda s: swap_synonyms(s, table, rng, 1),
110
+ lambda s: swap_synonyms(s, table, rng, 2),
111
+ rotate_clauses,
112
+ lambda s: swap_adjacent(s, rng),
113
+ ]
114
+ if with_fillers:
115
+ ops += [lambda s: add_filler(swap_adjacent(s, rng), rng),
116
+ lambda s: add_filler(swap_synonyms(s, table, rng, 1), rng)]
117
+ for _ in range(count * 4): # retry budget for dedup
118
+ if len(out) >= count:
119
+ break
120
+ op = rng.choice(ops)
121
+ v = op(state)
122
+ if v.lower() in seen or not v.strip():
123
+ continue
124
+ seen.add(v.lower())
125
+ out.append(v)
126
+ return out
127
+
128
+
129
+ def main() -> int:
130
+ args = [a for a in sys.argv[1:] if not a.startswith("--")]
131
+ with_fillers = "--full" in sys.argv
132
+ if not args:
133
+ print("usage: gen_variants.py FILE_train.jsonl [--full] (refuses *_heldout*)")
134
+ return 2
135
+ src = Path(args[0])
136
+ if "heldout" in src.name:
137
+ print(f"REFUSED: {src.name} is held-out eval data; never transformed, never taught from")
138
+ return 2
139
+ if not src.name.endswith("_train.jsonl"):
140
+ print(f"REFUSED: {src.name} must be a *_train.jsonl file (train-side discipline)")
141
+ return 2
142
+ count = 8 if not with_fillers else 10
143
+ for a in sys.argv[1:]:
144
+ if a.startswith("--count="):
145
+ count = int(a.split("=", 1)[1])
146
+
147
+ table = load_synonyms(src.parent / "synonyms.txt")
148
+ stem = src.name.replace("_train.jsonl", "")
149
+ out_path = src.parent / (f"{stem}_expanded_full.jsonl" if with_fillers
150
+ else f"{stem}_expanded.jsonl")
151
+ rows = [json.loads(l) for l in src.read_text(encoding="utf-8").splitlines() if l.strip()]
152
+
153
+ written = 0
154
+ with out_path.open("w", encoding="utf-8") as f:
155
+ for idx, row in enumerate(rows):
156
+ rng = random.Random(SEED + idx) # deterministic per row
157
+ state = row.get("state", "")
158
+ for v in variants_for(state, table, rng, count, with_fillers):
159
+ f.write(json.dumps({"state": v, "questions": row["questions"],
160
+ "labels": row["labels"]}, ensure_ascii=False) + "\n")
161
+ written += 1
162
+ print(f"{src.name}: {len(rows)} taught states -> {written} variants -> {out_path.name}"
163
+ f" ({'full' if with_fillers else 'reorder+synonym'} mode)")
164
+ return 0
165
+
166
+
167
+ if __name__ == "__main__":
168
+ sys.exit(main())
engine/tools/giant_bench.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Giant-model manual benchmark: per-domain hidden scoring + router +
3
+ end-to-end + handcrafted probes, through the ctypes bridge.
4
+
5
+ Everything is measured with energy_norm ON (mandatory at corpus scale —
6
+ v3.1.0 finding). Router accuracy: the 'domain' question asked on every
7
+ hidden row. End-to-end: router correct AND class correct in one decide call
8
+ (the bridge returns answers for every question in one shot).
9
+
10
+ Usage:
11
+ python3 tools/giant_bench.py --model-slug giant-latin --domains \
12
+ tickets_en,bank77,sms,clinc,... [--limit N] [--dump out.jsonl]
13
+ python3 tools/giant_bench.py --probes --model-slug giant-latin
14
+ """
15
+ import argparse
16
+ import json
17
+ import os
18
+ import sys
19
+ import time
20
+ from pathlib import Path
21
+
22
+ ROOT = Path(__file__).resolve().parent.parent
23
+ sys.path.insert(0, str(ROOT / "server"))
24
+ from syfox_bridge import SyFoxEngine # noqa: E402
25
+
26
+ GIANT = Path(os.environ.get("GIANT_DIR", str(ROOT / "data" / "giant")))
27
+
28
+
29
+ def rank_of(gold: str, probs: dict) -> int:
30
+ order = sorted(probs.items(), key=lambda kv: -kv[1])
31
+ for i, (k, _) in enumerate(order, 1):
32
+ if k == gold:
33
+ return i
34
+ return len(order) + 1
35
+
36
+
37
+ def load_schemas() -> dict:
38
+ return json.load(open(GIANT / "schemas.json"))
39
+
40
+
41
+ def build_questions(r: dict, schemas: dict) -> dict:
42
+ """Full-schema rows pass through; schema-free rows (state/domain/labels,
43
+ as shipped in the HF repo) get their questions rebuilt from schemas."""
44
+ if "questions" in r:
45
+ return r["questions"]
46
+ dom = r["domain"]
47
+ spec = schemas["domains"][dom]
48
+ if spec.get("type") == "noul_multi":
49
+ return r["questions"] # noul keeps its questions inline
50
+ rq = {"type": "choice", "instructions": "",
51
+ "criteria": schemas["domains"]["_router"]["criteria"]}
52
+ cq = {"type": "choice", "instructions": "", "criteria": spec["criteria"]}
53
+ return {"domain": rq, spec["qkey"]: cq}
54
+
55
+
56
+ def hidden_path(dom: str) -> Path:
57
+ for cand in (GIANT / f"{dom}_hidden.jsonl", GIANT / "eval" / f"{dom}_hidden.jsonl"):
58
+ if cand.exists():
59
+ return cand
60
+ return GIANT / f"{dom}_hidden.jsonl"
61
+
62
+
63
+ def run_domain(eng: SyFoxEngine, dom: str, limit: int, dump: list,
64
+ schemas: dict) -> dict:
65
+ rows = [json.loads(l) for l in open(hidden_path(dom))]
66
+ if limit:
67
+ rows = rows[:limit]
68
+ rows = [{**r, "questions": build_questions(r, schemas)} for r in rows]
69
+ qkeys = [k for k in rows[0]["questions"] if k != "domain"]
70
+ qkey = qkeys[0]
71
+ rt_ok = cl_ok = e2e_ok = defer = 0
72
+ n = 0
73
+ t0 = time.time()
74
+ for i, r in enumerate(rows):
75
+ answers, usage, _ = eng.decide(r["state"], r["questions"],
76
+ {"energy_norm": True})
77
+ n += 1
78
+ da = answers.get("domain", {})
79
+ if da.get("deferred"):
80
+ defer += 1
81
+ continue
82
+ rt_hit = da.get("choice") == r["labels"]["domain"]
83
+ rt_ok += rt_hit
84
+ ca = answers.get(qkey, {})
85
+ gold = r["labels"].get(qkey)
86
+ if ca.get("deferred"):
87
+ continue
88
+ if gold == "true" or gold == "false":
89
+ cl_hit = (ca.get("choice") == gold)
90
+ else:
91
+ cl_hit = (ca.get("choice") == gold)
92
+ cl_ok += cl_hit
93
+ e2e_ok += (rt_hit and cl_hit)
94
+ if dump is not None:
95
+ probs = ca.get("probabilities", {})
96
+ top = sorted(probs.items(), key=lambda kv: -kv[1])
97
+ dump.append(json.dumps({
98
+ "domain": dom, "i": i, "gold_router": r["labels"]["domain"],
99
+ "pred_router": da.get("choice"),
100
+ "gold": gold, "pred": ca.get("choice"),
101
+ "correct": bool(cl_hit), "conf": ca.get("confidence", 0),
102
+ "gold_rank": rank_of(gold, probs) if probs else 0,
103
+ "margin": round(top[0][1] - (top[1][1] if len(top) > 1 else 0),
104
+ 5) if top else 0,
105
+ }, ensure_ascii=False))
106
+ if (i + 1) % 1000 == 0:
107
+ print(f" {dom}: {i + 1}/{len(rows)} "
108
+ f"({time.time() - t0:.0f}s)", flush=True)
109
+ secs = time.time() - t0
110
+ return {"domain": dom, "n": n, "router_acc": rt_ok / n,
111
+ "class_acc": cl_ok / max(1, n - defer),
112
+ "e2e_acc": e2e_ok / n, "deferred": defer, "secs": round(secs, 1),
113
+ "ms_per_row": round(1000 * secs / max(1, n), 2),
114
+ "qkey": qkey,
115
+ "note": "noul_multi" if qkey == "irreversible" else ""}
116
+
117
+
118
+ def run_probes(model_slug: str) -> None:
119
+ eng = SyFoxEngine(f"model-{model_slug}")
120
+ schemas = json.load(open(GIANT / "schemas.json"))
121
+ inv = {d: {v: k for k, v in schemas["domains"][d]["classes"].items()}
122
+ for d in schemas["domains"]
123
+ if schemas["domains"][d].get("classes")}
124
+ rows = [json.loads(l) for l in open(GIANT / "probes.jsonl")]
125
+ hits_r = hits_c = scored = 0
126
+ print(f"{'id':5s} {'domain':11s} {'router':7s} {'class':7s} "
127
+ f"{'conf':>5s} state")
128
+ for p in rows:
129
+ answers, _, _ = eng.decide(p["state"], p["questions"],
130
+ {"energy_norm": True})
131
+ da = answers.get("domain", {})
132
+ dom = p["domain"]
133
+ qkey = schemas["domains"][dom]["qkey"]
134
+ ca = answers.get(qkey, {})
135
+ r_ok = (not da.get("deferred")
136
+ and da.get("choice") == p["expected_router"])
137
+ hits_r += r_ok
138
+ line = f"{p['id']:5s} {dom:11s} {'ok' if r_ok else 'MISS':7s}"
139
+ if p["expected_class"] is None:
140
+ d = ca.get("deferred", da.get("deferred", False))
141
+ line += (f" {'defer' if d else 'ANSWERED':7s} "
142
+ f"{ca.get('confidence', 0):5.3f} {p['state'][:48]}")
143
+ else:
144
+ scored += 1
145
+ c_ok = (not ca.get("deferred")
146
+ and ca.get("choice") == p["expected_class"])
147
+ hits_c += c_ok
148
+ name = schemas["domains"][dom]["classes"].get(
149
+ ca.get("choice", ""), ca.get("choice", "?"))
150
+ line += (f" {'ok' if c_ok else 'MISS':7s} "
151
+ f"{ca.get('confidence', 0):5.3f} -> {name[:26]}")
152
+ print(line, flush=True)
153
+ print(f"\nrouter {hits_r}/{len(rows)} = {hits_r/len(rows):.3f} "
154
+ f"class {hits_c}/{scored} = {hits_c/max(1, scored):.3f} "
155
+ f"(OOD probes: answered-instead-of-deferred counted as MISS on router)")
156
+
157
+
158
+ def main() -> None:
159
+ ap = argparse.ArgumentParser()
160
+ ap.add_argument("--model-slug", default="giant-latin",
161
+ help="model dir suffix, e.g. giant-latin")
162
+ ap.add_argument("--domains",
163
+ default="tickets_en,game,guard,bank77,sms,clinc,enron,"
164
+ "emotion,hate,agnews,polarity,dbpedia,boolq")
165
+ ap.add_argument("--limit", type=int, default=0)
166
+ ap.add_argument("--probes", action="store_true")
167
+ ap.add_argument("--dump", default="")
168
+ args = ap.parse_args()
169
+
170
+ if args.probes:
171
+ run_probes(args.model_slug)
172
+ return
173
+
174
+ eng = SyFoxEngine(f"model-{args.model_slug}")
175
+ info = eng.info()
176
+ schemas = load_schemas()
177
+ print(f"model-{args.model_slug}: {info.get('nodes')} nodes / "
178
+ f"{info.get('lanes')} lanes, energy_norm on")
179
+ dump = [] if args.dump else None
180
+ results = []
181
+ for dom in args.domains.split(","):
182
+ dom = dom.strip()
183
+ f = hidden_path(dom)
184
+ if not f.exists():
185
+ print(f"skip {dom} (no hidden file)")
186
+ continue
187
+ r = run_domain(eng, dom, args.limit, dump, schemas)
188
+ results.append(r)
189
+ print(f"{r['domain']:11s} n={r['n']:5d} router={r['router_acc']:.3f} "
190
+ f"class={r['class_acc']:.3f} e2e={r['e2e_acc']:.3f} "
191
+ f"defer={r['deferred']:4d} ({r['ms_per_row']} ms/row)"
192
+ f"{' [' + r['note'] + ']' if r['note'] else ''}", flush=True)
193
+
194
+ tot_n = sum(r["n"] for r in results)
195
+ if tot_n:
196
+ print(f"\nTOTAL rows={tot_n} "
197
+ f"router={sum(r['router_acc']*r['n'] for r in results)/tot_n:.3f} "
198
+ f"class={sum(r['class_acc']*(r['n']-r['deferred']) for r in results)/tot_n:.3f} "
199
+ f"e2e={sum(r['e2e_acc']*r['n'] for r in results)/tot_n:.3f}")
200
+ if args.dump:
201
+ out = Path(args.dump)
202
+ out.write_text("\n".join(dump) + "\n")
203
+ print(f"per-row dump -> {out} ({len(dump)} rows)")
204
+ (GIANT / "bench_hidden_summary.json").write_text(
205
+ json.dumps(results, indent=1))
206
+
207
+
208
+ if __name__ == "__main__":
209
+ main()
engine/tools/giant_prepare.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build the giant-model training corpus from 16 real domains.
3
+
4
+ RCA fixes baked in (the point of this corpus):
5
+ Failure 2 (identical per-row instructions are hub pollution at learn)
6
+ -> instructions are EMPTY on every row of every domain.
7
+ Failure 3 (natural labels tokenize into shared hubs: "card", "true"...)
8
+ -> globally-unique opaque anchors per class (te00, ga00, gu00, c00..,
9
+ sm00, cl000...); no anchor token is shared across domains.
10
+ Failure 1 (sequential multi-domain training makes late domains weak)
11
+ -> domains are ROUND-ROBIN INTERLEAVED in the train file, so every
12
+ domain gets lessons in every region of the stream; 3-epoch
13
+ consolidation then strengthens rather than drowns.
14
+
15
+ Also emits: per-script calibration files, per-domain hidden eval files
16
+ (router + class questions per row), a handcrafted probe file, schemas.json
17
+ (anchors, class names, criteria) and MANIFEST.json (counts + SHA-256).
18
+
19
+ Hidden files carry "hidden" in their names -> the M1 firewall refuses them
20
+ for learn/calibrate. Data policy: every state string is verbatim dataset
21
+ text (truncation is the only edit). Criteria for pre-existing domains are
22
+ preserved verbatim (only keys remapped to anchors); criteria for the new HF
23
+ domains are mined from TRAIN rows only (log-ratio, top-20).
24
+ """
25
+ import hashlib
26
+ import json
27
+ import random
28
+ import sys
29
+ from collections import Counter, defaultdict
30
+ from pathlib import Path
31
+
32
+ ROOT = Path(__file__).resolve().parent.parent
33
+ sys.path.insert(0, str(ROOT / "tools"))
34
+ from bank77_prepare import mine_criteria # noqa: E402
35
+
36
+ GIANT = ROOT / "data" / "giant"
37
+ HF_RAW = ROOT / "data" / "hf_raw"
38
+ BIG = ROOT / "data" / "big"
39
+ SEED = 77
40
+
41
+ # domain -> question key + anchor prefix + class-name resolution
42
+ DOMAINS = {
43
+ "tickets_en": {"qkey": "department", "prefix": "te", "source": "big",
44
+ "router": "support billing sales technical"},
45
+ "tickets_bn": {"qkey": "department", "prefix": "tb", "source": "big",
46
+ "router": "support tickets bengali"},
47
+ "tickets_hi": {"qkey": "department", "prefix": "th", "source": "big",
48
+ "router": "support tickets hindi"},
49
+ "tickets_ru": {"qkey": "department", "prefix": "tr", "source": "big",
50
+ "router": "support tickets russian"},
51
+ "game": {"qkey": "action", "prefix": "ga", "source": "big",
52
+ "router": "game commands actions"},
53
+ "guard": {"qkey": "irreversible", "prefix": "gu", "source": "big",
54
+ "router": "safety destructive irreversible",
55
+ "keep_schema": True}, # noul: instructions are the probe carrier
56
+ "bank77": {"qkey": "intent", "prefix": "c", "source": "bank77",
57
+ "router": "banking cards payments"},
58
+ "sms": {"qkey": "intent", "prefix": "sm", "source": "sms",
59
+ "router": "text messages spam"},
60
+ "clinc": {"qkey": "intent", "prefix": "cl", "source": "hf",
61
+ "router": "assistant requests weather"},
62
+ "enron": {"qkey": "spam", "prefix": "en", "source": "hf",
63
+ "router": "email inbox messages"},
64
+ "emotion": {"qkey": "emotion", "prefix": "em", "source": "hf",
65
+ "router": "feelings emotions reactions"},
66
+ "hate": {"qkey": "speech", "prefix": "ha", "source": "hf",
67
+ "router": "social offensive posts"},
68
+ "agnews": {"qkey": "topic", "prefix": "ag", "source": "hf",
69
+ "router": "news headlines sports"},
70
+ "polarity": {"qkey": "sentiment", "prefix": "po", "source": "hf",
71
+ "router": "product reviews opinions"},
72
+ "dbpedia": {"qkey": "entity", "prefix": "db", "source": "hf",
73
+ "router": "encyclopedia entities topics"},
74
+ "boolq": {"qkey": "truth", "prefix": "bo", "source": "hf",
75
+ "router": "boolean question passage"},
76
+ }
77
+
78
+ CLASS_NAMES = {
79
+ "agnews": {"0": "world", "1": "sports", "2": "business", "3": "scitech"},
80
+ "emotion": {"0": "sadness", "1": "joy", "2": "love", "3": "anger",
81
+ "4": "fear", "5": "surprise"},
82
+ "polarity": {"0": "negative", "1": "positive"},
83
+ "hate": {"0": "hate", "1": "offensive", "2": "neither"},
84
+ "enron": {"0": "ham", "1": "spam"},
85
+ "boolq": {"False": "false", "True": "true"},
86
+ "dbpedia": {str(i): n for i, n in enumerate(
87
+ ["company", "educational_institution", "artist", "athlete",
88
+ "office_holder", "mean_of_transportation", "building",
89
+ "natural_place", "village", "animal", "plant", "album", "film",
90
+ "written_work"])},
91
+ }
92
+
93
+ TEXT_CAPS = {"enron": 400, "hate": 280, "agnews": 250, "polarity": 350,
94
+ "dbpedia": 250, "boolq": 350}
95
+ TRAIN_CAPS = {"clinc": 8000, "enron": 4000, "emotion": 4000, "hate": 4078,
96
+ "agnews": 4000, "polarity": 4000, "dbpedia": 4000, "boolq": 4000}
97
+ HIDDEN_CAPS = {"clinc": 4500, "enron": 2000, "emotion": 2000, "hate": 1500,
98
+ "agnews": 2000, "polarity": 2000, "dbpedia": 2000, "boolq": 1500}
99
+ CAL_CAPS = {"clinc": 3000, "enron": 800, "emotion": 700, "hate": 400,
100
+ "agnews": 400, "polarity": 400, "dbpedia": 400, "boolq": 500}
101
+ IMBALANCE_TRAIN_CAP = {"hate": {"1": 2500}} # offensive: real-world 78% share
102
+
103
+
104
+ def load_jsonl(p: Path) -> list:
105
+ return [json.loads(l) for l in open(p) if l.strip()]
106
+
107
+
108
+ def dump_jsonl(p: Path, rows: list) -> None:
109
+ p.write_text("\n".join(json.dumps(r, ensure_ascii=False) for r in rows) + "\n")
110
+
111
+
112
+ def sha256(p: Path) -> str:
113
+ return hashlib.sha256(p.read_bytes()).hexdigest()
114
+
115
+
116
+ def hf_load(dom: str, tag: str) -> list:
117
+ p = HF_RAW / f"{dom}_{tag}.json"
118
+ if not p.exists():
119
+ return []
120
+ return json.loads(p.read_text())
121
+
122
+
123
+ def hf_state(dom: str, r: dict) -> str:
124
+ t = " ".join(str(r["text"]).split())
125
+ cap = TEXT_CAPS.get(dom, 0)
126
+ return t[:cap] if cap else t
127
+
128
+
129
+ def stratified_take(rows: list, n: int, rng: random.Random) -> list:
130
+ """Deterministic stratified sample of n rows (as balanced as possible)."""
131
+ by = defaultdict(list)
132
+ for r in rows:
133
+ by[r["label"]].append(r)
134
+ for v in by.values():
135
+ rng.shuffle(v)
136
+ out, i = [], 0
137
+ while len(out) < n and any(by.values()):
138
+ for v in by.values():
139
+ if v:
140
+ out.append(v.pop())
141
+ if len(out) >= n:
142
+ break
143
+ i += 1
144
+ return out
145
+
146
+
147
+ def carve(dom: str, rows: list) -> dict:
148
+ """For domains without official cal/hidden: carve hidden + cal out."""
149
+ rng = random.Random(SEED)
150
+ by = defaultdict(list)
151
+ for r in rows:
152
+ by[r["label"]].append(r)
153
+ for v in by.values():
154
+ rng.shuffle(v)
155
+ hidden_n, cal_n = HIDDEN_CAPS.get(dom, 0), CAL_CAPS.get(dom, 0)
156
+ hidden, cal = [], []
157
+ for cls, v in by.items():
158
+ h = min(len(v), max(1, round(hidden_n * len(v) / len(rows))))
159
+ hidden.extend(v[:h])
160
+ c = min(len(v) - h, max(1, round(cal_n * len(v) / len(rows))))
161
+ cal.extend(v[h:h + c])
162
+ del v[:h + c]
163
+ train = [r for v in by.values() for r in v]
164
+ return {"train": train, "cal": cal, "hidden": hidden}
165
+
166
+
167
+ # --------------------------------------------------------------------------
168
+ # domain loading -> {"train": [...], "cal": [...], "hidden": [...]} with
169
+ # {"text", "label"} rows; labels are the DOMAIN's natural class names.
170
+
171
+ def norm_big(dom: str, split: str) -> list:
172
+ out = []
173
+ for r in load_jsonl(BIG / f"{dom}_{split}.jsonl"):
174
+ qk = next(iter(r["questions"]))
175
+ if r["state"].strip() and r["labels"].get(qk):
176
+ out.append({"text": r["state"], "label": r["labels"][qk],
177
+ "row": r})
178
+ return out
179
+
180
+
181
+ def norm_bank77(split: str) -> list:
182
+ fn = {"train": "bank77_train.jsonl", "cal": "bank77_cal_bare.jsonl",
183
+ "hidden": "bank77_hidden.jsonl"}[split]
184
+ out = []
185
+ for r in load_jsonl(ROOT / "data" / fn):
186
+ if r["state"].strip():
187
+ out.append({"text": r["state"], "label": r["labels"]["intent"],
188
+ "row": r})
189
+ return out
190
+
191
+
192
+ def norm_sms(split: str) -> list:
193
+ out = []
194
+ for r in load_jsonl(ROOT / "data" / f"sms_{split}.jsonl"):
195
+ if r["state"].strip():
196
+ out.append({"text": r["state"], "label": r["labels"]["intent"],
197
+ "row": r})
198
+ return out
199
+
200
+
201
+ def norm_hf_split(dom: str, split: str) -> list:
202
+ out = []
203
+ for r in hf_load(dom, split):
204
+ if r["text"].strip() and r["label"] is not None:
205
+ out.append({"text": hf_state(dom, r), "label": str(r["label"])})
206
+ return out
207
+
208
+
209
+ def _ids(rows: list) -> set:
210
+ return {(r["text"], r["label"]) for r in rows}
211
+
212
+
213
+ def _drop(rows: list, ids: set) -> list:
214
+ return [r for r in rows if (r["text"], r["label"]) not in ids]
215
+
216
+
217
+ def load_domain(dom: str) -> dict:
218
+ spec = DOMAINS[dom]
219
+ src = spec["source"]
220
+ if src == "big":
221
+ return {s: norm_big(dom, s) for s in ("train", "cal", "hidden")}
222
+ if src == "bank77":
223
+ return {s: norm_bank77(s) for s in ("train", "cal", "hidden")}
224
+ if src == "sms":
225
+ return {s: norm_sms(s) for s in ("train", "cal", "hidden")}
226
+ pools = {s: norm_hf_split(dom, s) for s in ("train", "cal", "hidden")}
227
+ rng = random.Random(SEED)
228
+ if dom == "hate": # single official split -> carve
229
+ pools = carve(dom, pools["train"])
230
+ if not pools["cal"]: # official train+test only
231
+ pools["cal"] = stratified_take(pools["train"], CAL_CAPS[dom], rng)
232
+ pools["train"] = _drop(pools["train"], _ids(pools["cal"]))
233
+ if dom == "boolq": # one validation pool -> cal+hidden
234
+ pool = pools["cal"]
235
+ pools["hidden"] = stratified_take(pool, HIDDEN_CAPS[dom], rng)
236
+ pools["cal"] = stratified_take(_drop(pool, _ids(pools["hidden"])),
237
+ CAL_CAPS[dom], rng)
238
+ # global disjointness: cal/hidden may never overlap each other or train
239
+ pools["hidden"] = _drop(pools["hidden"], _ids(pools["cal"]))
240
+ pools["hidden"] = _drop(pools["hidden"], _ids(pools["train"]))
241
+ pools["cal"] = _drop(pools["cal"], _ids(pools["train"]))
242
+ if dom in TRAIN_CAPS:
243
+ pool = pools["train"]
244
+ for lbl, cap in IMBALANCE_TRAIN_CAP.get(dom, {}).items():
245
+ group = [r for r in pool if r["label"] == lbl]
246
+ rest = [r for r in pool if r["label"] != lbl]
247
+ pool = stratified_take(group, cap, rng) + rest
248
+ rng.shuffle(pool)
249
+ if len(pool) > TRAIN_CAPS[dom]:
250
+ pool = stratified_take(pool, TRAIN_CAPS[dom], rng)
251
+ pools["train"] = pool
252
+ if len(pools["hidden"]) > HIDDEN_CAPS.get(dom, 10**9):
253
+ pools["hidden"] = stratified_take(pools["hidden"], HIDDEN_CAPS[dom], rng)
254
+ if len(pools["cal"]) > CAL_CAPS.get(dom, 10**9):
255
+ pools["cal"] = stratified_take(pools["cal"], CAL_CAPS[dom], rng)
256
+ return pools
257
+
258
+
259
+ def alloc_anchors(dom: str, classes: list) -> dict:
260
+ """Natural class name (or bank77 c## id) -> unique opaque anchor."""
261
+ spec = DOMAINS[dom]
262
+ if dom == "bank77":
263
+ return {c: c for c in classes} # already opaque (c00..c76)
264
+ width = 3 if len(classes) > 99 else 2
265
+ return {c: f"{spec['prefix']}{i:0{width}d}" for i, c in enumerate(classes)}
266
+
267
+
268
+ def base_criteria(dom: str, train: list, anchor_of: dict) -> dict:
269
+ """anchor -> criteria text. Existing domains keep their criteria verbatim
270
+ (keys remapped); new HF domains mine top-20 from TRAIN rows only."""
271
+ spec = DOMAINS[dom]
272
+ src = spec["source"]
273
+ if src in ("big", "bank77", "sms"):
274
+ c0 = train[0]["row"]["questions"][spec["qkey"]]["criteria"]
275
+ if dom == "bank77":
276
+ return {k: v for k, v in c0.items()}
277
+ return {anchor_of[nat]: txt for nat, txt in c0.items()
278
+ if nat in anchor_of}
279
+ by = defaultdict(list)
280
+ for r in train:
281
+ by[r["label"]].append(r["text"])
282
+ mined = mine_criteria(dict(by), 10, 2)
283
+ return {anchor_of[c]: mined.get(c, "") for c in by}
284
+
285
+
286
+ # --------------------------------------------------------------------------
287
+ # Handcrafted probes (written here, NOT copied from any dataset). For clinc
288
+ # the expected intent resolves at runtime by substring hint against the real
289
+ # 151 intent names. expected=None -> OOD probe, should defer.
290
+
291
+ PROBES = [
292
+ ("tickets_en", "I was charged twice on my last invoice for the same seat, please refund the duplicate.", "billing"),
293
+ ("tickets_en", "Our whole team gets a login error since this morning, the page just spins.", "technical"),
294
+ ("tickets_en", "We want to move 40 seats from the starter plan to the annual business plan.", "sales"),
295
+ ("tickets_bn", "আমার কার্ড থেকে দুইবার টাকা কেটেছে, অনুগ্রহ করে ফেরত দিন।", "billing"),
296
+ ("tickets_ru", "Списали деньги дважды за одну подписку, верните пожалуйста.", "billing"),
297
+ ("game", "Two skeletons flank the corridor ahead and my health is low; I retreat toward the torchlit hall.", "flee"),
298
+ ("game", "The wall ahead is cracked and my pickaxe is fresh.", "dig_in"),
299
+ ("game", "One zombie blocks the only doorway; my blade is sharp and I have room to swing.", "fight"),
300
+ ("guard", "Delete every user account and all audit logs right now, we do not need them anymore.", "true"),
301
+ ("guard", "Send the monthly summary email to the team alias.", "false"),
302
+ ("bank77", "Why was I charged an extra fee on my card payment?", "card_payment_fee_charged"),
303
+ ("bank77", "I transferred money to a friend two days ago and it has not arrived yet.", "transfer_not_received_by_recipient"),
304
+ ("bank77", "Please cancel the transfer I made this morning.", "cancel_transfer"),
305
+ ("sms", "Congratulations! You won a £1000 prize. Call 09058094518 now to claim!", "spam"),
306
+ ("sms", "Hey, running 10 min late, see you at the usual spot.", "ham"),
307
+ ("clinc", "does it look cloudy outside today", ["weather"]),
308
+ ("clinc", "book me a table for two tonight", ["restaurant"]),
309
+ ("clinc", "wake me up at six tomorrow morning", ["alarm"]),
310
+ ("clinc", "how do you say thank you in japanese", ["translate"]),
311
+ ("enron", "Team, attached are the Q3 numbers for the board meeting, send comments before Friday.", "ham"),
312
+ ("enron", "URGENT NOTICE: your mailbox will be deactivated, verify your password at the link now!", "spam"),
313
+ ("emotion", "I finally got the job offer I have been dreaming about, I am over the moon!", "joy"),
314
+ ("emotion", "She left without saying goodbye and I keep staring at my phone.", "sadness"),
315
+ ("emotion", "That sudden noise in the dark hallway made my heart race.", "fear"),
316
+ ("hate", "People like you ruin everything, you should not be allowed here.", "offensive"),
317
+ ("hate", "The team played terribly last night and the coach should be questioned.", "neither"),
318
+ ("hate", "I hate mondays, everything is awful today.", "neither"),
319
+ ("agnews", "Oil prices slide as OPEC members signal output increase", "business"),
320
+ ("agnews", "The quarterback threw five touchdowns in the season opener", "sports"),
321
+ ("agnews", "UN climate summit ends with a new emissions pledge", "world"),
322
+ ("polarity", "The headphones broke after two days and support ignored my emails.", "negative"),
323
+ ("polarity", "Exactly what I hoped for: sturdy, elegant and worth every cent.", "positive"),
324
+ ("dbpedia", "The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris.", "building"),
325
+ ("dbpedia", "The Amazon river dolphin is a freshwater cetacean native to South America.", "animal"),
326
+ ("dbpedia", "Toyota is a Japanese multinational automotive manufacturer headquartered in Aichi.", "company"),
327
+ ("boolq", "is the zugspitze the highest mountain in germany? The Zugspitze is Germany's highest peak at 2,962 metres.", "true"),
328
+ ("boolq", "did the roman empire fall in 476 bc? Romulus Augustulus was deposed in AD 476.", "false"),
329
+ ]
330
+
331
+ OOD_PROBES = [
332
+ "zzqvv plork wumfus xanquu blorp",
333
+ "fragile dashboard vector quantum tulip echo forty-two",
334
+ "seventeen purple o'clock beneath soon the",
335
+ "qq zz pp xx vv kk jj ww ff dd",
336
+ ]
337
+
338
+
339
+ def clinc_intent_names() -> list:
340
+ """Ordered intent-name list (int id -> name), cached from first-rows."""
341
+ cache = ROOT / "data" / "hf_cache" / "clinc_names.json"
342
+ if cache.exists():
343
+ return json.loads(cache.read_text())
344
+ import urllib.request
345
+ url = ("https://datasets-server.huggingface.co/first-rows"
346
+ "?dataset=clinc%2Fclinc_oos&config=plus&split=validation")
347
+ with urllib.request.urlopen(url, timeout=30) as r:
348
+ data = json.loads(r.read().decode())
349
+ names = next(f["type"]["names"] for f in data["features"]
350
+ if f["name"] == "intent")
351
+ cache.parent.mkdir(parents=True, exist_ok=True)
352
+ cache.write_text(json.dumps(names))
353
+ return names
354
+
355
+
356
+ def main() -> None:
357
+ GIANT.mkdir(parents=True, exist_ok=True)
358
+ names = clinc_intent_names()
359
+ schemas, pools_by_dom, anchor_maps = {}, {}, {}
360
+ for dom in sorted(DOMAINS):
361
+ pools = load_domain(dom)
362
+ spec = DOMAINS[dom]
363
+ if spec.get("keep_schema"):
364
+ # noul domain: keep the proven multi-question schema verbatim
365
+ tmpl = pools["train"][0]["row"]["questions"]
366
+ schemas[dom] = {"qkey": spec["qkey"], "source": spec["source"],
367
+ "type": "noul_multi", "classes": {},
368
+ "criteria": {}, "router_anchor": None,
369
+ "template_questions": tmpl}
370
+ anchor_maps[dom] = {}
371
+ pools_by_dom[dom] = pools
372
+ print(f"{dom:11s} {spec['source']:6s} train={len(pools['train']):6d} "
373
+ f"cal={len(pools['cal']):5d} hidden={len(pools['hidden']):5d} "
374
+ f"classes=noul(x2)+scope")
375
+ continue
376
+ classes = sorted({r["label"] for r in pools["train"] + pools["cal"]
377
+ + pools["hidden"]})
378
+ anchor_of = alloc_anchors(dom, classes)
379
+ if dom == "bank77":
380
+ cat = json.load(open(ROOT / "data" / "bank77_categories.json"))
381
+ inv_lbl = {v: k for k, v in cat["label_of"].items()}
382
+ name_of = {c: inv_lbl[c] for c in classes}
383
+ elif dom == "clinc":
384
+ name_of = {c: names[int(c)] for c in classes}
385
+ elif spec["source"] == "hf":
386
+ name_of = {c: CLASS_NAMES[dom].get(c, c) for c in classes}
387
+ else:
388
+ name_of = {c: c for c in classes}
389
+ crit = base_criteria(dom, pools["train"], anchor_of)
390
+ anchor_maps[dom] = anchor_of
391
+ schemas[dom] = {"qkey": spec["qkey"], "source": spec["source"],
392
+ "classes": {anchor_of[c]: name_of[c] for c in classes},
393
+ "criteria": crit, "router_anchor": None}
394
+ pools_by_dom[dom] = pools
395
+ print(f"{dom:11s} {spec['source']:6s} train={len(pools['train']):6d} "
396
+ f"cal={len(pools['cal']):5d} hidden={len(pools['hidden']):5d} "
397
+ f"classes={len(classes)}")
398
+
399
+ doms = sorted(DOMAINS)
400
+ rt_of = {d: f"rt{i:02d}" for i, d in enumerate(doms)}
401
+ for d in doms:
402
+ schemas[d]["router_anchor"] = rt_of[d]
403
+ router_q = {"type": "choice", "instructions": "",
404
+ "criteria": {rt_of[d]: DOMAINS[d]["router"] for d in doms}}
405
+ schemas["_router"] = {"criteria": router_q["criteria"]}
406
+
407
+ seen = {}
408
+ for d in doms:
409
+ for a in schemas[d]["classes"]:
410
+ assert a not in seen, f"anchor collision {a}: {d} vs {seen[a]}"
411
+ seen[a] = d
412
+ print(f"anchors: {len(seen)} unique across {len(doms)} domains")
413
+
414
+ def class_q_of(dom: str) -> dict:
415
+ return {"type": "choice", "instructions": "",
416
+ "criteria": schemas[dom]["criteria"]}
417
+
418
+ # emit + write ----------------------------------------------------------
419
+ cal_by_script, hidden_out, manifest_rows = {}, {}, []
420
+ SCRIPT_OF = {"tickets_bn": "bengali", "tickets_hi": "devanagari",
421
+ "tickets_ru": "cyrillic"}
422
+ queues = {d: [] for d in doms} # per-domain train queues
423
+ for dom in doms:
424
+ pools = pools_by_dom[dom]
425
+ rt = rt_of[dom]
426
+ if DOMAINS[dom].get("keep_schema"):
427
+ tmpl = schemas[dom]["template_questions"]
428
+ for split, rows in pools.items():
429
+ conv = [{"state": r["row"]["state"],
430
+ "questions": {"domain": router_q,
431
+ **r["row"]["questions"]},
432
+ "labels": {"domain": rt, **r["row"]["labels"]}}
433
+ for r in rows]
434
+ if split == "train":
435
+ queues[dom].extend(conv)
436
+ elif split == "cal":
437
+ cal_by_script.setdefault("latin", []).extend(conv)
438
+ else:
439
+ hidden_out[dom] = conv
440
+ manifest_rows.append(
441
+ {"domain": dom, "source": "big", "schema": "noul_multi",
442
+ "train": len(pools["train"]), "cal": len(pools["cal"]),
443
+ "hidden": len(pools["hidden"]), "classes": 2})
444
+ continue
445
+ qkey = DOMAINS[dom]["qkey"]
446
+ cq = class_q_of(dom)
447
+ amap = anchor_maps[dom]
448
+ for split, rows in pools.items():
449
+ conv = [{"state": r["text"], "questions": {"domain": router_q,
450
+ qkey: cq},
451
+ "labels": {"domain": rt, qkey: amap[r["label"]]}}
452
+ for r in rows]
453
+ if split == "train":
454
+ queues[dom].extend(conv)
455
+ elif split == "cal":
456
+ sc = SCRIPT_OF.get(dom, "latin")
457
+ cal_by_script.setdefault(sc, []).extend(conv)
458
+ else:
459
+ hidden_out[dom] = conv
460
+ manifest_rows.append({"domain": dom, "source": schemas[dom]["source"],
461
+ "train": len(pools["train"]),
462
+ "cal": len(pools["cal"]),
463
+ "hidden": len(pools["hidden"]),
464
+ "classes": len(schemas[dom]["classes"])})
465
+
466
+ # round-robin interleave across domains (Failure-1 fix)
467
+ interleaved, exhausted = [], set()
468
+ while len(exhausted) < len(doms):
469
+ for d in doms:
470
+ if d in exhausted:
471
+ continue
472
+ if not queues[d]:
473
+ exhausted.add(d)
474
+ continue
475
+ interleaved.append(queues[d].pop(0))
476
+ dump_jsonl(GIANT / "train.jsonl", interleaved)
477
+
478
+ for sc, rows in sorted(cal_by_script.items()):
479
+ dump_jsonl(GIANT / f"cal_{sc}.jsonl", rows)
480
+ for dom, rows in sorted(hidden_out.items()):
481
+ dump_jsonl(GIANT / f"{dom}_hidden.jsonl", rows)
482
+
483
+ # handcrafted probes ----------------------------------------------------
484
+ probes = []
485
+ pid = 0
486
+ for dom, state, expected in PROBES:
487
+ spec = DOMAINS[dom]
488
+ qkey = spec["qkey"]
489
+ if spec.get("keep_schema"):
490
+ questions = {"domain": router_q,
491
+ **schemas[dom]["template_questions"]}
492
+ else:
493
+ questions = {"domain": router_q, qkey: class_q_of(dom)}
494
+ if dom == "clinc":
495
+ hits = [c for c in schemas[dom]["classes"]
496
+ if any(h in schemas[dom]["classes"][c] for h in expected)]
497
+ if not hits:
498
+ continue
499
+ anchor = hits[0]
500
+ elif spec.get("keep_schema"):
501
+ anchor = expected # noul: literal "true"/"false"
502
+ else:
503
+ inv = {v: k for k, v in schemas[dom]["classes"].items()}
504
+ anchor = inv[expected]
505
+ probes.append({"id": f"p{pid:02d}", "domain": dom, "state": state,
506
+ "expected_router": rt_of[dom], "expected_class": anchor,
507
+ "questions": questions})
508
+ pid += 1
509
+ for state in OOD_PROBES:
510
+ dom = "tickets_en" # most familiar question schema
511
+ probes.append({"id": f"p{pid:02d}", "domain": dom, "state": state,
512
+ "expected_router": rt_of[dom], "expected_class": None,
513
+ "questions": {"domain": router_q,
514
+ "department": class_q_of(dom)}})
515
+ pid += 1
516
+ dump_jsonl(GIANT / "probes.jsonl", probes)
517
+
518
+ # schemas + manifest ----------------------------------------------------
519
+ (GIANT / "schemas.json").write_text(json.dumps(
520
+ {"domains": schemas, "router": rt_of}, ensure_ascii=False, indent=1))
521
+ files = {}
522
+ for f in sorted(GIANT.glob("*.jsonl")) + [GIANT / "schemas.json"]:
523
+ files[f.name] = {"bytes": f.stat().st_size, "sha256": sha256(f)}
524
+ manifest = {
525
+ "seed": SEED,
526
+ "recipe": {
527
+ "instructions": "empty on every row (Failure-2 fix)",
528
+ "anchors": "globally-unique opaque per-class anchors (Failure-3 fix)",
529
+ "train_order": "round-robin domain interleave (Failure-1 fix)",
530
+ "epochs": 3,
531
+ "criteria": "existing domains verbatim (keys remapped); new HF domains mined top-20 from train only",
532
+ },
533
+ "sources": {
534
+ "big": "data/big/* synthetic corpora (SHA-256 MANIFEST.json)",
535
+ "bank77": "PolyAI banking77 official splits",
536
+ "sms": "UCI SMS Spam Collection",
537
+ "hf": ["clinc/clinc_oos", "SetFit/enron_spam", "dair-ai/emotion",
538
+ "tdavidson/hate_speech_offensive", "fancyzhx/ag_news",
539
+ "fancyzhx/amazon_polarity", "fancyzhx/dbpedia_14",
540
+ "google/boolq"],
541
+ },
542
+ "domains": manifest_rows,
543
+ "train_rows": len(interleaved),
544
+ "lessons_per_epoch": 2 * len(interleaved),
545
+ "files": files,
546
+ }
547
+ (GIANT / "MANIFEST.json").write_text(json.dumps(
548
+ manifest, ensure_ascii=False, indent=1))
549
+ print(f"train rows {len(interleaved)} ({2*len(interleaved)} lessons/epoch)")
550
+ print(f"probes {len(probes)} ({len(OOD_PROBES)} OOD)")
551
+ print(f"cal files: { {k: len(v) for k, v in cal_by_script.items()} }")
552
+
553
+
554
+ if __name__ == "__main__":
555
+ main()
engine/tools/handmade_gate.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Score the HANDMADE probe set (data/handmade_probes.jsonl).
3
+
4
+ These probes are written by hand, deliberately NOT drawn from any training
5
+ split, any evaluation split, or any mined-criteria vocabulary — they are
6
+ sentences a person would actually type, with everyday wording. They exist to
7
+ answer one question: does the fabric GENERALISE, or does it only recognise the
8
+ exact templates it was taught?
9
+
10
+ Every row carries an explicit label (the intent / class / department), so the
11
+ gate is pass/fail per domain, with the failures printed so the failure SHAPE
12
+ is visible (not just the count).
13
+
14
+ Usage:
15
+ python3 tools/handmade_gate.py --schemas datasets/schemas.json \
16
+ --models bank77=model/b77-sem router=model/router16 \
17
+ --model-default model/giant-latin [--per-domain] [--dump out.jsonl]
18
+ """
19
+ import argparse
20
+ import json
21
+ import os
22
+ import sys
23
+ from collections import Counter, defaultdict
24
+
25
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+ sys.path.insert(0, os.path.join(ROOT, "server"))
27
+ from syfox_bridge import SyFoxEngine # noqa: E402
28
+
29
+ ROUTER_DOMAIN = "router"
30
+
31
+
32
+ def main():
33
+ ap = argparse.ArgumentParser()
34
+ ap.add_argument("--probes", default=os.path.join(ROOT, "data", "handmade_probes.jsonl"))
35
+ ap.add_argument("--schemas", default=os.path.join(ROOT, "datasets", "schemas.json"))
36
+ ap.add_argument("--models", default="", help="domain=dir,domain=dir (router domain included)")
37
+ ap.add_argument("--model-default", default="model/giant-latin")
38
+ ap.add_argument("--router-criteria", default="", help="JSON file overriding the router criteria")
39
+ ap.add_argument("--dump", default="")
40
+ ap.add_argument("--quiet", action="store_true")
41
+ ap.add_argument("--affinity-mix", type=float, default=None,
42
+ help="v4.0 affinity field readout channel (0 = legacy, 1 = affinity); "
43
+ "unset = use the model's RECORDED composition")
44
+ ap.add_argument("--affinity-pmi", action="store_true",
45
+ help="v4.0: log-odds (PMI) form of the contrast instead of the linear one")
46
+ ap.add_argument("--ngrams", choices=["on", "off"], default="off",
47
+ help="the character-trigram bridge (sub-word routing for unseen words)")
48
+ args = ap.parse_args()
49
+
50
+ schemas = json.load(open(args.schemas))
51
+ doms = schemas["domains"]
52
+ router_crit = doms["_router"]["criteria"]
53
+ if args.router_criteria:
54
+ router_crit = json.load(open(args.router_criteria))
55
+ if isinstance(router_crit, dict) and "criteria" in router_crit:
56
+ router_crit = router_crit["criteria"]
57
+
58
+ per_model = {}
59
+ for kv in args.models.split(","):
60
+ if "=" in kv:
61
+ k, v = kv.split("=", 1)
62
+ per_model[k.strip()] = v.strip()
63
+
64
+ rows = [json.loads(l) for l in open(args.probes) if l.strip()]
65
+ by_domain = defaultdict(list)
66
+ for r in rows:
67
+ by_domain[r["domain"]].append(r)
68
+
69
+ engines = {}
70
+ dump = []
71
+ total_hit = total_n = 0
72
+ print(f"{'domain':<14}{'n':>5}{'hit':>6}{'acc':>9} model")
73
+ print("-" * 62)
74
+ for dom in sorted(by_domain):
75
+ if dom == ROUTER_DOMAIN:
76
+ mdir = per_model.get(dom, args.model_default)
77
+ q = {"domain": {"type": "choice", "instructions": "", "criteria": router_crit}}
78
+ qkey = "domain"
79
+ else:
80
+ spec = doms.get(dom)
81
+ if spec is None:
82
+ print(f"{dom:<14} NO SCHEMA")
83
+ continue
84
+ mdir = per_model.get(dom, args.model_default)
85
+ qkey = spec["qkey"]
86
+ q = {qkey: {"type": "choice", "instructions": "", "criteria": spec["criteria"]}}
87
+ if mdir not in engines:
88
+ eng = SyFoxEngine(mdir)
89
+ eng.set_energy_norm(True)
90
+ # only override the model's RECORDED composition when the operator
91
+ # explicitly asked for a different readout (unset = keep it)
92
+ if args.affinity_mix is not None:
93
+ eng.set_affinity(args.affinity_mix, args.affinity_pmi)
94
+ if args.ngrams != "off":
95
+ eng.set_ngrams(args.ngrams == "on")
96
+ engines[mdir] = eng
97
+ eng = engines[mdir]
98
+ hit = 0
99
+ fails = []
100
+ for r in by_domain[dom]:
101
+ a, _, _ = eng.decide(r["state"], q, {"energy_norm": True})
102
+ ans = a.get(qkey, {})
103
+ pred = ans.get("choice", "")
104
+ ok = (pred == r["label"]) and not ans.get("deferred")
105
+ hit += ok
106
+ total_hit += ok
107
+ total_n += 1
108
+ if not ok:
109
+ fails.append((r["id"], r["label"], pred, ans.get("deferred", False),
110
+ ans.get("confidence", 0.0), r["state"][:52]))
111
+ if args.dump:
112
+ dump.append(json.dumps({"id": r["id"], "domain": dom, "gold": r["label"],
113
+ "pred": pred, "deferred": ans.get("deferred", False),
114
+ "confidence": ans.get("confidence", 0.0),
115
+ "state": r["state"]}, ensure_ascii=False))
116
+ acc = hit / len(by_domain[dom]) if by_domain[dom] else 0.0
117
+ print(f"{dom:<14}{len(by_domain[dom]):>5}{hit:>6}{acc:>9.3f} {mdir}")
118
+ if not args.quiet and fails:
119
+ for fid, gold, pred, dfr, conf, st in fails[:14]:
120
+ print(f" miss {fid:<10} gold={gold:<10} pred={pred:<10} "
121
+ f"{'DEFER' if dfr else f'conf {conf:.2f}'} {st}")
122
+ if len(fails) > 14:
123
+ print(f" ... and {len(fails)-14} more")
124
+
125
+ print("-" * 62)
126
+ print(f"{'TOTAL':<14}{total_n:>5}{total_hit:>6}{total_hit/max(1,total_n):>9.3f}")
127
+ if args.dump:
128
+ with open(args.dump, "w") as f:
129
+ f.write("\n".join(dump) + "\n")
130
+ print(f"per-row dump -> {args.dump}")
131
+ return 0
132
+
133
+
134
+ if __name__ == "__main__":
135
+ sys.exit(main())
engine/tools/hf_fetch.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fetch real HF datasets for the giant model via parquet shards.
3
+
4
+ For each dataset+split: GET /api/datasets/{id}/parquet -> shard URLs, download
5
+ up to 3 evenly-spaced shards (cached under data/hf_cache/parquet/), then sample
6
+ rows EVENLY over the concatenated shard rows (numpy linspace) so class-ordered
7
+ corpora still give proportional class coverage. Output: data/hf_raw/{dom}_{split}.json
8
+ with verbatim dataset text (truncation happens later in giant_prepare.py).
9
+
10
+ No synthetic text is added here.
11
+ """
12
+ import json
13
+ import sys
14
+ import time
15
+ import urllib.request
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+
21
+ ROOT = Path(__file__).resolve().parent.parent
22
+ CACHE = ROOT / "data" / "hf_cache" / "parquet"
23
+ OUT = ROOT / "data" / "hf_raw"
24
+ UA = {"User-Agent": "syfox-giant-prepare/1.0"}
25
+
26
+
27
+ def http_get(url: str, dest: Path) -> None:
28
+ for attempt in range(4):
29
+ try:
30
+ req = urllib.request.Request(url, headers=UA)
31
+ with urllib.request.urlopen(req, timeout=120) as r, open(dest, "wb") as f:
32
+ while True:
33
+ chunk = r.read(1 << 20)
34
+ if not chunk:
35
+ break
36
+ f.write(chunk)
37
+ return
38
+ except Exception as e: # noqa: BLE001
39
+ if attempt == 3:
40
+ raise
41
+ print(f" retry {attempt + 1} for {dest.name}: {e}", file=sys.stderr)
42
+ time.sleep(3 * (attempt + 1))
43
+
44
+
45
+ def shard_urls(ds: str) -> dict:
46
+ req = urllib.request.Request(
47
+ f"https://huggingface.co/api/datasets/{ds}/parquet", headers=UA)
48
+ with urllib.request.urlopen(req, timeout=30) as r:
49
+ return json.loads(r.read().decode())
50
+
51
+
52
+ def pick(urls: list, n: int) -> list:
53
+ if len(urls) <= n:
54
+ return urls
55
+ idx = np.linspace(0, len(urls) - 1, n).round().astype(int)
56
+ return [urls[i] for i in dict.fromkeys(idx.tolist())]
57
+
58
+
59
+ def fetch_split(ds: str, cfg: str, split: str, n_sample: int,
60
+ textf: str, labf: str, tag: str) -> list:
61
+ tree = shard_urls(ds)
62
+ urls = pick(tree[cfg][split], 3 if split == "train" else 2)
63
+ frames = []
64
+ for u in urls:
65
+ name = "__".join(u.split("/datasets/")[1].split("/"))
66
+ dest = CACHE / name
67
+ if not dest.exists():
68
+ CACHE.mkdir(parents=True, exist_ok=True)
69
+ print(f" downloading {name}")
70
+ http_get(u, dest)
71
+ cols = ([textf] if isinstance(textf, str) else list(textf)) + [labf]
72
+ frames.append(pd.read_parquet(dest, columns=cols))
73
+ df = pd.concat(frames, ignore_index=True)
74
+ if len(df) > n_sample:
75
+ sel = np.linspace(0, len(df) - 1, n_sample).round().astype(int)
76
+ df = df.iloc[sel]
77
+ cols = [textf] if isinstance(textf, str) else list(textf)
78
+ rows = [{"text": " ".join(str(x) for x in t), "label": l}
79
+ for t, l in zip(df[cols].to_numpy().tolist(), df[labf].tolist())]
80
+ out = OUT / f"{tag}.json"
81
+ out.write_text(json.dumps(rows, ensure_ascii=False))
82
+ labs = sorted({str(r["label"]) for r in rows})
83
+ print(f"{tag}: {len(rows)} rows, {len(labs)} labels "
84
+ f"e.g. {labs[:6]} | sample {rows[0]['text'][:50]!r}")
85
+ return rows
86
+
87
+
88
+ PLAN = [
89
+ ("clinc", ("text", "intent"), {
90
+ "train": ("clinc/clinc_oos", "plus", "train", 12000),
91
+ "cal": ("clinc/clinc_oos", "imbalanced", "validation", 3300),
92
+ "hidden": ("clinc/clinc_oos", "plus", "test", 4600)}),
93
+ ("enron", ("text", "label"), {
94
+ "train": ("SetFit/enron_spam", "default", "train", 8000),
95
+ "cal": ("SetFit/enron_spam", "default", "test", 800),
96
+ "hidden": ("SetFit/enron_spam", "default", "test", 2600)}),
97
+ ("emotion", ("text", "label"), {
98
+ "train": ("dair-ai/emotion", "split", "train", 8000),
99
+ "cal": ("dair-ai/emotion", "split", "validation", 700),
100
+ "hidden": ("dair-ai/emotion", "split", "test", 2100)}),
101
+ ("hate", ("tweet", "class"), {
102
+ "train": ("tdavidson/hate_speech_offensive", "default", "train", 9000)}),
103
+ ("agnews", ("text", "label"), {
104
+ "train": ("fancyzhx/ag_news", "default", "train", 8000),
105
+ "hidden": ("fancyzhx/ag_news", "default", "test", 2000)}),
106
+ ("polarity", ("content", "label"), {
107
+ "train": ("fancyzhx/amazon_polarity", "amazon_polarity", "train", 8000),
108
+ "hidden": ("fancyzhx/amazon_polarity", "amazon_polarity", "test", 2000)}),
109
+ ("dbpedia", ("content", "label"), {
110
+ "train": ("fancyzhx/dbpedia_14", "dbpedia_14", "train", 8000),
111
+ "hidden": ("fancyzhx/dbpedia_14", "dbpedia_14", "test", 2000)}),
112
+ ("boolq", (("question", "passage"), "answer"), {
113
+ "train": ("google/boolq", "default", "train", 7500),
114
+ "cal": ("google/boolq", "default", "validation", 3300)}),
115
+ ]
116
+
117
+
118
+ def main() -> None:
119
+ for dom, fields, splits in PLAN:
120
+ for tag, (ds, cfg, split, n) in splits.items():
121
+ fetch_split(ds, cfg, split, n, fields[0], fields[1], f"{dom}_{tag}")
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()
engine/tools/jev_bench.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """SyFox vs JEV AI — measured head-to-head (v3.6.0).
3
+
4
+ JEV AI (TypeSafe AI, Sept 2026 early access) is the "System One" decision
5
+ model: state + typed questions (noul/choice/score) in, per-question value +
6
+ probability + confidence out, no text generation. SyFox shares that
7
+ architecture (state + typed questions -> honest decided answers over a
8
+ settled energy field), so the competition is measurable on JEV's own axes:
9
+
10
+ workflow accuracy JEV's vendor claim is 0.955; the launch-day self-report
11
+ was 0.678; syfox measures choice/score accuracy + defer
12
+ rates per fabric.
13
+ latency JEV's third-party p50 is 236-276 ms for one question
14
+ (launch range 70-500 ms); syfox measures the
15
+ in-process decide path (latency_us p50/p95 in the bench).
16
+ guardrail JEV reports a hold-precision axis (0.88); syfox measures
17
+ its guardrail confusion matrix + OOD defer rate.
18
+ calibration JEV's third-party ECE is 0.246 (laya-model.com/benchmarks);
19
+ syfox publishes measured ECE per question type.
20
+ cost JEV: $0.042 / M input tokens, output free; syfox runs
21
+ locally at $0 compute cost (open core, no API meter).
22
+
23
+ This tool reads the JSON the C++ bench already measured (make bench ->
24
+ build/bench-*.json) and prints the head-to-head. Every syfox number comes
25
+ from an actual run in this repository; every JEV number is the PUBLISHED
26
+ figure carried in the bench's jev_reference block. No syfox number is ever
27
+ estimated, and no JEV number is invented: their own press states the
28
+ multipliers are self-reported ceilings.
29
+ """
30
+ import json
31
+ import os
32
+ import sys
33
+
34
+ BENCH_FILES = [
35
+ ("model-tickets", "build/bench-tickets.json"),
36
+ ("model-game", "build/bench-game.json"),
37
+ ("model-guard", "build/bench-guard.json"),
38
+ ]
39
+
40
+
41
+ def load(path):
42
+ if not os.path.exists(path):
43
+ return None
44
+ with open(path) as f:
45
+ return json.load(f)
46
+
47
+
48
+ def pct(x):
49
+ return f"{100.0 * x:.1f}%"
50
+
51
+
52
+ def main():
53
+ rows = []
54
+ for model, path in BENCH_FILES:
55
+ d = load(path)
56
+ if d is None:
57
+ print(f"missing {path}: run `make bench` first", file=sys.stderr)
58
+ continue
59
+ if not d.get("suite", "").startswith("syfox-jev-parity"):
60
+ print(f"{path} is not a parity-suite run", file=sys.stderr)
61
+ continue
62
+ rows.append((model, d))
63
+
64
+ if not rows:
65
+ sys.exit("no parity bench JSON found — run `make bench` first")
66
+
67
+ # Aggregate measured syfox numbers over the seed fabrics.
68
+ answered_accs, all_lat, eces, ood = [], [], [], []
69
+ for model, d in rows:
70
+ r = d["routing"]
71
+ if r.get("choice_n"):
72
+ answered_accs.append((r["choice_accuracy"], r["choice_n"]))
73
+ if r.get("score_n"):
74
+ answered_accs.append((r["score_accuracy"], r["score_n"]))
75
+ all_lat.append(d["latency_us"]["p50"])
76
+ all_lat.append(d["latency_us"]["p95"])
77
+ c = d.get("calibration", {})
78
+ for k in ("choice_ece", "score_ece"):
79
+ if k in c:
80
+ eces.append(c[k])
81
+ ood.append(d["honesty"]["ood_defer_rate"])
82
+
83
+ n_acc = sum(n for _, n in answered_accs)
84
+ acc = sum(a * n for a, n in answered_accs) / n_acc if n_acc else 0.0
85
+ lat_p50_max = max(all_lat)
86
+ ece = sum(eces) / len(eces) if eces else 0.0
87
+ ood_min = min(ood)
88
+
89
+ jev = rows[0][1]["jev_reference"]
90
+
91
+ print("=" * 74)
92
+ print("SYFOX vs JEV AI (TypeSafe) — measured head-to-head on JEV's axes")
93
+ print("=" * 74)
94
+ print(f"{'axis':<28}{'JEV AI (published)':<24}{'syfox (measured now)':<22}")
95
+ print("-" * 74)
96
+ print(f"{'decision API':<28}{'POST /v1/systemone':<24}{'POST /v1/systemone':<22}")
97
+ print(f"{'question types':<28}{'noul/choice/score':<24}{'noul/choice/score':<22}")
98
+ print(f"{'batch questions/call':<28}{'yes (parallel)':<24}{'yes (one settle)':<22}")
99
+ print(f"{'workflow accuracy (vendor)':<28}{pct(jev.get('workflow_accuracy_vendor', 0.955)):<24}{pct(acc) + f' (n={n_acc} answered)':<22}")
100
+ print(f"{'workflow accuracy (launch)':<28}{pct(jev['workflow_accuracy']):<24}{'-':<24}")
101
+ print(f"{'latency (p50)':<28}{jev['latency_ms'] + ' ms':<24}{'<= ' + f'{lat_p50_max:.0f}' + ' us':<22}")
102
+ print(f"{'input cost':<28}{'$0.042 / M tokens':<24}{'$0 (local core)':<22}")
103
+ print(f"{'output cost':<28}{'free (typed value)':<24}{'free (typed value)':<22}")
104
+ print(f"{'ECE (lower better)':<28}{str(jev.get('ece', 'n/a')):<24}{'measured ' + f'{ece:.3f}' + ':<22}")
105
+ print(f"{'calibration study':<28}{'third-party ECE 0.246':<24}{'ECE published (mean ' + f'{ece:.3f}' + ')':<22}")
106
+ print(f"{'honest defer w/ reason':<28}{'confidence only':<24}{'defer + reason (OOD ' + pct(ood_min) + ')':<22}")
107
+ print(f"{'option cap / choice':<28}{'255 then two-stage':<24}{'unbounded criteria map':<22}")
108
+ print(f"{'determinism':<28}{'not published':<24}{'bit-reproducible (CI)':<22}")
109
+ print(f"{'full decision audit':<28}{'no':<24}{'evidence JSON + ledger':<22}")
110
+ print("-" * 74)
111
+ print(f"JEV reference source: {jev['source']}")
112
+ print("syfox source: " + ", ".join(f"{m} ({p})" for m, p in BENCH_FILES if load(p)))
113
+ print("syfox latency = in-process decide path (settle + readout), this tree,")
114
+ print("measured by core/bench.hpp; JEV latency = their published end-to-end range.")
115
+
116
+ out = {
117
+ "suite": "syfox-vs-jev-head-to-head",
118
+ "syfox_measured": {
119
+ "answered_accuracy": acc,
120
+ "answered_n": n_acc,
121
+ "latency_us_p50_max": lat_p50_max,
122
+ "mean_ece": ece,
123
+ "ood_defer_rate_min": ood_min,
124
+ "per_model": [
125
+ {"model": m, "routing": d["routing"], "calibration": d.get("calibration", {}),
126
+ "latency_us": d["latency_us"], "honesty": d["honesty"],
127
+ "guardrail": d.get("guardrail", {})} for m, d in rows
128
+ ],
129
+ },
130
+ "jev_published": jev,
131
+ }
132
+ with open("build/jev_comparison.json", "w") as f:
133
+ json.dump(out, f, indent=2)
134
+ print("wrote build/jev_comparison.json")
135
+
136
+
137
+ if __name__ == "__main__":
138
+ main()
engine/tools/reasoning_probes.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reasoning probe suite (v3.3): question-context selection before/after the
3
+ question-conditioned readout gate.
4
+
5
+ Builds a small QA-style fabric (the same shape as the user's dense benchmark:
6
+ statements + QA pairs as lessons), then runs the reported failure probes:
7
+
8
+ Test 1 who found the radio -> expect Tariq, was radio (salient noun)
9
+ Test 2 same, {Tariq,Salma} only -> tie broken by criteria order, was Salma
10
+ Test 4 unknown options xyz/abc/def -> winner by noise, exact-tie case
11
+ Test 10 A->B->C chain -> transitive propagation
12
+ Test 16 latest temperature -> temporal ordering
13
+ Test 17 purple elephant / submarine -> OOD abstention
14
+
15
+ Usage:
16
+ python3 tools/reasoning_probes.py [--rebuild] [--json-out F]
17
+ """
18
+ import argparse
19
+ import json
20
+ import subprocess
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ ROOT = Path(__file__).resolve().parent.parent
25
+ BIN = str(ROOT / "build" / "syfox")
26
+ MODEL = str(ROOT / "model-reasoning-probe")
27
+
28
+ LESSONS = [
29
+ # --- Test 1/2 fabric: Tariq / Salma / radio ---
30
+ ("tariq found the radio in the lab", "tariq"),
31
+ ("the radio was found by tariq", "tariq"),
32
+ ("tariq picked up the radio", "tariq"),
33
+ ("salma was there in the room", "salma"),
34
+ ("salma saw the radio on the table", "salma"),
35
+ ("who found the radio tariq did", "tariq"),
36
+ ("who saw the radio salma did", "salma"),
37
+ # --- Test 10 chain fabric: A -> B -> C (as event words) ---
38
+ ("the alarm rang then the lights turned on", "lights"),
39
+ ("the lights turned on then the door opened", "door"),
40
+ ("what happens after the alarm the lights", "lights"),
41
+ # --- Test 16 temporal fabric ---
42
+ ("the temperature was twenty degrees in the morning", "twenty"),
43
+ ("the temperature rose to twenty five degrees at noon", "twentyfive"),
44
+ ("the temperature fell to twenty two degrees in the evening", "twentytwo"),
45
+ ("the latest temperature reading was twenty two degrees", "twentytwo"),
46
+ # --- v3.4 multi-hop chains (reported Tests 18/21 analogs) ---
47
+ ("a sparrow is a bird", "bird"),
48
+ ("a bird is an animal", "animal"),
49
+ ("a sparrow has feathers and wings", "bird"),
50
+ ("alpha relays to bravo", "bravo"),
51
+ ("bravo relays to charlie", "charlie"),
52
+ ("charlie relays to delta", "delta"),
53
+ ("delta relays to echo", "echo"),
54
+ # --- OOD block: no submarine / favorite-color lessons anywhere ---
55
+ ]
56
+
57
+ PROBES = [
58
+ {
59
+ "name": "Test 1: who found the radio",
60
+ "state": "The radio was found by Tariq. Salma was there.",
61
+ "q": {"i": {"type": "choice", "instructions": "Who found the radio?",
62
+ "criteria": {"Tariq": "the person who found it",
63
+ "Salma": "a person present",
64
+ "radio": "the object found"}}},
65
+ "expect": "Tariq", "reported_failure": "radio (0.399) — salient noun",
66
+ },
67
+ {
68
+ "name": "Test 2: two-person tie",
69
+ "state": "The radio was found by Tariq. Salma was there.",
70
+ "q": {"i": {"type": "choice", "instructions": "Who found the radio?",
71
+ "criteria": {"Tariq": "the person who found it",
72
+ "Salma": "a person present"}}},
73
+ "expect": "Tariq", "reported_failure": "Salma 0.5 tie (criteria order)",
74
+ },
75
+ {
76
+ "name": "Test 4: unknown options",
77
+ "state": "The radio was found by Tariq. Salma was there.",
78
+ "q": {"i": {"type": "choice", "instructions": "Who found the radio?",
79
+ "criteria": {"xyz": "", "abc": "", "def": ""}}},
80
+ "expect": "defer or tie disclosure", "reported_failure": "abc 0.344 by noise",
81
+ },
82
+ {
83
+ "name": "Test 10: alarm-lights-door chain",
84
+ "state": "The alarm rang.",
85
+ "q": {"i": {"type": "choice", "instructions": "What turned on next?",
86
+ "criteria": {"alarm": "the alarm", "lights": "the lights",
87
+ "door": "the door", "unknown": "nothing"}}},
88
+ "expect": "lights (2-hop)", "reported_failure": "near-uniform",
89
+ },
90
+ {
91
+ "name": "Test 16: latest temperature",
92
+ "state": "The temperature was twenty degrees then rose to twenty five degrees then fell to twenty two degrees.",
93
+ "q": {"i": {"type": "choice", "instructions": "What is the latest temperature?",
94
+ "criteria": {"twenty": "20 degrees", "twentyfive": "25 degrees",
95
+ "twentytwo": "22 degrees"}}},
96
+ "expect": "twentytwo", "reported_failure": "chose 20",
97
+ },
98
+ {
99
+ "name": "Test 18: sparrow->bird->animal (3-hop)",
100
+ "state": "What is a sparrow?",
101
+ "q": {"i": {"type": "choice", "instructions": "What is a sparrow?",
102
+ "criteria": {"sparrow": "sparrow", "bird": "bird",
103
+ "animal": "animal"}}},
104
+ "expect": "animal (2 lane hops)", "reported_failure": "near-uniform, conf 0.019",
105
+ },
106
+ {
107
+ "name": "Test 21: alpha..echo relay (4-hop)",
108
+ "state": "Where does the alpha relay to?",
109
+ "q": {"i": {"type": "choice", "instructions": "Where does the alpha relay to?",
110
+ "criteria": {"bravo": "bravo", "charlie": "charlie",
111
+ "delta": "delta", "echo": "echo"}}},
112
+ "expect": "echo (4 lane hops)", "reported_failure": "barely propagates",
113
+ },
114
+ {
115
+ "name": "Test 17: OOD submarine color",
116
+ "state": "The purple elephant boarded the spaceship.",
117
+ "q": {"i": {"type": "choice", "instructions": "What was the submarine's favorite color?",
118
+ "criteria": {"purple": "purple", "blue": "blue", "green": "green"}}},
119
+ "expect": "defer (unanswerable)", "reported_failure": "purple 0.472",
120
+ },
121
+ ]
122
+
123
+
124
+ def decide(state, q, extra):
125
+ cmd = [BIN, "decide", "--model", MODEL, "--energy-norm",
126
+ "--state", state, "--questions", json.dumps(q)] + extra
127
+ p = subprocess.run(cmd, capture_output=True, text=True)
128
+ if p.returncode != 0:
129
+ return {"error": p.stderr.strip()}
130
+ return json.loads(p.stdout)
131
+
132
+
133
+ def build_model():
134
+ subprocess.run(["rm", "-rf", MODEL], check=True)
135
+ rows = []
136
+ for i, (state, label) in enumerate(LESSONS):
137
+ rows.append({"state": state,
138
+ "questions": {"i": {"type": "choice", "instructions": "",
139
+ "criteria": {label: label}}},
140
+ "labels": {"i": label}})
141
+ path = ROOT / "data" / "reasoning_probe_lessons.jsonl"
142
+ with open(path, "w") as f:
143
+ for r in rows:
144
+ f.write(json.dumps(r) + "\n")
145
+ subprocess.run([BIN, "learn", "--model", MODEL, "--examples", str(path)],
146
+ check=True, cwd=str(ROOT))
147
+ subprocess.run([BIN, "calibrate", "--model", MODEL,
148
+ "--examples", str(path), "--energy-norm"],
149
+ check=True, cwd=str(ROOT))
150
+
151
+
152
+ def main():
153
+ ap = argparse.ArgumentParser()
154
+ ap.add_argument("--rebuild", action="store_true")
155
+ ap.add_argument("--json-out", default="")
156
+ a = ap.parse_args()
157
+ if a.rebuild or not Path(MODEL, "substrate.bin").exists():
158
+ build_model()
159
+
160
+ configs = [
161
+ ("gate OFF (default)", []),
162
+ ("gate ON floor 0.10", ["--question-gate", "--question-gate-floor", "0.10"]),
163
+ ("gate ON floor 0.25", ["--question-gate"]),
164
+ ("gate ON floor 0.50", ["--question-gate", "--question-gate-floor", "0.50"]),
165
+ ("hops 1 (legacy)", []),
166
+ ("hops 2", ["--hops", "2"]),
167
+ ("hops 4", ["--hops", "4"]),
168
+ ]
169
+ table = {}
170
+ for cname, extra in configs:
171
+ recs = []
172
+ for pr in PROBES:
173
+ out = decide(pr["state"], pr["q"], extra)
174
+ ans = out.get("answers", {}).get("i", {})
175
+ recs.append({
176
+ "choice": ans.get("choice", ""),
177
+ "conf": ans.get("confidence", 0),
178
+ "deferred": ans.get("deferred", False),
179
+ "tied": ans.get("tied", False),
180
+ "gate": ans.get("question_gate", []),
181
+ "probs": ans.get("probabilities", {}),
182
+ })
183
+ table[cname] = recs
184
+
185
+ for i, pr in enumerate(PROBES):
186
+ print(f"\n== {pr['name']} [expect: {pr['expect']}; reported: {pr['reported_failure']}]")
187
+ for cname, _ in configs:
188
+ r = table[cname][i]
189
+ tag = "DEFER" if r["deferred"] else f"{r['choice']} @ {r['conf']}"
190
+ tie = " TIED" if r["tied"] else ""
191
+ gt = f" gate={r['gate']}" if r["gate"] else ""
192
+ print(f" {cname:<30} -> {tag}{tie}{gt}")
193
+
194
+ if a.json_out:
195
+ json.dump({"probes": [p["name"] for p in PROBES],
196
+ "configs": table}, open(a.json_out, "w"), indent=1)
197
+ print(f"\nwrote {a.json_out}")
198
+
199
+
200
+ if __name__ == "__main__":
201
+ main()
engine/tools/rebuild_router_criteria.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rebuild a question's CRITERIA from the fabric's own label-exclusive lanes.
3
+
4
+ THE PROBLEM. A SyFox `choice` question gives each candidate a KEY (the
5
+ label/anchor) and a DESCRIPTION (the criteria text). Two things happen with
6
+ that description:
7
+
8
+ 1. `probe_energy(label, desc)` reads out on `normalize(label + " " + desc)`,
9
+ and `Substrate::readout()` SKIPS every token that is not a fabric node
10
+ (`auto it = index_.find(t); if (it == index_.end()) continue;`). So a
11
+ description made of words the fabric never interned contributes
12
+ NOTHING to its own candidate's measurement.
13
+
14
+ 2. `decide()` injects the description tokens into the SHARED settled field
15
+ (`si_.inject(qtoks, state_dose(qtoks))`) — the "direct-term harvest".
16
+ Words that are not fabric nodes inject nothing; words that ARE nodes
17
+ harvest energy into whatever anchor their lanes point at.
18
+
19
+ Measured on the shipped `model/giant-latin` fabric, the router's descriptions
20
+ are mostly non-words of the fabric: rt01 ("banking cards payments transfers
21
+ refunds loans") has 0 of 6 words as fabric nodes, rt00 has 1 of 6, rt13 has
22
+ 1 of 6. Worse, the words that DO exist are shared ("support", "in", "world")
23
+ across several candidates, so the harvest lights up several anchors at once —
24
+ pure noise. The router's whole discrimination signal is reduced to the anchor
25
+ node plus one hop.
26
+
27
+ THE FIX. Build each candidate's description from the tokens the fabric itself
28
+ uses to reach that anchor, preferring the ones that reach it EXCLUSIVELY:
29
+
30
+ for each token x and anchor A:
31
+ w(x,A) = the lane weight from x to A
32
+ total(x) = sum over all anchors A' of w(x,A')
33
+ exclusive(x,A) = w(x,A) / total(x) # how exclusively x points at A
34
+ score(x,A) = w(x,A) * exclusive(x,A) = w^2 / total
35
+
36
+ The top-k tokens by that score become the candidate's description. They are
37
+ real fabric nodes (so they are measurable AND harvestable) and they point at
38
+ this anchor more than at any other (so the harvest discriminates instead of
39
+ diluting).
40
+
41
+ Usage:
42
+ python3 tools/rebuild_router_criteria.py --model model-router16 \
43
+ --anchors rt00,rt01,... [--topk 4] [--min-exclusive 0.35] \
44
+ [--out router_criteria.json]
45
+ """
46
+ import argparse
47
+ import json
48
+ import struct
49
+ from collections import defaultdict
50
+
51
+
52
+ def load_substrate(path):
53
+ """-> (nodes: list[str], lanes: list[(a,b,w)])"""
54
+ d = open(path, "rb").read()
55
+ o = 0
56
+ n = struct.unpack_from("<I", d, o)[0]
57
+ o += 4
58
+ nodes = []
59
+ for _ in range(n):
60
+ ln = struct.unpack_from("<I", d, o)[0]
61
+ o += 4
62
+ nodes.append(d[o:o + ln].decode("utf-8", "replace"))
63
+ o += ln + 4 # concept bytes + float mass
64
+ nl = struct.unpack_from("<I", d, o)[0]
65
+ o += 4
66
+ lanes = []
67
+ for _ in range(nl):
68
+ a, b, w = struct.unpack_from("<II f", d, o)
69
+ o += 12
70
+ lanes.append((a, b, w))
71
+ return nodes, lanes
72
+
73
+
74
+ def main():
75
+ ap = argparse.ArgumentParser()
76
+ ap.add_argument("--model", required=True, help="model dir (contains substrate.bin)")
77
+ ap.add_argument("--anchors", required=True,
78
+ help="comma-separated candidate keys, e.g. rt00,rt01")
79
+ ap.add_argument("--topk", type=int, default=4)
80
+ ap.add_argument("--min-exclusive", type=float, default=0.35,
81
+ help="minimum share of the token's anchor mass for exclusivity")
82
+ ap.add_argument("--out", default="")
83
+ args = ap.parse_args()
84
+
85
+ nodes, lanes = load_substrate(f"{args.model}/substrate.bin")
86
+ index = {c: i for i, c in enumerate(nodes)}
87
+ anchors = [a.strip() for a in args.anchors.split(",") if a.strip()]
88
+ missing = [a for a in anchors if a not in index]
89
+ if missing:
90
+ raise SystemExit(f"anchors not in this fabric: {missing}")
91
+ anchor_ids = {a: index[a] for a in anchors}
92
+
93
+ # in-edges into each anchor, from every token
94
+ to_anchor = defaultdict(list) # anchor -> [(token_id, weight)]
95
+ for a, b, w in lanes:
96
+ if b in anchor_ids.values() and w > 0:
97
+ to_anchor[b].append((a, w))
98
+
99
+ # total mass of each token across ALL anchors
100
+ total = defaultdict(float)
101
+ for anc, lst in to_anchor.items():
102
+ for tid, w in lst:
103
+ total[tid] += w
104
+
105
+ out = {}
106
+ for anc in anchors:
107
+ aid = anchor_ids[anc]
108
+ scored = []
109
+ for tid, w in to_anchor.get(aid, []):
110
+ t = total.get(tid, 0.0)
111
+ if t <= 0:
112
+ continue
113
+ excl = w / t
114
+ if excl < args.min_exclusive:
115
+ continue
116
+ scored.append((w * excl, excl, w, tid))
117
+ scored.sort(reverse=True)
118
+ picked = []
119
+ for score, excl, w, tid in scored:
120
+ tok = nodes[tid]
121
+ # skip pure stopword-ish anchors that are shared boilerplate
122
+ if tok in picked:
123
+ continue
124
+ picked.append(tok)
125
+ if len(picked) >= args.topk:
126
+ break
127
+ out[anc] = {
128
+ "criteria": " ".join(picked),
129
+ "tokens": picked,
130
+ "detail": [{"token": nodes[tid], "w": round(w, 6),
131
+ "exclusive": round(excl, 4), "score": round(score, 6)}
132
+ for score, excl, w, tid in scored[:args.topk * 3]],
133
+ }
134
+
135
+ print(json.dumps({k: v["criteria"] for k, v in out.items()}, indent=1))
136
+ if args.out:
137
+ with open(args.out, "w") as f:
138
+ json.dump(out, f, indent=1)
139
+ print(f"\nwrote {args.out}")
140
+ return out
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()
engine/tools/router_prepare.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # ============================================================================
3
+ # router_prepare.py — v3.2 two-stage architecture, stage 1.
4
+ # Builds the DEDICATED ROUTER FABRIC: a small (500-node class) substrate
5
+ # whose only job is domain routing — 16 anchors, one per domain, physics
6
+ # only (no classifier, no ML; the same SI substrate decides).
7
+ #
8
+ # Source: data/giant/train.jsonl rows already carry the router question
9
+ # (qkey "domain": criteria for rt00..rt15). We carve a balanced sample:
10
+ # data/router16_train.jsonl — train rows for the router fabric
11
+ # data/router16_cal.jsonl — small cal carve (router accuracy check)
12
+ # data/router16_router.json — ships as router.json in the model dir:
13
+ # {"anchors": {rtNN: criteria}, "models": {rtNN: model-dir},
14
+ # "domains": {rtNN: domain-name}}
15
+ #
16
+ # The two-stage contract (CLI: decide --router model-router16 ...):
17
+ # stage 1: model-router16 settles the state -> picks the domain anchor
18
+ # stage 2: the mapped domain fabric decides the actual questions
19
+ # Domain fabrics stay isolated; the router fabric never sees domain labels.
20
+ # ============================================================================
21
+ import argparse
22
+ import json
23
+ from collections import Counter, defaultdict
24
+ from pathlib import Path
25
+
26
+
27
+ def main() -> None:
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("--train", default="data/giant/train.jsonl")
30
+ ap.add_argument("--schemas", default="data/giant/schemas.json")
31
+ ap.add_argument("--out-train", default="data/router16_train.jsonl")
32
+ ap.add_argument("--out-cal", default="data/router16_cal.jsonl")
33
+ ap.add_argument("--out-router", default="data/router16_router.json")
34
+ ap.add_argument("--per-domain", type=int, default=60)
35
+ ap.add_argument("--cal-per-domain", type=int, default=10)
36
+ ap.add_argument("--bank77-model", default="model-b77-sem")
37
+ ap.add_argument("--default-model", default="model-giant-latin")
38
+ args = ap.parse_args()
39
+
40
+ schemas = json.loads(Path(args.schemas).read_text())
41
+ # labels.domain carries the ANCHOR (rt00..rt15); schemas.router maps domain -> anchor
42
+ domain_of = {a: d for d, a in schemas["router"].items() if not d.startswith("_")}
43
+ anchors = sorted(domain_of) # deterministic order
44
+ print(f"domains ({len(anchors)}):",
45
+ ", ".join(f"{domain_of[a]}->{a}" for a in anchors))
46
+
47
+ # one pass: bucket rows by router anchor, stride-sample inside each bucket.
48
+ # Rows are REWRITTEN to carry ONLY the domain question: learn teaches every
49
+ # question in a row, and the router fabric must never see domain labels.
50
+ buckets = defaultdict(list)
51
+ with open(args.train) as src:
52
+ for line in src:
53
+ if not line.strip():
54
+ continue
55
+ row = json.loads(line)
56
+ a = row.get("labels", {}).get("domain")
57
+ if a is None:
58
+ continue
59
+ slim = {
60
+ "state": row["state"],
61
+ "questions": {"domain": row["questions"]["domain"]},
62
+ "labels": {"domain": a},
63
+ }
64
+ buckets[a].append(json.dumps(slim, ensure_ascii=False))
65
+
66
+ train_rows, cal_rows = [], []
67
+ for a in anchors:
68
+ rows = buckets.get(a, [])
69
+ if not rows:
70
+ print(f" WARNING: no rows for anchor {a} ({domain_of[a]})")
71
+ continue
72
+ stride = max(1, len(rows) // max(1, args.per_domain))
73
+ picked = rows[::stride][: args.per_domain]
74
+ train_rows.extend(picked)
75
+ # deterministic cal carve: the row after each picked stride boundary
76
+ cal_idx = [min(i * stride + 1, len(rows) - 1) for i in range(args.cal_per_domain)]
77
+ seen = set()
78
+ for ci in cal_idx:
79
+ if rows[ci] not in seen and rows[ci] not in picked:
80
+ cal_rows.append(rows[ci])
81
+ seen.add(rows[ci])
82
+ print(f"train rows: {len(train_rows)} cal rows: {len(cal_rows)}")
83
+
84
+ Path(args.out_train).write_text("\n".join(train_rows) + "\n")
85
+ Path(args.out_cal).write_text("\n".join(cal_rows) + "\n")
86
+
87
+ # router.json: anchors = the modal criteria text per anchor across rows
88
+ crit_votes = defaultdict(Counter)
89
+ for line in train_rows:
90
+ row = json.loads(line)
91
+ crit = row["questions"]["domain"]["criteria"]
92
+ items = crit.obj.items() if hasattr(crit, "obj") else crit.items()
93
+ for tgt, text in items:
94
+ crit_votes[tgt][text] += 1
95
+ keep = set(anchors)
96
+ anchors_out = {a: votes.most_common(1)[0][0]
97
+ for a, votes in sorted(crit_votes.items()) if a in keep}
98
+ models = {}
99
+ for a in anchors:
100
+ d = domain_of[a]
101
+ models[a] = args.bank77_model if d == "bank77" else args.default_model
102
+ router = {
103
+ "anchors": anchors_out,
104
+ "models": models,
105
+ "domains": {a: domain_of[a] for a in anchors},
106
+ }
107
+ Path(args.out_router).write_text(json.dumps(router, indent=1))
108
+ print(f"wrote {args.out_router} ({len(anchors_out)} anchors)")
109
+
110
+
111
+ if __name__ == "__main__":
112
+ main()
engine/tools/router_routes.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Router route distribution across the 16 domains (v3.2.1 verification).
3
+
4
+ Stage-1 only: every row's state is settled on model-router16 with the 16
5
+ anchors from router.json; the winning anchor is tabulated per true domain.
6
+ Read-only evaluation of the shipped router (no selection, no training) —
7
+ same discipline as the v3.1.3 blind-router pass.
8
+
9
+ Usage: python3 tools/router_routes.py [--per-domain N] [--json-out F]
10
+ """
11
+ import argparse
12
+ import json
13
+ import sys
14
+ from collections import Counter, defaultdict
15
+ from pathlib import Path
16
+
17
+ ROOT = Path(__file__).resolve().parent.parent
18
+ sys.path.insert(0, str(ROOT / "server"))
19
+ from syfox_bridge import SyFoxEngine # noqa: E402
20
+
21
+ def main() -> None:
22
+ ap = argparse.ArgumentParser()
23
+ ap.add_argument("--router", default="model-router16")
24
+ ap.add_argument("--router-json", default="data/router16_router.json")
25
+ ap.add_argument("--giant-dir", default="data/giant")
26
+ ap.add_argument("--per-domain", type=int, default=15)
27
+ ap.add_argument("--json-out", default="")
28
+ a = ap.parse_args()
29
+
30
+ rj = json.load(open(a.router_json))
31
+ anchors = rj["anchors"] # rt00..rt15 -> anchor text
32
+ models = rj.get("models", {})
33
+ eng = SyFoxEngine(a.router)
34
+ q = {"route": {"type": "choice", "instructions":
35
+ "which domain does this state belong to",
36
+ "criteria": anchors}}
37
+
38
+ files = sorted(Path(a.giant_dir).glob("*_hidden.jsonl"))
39
+ table, confs = {}, {}
40
+ for f in files:
41
+ dom = f.name.replace("_hidden.jsonl", "")
42
+ hits, cs = Counter(), []
43
+ n = 0
44
+ for line in open(f):
45
+ if n >= a.per_domain:
46
+ break
47
+ r = json.loads(line)
48
+ if not r.get("state"):
49
+ continue
50
+ ans_a, _u, _e = eng.decide(r["state"], q,
51
+ {"semantics": True, "retrieval": True,
52
+ "hierarchy": True})
53
+ ans = ans_a.get("route", {})
54
+ if not ans.get("deferred") and ans.get("choice"):
55
+ hits[ans["choice"]] += 1
56
+ cs.append(ans.get("confidence", 0.0))
57
+ n += 1
58
+ table[dom] = dict(hits.most_common(4))
59
+ confs[dom] = round(sum(cs) / len(cs), 3) if cs else 0.0
60
+ print(f"{dom:<10} n={n:<3} top={dict(hits.most_common(3))} meanC={confs[dom]}")
61
+
62
+ # distribution shape: how concentrated is each domain's routing?
63
+ total = sum(sum(v.values()) for v in table.values())
64
+ top_agree = sum(next(iter(v.values())) for v in table.values() if v)
65
+ print(f"\nrouted rows: {total}, routed-to-modal-anchor agreement: "
66
+ f"{top_agree}/{total} = {top_agree/total:.3f}")
67
+ if a.json_out:
68
+ json.dump({"table": table, "mean_conf": confs},
69
+ open(a.json_out, "w"), indent=1)
70
+ print(f"wrote {a.json_out}")
71
+
72
+ if __name__ == "__main__":
73
+ main()