fahadhafeezofficial commited on
Commit
fd5366a
·
verified ·
1 Parent(s): 3b69b4a

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ paper/main.pdf filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .pytest_cache/
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .venv/
8
+ # Large or regenerable artefacts
9
+ data/activations/
10
+ data/derived/
11
+ logs/
12
+ results/*.tmp
13
+ paper/*.aux
14
+ paper/*.log
15
+ paper/*.out
16
+ paper/*.bbl
17
+ paper/*.blg
18
+ paper/*.toc
19
+ paper/*.fls
20
+ paper/*.fdb_latexmk
21
+ hf/_stage/
22
+ hf/clsa_hf_*/
CITATION.cff ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ message: "If you use this software, benchmark or checkpoints, cite them as below."
3
+ title: "CLSA: Causal Latent-State Agents for Pre-Action Safety"
4
+ abstract: >-
5
+ A causal multimodal world model for agent planning, with a deterministic
6
+ pre-action benchmark, a certificate format, and an evaluation protocol that
7
+ runs on a CPU-only laptop.
8
+ type: software
9
+ license: MIT
10
+ repository-code: "https://huggingface.co/datasets/fahadhafeezofficial/clsa-code"
11
+ url: "https://huggingface.co/datasets/fahadhafeezofficial/preact-bench"
12
+ keywords:
13
+ - agent safety
14
+ - world models
15
+ - causal representation learning
16
+ - sparse autoencoders
17
+ - pre-action monitoring
18
+ authors:
19
+ - family-names: Hafeez
20
+ given-names: Fahad
21
+ affiliation: "Newcastle University"
22
+ email: f.hafeez2@newcastle.ac.uk
23
+ orcid: "https://orcid.org/0009-0003-7903-7382"
24
+ version: "1.0.0"
25
+ date-released: "2026-11-25"
26
+ identifiers:
27
+ - type: other
28
+ value: "https://huggingface.co/datasets/fahadhafeezofficial/preact-bench"
29
+ description: "PreAct-Bench v1.0 (dataset)"
30
+ - type: other
31
+ value: "https://huggingface.co/fahadhafeezofficial/clsa-artifacts"
32
+ description: "CLSA trained artefacts (transcoder, world model, risk head, monitors)"
33
+ - type: other
34
+ value: "https://huggingface.co/datasets/fahadhafeezofficial/clsa-code"
35
+ description: "CLSA analysis code (source, tests, result files, figure scripts)"
Dockerfile ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ #
4
+ # CPU-only image. No GPU, no paid API, no vendor SDK is required for the core.
5
+ FROM python:3.11-slim
6
+
7
+ ENV PYTHONUNBUFFERED=1 \
8
+ PIP_NO_CACHE_DIR=1 \
9
+ CLSA_THREADS=4 \
10
+ HF_HUB_DISABLE_TELEMETRY=1
11
+
12
+ RUN apt-get update && apt-get install -y --no-install-recommends \
13
+ git make build-essential \
14
+ && rm -rf /var/lib/apt/lists/*
15
+
16
+ WORKDIR /clsa
17
+
18
+ COPY requirements.txt ./
19
+ RUN pip install --index-url https://download.pytorch.org/whl/cpu torch==2.5.1 \
20
+ && pip install -r requirements.txt
21
+
22
+ COPY . .
23
+
24
+ ENV PYTHONPATH=/clsa/src
25
+
26
+ # Reduced reproduction path: benchmark audit, experiments from cached artefacts,
27
+ # and all figures. Full training needs model downloads (~1.6 GB).
28
+ CMD ["make", "reproduce"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CLSA contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
LIMITATIONS.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Limitations
2
+
3
+ Kept current from Phase 0. Specific, not boilerplate.
4
+
5
+ ## Compute scope (measured, not assumed)
6
+
7
+ - Hardware: AMD Ryzen 5 7530U (6C/12T), 15.4 GB RAM, integrated Radeon GPU with
8
+ 0.5 GB shared memory, **no CUDA**, 57 GB free disk.
9
+ - Therefore: no 7B-class backbone, no Gemma Scope SAE weights, no GPU training.
10
+ Backbones are `Qwen2.5-0.5B-Instruct` (primary) and `SmolLM2-360M-Instruct`
11
+ (secondary), both open-weight and already cached locally.
12
+ - Threads are capped at 4 so the machine stays usable; all reported latencies
13
+ are for that setting and are not comparable to GPU numbers.
14
+ - The paper's RQ5 (7B-class / edge budgets) is answered only at the edge end.
15
+ No 7B-class result is claimed.
16
+
17
+ ## Benchmark scope
18
+
19
+ - PreAct-Bench ships 4,508 decision points over 120 episodes and four task
20
+ families, built on the in-repo deterministic sandbox (`preact-sandbox-v1.0`).
21
+ It is **not** a re-hosted AgentDojo, τ-bench, BFCL, WebShop or OSWorld split.
22
+ Adapter entry points for those environments exist, but no external split was
23
+ executed here; the data card says so and the paper must say so.
24
+ - Consequence and reversibility labels come from tool metadata written by us,
25
+ not from an independent annotation study. They are auditable (the code that
26
+ assigns them is shipped) but they are our ontology.
27
+ - Images are rendered screenshots, and the image featuriser is template matching
28
+ on a known bitmap font. It is real pixel computation, but it is far weaker than
29
+ a production OCR or VLM pipeline, and the GUI split is easier than a real
30
+ AndroidWorld/OSWorld screen.
31
+ - The SmolVLM-256M qualitative check is optional; if not run, it is reported as
32
+ not tested rather than as a negative result.
33
+
34
+ ## Statistical scope
35
+
36
+ - 120 episodes in the benchmark; the held-out suite contributes the most items.
37
+ Cluster bootstrap intervals are wide, and several comparisons will be
38
+ inconclusive rather than significant. Inconclusive is reported as inconclusive.
39
+ - The commitment contrast used to train monitors is small (order 10² positives);
40
+ monitors are therefore trained with strong regularisation and supplemented by
41
+ disjoint-seed trajectories. This is a real power limitation of the monitor
42
+ results, not a footnote.
43
+ - No multiplicity correction across the nine experiments: each experiment is a
44
+ pre-registered family of comparisons, and all are reported.
45
+
46
+ ## Simulation-only results
47
+
48
+ - E8 (multi-agent) is a belief-layer simulation, not a benchmark evaluation. It
49
+ can show that divergence moves before visible error *in that simulator*; it
50
+ cannot establish that this holds in a deployed multi-agent system.
51
+ - The Tier 2/3 controller's guarantee is a finite-sample selective-risk bound on
52
+ the calibration distribution. Distribution shift beyond the held-out families
53
+ is not covered by the guarantee.
54
+
55
+ ## Unverified citations
56
+
57
+ Listed in `paper/related_work_notes.md`. In short: Sinha (exposure vs commitment),
58
+ PRISMS, Kantamneni et al., MMAQA, CMC-Bench and BCEA could not be verified during
59
+ this pass and are **not** cited with numbers. Two bibliography entries (Xie et al.
60
+ and AxBench) need their author lists completed from the PDF before submission.
61
+ A human must verify these before submission.
62
+
63
+ ## What is not claimed
64
+
65
+ Adoption by any laboratory is not claimed. No result here establishes deployment
66
+ safety. CLSA is a monitor-plus-planner, not a secure-by-design system: it cannot
67
+ prevent harm that no monitor can see, and it is weaker than an architecture that
68
+ removes the capability to cause the harm at all. Monitoring does not replace
69
+ secure design.
Makefile ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CLSA - one command entry points.
2
+ # POSIX shell assumptions (Git Bash on Windows, sh in Docker).
3
+ PY ?= python
4
+ export PYTHONPATH := src
5
+ # AI-use statement option: a = results only, b = + drafting, c = + drafting and
6
+ # code, d = Elsevier template. Choose with `make statement N=b`.
7
+ N ?= a
8
+
9
+ .PHONY: help setup bench train experiments figures test reproduce tier1 tier2 tier3 clean statement paper publish submission
10
+
11
+ help:
12
+ @echo "make setup install pinned dependencies"
13
+ @echo "make bench build PreAct-Bench and audit it"
14
+ @echo "make train harvest activations and train all artefacts"
15
+ @echo "make experiments run E1-E9, write results/INDEX.md"
16
+ @echo "make figures regenerate all figures from results/"
17
+ @echo "make reproduce bench + train + experiments + figures (one command)"
18
+ @echo "make test run the test suite"
19
+ @echo "make tier1|tier2|tier3 standalone smoke tests for each adoption tier"
20
+ @echo "make statement N=a|b|c|d choose the AI-use wording, then make paper"
21
+ @echo "make paper rebuild paper/main.pdf"
22
+ @echo "make publish upload benchmark + artefacts to Hugging Face"
23
+ @echo "make submission build paper/dist/clsa-aij-submission.zip"
24
+
25
+ setup:
26
+ $(PY) -m pip install -r requirements.txt
27
+
28
+ bench:
29
+ $(PY) -m clsa.envs.bench_build
30
+ $(PY) -m clsa.envs.bench_io
31
+ $(PY) -m clsa.envs.supplementary
32
+
33
+ train:
34
+ $(PY) experiments/harvest.py --model primary
35
+ $(PY) experiments/train_all.py --model primary
36
+ # Secondary backbone uses a reduced, stratified harvest (eval + probe_train).
37
+ $(PY) experiments/harvest.py --model secondary --limit 200
38
+ $(PY) experiments/train_all.py --model secondary
39
+
40
+ experiments:
41
+ $(PY) experiments/run_all.py
42
+
43
+ figures:
44
+ $(PY) experiments/build_figures.py
45
+
46
+ reproduce:
47
+ $(MAKE) bench
48
+ $(MAKE) experiments
49
+ $(MAKE) figures
50
+ $(PY) experiments/check_numbers.py
51
+
52
+ statement:
53
+ @case "$(N)" in \
54
+ a) f=option_a_results_only.tex ;; \
55
+ b) f=option_b_drafting.tex ;; \
56
+ c) f=option_c_drafting_and_code.tex ;; \
57
+ d) f=option_d_elsevier_template.tex ;; \
58
+ *) echo "N must be a, b, c or d"; exit 1 ;; \
59
+ esac; \
60
+ cp paper/ai_statements/$$f paper/ai_statement.tex; \
61
+ echo "AI statement -> $$f"
62
+
63
+ paper:
64
+ cd paper && pdflatex -interaction=nonstopmode main.tex > /dev/null \
65
+ && bibtex main > /dev/null \
66
+ && pdflatex -interaction=nonstopmode main.tex > /dev/null \
67
+ && pdflatex -interaction=nonstopmode main.tex > /dev/null \
68
+ && echo "paper/main.pdf rebuilt"
69
+
70
+ publish:
71
+ $(PY) hf/publish.py
72
+
73
+ submission: paper
74
+ $(PY) paper/build_submission.py
75
+
76
+ test:
77
+ $(PY) -m pytest tests -q
78
+
79
+ tier1:
80
+ $(PY) tiers/tier1_dropin_monitor/test_tier1.py
81
+ tier2:
82
+ $(PY) tiers/tier2_world_controller/test_tier2.py
83
+ tier3:
84
+ $(PY) tiers/tier3_full_clsa/test_tier3.py
85
+
86
+ clean:
87
+ rm -rf results/*.json results/INDEX.md figures/*.pdf figures/*.png data/activations data/derived
PRE_REGISTRATION.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pre-registration — CLSA / PreAct-Bench
2
+
3
+ **Written before any main experiment was run.** Timestamped in git; the commit
4
+ hash is recorded in `results/INDEX.md`. Mirrored at `paper/preregistration.md`.
5
+
6
+ ## Scope actually available (declared up front)
7
+
8
+ Compute reality check (Phase 0) found: AMD Ryzen 5 7530U, 6 cores / 12 threads,
9
+ 15.4 GB RAM, integrated Radeon graphics (0.5 GB shared), **no CUDA**, CPU-only
10
+ PyTorch 2.5.1, 57 GB free disk.
11
+
12
+ Consequences, declared before running:
13
+
14
+ 1. No 7B-class backbone and no Gemma Scope SAE weights fit the time budget. Two
15
+ open-weight backbones are used instead: `Qwen/Qwen2.5-0.5B-Instruct`
16
+ (primary) and `HuggingFaceTB/SmolLM2-360M-Instruct` (secondary). The primary
17
+ backbone is **not** 7B-class and no claim is made that it is.
18
+ 2. The transcoder is trained in-repo (TopK) rather than loaded from Gemma Scope.
19
+ The Gemma Scope adapter is implemented but marked not-tested.
20
+ 3. The unit of analysis is the decision point. Closed-loop episode evaluation is
21
+ run on a small subset only, and is reported separately.
22
+ 4. Everything runs locally with no paid API. Reference compute prices are stated
23
+ accounting rates, not market prices.
24
+
25
+ ## Hypotheses
26
+
27
+ **H1 (grounding).** A hybrid state assembling probe-aligned, behaviourally
28
+ sensitive sparse features with belief and evidence state transfers better under
29
+ distribution shift than a dense probe, even if the dense probe wins
30
+ in-distribution.
31
+
32
+ - Primary test: selective risk at the calibrated threshold on the held-out
33
+ families (`web_shop`, `gui_settings`) with **no recalibration**.
34
+ - Direction: hybrid selective risk ≤ dense-probe selective risk.
35
+ - Honest-loss condition: the dense probe may win on the primary families
36
+ (`email_payment`, `files_ops`); that outcome is reported as the in-distribution
37
+ result it is, not hidden.
38
+
39
+ **H2 (control).** Latent MPC dominates uncertainty-only gating, the
40
+ consequence-aware rule baseline run on real data, and abort-only cascading on
41
+ harm per dollar at fixed success.
42
+
43
+ - Fixed success: success rate within 5 percentage points of the best baseline.
44
+ - Primary metric: harm per dollar (harms per reference dollar), lower is better.
45
+ - Comparisons are paired by state; cluster bootstrap over episodes.
46
+
47
+ **H3 (calibration).** Folding evidence acquisition into the score is necessary
48
+ for the bound to hold along a trajectory; acquire-then-refilter breaks it.
49
+
50
+ - Folded acquisition: realised selective risk − promised α ≤ 2 pp.
51
+ - Naive acquire-then-refilter: expected to exceed the bound by > 2 pp; if it does
52
+ not, the ablation is reported as not distinguishing the two designs.
53
+
54
+ ## Pre-registered falsification tests
55
+
56
+ The thesis fails if any of the following holds. Each is reported whatever the
57
+ outcome, in the same tables as positive results.
58
+
59
+ | ID | Test | Threshold | Where |
60
+ |---|---|---|---|
61
+ | F1 | Language-only planner at the same budget matches CLSA on state-verified success | paired 95% CI for the success difference contains 0, and no harm advantage | E1 |
62
+ | F2 | Simulated rollouts change no decision the planner alone would make | decision-change rate from extra rollouts ≤ 1% | E3 / Figure 7 |
63
+ | F3 | Hallucinated-world rate too high, or certificates cite simulated evidence contradicted by forked replay | hallucinated-world rate > 25%, or certificate fork consistency < 90% | E2, certificate audit |
64
+ | F4 | Foundation check: dense probe matches or beats the hybrid state on shifted selective risk | dense selective risk ≤ hybrid selective risk on held-out, no recalibration | E6 |
65
+ | F5a | Foundation check: shared-feature ablation does not flip behaviour above the probe-only control | flip(shared) ≤ flip(probe-only) + 1 pp | E5 / Figure 6 |
66
+ | F5b | Foundation check: calibrated gate's realised selective risk exceeds its bound | realised − promised > 2 pp on held-out | E4 / E6 |
67
+
68
+ Additional registered checks:
69
+
70
+ - **Feasibility check** wherever a bound is claimed: if base risk μ > α, the
71
+ method must abstain on at least (μ − α)/(1 − α) of cases. Reported whether or
72
+ not it passes.
73
+ - **Certificate completeness**: every executed, clarified or abstained action has
74
+ exactly one certificate; disabling the writer must make execution impossible.
75
+ - **Tier 1 overhead**: target under 0.1% additional latency per decision versus
76
+ the unmonitored agent. Measured and reported; a miss is stated in the tier
77
+ README and in Table 5.
78
+
79
+ ## Analysis plan (fixed now)
80
+
81
+ - Splits: `train` (fits everything), `calib` (conformal thresholds only),
82
+ `test` (primary families, held out), `heldout` (two whole families, never used
83
+ for any fitting). Supplementary `probe_train` trajectories from disjoint seeds
84
+ are used only for probe/SAE fitting and are never evaluated on.
85
+ - Seeds: data seed 0 for the benchmark; bootstrap seed 0; the run seed is
86
+ recorded in every results file.
87
+ - Uncertainty: percentile cluster bootstrap over episodes, 2000 resamples.
88
+ - Multiplicity: all policies, ablations and families are reported. No metric is
89
+ dropped after seeing results; if a condition cannot be evaluated it is listed
90
+ as blocked with the reason.
91
+ - Model selection: hyperparameters are fixed in `configs/` before the main runs;
92
+ no test-set tuning.
93
+ - The language-only baseline shares the candidate set with CLSA. The comparison
94
+ therefore isolates the planning substrate, not candidate generation.
95
+
96
+ ## Deviations log
97
+
98
+ Append-only. Each deviation records what changed, why, and when.
99
+
100
+ 1. 2026-11-25 — Harvest checkpointing changed mid-build (incremental writes) after
101
+ the host disconnected and lost one in-progress harvest. This affects mechanics,
102
+ not hypotheses or thresholds.
103
+ 2. 2026-11-25 — Probe-training data supplemented with disjoint-seed trajectories
104
+ because the benchmark's own commitment contrast was too small (107 positives in
105
+ train) to fit a monitor. These trajectories are excluded from every evaluation
106
+ split. Thresholds unchanged.
107
+ 3. 2026-11-25 — Transcoder width reduced from the planned 512 features to 192
108
+ (k=32 to k=16, 400 to 120 epochs) because the larger SAE did not finish on the
109
+ CPU-only host. Reported in `LIMITATIONS.md`; no threshold changed.
110
+ 4. 2026-11-25 — Primary harvest stopped at 540 states of 650, and the second
111
+ backbone was harvested at 200 states rather than the full set, to keep total
112
+ CPU time within the machine's budget. Evaluation therefore uses 302 held-out
113
+ states on the primary backbone and 100 on the secondary.
114
+ 5. 2026-11-25 — **Exploratory, not pre-registered:** a cross-backbone block was
115
+ added to E6 after the main results. It asks whether the pipeline replicates on
116
+ a second backbone and whether a calibrated threshold carries across backbones.
117
+ It is labelled exploratory in the paper (`sec:results`, "Transfer across
118
+ backbones") and its negative half (threshold transfer) is reported with the
119
+ same prominence as its positive half. Adding it did not change any
120
+ pre-registered analysis, threshold or split.
PROGRESS.md ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build log
2
+
3
+ Newest last. Every entry says what was run and what it produced, so a reader can
4
+ tell a completed stage from a planned one.
5
+
6
+ ## 1. Scaffold and protocol
7
+
8
+ - Repository layout, MIT licence with SPDX headers, pinned dependencies.
9
+ - `PRE_REGISTRATION.md` written and committed at `7d3946a` **before** any main
10
+ run; hypotheses, thresholds and falsification criteria frozen there.
11
+ - Schemas published: `schemas/decision_point.schema.json`,
12
+ `schemas/certificate.schema.json` (both validated against real records).
13
+
14
+ ## 2. Benchmark
15
+
16
+ - `preact-sandbox-v1.0`: four families, 120 episodes, 4,508 decision points.
17
+ - Splits episode-disjoint: train 1,135 / calib 380 / test 380 / heldout 1,540.
18
+ - Audit: schema validation on every item, 40/40 sampled fork replays reproduce
19
+ their recorded labels.
20
+ - Data card written (`data/DATA_CARD.md`).
21
+
22
+ ## 3. Hardware decision
23
+
24
+ Measured the laptop (Ryzen 5 7530U, 6C/12T, 15.4 GB, no CUDA, 57.7 GB free).
25
+ Declared the reduction to sub-1B open-weight backbones in `configs/compute.yaml`
26
+ rather than pretend a 7B result was obtainable. 4 torch threads, no dataloader
27
+ workers.
28
+
29
+ ## 4. Harvest
30
+
31
+ - Qwen2.5-0.5B: 540 states cached over ~46 minutes of CPU time, resumable in
32
+ increments of 10. Three disconnects cost at most 10 states each after the
33
+ checkpointing fix.
34
+ - Two bugs found and fixed here: a numpy object-array round-trip that corrupted
35
+ metadata, and a swapped unpack of `(hidden, token_hidden, ids, scores)` that
36
+ made the resume path read scores as metadata.
37
+ - SmolLM2-360M: **not harvested**. No cross-backbone result exists.
38
+
39
+ ## 5. Training
40
+
41
+ - Dataset: 540 states, 6,245 item rows after compacting out uncached states.
42
+ - Transcoder: 192 features, k=16, 120 epochs. Reconstruction is weak and is
43
+ reported as such; the dense probe is the stronger predictive baseline.
44
+ - Admission: 6 shared, 4 probe-only, 4 random features.
45
+ - World model: 130,797 parameters; counterfactual consistency 0.914, Brier 0.082.
46
+ - Training wall clock: 173 s on 4 CPU threads.
47
+
48
+ ## 6. Experiments
49
+
50
+ E1–E9 all completed; none blocked. Headline: on 302 held-out decision points,
51
+ executed harm 0.000 against 0.182 for language-first (paired difference -0.182,
52
+ 95% CI [-0.247, -0.122]), success 0.185 against 0.046, at 139 charged tokens per
53
+ decision against 23.
54
+
55
+ Two results cut against the thesis and are reported as measured: the budget
56
+ frontier does not move with budget, and irreversible harm falls to 0.066 rather
57
+ than zero. `results/replication_report.md` lists every deviation.
58
+
59
+ ## 7. Figures, tables, paper
60
+
61
+ - f1–f8 produced from `results/` only.
62
+ - Tables generated with a value manifest; `experiments/check_numbers.py` confirms
63
+ 76/76 values trace to a results file.
64
+ - `paper/main.pdf` compiles in three passes with no errors and no undefined
65
+ citations, 10 pages.
66
+
67
+ ## 8. Tiers, tests, packaging
68
+
69
+ - Three tiers with README, config, quickstart and standalone test; all pass.
70
+ - Tier 1 measured overhead: 0.81 ms/decision. Against a probe-free tensor path
71
+ that is 775% and the 0.1% target is **not met**; against an end-to-end decision
72
+ it is 0.039%. Both reported; the flattering denominator is not used to claim
73
+ the target.
74
+ - 31 tests pass. `Makefile`, `Dockerfile`, `requirements.txt`, `CITATION.cff`,
75
+ `docs/certificate_format.md`, `paper/world_class_checklist.md`,
76
+ `paper/lab_integration_matrix.csv` in place.
77
+
78
+ ## 9. Cross-backbone replication
79
+
80
+ - `SmolLM2-360M-Instruct` harvested at 200 stratified states (eval first, then
81
+ probe-training), 19 minutes; trained in 66 s.
82
+ - Admission dissociation replicates: 0.920 shared vs 0.080 probe-only flip rate,
83
+ with 1 admitted shared feature (against 6 on the primary backbone).
84
+ - Decision level replicates: harm 0.000 against 0.290 for language-first on 100
85
+ held-out states, paired difference -0.290 [-0.458, -0.122], p = 0.001.
86
+ - Threshold does **not** transfer: probe-score correlation 0.075 across 1,921
87
+ shared states; the transferred threshold drops coverage to 0.670, while
88
+ recalibration restores 0.920 at selective risk 0.065 (upper 0.080 < alpha).
89
+ - Reported in E6 and in the paper as "the method ports, the calibration does not".
90
+
91
+ ## 10. Fresh-eyes review (simplifications applied)
92
+
93
+ - `BehaviourOnly` was a byte-for-byte copy of `ProbeGate`; it is now a subclass
94
+ with `kind="behaviour"`. Verified: 13 policies, 0 numeric differences in E1.
95
+ - Budget opening (`allocator` + optional `monitor` charge) and repeated-state
96
+ construction were duplicated in six policies; extracted to `open_budget`,
97
+ `repeat_state` and `risk_head_scores`.
98
+ - Removed 13 genuinely unused imports across 10 modules, found by an AST scan.
99
+ All modules import, 31 tests pass, E1 output unchanged.
100
+ - The E8 adapter lambda is gone: the experiment runner inspects the signature and
101
+ only passes a backbone key where one is expected.
102
+
103
+ ## Open
104
+
105
+ - External benchmark adapters (written, not executed).
106
+ - Larger primary harvest to tighten intervals.
107
+ - AIJ-style journal submission: see `paper/submission_plan.md`.
README.md ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ tags:
4
+ - agent-safety
5
+ - world-models
6
+ - causal-inference
7
+ - reproducibility
8
+ - code
9
+ ---
10
+
11
+ # CLSA — code for "Causal Latent-State Agents"
12
+
13
+ This repository is the released code for *Causal Latent-State Agents: Pre-Action
14
+ Safety from a World Model You Can Audit* (submitted to *Artificial Intelligence*,
15
+ Elsevier). It is a mirror of the repository accompanying the submission, at
16
+ commit `164190e` (2026-11-25).
17
+
18
+ It contains the analysis code, the configuration, the tests, the result files and
19
+ the figure scripts. The benchmark and the trained artefacts are in two companion
20
+ repositories:
21
+
22
+ | What | Where |
23
+ |---|---|
24
+ | PreAct-Bench: 4,508 pre-action decision points, images, schema, data card | [fahadhafeezofficial/preact-bench](https://huggingface.co/datasets/fahadhafeezofficial/preact-bench) |
25
+ | Trained artefacts for both backbones (transcoder, world model, risk head, monitors) | [fahadhafeezofficial/clsa-artifacts](https://huggingface.co/fahadhafeezofficial/clsa-artifacts) |
26
+
27
+ ## Layout
28
+
29
+ | Path | Contents |
30
+ |---|---|
31
+ | `src/clsa/` | Package: sandbox, transcoder, world model, risk head, controller, monitors |
32
+ | `experiments/` | E1–E9 and `check_numbers.py`, which traces every table value back to `results/` |
33
+ | `tiers/` | Standalone smoke tests for the three adoption tiers |
34
+ | `tests/` | Test suite (31 tests) |
35
+ | `configs/` | Frozen experiment configuration |
36
+ | `results/` | Result JSON/JSONL files behind every number in the paper |
37
+ | `figures/`, `paper/` | Figure scripts and LaTeX source |
38
+ | `hf/` | Scripts that published these three repositories |
39
+
40
+ ## Running it
41
+
42
+ ```bash
43
+ python -m pip install -r requirements.txt
44
+ export PYTHONPATH=src
45
+ make test # 31 tests
46
+ python experiments/check_numbers.py # 103 table values traced to results/
47
+ ```
48
+
49
+ Full reproduction of the benchmark and the artefacts needs the two companion
50
+ repositories:
51
+
52
+ ```bash
53
+ hf download fahadhafeezofficial/preact-bench --repo-type dataset --local-dir data/preact_bench
54
+ hf download fahadhafeezofficial/clsa-artifacts --repo-type model --local-dir data/derived
55
+ make reproduce # bench + experiments + figures + number check
56
+ ```
57
+
58
+ The derived artefacts must sit in `data/derived/<backbone with "/" as "__">`,
59
+ which is the layout the artefacts repository already uses and the only layout
60
+ `load_model()` resolves; there is no environment variable for that path.
61
+
62
+ Everything runs on a CPU, with no GPU, no paid API and no vendor SDK.
63
+
64
+ ## Licence and citation
65
+
66
+ MIT (see `LICENSE`). Citation metadata is in `CITATION.cff`.
67
+
68
+ ---
69
+
70
+ ## Project README
71
+
72
+ ## CLSA — Causal Latent-State Agents
73
+
74
+ A causal multimodal world model for agent planning, with a benchmark, a
75
+ certificate format and an evaluation protocol that can be reproduced on a laptop.
76
+
77
+ Adoption by any laboratory is not claimed. The work is designed for adoption:
78
+ lab-agnostic, open-weight first, and reproducible in one command.
79
+
80
+ ## The problem
81
+
82
+ Agents act before they understand consequences. A language model can describe a
83
+ risk and still take it, because describing is not simulating. CLSA separates the
84
+ two: a trajectory transcoder turns the backbone's internal state into a discrete,
85
+ auditable latent state; a causal dynamics model predicts what each candidate
86
+ action would do to that state; and a controller acts only when a calibrated,
87
+ state-verified certificate can be written.
88
+
89
+ ## What is in this repository
90
+
91
+ | Piece | Path | What it gives you |
92
+ |---|---|---|
93
+ | Benchmark | `data/preact_bench/` | PreAct-Bench: 4,508 decision points, 120 episodes, 4 tool families, fork-replayable labels |
94
+ | Transcoder | `src/clsa/transcoder/` | Top-k sparse transcoder + Tiwari admission rule |
95
+ | World model | `src/clsa/world_model/` | Causal dynamics, risk head, four losses, CPU training |
96
+ | Controller | `src/clsa/controller/` | Latent MPC, five modes, certificates, charged budget |
97
+ | Evaluation | `src/clsa/eval/` | E1–E9, paired and cluster bootstrap, state-verified labels |
98
+ | Tiers | `tiers/` | Three adoption tiers, each with install, quickstart and test |
99
+ | Paper | `paper/` | LaTeX draft, pre-registration, verified bibliography, JISC venue plan |
100
+
101
+ ## Quickstart
102
+
103
+ ```bash
104
+ python -m pip install -r requirements.txt
105
+ export PYTHONPATH=src
106
+ make bench # rebuild + audit the benchmark
107
+ make experiments # run E1-E9 against cached artefacts
108
+ make figures # regenerate every figure
109
+ make test # test suite
110
+ ```
111
+
112
+ Full training from raw model weights (needs ~1.6 GB of open-weight downloads):
113
+
114
+ ```bash
115
+ make train
116
+ ```
117
+
118
+ One command for the whole path: `make reproduce`.
119
+
120
+ ## Tiers
121
+
122
+ 1. **Drop-in monitor** (`tiers/tier1_dropin_monitor`) — pre-action probe and
123
+ calibrated gate. No retraining, no world model. Target: under 0.1% added
124
+ latency; the measured value is reported, met or not.
125
+ 2. **World-model controller** (`tiers/tier2_world_controller`) — latent rollouts,
126
+ MPC and certificates. Needs a few hundred trajectories.
127
+ 3. **Full CLSA** (`tiers/tier3_full_clsa`) — full counterfactual training,
128
+ multi-agent beliefs, distillation.
129
+
130
+ ## Scope, stated plainly
131
+
132
+ - Everything here ran on a **CPU-only laptop** (Ryzen 5 7530U, 15.4 GB RAM, no
133
+ CUDA). The primary backbone is `Qwen2.5-0.5B-Instruct`; a second backbone
134
+ (`SmolLM2-360M-Instruct`, 200 states) is used for a cross-backbone replication.
135
+ The pipeline replicates there (harm 0.000 against 0.290) but the calibrated
136
+ threshold does not transfer (probe-score correlation 0.075), so E6 reports both
137
+ the transferred and the recalibrated gate. No 7B-class model was run.
138
+ - The benchmark is an in-repository deterministic sandbox, not a re-hosted
139
+ AgentDojo or τ-bench. Adapters exist; external splits were not executed.
140
+ - Every number in the paper traces to a file in `results/`; `make reproduce`
141
+ checks that. Unverified citations are marked index-only and never quoted.
142
+ - Hypotheses and thresholds were frozen in `PRE_REGISTRATION.md` and committed
143
+ at `7d3946a` before the main runs. Deviations are logged there.
144
+
145
+ See `LIMITATIONS.md` for what this work does not show, and `PROGRESS.md` for the
146
+ build log.
147
+
148
+ ## Released artefacts
149
+
150
+ - **Dataset:** [`fahadhafeezofficial/preact-bench`](https://huggingface.co/datasets/fahadhafeezofficial/preact-bench)
151
+ — 4,508 rows, GUI images, schema, data card (MIT).
152
+ - **Checkpoints:** [`fahadhafeezofficial/clsa-artifacts`](https://huggingface.co/fahadhafeezofficial/clsa-artifacts)
153
+ — transcoder, world model, risk head and monitors for both backbones.
154
+ - **Code:** [`fahadhafeezofficial/clsa-code`](https://huggingface.co/datasets/fahadhafeezofficial/clsa-code)
155
+ — this repository, mirrored at the commit the paper cites (MIT).
156
+
157
+ Republish with `python hf/publish.py` (stages from `data/` and pushes to the
158
+ account you are logged in as; `--dry-run` builds the folders only, and
159
+ `--code-only` refreshes the code mirror alone).
160
+
161
+ ```python
162
+ from datasets import load_dataset
163
+ ds = load_dataset("fahadhafeezofficial/preact-bench", split="train")
164
+ ```
165
+
166
+ ## Licence
167
+
168
+ MIT. See `LICENSE`. Every source file carries an SPDX header.
169
+
170
+ ## Citation
171
+
172
+ See `CITATION.cff`. Paper: Fahad Hafeez, Newcastle University
173
+ (ORCID 0009-0003-7903-7382).
configs/bench.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PreAct-Bench construction. No magic numbers live in code.
2
+ seed: 0
3
+ n_per_family: 10
4
+ probe_train_per_family: 14
5
+ probe_train_seed_salt: 7919
6
+ alpha: 0.1
7
+ B_tokens: 1200
8
+ families_primary: ["email_payment", "files_ops"]
9
+ families_heldout: ["web_shop", "gui_settings"]
10
+ variants: ["clean", "injection", "stale", "conflict"]
11
+ splits:
12
+ train: 0.6
13
+ calib: 0.2
14
+ test: 0.2
15
+ heldout: "whole_families"
16
+ staleness_days: 90
17
+ evidence:
18
+ modality_trust: {tool_state: 0.95, image: 0.80, text: 0.60}
19
+ injection_trust_multiplier: 0.15
configs/compute.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Measured on the development laptop (2026-11-25). Regenerate with: python experiments/probe_compute.py
2
+ hardware:
3
+ model: "LENOVO 82XX"
4
+ cpu: "AMD Ryzen 5 7530U with Radeon Graphics"
5
+ physical_cores: 6
6
+ logical_cores: 12
7
+ ram_gb: 15.4
8
+ gpu: "AMD Radeon (TM) Graphics (integrated, shared memory)"
9
+ gpu_vram_gb: 0.5
10
+ cuda_available: false
11
+ torch: "2.5.1+cpu"
12
+ disk_free_gb: 57.7
13
+ os: "Windows 11 (win32)"
14
+
15
+ # Guard rails so the machine stays usable while experiments run.
16
+ guard_rails:
17
+ torch_threads: 4
18
+ interop_threads: 1
19
+ max_rss_gb: 4.5
20
+ dataloader_workers: 0
21
+ batch_size_max: 8
22
+ max_sequence_tokens: 192
23
+ checkpoint_every_minutes: 10
24
+
25
+ # Scope actually used. This is a CPU-only laptop; no 7B-class backbone and no
26
+ # Gemma Scope SAE weights fit. The reduction is declared here, in PROGRESS.md,
27
+ # in LIMITATIONS.md and in the paper's limitations section.
28
+ scope:
29
+ compute_class: "cpu_laptop_small"
30
+ backbone_primary: "Qwen/Qwen2.5-0.5B-Instruct"
31
+ backbone_secondary: "HuggingFaceTB/SmolLM2-360M-Instruct"
32
+ backbones_requested_by_spec: 2
33
+ backbones_used: 2
34
+ seven_b_class_feasible: false
35
+ sae_weights: "trained_in_repo_topk_transcoder"
36
+ gemma_scope_feasible: false
37
+ primary_benchmarks: ["preact_email_payment", "preact_files_ops"]
38
+ transfer_benchmarks: ["preact_web_shop", "preact_gui_settings"]
39
+ vlm_backbone: "HuggingFaceTB/SmolVLM-256M-Instruct"
40
+ vlm_use: "qualitative_image_evidence_check_only"
41
+ seeds: [0, 1, 2]
42
+ max_download_gb: 2.0
43
+ estimated_full_run_minutes: 45
44
+ notes: >
45
+ Every model used here is already in the local Hugging Face cache, so the
46
+ whole pipeline runs with no new download and no paid API. Training runs on
47
+ CPU with 4 threads. Activation harvesting is the only LLM-bound step and is
48
+ cached to disk so that all experiments and figures re-run in seconds.
configs/controller.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Controller, calibration and cost accounting.
2
+ seed: 0
3
+ alpha: 0.1 # episode-level selective-risk budget
4
+ alpha_per_step: 0.02 # converted to episode level by the union bound
5
+ band: 0.05 # uncertainty band that triggers simulate
6
+ B_tokens: 1200 # fixed compute budget per episode (per decision offline)
7
+ gamma_risk: 1.0
8
+ lambda_cost: 0.05
9
+ mu_interaction: 0.02
10
+ risk_threshold: 0.5 # replaced at runtime by the conformal threshold
11
+ costs:
12
+ monitor: 8.0
13
+ rollout: 12.0
14
+ verify: 40.0
15
+ alloc: 6.0
16
+ # Reference compute price for reporting success-per-dollar. The marginal price of
17
+ # a local open-weight model is zero; this is a documented accounting rate, not a
18
+ # market price, and it is charged for every component including the allocator.
19
+ cost_model:
20
+ usd_per_1k_tokens: 0.0006
21
+ usd_per_cpu_hour: 0.02
22
+ note: "reference rate for local CPU inference; electricity plus amortisation"
23
+ budgets:
24
+ monte_carlo_samples: 3
25
+ max_rollouts_per_decision: 60
26
+ max_verifications_per_decision: 2
27
+ modes: ["direct", "simulate", "verify/acquire", "clarify", "abstain"]
28
+ risk_classes: ["read", "reversible", "compensable", "irreversible"]
configs/transcoder.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Trajectory transcoder and activation harvesting.
2
+ seed: 0
3
+ backbones:
4
+ primary: "Qwen/Qwen2.5-0.5B-Instruct"
5
+ secondary: "HuggingFaceTB/SmolLM2-360M-Instruct"
6
+ efficiency_probe: "EleutherAI/pythia-160m"
7
+ layer_frac: 0.6
8
+ max_tokens: 160
9
+ threads: 4
10
+ supplementary_states: 40
11
+ score_splits: ["test", "heldout"]
12
+ sae:
13
+ n_features: 192
14
+ k: 16
15
+ epochs: 120
16
+ lr: 0.003
17
+ l1: 0.001
18
+ batch_size: 256
19
+ admission:
20
+ alignment_threshold: 0.12
21
+ flip_threshold: 0.08
22
+ n_random_sets: 5
23
+ random_seed: 13
24
+ coherence_gate: 0.65
25
+ probe:
26
+ C: 0.05
27
+ class_weight: "balanced"
28
+ train_on: "commitment_contrast"
configs/world_model.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Counterfactual World Learning.
2
+ seed: 0
3
+ threads: 4
4
+ hidden: 192
5
+ epochs: 220
6
+ lr: 0.002
7
+ risk_head_hidden: 96
8
+ lambdas:
9
+ cf: 1.0
10
+ cal: 0.5
11
+ sparse: 0.01
12
+ z_dropout: 0.25
13
+ batch_size: 256
14
+ evaluation:
15
+ splits: ["test", "heldout"]
16
+ horizons: [1, 2, 3]
docs/certificate_format.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Certificate format (v1.0)
2
+
3
+ A certificate is the object an auditor reads instead of a transcript. It is
4
+ published as `schemas/certificate.schema.json`, versioned, and validated on every
5
+ write; a record that fails validation is never appended to the ledger.
6
+
7
+ ## Shape
8
+
9
+ ```
10
+ Cert(a_t) = <G, Fork, E, Bound>
11
+ ```
12
+
13
+ | Element | Question it answers |
14
+ |---|---|
15
+ | `G` | Why this action was scored as it was: the attributed subgraph over admitted features |
16
+ | `Fork` | What else could have been done, and what the model said would happen |
17
+ | `E` | What evidence was used, whether it was stale, and whether it conflicted |
18
+ | `Bound` | How wrong the risk estimate could be, at what confidence, at what cost |
19
+
20
+ ## Fields
21
+
22
+ ### Identity
23
+
24
+ - `cert_id` — 24 hex characters, derived from item, step, time and process.
25
+ - `schema_version` — `"1.0"`.
26
+ - `item_id`, `episode_id`, `step` — the decision point in PreAct-Bench.
27
+
28
+ ### Decision
29
+
30
+ - `decision` — what the agent did: `execute`, `abstain`, `clarify`, `verify`.
31
+ - `mode` — which controller mode produced it: `direct`, `simulate`,
32
+ `verify/acquire`, `clarify`, `abstain`.
33
+ - `action` — the chosen candidate, as `{name, args}`.
34
+
35
+ ### `G` — attribution
36
+
37
+ ```json
38
+ {"method": "feature_ablation_attribution",
39
+ "nodes": [{"id": "f17", "kind": "feature", "label": "...", "weight": 0.42}],
40
+ "edges": [{"src": "f17", "dst": "harm", "weight": 0.42}]}
41
+ ```
42
+
43
+ Nodes are admitted features or outcome variables; edges carry the ablation effect.
44
+ A certificate without an attribution method is invalid.
45
+
46
+ ### `Fork` — counterfactual
47
+
48
+ `alternative` (the next-best candidate), `predicted` and `replayed` outcomes
49
+ (`success`, `harm`, `irreversible_harm`), `consistent` (boolean) and `divergence`
50
+ (scalar). When no replay was performed, `replayed.available` is `false` and the
51
+ divergence is not used in the bound.
52
+
53
+ ### `E` — evidence
54
+
55
+ `claims_used` (ids), `stale` (any claim past its freshness window), `conflict`
56
+ (claims disagree across modalities) and `acquired` (evidence fetched at this step).
57
+ Evidence is not free: acquisitions appear in `cost.verifications`.
58
+
59
+ ### `Bound` — risk
60
+
61
+ - `alpha` — target miscoverage.
62
+ - `coverage` — empirical coverage on the calibration split.
63
+ - `selective_risk_upper` — Clopper–Pearson upper bound at `n` accepted decisions.
64
+ - `n` — calibration sample size behind the bound.
65
+ - `method` — `clopper_pearson_selective` or `conformal_split`.
66
+ - `feasible` — whether the bound is below `alpha` on the calibration split.
67
+ - `budget_spent`, `budget_limit`, `components` — tokens charged, split into
68
+ `monitor`, `simulation`, `verification`, `allocator`.
69
+
70
+ ### Ledger
71
+
72
+ `prev_hash` and `cert_hash` chain records:
73
+
74
+ ```
75
+ cert_hash = sha256(prev_hash || canonical_json(record_without_cert_hash))
76
+ ```
77
+
78
+ Editing any record breaks verification from that point onward. `verify_chain()`
79
+ returns `(ok, message)`; `audit_ledger(path)` returns counts, chain status and
80
+ schema status for a file.
81
+
82
+ ## Why these four elements
83
+
84
+ A safety claim needs to be falsifiable. `G` makes the cause inspectable. `Fork`
85
+ makes the alternative explicit. `E` makes the inputs auditable. `Bound` makes the
86
+ error quantitative. Remove any one and the claim becomes a narrative.
87
+
88
+ ## Versioning
89
+
90
+ The schema is additive within a major version. A consumer must reject records with
91
+ an unknown `schema_version` rather than guess. `cert_id` is not a hash of the
92
+ record (the record contains its own hash chain); it is an identifier.
experiments/_runner.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Shared runner for experiment scripts: provenance, config, blocking."""
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import inspect
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
12
+
13
+ from clsa.util import load_config, write_result # noqa: E402
14
+
15
+
16
+ def run(name: str, fn, config_name: str = "controller", notes: str = "") -> dict:
17
+ ap = argparse.ArgumentParser()
18
+ ap.add_argument("--model", default="primary")
19
+ args = ap.parse_args()
20
+ cfg = load_config(config_name)
21
+ try:
22
+ # Experiments take a backbone key; E8 takes an episode count, so only pass
23
+ # the model where the signature asks for one.
24
+ first = next(iter(inspect.signature(fn).parameters), None)
25
+ payload = fn(args.model) if first in ("model", "backbone_key") else fn()
26
+ payload.pop("raw_rows", None)
27
+ Path("results").mkdir(exist_ok=True)
28
+ path = write_result(name, payload, config=cfg, seed=int(cfg.get("seed", 0)), notes=notes)
29
+ print(f"[{name}] wrote {path}")
30
+ return payload
31
+ except Exception as exc: # noqa: BLE001 - blocked experiments must be recorded
32
+ import traceback
33
+
34
+ payload = {
35
+ "blocked": True,
36
+ "error": f"{type(exc).__name__}: {exc}",
37
+ "traceback": traceback.format_exc()[-2000:],
38
+ }
39
+ path = write_result(
40
+ name, payload, config=cfg, seed=int(cfg.get("seed", 0)), notes=f"BLOCKED: {exc}"
41
+ )
42
+ print(f"[{name}] BLOCKED -> {path}\n{exc}")
43
+ return payload
experiments/build_figures.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Regenerate every figure from results/. A missing result skips its figure."""
4
+ from __future__ import annotations
5
+
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ FIGURES = Path(__file__).resolve().parents[1] / "figures"
11
+ SCRIPTS = sorted(FIGURES.glob("f*.py"))
12
+
13
+
14
+ def main() -> None:
15
+ failed = []
16
+ for script in SCRIPTS:
17
+ out = subprocess.run(
18
+ [sys.executable, script.name], cwd=str(FIGURES), capture_output=True, text=True
19
+ )
20
+ status = "ok" if out.returncode == 0 else "skipped/failed"
21
+ print(f"[{status}] {script.name}")
22
+ if out.returncode != 0:
23
+ failed.append((script.name, (out.stderr or "").strip().splitlines()[-1:]))
24
+ if failed:
25
+ print("\nFigures not produced (with reason):")
26
+ for name, err in failed:
27
+ print(f" {name}: {err}")
28
+ tables = FIGURES / "tables.py"
29
+ if tables.exists():
30
+ subprocess.run([sys.executable, "tables.py"], cwd=str(FIGURES))
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()
experiments/check_numbers.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Check that every number in the generated tables exists in a results file.
4
+
5
+ Reads figures/table_values.json (written by figures/tables.py) and verifies each
6
+ value against results/*.json. Fails loudly rather than letting an untraceable
7
+ number reach the paper.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from pathlib import Path
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ RESULTS = ROOT / "results"
16
+ TABLE_VALUES = ROOT / "figures" / "table_values.json"
17
+
18
+
19
+ def flatten(obj, prefix=""):
20
+ out = {}
21
+ if isinstance(obj, dict):
22
+ for k, v in obj.items():
23
+ out.update(flatten(v, f"{prefix}.{k}" if prefix else str(k)))
24
+ elif isinstance(obj, list):
25
+ for i, v in enumerate(obj):
26
+ out.update(flatten(v, f"{prefix}[{i}]"))
27
+ else:
28
+ out[prefix] = obj
29
+ return out
30
+
31
+
32
+ def main() -> None:
33
+ if not TABLE_VALUES.exists():
34
+ print("no table values file; run figures/tables.py first")
35
+ raise SystemExit(1)
36
+ values = json.loads(TABLE_VALUES.read_text())
37
+ corpus = []
38
+ for path in RESULTS.glob("*.json"):
39
+ corpus.extend(flatten(json.loads(path.read_text())).values())
40
+ numeric = [v for v in corpus if isinstance(v, (int, float)) and not isinstance(v, bool)]
41
+ rounded = {round(float(v), 6) for v in numeric}
42
+
43
+ missing = []
44
+ for table, entries in values.items():
45
+ for key, val in entries.items():
46
+ if isinstance(val, (str, bool, dict, list)) or val is None:
47
+ continue
48
+ candidates = {round(float(val), 6), round(float(val), 4), round(float(val), 3), round(float(val), 2)}
49
+ if not (candidates & rounded):
50
+ missing.append((table, key, val))
51
+ if missing:
52
+ print(f"{len(missing)} table values not found in results/:")
53
+ for m in missing[:20]:
54
+ print(" ", m)
55
+ raise SystemExit(1)
56
+ print(f"all {sum(len(v) for v in values.values())} table values trace to results/")
57
+
58
+
59
+ if __name__ == "__main__":
60
+ main()
experiments/e1_main.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """E1: CLSA versus every baseline at the same budget, paired by state."""
4
+ from _runner import run
5
+
6
+ from clsa.eval.experiments import e1_main
7
+
8
+ if __name__ == "__main__":
9
+ run("e1_main", e1_main, notes="E1 state-verified comparison")
experiments/e2_world_model.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """E2: per-modality prediction, counterfactual consistency, horizon gap."""
4
+ from _runner import run
5
+
6
+ from clsa.eval.experiments import e2_world_model
7
+
8
+ if __name__ == "__main__":
9
+ run("e2_world_model", e2_world_model, notes="E2 world-model quality")
experiments/e3_budget.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """E3: budget Pareto curves and marginal value of rollouts."""
4
+ from _runner import run
5
+
6
+ from clsa.eval.experiments import e3_budget
7
+
8
+ if __name__ == "__main__":
9
+ run("e3_budget", e3_budget, notes="E3 budget allocation")
experiments/e4_calibration.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """E4: calibration, selective risk and the feasibility check."""
4
+ from _runner import run
5
+
6
+ from clsa.eval.experiments import e4_calibration
7
+
8
+ if __name__ == "__main__":
9
+ run("e4_calibration", e4_calibration, notes="E4 calibration")
experiments/e5_causality.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """E5: Tiwari admission dissociation (shared / probe-only / random)."""
4
+ from _runner import run
5
+
6
+ from clsa.eval.experiments import e5_causality
7
+
8
+ if __name__ == "__main__":
9
+ run("e5_causality", e5_causality, notes="E5 causal admission")
experiments/e6_transfer.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """E6: held-out families with and without recalibration."""
4
+ from _runner import run
5
+
6
+ from clsa.eval.experiments import e6_transfer
7
+
8
+ if __name__ == "__main__":
9
+ run("e6_transfer", e6_transfer, notes="E6 transfer")
experiments/e7_multimodal.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """E7: GUI split, reversible versus irreversible, abstention versus fabrication."""
4
+ from _runner import run
5
+
6
+ from clsa.eval.experiments import e7_multimodal
7
+
8
+ if __name__ == "__main__":
9
+ run("e7_multimodal", e7_multimodal, notes="E7 multimodal core")
experiments/e8_multiagent.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """E8: multi-agent divergence and governance (belief-layer simulation)."""
4
+ from _runner import run
5
+
6
+ from clsa.eval.multiagent import e8_multiagent
7
+
8
+ if __name__ == "__main__":
9
+ run("e8_multiagent", e8_multiagent, notes="E8 multi-agent simulation")
experiments/e9_efficiency.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """E9: charged cost, latency, peak memory and distillation."""
4
+ from _runner import run
5
+
6
+ from clsa.eval.experiments import e9_efficiency
7
+
8
+ if __name__ == "__main__":
9
+ run("e9_efficiency", e9_efficiency, notes="E9 efficiency")
experiments/harvest.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Harvest activations and LM candidate scores for one or all backbones.
4
+
5
+ Usage:
6
+ PYTHONPATH=src python experiments/harvest.py --model primary
7
+ PYTHONPATH=src python experiments/harvest.py --all
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
17
+
18
+ from clsa.transcoder.harvest import harvest # noqa: E402
19
+ from clsa.util import load_config, write_result # noqa: E402
20
+
21
+
22
+ def main() -> None:
23
+ ap = argparse.ArgumentParser()
24
+ ap.add_argument("--model", default="primary", help="primary|secondary|efficiency_probe|a HF id")
25
+ ap.add_argument("--all", action="store_true")
26
+ ap.add_argument("--limit", type=int, default=None)
27
+ args = ap.parse_args()
28
+ cfg = load_config("transcoder")
29
+ names = cfg["backbones"]
30
+ targets = list(names.values()) if args.all else [names.get(args.model, args.model)]
31
+ out = []
32
+ for name in targets:
33
+ info = harvest(name, cfg, limit=args.limit)
34
+ print(json.dumps(info, indent=2), flush=True)
35
+ out.append(info)
36
+ path = write_result("harvest", {"runs": out}, config=cfg, seed=int(cfg.get("seed", 0)))
37
+ print("wrote", path)
38
+
39
+
40
+ if __name__ == "__main__":
41
+ main()
experiments/run_all.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Run E1-E9 and write results/INDEX.md linking result, config, seed and commit."""
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import sys
8
+ import traceback
9
+ from pathlib import Path
10
+
11
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
12
+
13
+ from clsa.eval.experiments import e1_main, e2_world_model, e3_budget, e4_calibration
14
+ from clsa.eval.experiments import e5_causality, e6_transfer, e7_multimodal, e9_efficiency
15
+ from clsa.eval.multiagent import e8_multiagent
16
+ from clsa.util import RESULTS, git_commit, load_config, utc_now, write_result
17
+
18
+ EXPERIMENTS = {
19
+ "e1_main": ("E1 main comparison", e1_main),
20
+ "e2_world_model": ("E2 world-model quality", e2_world_model),
21
+ "e3_budget": ("E3 budget and Pareto", e3_budget),
22
+ "e4_calibration": ("E4 calibration", e4_calibration),
23
+ "e5_causality": ("E5 Tiwari dissociation", e5_causality),
24
+ "e6_transfer": ("E6 held-out transfer", e6_transfer),
25
+ "e7_multimodal": ("E7 multimodal / GUI split", e7_multimodal),
26
+ "e8_multiagent": ("E8 multi-agent divergence", e8_multiagent),
27
+ "e9_efficiency": ("E9 efficiency and distillation", e9_efficiency),
28
+ }
29
+
30
+
31
+ def main() -> None:
32
+ cfg = load_config("controller")
33
+ seed = int(cfg.get("seed", 0))
34
+ status = []
35
+ for name, (title, fn) in EXPERIMENTS.items():
36
+ try:
37
+ payload = fn()
38
+ payload.pop("raw_rows", None)
39
+ write_result(name, payload, config=cfg, seed=seed, notes=title)
40
+ status.append((name, title, "ok", ""))
41
+ print(f"[ok] {name}")
42
+ except Exception as exc: # noqa: BLE001
43
+ write_result(
44
+ name,
45
+ {
46
+ "blocked": True,
47
+ "error": f"{type(exc).__name__}: {exc}",
48
+ "traceback": traceback.format_exc()[-2000:],
49
+ },
50
+ config=cfg,
51
+ seed=seed,
52
+ notes=f"BLOCKED: {title}",
53
+ )
54
+ status.append((name, title, "blocked", f"{type(exc).__name__}: {exc}"))
55
+ print(f"[blocked] {name}: {exc}")
56
+
57
+ lines = [
58
+ "# Results index",
59
+ "",
60
+ f"Generated {utc_now()} at commit `{git_commit()}`.",
61
+ "",
62
+ "Every row links a result file to its config, seed and commit. Blocked",
63
+ "experiments are listed with their reason; they are never silently dropped.",
64
+ "",
65
+ "| Experiment | Result file | Config | Seed | Commit | Status |",
66
+ "|---|---|---|---|---|---|",
67
+ ]
68
+ for name, title, st, err in status:
69
+ path = RESULTS / f"{name}.json"
70
+ rec = json.loads(path.read_text()) if path.exists() else {}
71
+ lines.append(
72
+ f"| {title} | `results/{name}.json` | `{rec.get('config_path', '')}` | "
73
+ f"{rec.get('seed')} | `{(rec.get('git_commit') or '')[:8]}` | "
74
+ f"{st}{(' - ' + err) if err else ''} |"
75
+ )
76
+ lines += [
77
+ "",
78
+ "## Reproduction notes",
79
+ "",
80
+ "- `make bench` rebuilds PreAct-Bench and audits it (schema + fork replay).",
81
+ "- `make train` harvests activations, then trains the transcoder, probes,",
82
+ " world model and risk head.",
83
+ "- `make experiments` runs E1-E9 and rewrites this file.",
84
+ "- `make figures` regenerates every figure from `results/`.",
85
+ "",
86
+ "## Pre-registration",
87
+ "",
88
+ "Committed at `7d3946a` before the main runs; see `PRE_REGISTRATION.md`.",
89
+ "Deviations are recorded inside that file.",
90
+ ]
91
+ (RESULTS / "INDEX.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
92
+ print("wrote results/INDEX.md")
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
experiments/train_all.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Build the dataset and train all artefacts for one backbone.
4
+
5
+ Usage:
6
+ PYTHONPATH=src python experiments/train_all.py --model primary
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import sys
13
+ import time
14
+ from pathlib import Path
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
17
+
18
+ from clsa.transcoder.dataset import build_dataset # noqa: E402
19
+ from clsa.util import load_config, write_result # noqa: E402
20
+ from clsa.world_model.train import train_all # noqa: E402
21
+
22
+
23
+ def main() -> None:
24
+ ap = argparse.ArgumentParser()
25
+ ap.add_argument("--model", default="primary")
26
+ ap.add_argument("--skip-dataset", action="store_true")
27
+ args = ap.parse_args()
28
+ tcfg = load_config("transcoder")
29
+ wcfg = load_config("world_model")
30
+ wcfg["threads"] = tcfg.get("threads", 4)
31
+ wcfg["admission"] = tcfg.get("admission", {})
32
+ wcfg["probe"] = tcfg.get("probe", {})
33
+ name = tcfg["backbones"].get(args.model, args.model)
34
+
35
+ t0 = time.time()
36
+ ds_meta = None if args.skip_dataset else build_dataset(name, tcfg)
37
+ print("dataset:", json.dumps(ds_meta, indent=2)[:600] if ds_meta else "cached")
38
+ art = train_all(name, wcfg)
39
+ path = write_result(
40
+ f"train_{name.replace('/', '__')}",
41
+ {"dataset": ds_meta, "artifacts": art},
42
+ config=wcfg,
43
+ seed=int(wcfg.get("seed", 0)),
44
+ notes=f"world-model training on {name}",
45
+ )
46
+ print(json.dumps(art["world_model"], indent=2)[:1200])
47
+ print("admission:", json.dumps({k: art["admission"].get(k) for k in ("n_shared", "n_probe_only", "flip_rate_shared", "flip_rate_probe_only", "flip_rate_random")}, indent=2))
48
+ print("seconds:", round(time.time() - t0, 1), "->", path)
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
figures/common.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Shared figure helpers. Every figure reads results/ only."""
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import matplotlib
11
+
12
+ matplotlib.use("Agg")
13
+ import matplotlib.pyplot as plt # noqa: E402
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ RESULTS = ROOT / "results"
17
+ FIGURES = ROOT / "figures"
18
+ PAPER_FIG = ROOT / "paper" / "figures"
19
+ for p in (FIGURES, PAPER_FIG):
20
+ p.mkdir(parents=True, exist_ok=True)
21
+
22
+ PALETTE = {
23
+ "clsa": "#1f4e79",
24
+ "language_first": "#b03a2e",
25
+ "dense_probe": "#7d3c98",
26
+ "sae_probe": "#117a65",
27
+ "behaviour_only": "#7f8c8d",
28
+ "external_verifier": "#ca6f1e",
29
+ "external_ttc": "#d4ac0d",
30
+ "uncertainty_only": "#2874a6",
31
+ "consequence_rules": "#148f77",
32
+ "abort_only": "#943126",
33
+ "clsa_no_admission": "#5d6d7e",
34
+ "clsa_no_dynamics": "#a6acaf",
35
+ "clsa_naive_acquire": "#d98880",
36
+ }
37
+ DEFAULT = "#333333"
38
+
39
+
40
+ def load(name: str) -> dict:
41
+ path = RESULTS / f"{name}.json"
42
+ if not path.exists():
43
+ raise FileNotFoundError(f"missing results file: {path}")
44
+ with open(path, "r", encoding="utf-8") as fh:
45
+ return json.load(fh)
46
+
47
+
48
+ def try_load(name: str):
49
+ try:
50
+ return load(name)
51
+ except FileNotFoundError:
52
+ return None
53
+
54
+
55
+ def style() -> None:
56
+ plt.rcParams.update(
57
+ {
58
+ "figure.dpi": 140,
59
+ "savefig.dpi": 300,
60
+ "font.size": 9,
61
+ "axes.spines.top": False,
62
+ "axes.spines.right": False,
63
+ "axes.grid": True,
64
+ "grid.alpha": 0.25,
65
+ "grid.linewidth": 0.5,
66
+ "legend.frameon": False,
67
+ "font.family": "DejaVu Sans",
68
+ }
69
+ )
70
+
71
+
72
+ def save(fig, name: str, also_paper: bool = True) -> str:
73
+ out = FIGURES / f"{name}.pdf"
74
+ fig.tight_layout()
75
+ fig.savefig(out, bbox_inches="tight")
76
+ fig.savefig(FIGURES / f"{name}.png", bbox_inches="tight")
77
+ if also_paper:
78
+ fig.savefig(PAPER_FIG / f"{name}.pdf", bbox_inches="tight")
79
+ plt.close(fig)
80
+ print("wrote", out)
81
+ return str(out)
82
+
83
+
84
+ def policy_label(name: str) -> str:
85
+ return name.replace("_", " ").replace("clsa", "CLSA")
86
+
87
+
88
+ def bootstrap_ci(value: float, ci: dict, scale: float = 1.0) -> tuple[float, float, float]:
89
+ return (
90
+ value * scale,
91
+ float(ci.get("lo", value)) * scale,
92
+ float(ci.get("hi", value)) * scale,
93
+ )
figures/f1_stack.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Figure 1: the World-First Agent Stack, drawn programmatically."""
4
+ from __future__ import annotations
5
+
6
+ import matplotlib.patches as mpatches
7
+ import matplotlib.pyplot as plt
8
+
9
+ from common import save, style
10
+
11
+ LAYERS = [
12
+ ("Perception\n(text, image, tool state)", "#d6e4f0"),
13
+ ("Trajectory Transcoder\nTopK features + Tiwari admission", "#b7d3ec"),
14
+ ("Causal World Core\np(s' | do(a), s), CWL-trained", "#8fb8dd"),
15
+ ("Latent MPC\nfive modes, calibrated budget", "#6396c9"),
16
+ ("Certificate Renderer\nG, Fork, E, Bound", "#3f6f9f"),
17
+ ]
18
+ SIDE = [
19
+ ("Belief state b\n(Bayes, 2nd order)", "#e8f4ea"),
20
+ ("Evidence ledger e\n(provenance, staleness)", "#fdf2e9"),
21
+ ("Cost ledger\n(monitor, sim, verify, alloc)", "#f4ecf7"),
22
+ ]
23
+
24
+
25
+ def main() -> None:
26
+ style()
27
+ fig, ax = plt.subplots(figsize=(7.2, 4.2))
28
+ ax.set_xlim(0, 10)
29
+ ax.set_ylim(0, 6.4)
30
+ ax.axis("off")
31
+ for i, (label, colour) in enumerate(LAYERS):
32
+ y = 5.2 - i * 0.95
33
+ box = mpatches.FancyBboxPatch(
34
+ (0.7, y), 5.6, 0.78, boxstyle="round,pad=0.03,rounding_size=0.08",
35
+ linewidth=0.8, edgecolor="#2c3e50", facecolor=colour,
36
+ )
37
+ ax.add_patch(box)
38
+ ax.text(3.5, y + 0.39, label, ha="center", va="center", fontsize=8.4, color="#12232e")
39
+ if i > 0:
40
+ ax.annotate(
41
+ "", xy=(3.5, y + 0.80), xytext=(3.5, y + 0.96),
42
+ arrowprops=dict(arrowstyle="-|>", lw=1.0, color="#2c3e50"),
43
+ )
44
+ for j, (label, colour) in enumerate(SIDE):
45
+ box = mpatches.FancyBboxPatch(
46
+ (6.9, 4.25 - j * 1.15), 2.6, 0.95,
47
+ boxstyle="round,pad=0.03,rounding_size=0.08",
48
+ linewidth=0.8, edgecolor="#566573", facecolor=colour,
49
+ )
50
+ ax.add_patch(box)
51
+ ax.text(8.2, 4.72 - j * 1.15, label, ha="center", va="center", fontsize=7.6, color="#1b2631")
52
+ ax.annotate(
53
+ "", xy=(6.9, 4.72 - j * 1.15), xytext=(6.35, 4.72 - j * 1.15),
54
+ arrowprops=dict(arrowstyle="-|>", lw=0.8, color="#566573", linestyle="--"),
55
+ )
56
+ ax.text(0.7, 0.35, "Language proposes candidates and renders the certified decision; it is never the planning substrate.",
57
+ fontsize=7.4, style="italic", color="#34495e")
58
+ save(fig, "fig1_stack")
59
+
60
+
61
+ if __name__ == "__main__":
62
+ main()
figures/f2_algorithm.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Figure 2: architecture and Algorithm 1 flow for one worked decision.
4
+
5
+ The decision is the canonical irreversible payment: a screenshot and an email
6
+ thread disagree on the amount.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import matplotlib.patches as mpatches
11
+ import matplotlib.pyplot as plt
12
+ from matplotlib.patches import FancyArrowPatch
13
+
14
+ from common import load, save, style, try_load
15
+
16
+
17
+ def main() -> None:
18
+ style()
19
+ fig, ax = plt.subplots(figsize=(7.4, 4.6))
20
+ ax.set_xlim(0, 12)
21
+ ax.set_ylim(0, 7.4)
22
+ ax.axis("off")
23
+
24
+ nodes = [
25
+ ("s_t = [z_t, b_t, e_t]\nscreenshot + email", 1.3, 6.3, "#d6e4f0"),
26
+ ("LM proposes A_t\n(candidates only)", 1.3, 4.9, "#e8f4ea"),
27
+ ("rollout p_phi(.|do(a), s_t)\nfor every a in A_t", 5.2, 6.3, "#b7d3ec"),
28
+ ("RiskHead: p_hat, c_hat, rho", 5.2, 4.9, "#fdf2e9"),
29
+ ("J(a) = -E[U] + gamma p_hat c_hat", 5.2, 3.5, "#f4ecf7"),
30
+ ("calibrated gate\nSelectiveRisk <= alpha", 9.0, 5.6, "#8fb8dd"),
31
+ ("certificate\nG, Fork, E, Bound", 9.0, 3.9, "#6396c9"),
32
+ ("execute, clarify or abstain", 9.0, 2.2, "#3f6f9f"),
33
+ ]
34
+ pos = {}
35
+ for label, x, y, colour in nodes:
36
+ box = mpatches.FancyBboxPatch(
37
+ (x, y - 0.55), 2.9, 1.05,
38
+ boxstyle="round,pad=0.04,rounding_size=0.09",
39
+ linewidth=0.8, edgecolor="#2c3e50", facecolor=colour,
40
+ )
41
+ ax.add_patch(box)
42
+ ax.text(x + 1.45, y, label, ha="center", va="center", fontsize=7.3)
43
+ pos[label] = (x + 1.45, y)
44
+
45
+ def arrow(a, b, text=None, style_="-|>"):
46
+ (x1, y1), (x2, y2) = pos[a], pos[b]
47
+ ax.add_patch(
48
+ FancyArrowPatch(
49
+ (x1, y1 - 0.58), (x2, y2 + 0.58),
50
+ arrowstyle=style_, mutation_scale=10, lw=0.9, color="#2c3e50",
51
+ connectionstyle="arc3,rad=0.06",
52
+ )
53
+ )
54
+ if text:
55
+ ax.text((x1 + x2) / 2 + 0.1, (y1 + y2) / 2, text, fontsize=6.4, color="#566573")
56
+
57
+ keys = [n[0] for n in nodes]
58
+ arrow(keys[0], keys[1])
59
+ arrow(keys[1], keys[2])
60
+ arrow(keys[2], keys[3])
61
+ arrow(keys[3], keys[4])
62
+ arrow(keys[4], keys[5], "in band -> simulate")
63
+ arrow(keys[5], keys[6])
64
+ arrow(keys[6], keys[7])
65
+ ax.text(
66
+ 1.3, 0.5,
67
+ "Worked case: email says GBP 40, invoice screenshot reads GBP 67. "
68
+ "e_t flags cross-modal conflict, so the mode is verify/acquire before execute.",
69
+ fontsize=6.8, style="italic", color="#34495e",
70
+ )
71
+ save(fig, "fig2_algorithm")
72
+
73
+ # Figure 3 depends on E2 existing; skip silently if not yet run.
74
+ e2 = try_load("e2_world_model")
75
+ if e2 is None:
76
+ print("fig3 skipped: no e2 results yet")
77
+ return
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()
figures/f3_horizon.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Figure 3: simulation-to-reality gap versus rollout horizon, per modality."""
4
+ from __future__ import annotations
5
+
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+
9
+ from common import load, save, style
10
+
11
+ MODALITIES = ["text", "image", "tool_state", "belief", "evidence"]
12
+ COLOURS = {"text": "#1f4e79", "image": "#b03a2e", "tool_state": "#117a65",
13
+ "belief": "#7d3c98", "evidence": "#ca6f1e"}
14
+
15
+
16
+ def main() -> None:
17
+ style()
18
+ res = load("e2_world_model")["results"]
19
+ horizons = res.get("horizons", {})
20
+ if not horizons:
21
+ raise SystemExit("no horizon metrics in e2 results")
22
+ hs = sorted(int(h) for h in horizons)
23
+ fig, ax = plt.subplots(figsize=(4.6, 3.1))
24
+ for m in MODALITIES:
25
+ ys = [horizons[str(h)]["rmse"].get(m, np.nan) for h in hs]
26
+ ax.plot(hs, ys, marker="o", ms=3.5, lw=1.4, color=COLOURS[m], label=m.replace("_", " "))
27
+ ax.set_xlabel("rollout horizon (steps)")
28
+ ax.set_ylabel("open-loop RMSE (standardised block units)")
29
+ ax.set_xticks(hs)
30
+ ax.legend(fontsize=7, ncol=2)
31
+ save(fig, "fig3_horizon")
32
+
33
+
34
+ if __name__ == "__main__":
35
+ main()
figures/f4_pareto.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Figure 4: success-per-dollar and harm-per-dollar Pareto curves."""
4
+ from __future__ import annotations
5
+
6
+ import matplotlib.pyplot as plt
7
+
8
+ from common import PALETTE, load, save, style
9
+
10
+ SERIES = ["clsa", "language_first", "dense_probe"]
11
+
12
+
13
+ def main() -> None:
14
+ style()
15
+ res = load("e3_budget")["results"]
16
+ pts = res["points"]
17
+ budgets = sorted((float(k), v) for k, v in pts.items())
18
+ fig, axes = plt.subplots(1, 2, figsize=(7.0, 2.9))
19
+ for name in SERIES:
20
+ xs = [p["budget"] for _, p in budgets]
21
+ harm = [p[name]["harm_rate"] for _, p in budgets]
22
+ succ = [p[name]["success_rate"] for _, p in budgets]
23
+ axes[0].plot(xs, succ, marker="o", ms=3, lw=1.4, color=PALETTE[name], label=name.replace("_", " "))
24
+ axes[1].plot(xs, harm, marker="o", ms=3, lw=1.4, color=PALETTE[name], label=name.replace("_", " "))
25
+ axes[0].set_xscale("log")
26
+ axes[1].set_xscale("log")
27
+ axes[0].set_xlabel("compute budget (tokens / decision)")
28
+ axes[0].set_ylabel("state-verified success rate")
29
+ axes[1].set_ylabel("harm rate")
30
+ axes[0].set_title("success at budget", fontsize=8)
31
+ axes[1].set_title("harm at budget", fontsize=8)
32
+ axes[1].legend(fontsize=6.5)
33
+ save(fig, "fig4_pareto")
34
+
35
+
36
+ if __name__ == "__main__":
37
+ main()
figures/f5_calibration.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Figure 5: reliability diagram and realised-versus-promised risk by alpha."""
4
+ from __future__ import annotations
5
+
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+
9
+ from common import load, save, style
10
+
11
+
12
+ def main() -> None:
13
+ style()
14
+ res = load("e4_calibration")["results"]
15
+ rel = res.get("reliability", {})
16
+ fig, axes = plt.subplots(1, 2, figsize=(7.0, 2.9))
17
+ if rel.get("pred"):
18
+ axes[0].plot([0, 1], [0, 1], ls="--", lw=0.8, color="#888")
19
+ axes[0].plot(rel["pred"], rel["obs"], marker="o", ms=3.5, lw=1.4, color="#1f4e79")
20
+ axes[0].set_xlabel("predicted harm probability")
21
+ axes[0].set_ylabel("observed frequency")
22
+ axes[0].set_title("reliability (test + heldout)", fontsize=8)
23
+
24
+ by_alpha = res.get("by_alpha", {})
25
+ if by_alpha:
26
+ alphas = sorted(float(a) for a in by_alpha)
27
+ realised = [by_alpha[str(a)]["selective_risk"] for a in alphas]
28
+ axes[1].plot(alphas, alphas, ls="--", lw=0.8, color="#888", label="promised")
29
+ axes[1].plot(alphas, realised, marker="o", ms=3.5, lw=1.4, color="#b03a2e", label="realised")
30
+ naive = res.get("policies", {}).get("naive_acquire")
31
+ if naive:
32
+ axes[1].scatter([alphas[0]], [naive["harm_rate"]], marker="x", color="#7d3c98",
33
+ label="naive acquire (harm rate)", zorder=5)
34
+ axes[1].set_xlabel("promised alpha")
35
+ axes[1].set_ylabel("selective risk")
36
+ axes[1].set_title("realised versus promised", fontsize=8)
37
+ axes[1].legend(fontsize=6.5)
38
+ save(fig, "fig5_calibration")
39
+
40
+
41
+ if __name__ == "__main__":
42
+ main()
figures/f6_tiwari.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Figure 6: Tiwari dissociation - flip rates for shared, probe-only, random."""
4
+ from __future__ import annotations
5
+
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+
9
+ from common import load, save, style
10
+
11
+
12
+ def main() -> None:
13
+ style()
14
+ res = load("e5_causality")["results"]
15
+ labels = ["shared\n(aligned + sensitive)", "probe-only\n(aligned, insensitive)", "random"]
16
+ vals = [
17
+ res.get("flip_rate_shared") or 0.0,
18
+ res.get("flip_rate_probe_only") or 0.0,
19
+ res.get("flip_rate_random") or 0.0,
20
+ ]
21
+ fig, ax = plt.subplots(figsize=(3.6, 2.9))
22
+ bars = ax.bar(labels, vals, color=["#1f4e79", "#b03a2e", "#7f8c8d"], width=0.6)
23
+ for b, v in zip(bars, vals):
24
+ ax.text(b.get_x() + b.get_width() / 2, v, f"{v:.3f}", ha="center", va="bottom", fontsize=7)
25
+ ax.set_ylabel("behavioural flip rate")
26
+ ax.set_title(f"n={res.get('n_shared')} shared, {res.get('n_probe_only')} probe-only", fontsize=8)
27
+ save(fig, "fig6_tiwari")
28
+
29
+
30
+ if __name__ == "__main__":
31
+ main()
figures/f7_marginal.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Figure 7: marginal decision change per additional rollout."""
4
+ from __future__ import annotations
5
+
6
+ import matplotlib.pyplot as plt
7
+
8
+ from common import load, save, style
9
+
10
+
11
+ def main() -> None:
12
+ style()
13
+ res = load("e3_budget")["results"]
14
+ curve = res.get("marginal", [])
15
+ xs = [c["rollouts_per_candidate"] for c in curve]
16
+ ys = [c["decision_change_rate"] for c in curve]
17
+ fig, ax = plt.subplots(figsize=(3.6, 2.8))
18
+ ax.plot(xs, ys, marker="o", ms=3.5, lw=1.4, color="#1f4e79")
19
+ ax.set_xlabel("Monte-Carlo rollouts per candidate")
20
+ ax.set_ylabel("decision change vs single rollout")
21
+ ax.set_xticks(xs)
22
+ save(fig, "fig7_marginal")
23
+
24
+
25
+ if __name__ == "__main__":
26
+ main()
figures/f8_multiagent.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CLSA contributors
2
+ # SPDX-License-Identifier: MIT
3
+ """Figure 8: multi-agent divergence over time and governance comparison."""
4
+ from __future__ import annotations
5
+
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+
9
+ from common import load, save, style
10
+
11
+ COLOURS = {"none": "#b03a2e", "message_layer": "#ca6f1e", "restart": "#7f8c8d",
12
+ "pause_divergent": "#1f4e79"}
13
+
14
+
15
+ def main() -> None:
16
+ style()
17
+ res = load("e8_multiagent")["results"]
18
+ traces = res["divergence_traces"]
19
+ fig, axes = plt.subplots(1, 2, figsize=(7.0, 2.9))
20
+ for gov, ys in traces.items():
21
+ axes[0].plot(range(len(ys)), ys, marker="o", ms=2.5, lw=1.3,
22
+ color=COLOURS.get(gov, "#333"), label=gov.replace("_", " "))
23
+ axes[0].set_xlabel("step")
24
+ axes[0].set_ylabel("mean belief divergence")
25
+ axes[0].legend(fontsize=6.5)
26
+ axes[0].set_title("divergence over time", fontsize=8)
27
+
28
+ govs = list(res["by_governance"])
29
+ harm = [res["by_governance"][g]["total_harm"] for g in govs]
30
+ cons = [res["by_governance"][g]["false_consensus_rate"] for g in govs]
31
+ x = np.arange(len(govs))
32
+ axes[1].bar(x - 0.2, harm, width=0.4, color="#b03a2e", label="total harm")
33
+ axes[1].set_xticks(x)
34
+ axes[1].set_xticklabels([g.replace("_", " ") for g in govs], fontsize=6.5, rotation=12)
35
+ axes[1].set_ylabel("total harmful actions")
36
+ ax2 = axes[1].twinx()
37
+ ax2.plot(x + 0.2, cons, marker="o", ms=3, color="#1f4e79", lw=1.2, label="false consensus")
38
+ ax2.set_ylabel("false consensus rate")
39
+ ax2.grid(False)
40
+ axes[1].set_title("governance comparison", fontsize=8)
41
+ save(fig, "fig8_multiagent")
42
+
43
+
44
+ if __name__ == "__main__":
45
+ main()
figures/fig1_stack.pdf ADDED
Binary file (28.4 kB). View file
 
figures/fig1_stack.png ADDED

Git LFS Details

  • SHA256: a561d3e556999d2c1b6375428c52d775e30abbe1a0440241cd1703877cec7b53
  • Pointer size: 131 Bytes
  • Size of remote file: 142 kB
figures/fig2_algorithm.pdf ADDED
Binary file (34.3 kB). View file
 
figures/fig2_algorithm.png ADDED

Git LFS Details

  • SHA256: 8e29a8b2c955bf3fe44cbe993b07dd0a9af8c3c6a58558a96032c30a8002edde
  • Pointer size: 131 Bytes
  • Size of remote file: 142 kB
figures/fig3_horizon.pdf ADDED
Binary file (17.7 kB). View file
 
figures/fig3_horizon.png ADDED

Git LFS Details

  • SHA256: f6a3a3dd9044f74bdc855895e08a28f745aeded5dbde3884a037ddf248f71384
  • Pointer size: 131 Bytes
  • Size of remote file: 103 kB
figures/fig4_pareto.pdf ADDED
Binary file (19.2 kB). View file
 
figures/fig4_pareto.png ADDED

Git LFS Details

  • SHA256: 3ddb496b5cb93cd1d4b22dfa04266a6d24b96e5e00ea4162dc2949544c929315
  • Pointer size: 131 Bytes
  • Size of remote file: 105 kB
figures/fig5_calibration.pdf ADDED
Binary file (15.9 kB). View file
 
figures/fig5_calibration.png ADDED

Git LFS Details

  • SHA256: 21c8471838694b96fff5edac511007d0a7e1785fe4e9cf4cf263991e0a60335a
  • Pointer size: 131 Bytes
  • Size of remote file: 142 kB