jeorgexyz commited on
Commit
4b60bb3
·
verified ·
1 Parent(s): 46df388

Publish reproducible Lua agent experiments and traces

Browse files
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jeorge D. Anderson II
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.
README.md ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ tags:
6
+ - agents
7
+ - tool-calling
8
+ - constrained-decoding
9
+ - evaluation
10
+ - ablation
11
+ size_categories:
12
+ - n<1K
13
+ pretty_name: Lua Agent Evals
14
+ configs:
15
+ - config_name: decoder_trials
16
+ default: true
17
+ data_files:
18
+ - split: test
19
+ path: data/decoder_trials.jsonl
20
+ - config_name: loop_ablations
21
+ data_files:
22
+ - split: test
23
+ path: data/loop_ablations.jsonl
24
+ - config_name: qwen_runs
25
+ data_files:
26
+ - split: test
27
+ path: data/qwen_runs.jsonl
28
+ - config_name: tasks
29
+ data_files:
30
+ - split: test
31
+ path: data/tasks.jsonl
32
+ ---
33
+
34
+ # Lua Agent Evals
35
+
36
+ The evidence behind [lua-agent-lab](https://huggingface.co/spaces/jeorgexyz/lua-agent-lab),
37
+ from [lua-agent](https://github.com/jeorgexyz/lua-agent). The experiment separates
38
+ structural tool-call validity from useful tool selection and complete task success.
39
+
40
+ ## Contents
41
+
42
+ | Configuration | Unit | Method |
43
+ | --- | --- | --- |
44
+ | `decoder_trials` | 60 first-turn trials | TinyStories 15M; 30 constrained, 30 free; greedy sampling |
45
+ | `loop_ablations` | 64 agent runs | Eight scripted tasks × eight loop configurations |
46
+ | `qwen_runs` | 16 agent runs | Eight tasks × constrained/free Qwen 2.5 1.5B Q4_K_M |
47
+ | `tasks` | Eight task definitions | Prompts, allowed tools, expected outcomes, scripted turns |
48
+
49
+ The test split is an inspectable demonstration suite, not a training set or a
50
+ representative benchmark. Do not treat 30 trials as 30 independent problems:
51
+ ten prompts are repeated with 0, 1 and 2 trailing spaces, matching the original
52
+ ablation. No confidence interval or population-level claim is implied.
53
+
54
+ ## Collection and provenance
55
+
56
+ Generated with `python -m space.export_dataset --tiny --qwen` from the source
57
+ repository. Each measured row includes its UTC collection time, a SHA-256
58
+ digest of the relevant source, exact settings and pinned model revisions.
59
+ `manifest.json` records the checksum and row count of each data file.
60
+ The baseline source commit was `1738e7dd63bf0d65a055fd11a497c30b3f47eff4`;
61
+ the adapter and metadata additions are represented by the per-row source digest.
62
+ `provenance/source/` contains the exact normalized source and fixtures covered
63
+ by that digest, so the exported runs remain auditable without a moving branch.
64
+
65
+ TinyStories runs `backend/local.lua` and `grammar.lua` inside Lua 5.4 with
66
+ PyTorch float32 numerical kernels from `tools/llama2c.py`. The tokenizer is
67
+ the original Lua implementation. This differs numerically from the original
68
+ pure-Lua inference, so new rows are not attributed to the historical result.
69
+ Both arms scaffold `THOUGHT:` and `CALL:`. Constraints can append a final
70
+ grammar completion at the token limit; `forced_finishes` counts these cases,
71
+ and each affected step has `forced_finish: true`.
72
+
73
+ Qwen uses the official pinned GGUF repository and llama-cpp-python 0.3.16 on
74
+ CPU. Constrained decoding uses a schema describing the available tools;
75
+ free decoding omits that schema. Prompts and greedy sampling are otherwise
76
+ the same. The runtime scaffolds `CALL:` in both arms and does not repair free
77
+ output. These are distinct from the historical Ollama Qwen run.
78
+
79
+ Scripted rows use the original fixed turn lists and actual Lua loop, with
80
+ fresh virtual fixtures per run. They demonstrate control flow, not model
81
+ capability. The `large_context_budget` variant raises the budget to 100000
82
+ estimated tokens so eviction does not occur; it does not simulate overflow.
83
+ The approval-gate ablation only permits virtual writes. `drop_oldest` changes
84
+ the eviction policy; `no_error_recovery` removes both parse and tool recovery.
85
+
86
+ The historical **30/30 constrained versus 0/30 free** result, with **0/30
87
+ usable tool selections** in both arms, is preserved verbatim in
88
+ `provenance/constrained-vs-free.txt`. Complete historical trial traces were not
89
+ saved; none have been invented. `provenance/eval-qwen1.5b.txt` likewise preserves
90
+ the historical 6/8 Ollama report without implying complete raw traces exist.
91
+
92
+ ## Schema and metrics
93
+
94
+ The three run configurations use the same flat schema:
95
+
96
+ - `prompt`, `task_id`, `expected_tools`, `expected_outcome`: the task and labels.
97
+ - `selected_tools`, `answer`, `reason`, `passed`, `judge_note`: observed outcome.
98
+ - `generated_turns`, `valid_calls`, `tool_call_validity`: parsed tool calls /
99
+ generated turns, in percent. `answer` is a tool; argument correctness and
100
+ whether a tool is registered are not checked by this syntax metric.
101
+ - `first_tool`, `correct_first_tool`: first generated turn's choice against
102
+ accepted tools. A malformed first turn is incorrect. Unlabeled or
103
+ unavailable choices are null; the directory-listing decoder prompt has
104
+ no available suitable tool in the two-tool catalogue.
105
+ - `steps`, `malformed_calls`, `loop_detected`, `context_evicted`,
106
+ `forced_finishes`: measurements from the step records.
107
+ - `settings_json`, `trace_json`, `approvals_json`: JSON-encoded structured
108
+ records. Strings preserve arbitrary tool argument shapes without a lossy
109
+ Arrow union. Decode with `json.loads(row['trace_json'])`.
110
+ - `model`, `inference_kind`, `decoder`, `token_accounting`, `elapsed_seconds`,
111
+ `run_at`, `source_sha256`, `model_revisions_json`: provenance and conditions.
112
+
113
+ Task success uses the repository's `solved` functions for real models and
114
+ `check` functions for scripts. Scripted checks require the intended mechanism
115
+ to fire. Some judges are substring based and can accept spurious matches;
116
+ read traces rather than treating the score as a strong capability estimate.
117
+ First-turn decoder trials have `passed: null` because they do not run a full task.
118
+
119
+ ## Use
120
+
121
+ ```python
122
+ import json
123
+ from datasets import load_dataset
124
+
125
+ rows = load_dataset('jeorgexyz/lua-agent-evals', 'decoder_trials', split='test')
126
+ trace = json.loads(rows[0]['trace_json'])
127
+ ```
128
+
129
+ This dataset contains only developer-run experiments on synthetic tasks and
130
+ repository fixtures. Public Space visitors' prompts and traces are not collected
131
+ or uploaded. It is intended for reproducibility, teaching and debugging, not
132
+ training on private agent conversations. All source and authored fixtures are
133
+ MIT licensed; the original model repositories document their checkpoint licenses.
data/decoder_trials.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/loop_ablations.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/qwen_runs.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/tasks.jsonl ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {"id": "calc-single", "prompt": "What is 4871 * 209?", "tools": ["calc"], "expected_first_tools": ["calc"], "expected_outcome": "1018039; must use calc", "context_budget": 4096, "approve_write": false, "script_json": "[\"THOUGHT: I cannot do this in my head.\\nCALL: {\\\"tool\\\":\\\"calc\\\",\\\"args\\\":{\\\"expr\\\":\\\"4871 * 209\\\"}}\", \"THOUGHT: I have the product.\\nCALL: {\\\"tool\\\":\\\"answer\\\",\\\"args\\\":{\\\"text\\\":\\\"1018039\\\"}}\"]"}
2
+ {"id": "read-then-calc", "prompt": "How many lines are in eval/fixtures/notes.txt, times 3?", "tools": ["read_file", "calc"], "expected_first_tools": ["read_file"], "expected_outcome": "12; must read the fixture and use calc", "context_budget": 4096, "approve_write": false, "script_json": "[\"THOUGHT: First read the file.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"eval/fixtures/notes.txt\\\"}}\", \"THOUGHT: Four lines, so four times three.\\nCALL: {\\\"tool\\\":\\\"calc\\\",\\\"args\\\":{\\\"expr\\\":\\\"4 * 3\\\"}}\", \"THOUGHT: Done.\\nCALL: {\\\"tool\\\":\\\"answer\\\",\\\"args\\\":{\\\"text\\\":\\\"12\\\"}}\"]"}
3
+ {"id": "recover-parse-error", "prompt": "What is 2 + 2?", "tools": ["calc"], "expected_first_tools": ["calc"], "expected_outcome": "4; scripted run must recover from a parse error", "context_budget": 4096, "approve_write": false, "script_json": "[\"THOUGHT: Compute it.\\nCALL: {\\\"tool\\\":\\\"calc\\\",\\\"args\\\":{\\\"expr\\\":\\\"2 + 2\\\"\", \"THOUGHT: My JSON was cut off, let me redo it.\\nCALL: {\\\"tool\\\":\\\"calc\\\",\\\"args\\\":{\\\"expr\\\":\\\"2 + 2\\\"}}\", \"THOUGHT: Four.\\nCALL: {\\\"tool\\\":\\\"answer\\\",\\\"args\\\":{\\\"text\\\":\\\"4\\\"}}\"]"}
4
+ {"id": "recover-missing-file", "prompt": "Read the notes file and tell me the first word.", "tools": ["read_file", "list_dir"], "expected_first_tools": ["read_file", "list_dir"], "expected_outcome": "alpha; scripted run must recover from a missing file", "context_budget": 4096, "approve_write": false, "script_json": "[\"THOUGHT: Try the obvious path.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"notes.txt\\\"}}\", \"THOUGHT: Not there. Look in the fixtures directory.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"eval/fixtures/notes.txt\\\"}}\", \"THOUGHT: The first word is alpha.\\nCALL: {\\\"tool\\\":\\\"answer\\\",\\\"args\\\":{\\\"text\\\":\\\"alpha\\\"}}\"]"}
5
+ {"id": "loop-bait", "prompt": "Find the secret in the config.", "tools": ["read_file"], "expected_first_tools": ["read_file"], "expected_outcome": "Report no secret; scripted run must trigger repetition detection", "context_budget": 4096, "approve_write": false, "script_json": "[\"THOUGHT: Read the config.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"eval/fixtures/config.txt\\\"}}\", \"THOUGHT: Maybe I missed it.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"eval/fixtures/config.txt\\\"}}\", \"THOUGHT: Check once more.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"eval/fixtures/config.txt\\\"}}\", \"THOUGHT: Once more.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"eval/fixtures/config.txt\\\"}}\", \"THOUGHT: Once more.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"eval/fixtures/config.txt\\\"}}\", \"THOUGHT: Once more.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"eval/fixtures/config.txt\\\"}}\", \"THOUGHT: The nudge is right, there is no secret there.\\nCALL: {\\\"tool\\\":\\\"answer\\\",\\\"args\\\":{\\\"text\\\":\\\"no secret found in the config\\\"}}\"]"}
6
+ {"id": "oversized-observation", "prompt": "What is the MARKER line at the top of eval/fixtures/big.txt?", "tools": ["read_file", "calc"], "expected_first_tools": ["read_file"], "expected_outcome": "omega; scripted run must exercise context eviction", "context_budget": 400, "approve_write": false, "script_json": "[\"THOUGHT: Read the big file.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"eval/fixtures/big.txt\\\"}}\", \"THOUGHT: Add something to push the window.\\nCALL: {\\\"tool\\\":\\\"calc\\\",\\\"args\\\":{\\\"expr\\\":\\\"1 + 1\\\"}}\", \"THOUGHT: And again.\\nCALL: {\\\"tool\\\":\\\"calc\\\",\\\"args\\\":{\\\"expr\\\":\\\"2 + 2\\\"}}\", \"THOUGHT: The last word is omega.\\nCALL: {\\\"tool\\\":\\\"answer\\\",\\\"args\\\":{\\\"text\\\":\\\"omega\\\"}}\"]"}
7
+ {"id": "approved-write", "prompt": "Write the number 42 to out.txt, then read it back to confirm.", "tools": ["write_file", "read_file"], "expected_first_tools": ["write_file"], "expected_outcome": "Write 42 and read it back after approval", "context_budget": 4096, "approve_write": true, "script_json": "[\"THOUGHT: Write the value first.\\nCALL: {\\\"tool\\\":\\\"write_file\\\",\\\"args\\\":{\\\"path\\\":\\\"out.txt\\\",\\\"text\\\":\\\"42\\\"}}\", \"THOUGHT: Read it back to be sure it landed.\\nCALL: {\\\"tool\\\":\\\"read_file\\\",\\\"args\\\":{\\\"path\\\":\\\"out.txt\\\"}}\", \"THOUGHT: Confirmed.\\nCALL: {\\\"tool\\\":\\\"answer\\\",\\\"args\\\":{\\\"text\\\":\\\"Wrote 42 to out.txt and read it back.\\\"}}\"]"}
8
+ {"id": "denied-write", "prompt": "Save the number 42 to out.txt.", "tools": ["calc", "write_file"], "expected_first_tools": ["write_file"], "expected_outcome": "Do not write; report the refusal", "context_budget": 4096, "approve_write": false, "script_json": "[\"THOUGHT: Write the file.\\nCALL: {\\\"tool\\\":\\\"write_file\\\",\\\"args\\\":{\\\"path\\\":\\\"out.txt\\\",\\\"text\\\":\\\"42\\\"}}\", \"THOUGHT: I was denied, so I should say so.\\nCALL: {\\\"tool\\\":\\\"answer\\\",\\\"args\\\":{\\\"text\\\":\\\"I was not allowed to write out.txt.\\\"}}\"]"}
manifest.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "files": {
3
+ "decoder_trials.jsonl": {
4
+ "rows": 60,
5
+ "sha256": "39256f1d1282d46189ee981492fdca93a4d757c39081757ff389a5dc924c73b2"
6
+ },
7
+ "loop_ablations.jsonl": {
8
+ "rows": 64,
9
+ "sha256": "520036e43e5fc0159adde4b5784abdbb05cd4ccfe62c8f7d57ae0eeacc8205d6"
10
+ },
11
+ "qwen_runs.jsonl": {
12
+ "rows": 16,
13
+ "sha256": "58c622602ff01839c40365213d41eabbf76c12261c807a8dbbfa5bec6c55c1c0"
14
+ },
15
+ "tasks.jsonl": {
16
+ "rows": 8,
17
+ "sha256": "719d9869585bb5dcaace1c8a85f4f6383a93da18f8e4e6ea9453f5370220f189"
18
+ }
19
+ },
20
+ "model_revisions": {
21
+ "karpathy/tinyllamas": "0bd21da7698eaf29a0d7de3992de8a46ef624add",
22
+ "Qwen/Qwen2.5-1.5B-Instruct-GGUF": "91cad51170dc346986eccefdc2dd33a9da36ead9"
23
+ }
24
+ }
provenance/constrained-vs-free.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Constrained decoding vs free decoding
2
+ =====================================
3
+
4
+ Model: stories15M
5
+ Sampler: greedy (temperature 0.0), identical in both arms
6
+ Prompt: identical in both arms
7
+ Difference: logit masking, on or off
8
+ Trials: 30
9
+
10
+ Running constrained arm...
11
+ Running free arm...
12
+
13
+ arm parsed as a tool call picked a usable tool
14
+ ----------- --------------------- --------------------
15
+ constrained 30/30 (100.0%) 0/30 ( 0.0%)
16
+ free 0/30 ( 0.0%) 0/30 ( 0.0%)
17
+
18
+ (973s constrained, 553s free, pure Lua CPU inference)
19
+
20
+ The two columns are the whole point.
21
+
22
+ The first column is the GRAMMAR's work: whether the output is a
23
+ syntactically valid tool call. Masking takes it to 100% on a model
24
+ that has never seen JSON.
25
+
26
+ The second column is the MODEL's work: whether the tool it chose could
27
+ plausibly serve the task. The grammar cannot help here, and a 15M
28
+ TinyStories checkpoint has nothing to contribute.
29
+
30
+ Tool calling is a decoding constraint. Choosing the right tool is not.
31
+
32
+ Sample output, constrained arm:
33
+ {"tool":"answer","args":{"text":":ged to the file. ucked the file and put it away. The filewile was very sad and said "}}
34
+ {"tool":"answer","args":{"text":"One day, two days ago, a little girl was born. She was so happy that she could make her mommy proud. She was so proud of herself that she decided to do something special. She wanted to make her mommy proud. She grabbed her pencil and started to draw a p"}}
35
+ {"tool":"answer","args":{"text":"The 'A'. One day, I am going to the park to play with my friends. One day, I am going to the park to play with them."}}
36
+
37
+ Sample output, free arm:
38
+ ine nodded and said "Yes, I will be careful with it."
39
+ s and she was very proud of her daughter.
40
+ s and listens to the instructions.
provenance/eval-qwen1.5b.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Agent loop evaluation
2
+ =====================
3
+
4
+ Model: qwen2.5:1.5b-instruct (ollama backend, real inference)
5
+ Decode: the backend's own (grammar.lua is not in this loop)
6
+
7
+ task pass steps window tools it chose
8
+ ------------------------ ---- ----- ------ ------------------------
9
+ calc-single ok 2 68 calc,answer
10
+ read-then-calc ok 3 174 read_file,calc,answer
11
+ recover-parse-error ok 2 62 calc,answer
12
+ recover-missing-file FAIL 8 665 read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file
13
+ loop-bait FAIL 2 113 read_file,answer
14
+ oversized-observation ok 2 341 read_file,answer
15
+ approved-write ok 3 179 write_file,read_file,answer
16
+ denied-write ok 2 137 write_file,answer
17
+
18
+ 6/8 passed
provenance/source/agent.lua ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- agent.lua - The loop. This file is the artifact; everything else supports it.
2
+ --
3
+ -- One step is: build context -> call backend -> parse -> dispatch -> observe.
4
+ -- That is ten lines. Everything else in this file is the error taxonomy, and
5
+ -- the error taxonomy is the part that separates a demo from an agent.
6
+ --
7
+ -- Six terminal-ish states, each roughly ten lines, each with a test in
8
+ -- test.lua and a row in eval/ablate.lua:
9
+ --
10
+ -- parse_error the model's output was not a tool call
11
+ -- tool_error the tool raised, or the arguments failed validation
12
+ -- timeout the tool ran too long
13
+ -- repeat the same call came back N times; the agent is thrashing
14
+ -- denied the approval gate refused
15
+ -- budget the context window cannot fit even the next step
16
+ --
17
+ -- The unifying rule: A FAILURE IS AN OBSERVATION. Nothing here raises to the
18
+ -- caller. Every error is phrased for the model, appended to the transcript,
19
+ -- and the loop continues. That single decision is why recovery works at all,
20
+ -- and it is why the error strings in protocol.lua and tools.lua read like
21
+ -- instructions rather than diagnostics.
22
+
23
+ local context = require('context')
24
+ local protocol = require('protocol')
25
+ local trace = require('trace')
26
+
27
+ local Agent = {}
28
+ Agent.__index = Agent
29
+
30
+ -- opts:
31
+ -- backend (required) table with :complete(prompt, opts) -> text, meta
32
+ -- The backend returns the full turn including the THOUGHT: and
33
+ -- CALL: prefixes, whatever scaffolding it used internally.
34
+ -- tools (required) registry from tools.lua
35
+ -- tokenizer (required) anything with :encode(text) -> {ids}
36
+ -- max_steps default 12
37
+ -- max_tokens default 4096
38
+ -- repeat_threshold default 3
39
+ -- policy context eviction policy name
40
+ -- approve function(call) -> bool, for tools requiring approval
41
+ -- trace_path JSONL destination; nil disables tracing
42
+ -- verbose print the ledger and each step as it happens
43
+ -- fatal_on set of statuses to treat as terminal instead of
44
+ -- recoverable, e.g. {parse_error=true}. This exists so
45
+ -- eval/ablate.lua can switch recovery OFF and measure
46
+ -- what it was buying. Empty in normal operation -- the
47
+ -- whole design rests on failures being observations.
48
+ function Agent.new(opts)
49
+ opts = opts or {}
50
+ if not opts.backend then error("Agent.new: needs a backend") end
51
+ if not opts.tools then error("Agent.new: needs a tool registry") end
52
+ if not opts.tokenizer then error("Agent.new: needs a tokenizer") end
53
+
54
+ return setmetatable({
55
+ backend = opts.backend,
56
+ tools = opts.tools,
57
+ approve = opts.approve,
58
+ max_steps = opts.max_steps or 12,
59
+ repeat_threshold = opts.repeat_threshold or 3,
60
+ verbose = opts.verbose or false,
61
+ fatal_on = opts.fatal_on or {},
62
+ ctx = context.new(opts.tokenizer, opts.max_tokens or 4096, opts.policy),
63
+ tracer = trace.open(opts.trace_path, opts.trace_path and "record" or "off"),
64
+ steps = {},
65
+ }, Agent)
66
+ end
67
+
68
+ -- A call's identity, for loop detection. Canonical JSON, so argument order
69
+ -- cannot disguise a repeat.
70
+ local function call_key(call)
71
+ return trace.encode({ tool = call.tool, args = call.args or {} })
72
+ end
73
+
74
+ -- Real agents thrash by calling the same tool with the same arguments
75
+ -- forever. Ten lines stop it -- and without them, eval task `loop-bait`
76
+ -- runs to the step ceiling every time.
77
+ function Agent:is_repeating(call)
78
+ local key, n = call_key(call), 0
79
+ for _, s in ipairs(self.steps) do
80
+ if s.call and call_key(s.call) == key then n = n + 1 end
81
+ end
82
+ return n >= self.repeat_threshold, n
83
+ end
84
+
85
+ -- Assemble the prompt for the next step and report what had to be evicted.
86
+ function Agent:build_prompt(task)
87
+ local system = protocol.render_system(self.tools, task)
88
+ local fixed = self.ctx:count(system)
89
+ if fixed >= self.ctx.budget then
90
+ return nil, nil, "the tool catalogue alone exceeds the context budget"
91
+ end
92
+
93
+ local kept, note = self.ctx:fit(fixed, self.steps)
94
+ local body = protocol.render_transcript(kept)
95
+ local parts = { system, "" }
96
+ if note then parts[#parts + 1] = note end
97
+ if body ~= "" then parts[#parts + 1] = body end
98
+ local ledger = self.ctx:ledger(system, kept)
99
+ ledger.evicted = note ~= nil
100
+
101
+ -- The flat string is the protocol; the pieces are an optional courtesy.
102
+ -- A chat-shaped backend (Ollama, any provider's messages API) can render
103
+ -- the transcript as alternating turns, which is what an instruct model
104
+ -- is trained on -- qwen2.5:0.5b re-called a tool it had already run when
105
+ -- the whole history arrived as one blob. Backends that do not care keep
106
+ -- using the string and nothing changes for them.
107
+ return table.concat(parts, "\n"), ledger, nil, {
108
+ system = system, steps = kept, note = note,
109
+ }
110
+ end
111
+
112
+ -- One iteration. Split out from :run so tests can drive single steps and the
113
+ -- replay backend can be stepped deterministically.
114
+ --
115
+ -- Returns a step record: { thought, call, observation, status, tokens, ms }
116
+ function Agent:step(task)
117
+ local prompt, ledger, budget_err, structured = self:build_prompt(task)
118
+ if budget_err then
119
+ return { status = "budget", observation = "Error: " .. budget_err }
120
+ end
121
+
122
+ local started = os.clock()
123
+ local ok, raw, meta = pcall(self.backend.complete, self.backend, prompt, {
124
+ stop = protocol.STOP,
125
+ system = structured and structured.system,
126
+ steps = structured and structured.steps,
127
+ note = structured and structured.note,
128
+ task = task,
129
+ -- The catalogue + task, without the transcript: the opening user
130
+ -- turn for a chat-shaped backend.
131
+ task_block = structured and structured.system,
132
+ })
133
+ local elapsed = (os.clock() - started) * 1000
134
+
135
+ -- A backend failure is the one thing that is genuinely fatal: there is no
136
+ -- observation to feed back if the model itself is unreachable.
137
+ if not ok then
138
+ return { status = "fatal", observation = "Backend error: " .. tostring(raw) }
139
+ end
140
+
141
+ local rec = {
142
+ prompt = prompt,
143
+ raw = raw,
144
+ ms = elapsed,
145
+ evicted = ledger and ledger.evicted or nil,
146
+ tokens = {
147
+ window = ledger and ledger.total or 0,
148
+ budget = ledger and ledger.budget or 0,
149
+ },
150
+ }
151
+ if type(meta) == "table" then
152
+ rec.tokens.completion = meta.tokens
153
+ rec.legal_min = meta.min_legal
154
+ rec.constrained = meta.constrained
155
+ rec.forced_finish = meta.forced_finish
156
+ rec.finish_reason = meta.finish_reason
157
+ end
158
+
159
+ local turn, perr = protocol.parse(raw)
160
+ if not turn then
161
+ -- The parser's message is written for the model; hand it straight
162
+ -- back. This is the whole of parse recovery.
163
+ rec.status = "parse_error"
164
+ rec.observation = perr
165
+ return rec
166
+ end
167
+
168
+ rec.thought = turn.thought
169
+
170
+ if turn.kind == "answer" then
171
+ rec.status = "answer"
172
+ rec.call = { tool = protocol.ANSWER_TOOL, args = { text = turn.text } }
173
+ rec.answer = turn.text
174
+ return rec
175
+ end
176
+
177
+ rec.call = { tool = turn.tool, args = turn.args }
178
+
179
+ local repeating, seen = self:is_repeating(rec.call)
180
+ if repeating then
181
+ rec.status = "repeat"
182
+ rec.observation = string.format(
183
+ "You have already called %s with these exact arguments %d times and "
184
+ .. "the result has not changed. Try a different tool or different "
185
+ .. "arguments, or answer with what you have.", turn.tool, seen)
186
+ return rec
187
+ end
188
+
189
+ local ran, result, status = self.tools:invoke(turn.tool, turn.args, self.approve)
190
+ rec.observation = result
191
+ rec.status = ran and "continue" or status
192
+ return rec
193
+ end
194
+
195
+ -- Run one task to completion. Returns answer, reason, steps.
196
+ -- reason: "answer" | "max_steps" | "budget" | "fatal"
197
+ function Agent:run(task)
198
+ self.steps = {}
199
+ local answer, reason = nil, "max_steps"
200
+
201
+ for i = 1, self.max_steps do
202
+ local rec = self:step(task)
203
+ rec.step = i
204
+ self.steps[#self.steps + 1] = rec
205
+ self.tracer:write(rec)
206
+
207
+ if self.verbose then self:print_step(rec) end
208
+
209
+ if rec.status == "answer" then
210
+ answer, reason = rec.answer, "answer"
211
+ break
212
+ elseif rec.status == "fatal" or rec.status == "budget" then
213
+ reason = rec.status
214
+ break
215
+ elseif self.fatal_on[rec.status] then
216
+ -- Recovery deliberately disabled for this status (ablation only).
217
+ reason = rec.status
218
+ break
219
+ end
220
+ end
221
+
222
+ self.tracer:close()
223
+ return answer, reason, self.steps
224
+ end
225
+
226
+ function Agent:print_step(rec)
227
+ io.write(string.format("\n[step %d] %s\n", rec.step or 0, rec.status))
228
+ if rec.tokens and rec.tokens.window and rec.tokens.window > 0 then
229
+ io.write(string.format(" window: %d / %d tokens\n",
230
+ rec.tokens.window, rec.tokens.budget))
231
+ end
232
+ if rec.legal_min then
233
+ io.write(string.format(" grammar: narrowed to %d legal tokens at its tightest\n",
234
+ rec.legal_min))
235
+ end
236
+ if rec.thought then io.write(" thought: " .. rec.thought .. "\n") end
237
+ if rec.call then
238
+ io.write(" call: " .. trace.encode(rec.call) .. "\n")
239
+ end
240
+ if rec.observation then
241
+ local obs = rec.observation:gsub("\n", "\n ")
242
+ io.write(" result: " .. obs .. "\n")
243
+ end
244
+ io.flush()
245
+ end
246
+
247
+ return Agent
provenance/source/backend/local.lua ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- backend/local.lua - Drives the pure-Lua model from repo 1.
2
+ --
3
+ -- The backend the README leads with: no API key, no network, the whole stack
4
+ -- readable from the agent loop down to the matmul.
5
+ --
6
+ -- It binds to lua-llama's exported forward pass rather than its generate()
7
+ -- loop, because the entire point is to intervene BETWEEN logits and
8
+ -- sampling -- that is where grammar.lua masks. The seam:
9
+ --
10
+ -- gen.forward(model, token, pos, state, key_cache, value_cache, att_buf)
11
+ -- -> logits[1..vocab_size] (1-indexed array; token ids are 0-indexed)
12
+ --
13
+ -- No change to repo 1 is needed; forward() is already exported.
14
+ --
15
+ --
16
+ -- HOW A STEP IS GENERATED
17
+ --
18
+ -- The harness writes the scaffolding and the model fills the slots:
19
+ --
20
+ -- prompt ... "\nTHOUGHT: " <- harness
21
+ -- "the sun was very big" <- model, UNCONSTRAINED, one line
22
+ -- "\nCALL: " <- harness
23
+ -- {"tool":"answer","args":... <- model, CONSTRAINED by grammar.lua
24
+ --
25
+ -- Stated plainly because it matters for reading the result: the model is not
26
+ -- deciding whether to call a tool. It is deciding WHICH tool and with what
27
+ -- arguments. A 15M checkpoint left to choose freely emits neither, which is
28
+ -- the 0% arm of the ablation and is measured in eval/ablate.lua rather than
29
+ -- assumed.
30
+ --
31
+ --
32
+ -- HONEST LIMITATION
33
+ --
34
+ -- Pure-Lua inference runs ~3-4 tok/s at 15M, so ~0.05 tok/s at 1B. This
35
+ -- backend demonstrates the MECHANISM. backend/http.lua demonstrates the
36
+ -- CAPABILITY. The split is the point, not an apology.
37
+
38
+ local grammar = require('grammar')
39
+ local protocol = require('protocol')
40
+
41
+ local backend = {}
42
+
43
+ local Local = {}
44
+ Local.__index = Local
45
+
46
+ -- opts:
47
+ -- llama_path path to the lua-llama checkout, default "../lua_llama"
48
+ -- checkpoint default <llama_path>/stories15M.bin
49
+ -- tokenizer default <llama_path>/tokenizer.bin
50
+ -- tools registry, required when constrain is true
51
+ -- constrain default true; false reproduces the 0% arm of the ablation
52
+ -- temperature default 0.0 (greedy, so runs are reproducible)
53
+ -- max_thought default 24 tokens
54
+ -- max_call default 96 tokens
55
+ -- quiet suppress repo 1's load-time prints
56
+ function backend.new(opts)
57
+ opts = opts or {}
58
+ local root = opts.llama_path or "../lua_llama"
59
+
60
+ -- Repo 1's modules require() each other by bare name, so its directory
61
+ -- has to be on the path as well as ours.
62
+ package.path = root .. "/?.lua;" .. package.path
63
+
64
+ local Model = require('model')
65
+ local Tokenizer = require('tokenizer')
66
+ local gen = require('generate')
67
+
68
+ -- model.lua and tokenizer.lua print as they load. Useful in repo 1's CLI,
69
+ -- noise here.
70
+ local real_print = print
71
+ if opts.quiet ~= false then _G.print = function() end end
72
+ local ok, model = pcall(Model.new, opts.checkpoint or (root .. "/stories15M.bin"))
73
+ local tok
74
+ if ok then
75
+ ok, tok = pcall(Tokenizer.new,
76
+ opts.tokenizer or (root .. "/tokenizer.bin"), model.config.vocab_size)
77
+ end
78
+ _G.print = real_print
79
+ if not ok then
80
+ error("backend/local: " .. tostring(model or tok) ..
81
+ "\n looked in " .. root .. " -- set --llama-path if lua-llama is elsewhere", 0)
82
+ end
83
+
84
+ local self = setmetatable({
85
+ model = model,
86
+ tok = tok,
87
+ gen = gen,
88
+ cfg = model.config,
89
+ constrain = opts.constrain ~= false,
90
+ temperature = opts.temperature or 0.0,
91
+ max_thought = opts.max_thought or 24,
92
+ max_call = opts.max_call or 96,
93
+ stats = { calls = 0, parsed = 0, tokens = 0 },
94
+ }, Local)
95
+
96
+ if self.constrain then
97
+ if not opts.tools then error("backend/local: constrained mode needs the tool registry") end
98
+ self.grammar = grammar.compile(opts.tools, tok, self.cfg.vocab_size)
99
+ end
100
+
101
+ self:reset()
102
+ return self
103
+ end
104
+
105
+ -- Swap the tool set without reloading the model.
106
+ --
107
+ -- The grammar bakes the tool names and argument keys into its paths, so a
108
+ -- different tool set needs a different grammar -- but loading a checkpoint
109
+ -- takes ~17s and the eval runs one task per tool set. Recompiling is
110
+ -- milliseconds; reloading is not.
111
+ function Local:set_tools(reg)
112
+ if self.constrain then
113
+ self.grammar = grammar.compile(reg, self.tok, self.cfg.vocab_size)
114
+ end
115
+ end
116
+
117
+ -- KV cache lifecycle.
118
+ --
119
+ -- The agent re-prompts with a growing transcript every step, so the naive
120
+ -- implementation refills the cache from scratch each time -- O(n^2) over a
121
+ -- run, and the dominant cost at 3 tok/s. Instead the cache persists and only
122
+ -- the tokens the prompt grew by are forwarded.
123
+ --
124
+ -- The invariant that catches bugs here is the one repo 1 used for the
125
+ -- speculative draft path: a warm run and a cold run must produce identical
126
+ -- output at temperature 0. eval/ablate.lua checks it.
127
+ function Local:reset()
128
+ local c = self.cfg
129
+
130
+ -- Allocate once. Re-zeroing on every reset is pure waste: the cache is
131
+ -- position-indexed, and every slot below `pos` is written before it is
132
+ -- ever read again -- the same invariant `feed` relies on when it rewinds
133
+ -- after a prefix divergence. For the 42M checkpoint this is 8.4M Lua
134
+ -- numbers per reset, and the eval calls reset once per task.
135
+ if not self.key_cache then
136
+ self.state = self.model:create_run_state()
137
+ self.key_cache, self.value_cache = {}, {}
138
+ for i = 1, c.n_layers * c.seq_len * c.kv_dim do
139
+ self.key_cache[i], self.value_cache[i] = 0.0, 0.0
140
+ end
141
+ self.att_buf = {}
142
+ for i = 1, c.seq_len do self.att_buf[i] = 0.0 end
143
+ end
144
+
145
+ self.pos = 0
146
+ self.cached = {} -- token ids currently represented in the cache
147
+ end
148
+
149
+ -- Forward `tokens` starting at the current position, reusing the cache for
150
+ -- any shared prefix. Returns the logits after the last token.
151
+ function Local:feed(tokens)
152
+ local shared = 0
153
+ while shared < #self.cached and shared < #tokens
154
+ and self.cached[shared + 1] == tokens[shared + 1] do
155
+ shared = shared + 1
156
+ end
157
+
158
+ -- Divergence means the cache past `shared` is stale. The KV cache is
159
+ -- position-indexed, so rewinding is just moving pos back: entries beyond
160
+ -- it are overwritten before they are ever read again.
161
+ if shared < #self.cached then
162
+ self.pos = shared
163
+ for i = #self.cached, shared + 1, -1 do self.cached[i] = nil end
164
+ end
165
+
166
+ local logits
167
+ for i = shared + 1, #tokens do
168
+ if self.pos >= self.cfg.seq_len then
169
+ error(string.format(
170
+ "prompt exceeds the model's %d-token context", self.cfg.seq_len), 0)
171
+ end
172
+ logits = self.gen.forward(self.model, tokens[i], self.pos, self.state,
173
+ self.key_cache, self.value_cache, self.att_buf)
174
+ self.cached[i] = tokens[i]
175
+ self.pos = self.pos + 1
176
+ end
177
+ return logits
178
+ end
179
+
180
+ local function sample(logits, n, temperature)
181
+ if temperature < 0.01 then
182
+ local best, best_v = 1, -math.huge
183
+ for i = 1, n do
184
+ if logits[i] > best_v then best, best_v = i, logits[i] end
185
+ end
186
+ return best - 1
187
+ end
188
+ -- Softmax over the masked distribution. -inf entries drop out naturally.
189
+ local max_v = -math.huge
190
+ for i = 1, n do if logits[i] > max_v then max_v = logits[i] end end
191
+ local sum = 0
192
+ local probs = {}
193
+ for i = 1, n do
194
+ probs[i] = math.exp((logits[i] - max_v) / temperature)
195
+ sum = sum + probs[i]
196
+ end
197
+ local r, cdf = math.random() * sum, 0
198
+ for i = 1, n do
199
+ cdf = cdf + probs[i]
200
+ if r < cdf then return i - 1 end
201
+ end
202
+ return n - 1
203
+ end
204
+
205
+ -- Generate freely until a stop string appears or the ceiling is hit.
206
+ function Local:generate_free(tokens, max_new, stops)
207
+ local out, n = {}, self.cfg.vocab_size
208
+ local logits = self:feed(tokens)
209
+ for _ = 1, max_new do
210
+ local id = sample(logits, n, self.temperature)
211
+ if id == 2 then break end -- EOS
212
+ local piece = self.tok:decode(id)
213
+ out[#out + 1] = piece
214
+ local text = table.concat(out)
215
+ for _, s in ipairs(stops or {}) do
216
+ if text:find(s, 1, true) then
217
+ return text:sub(1, text:find(s, 1, true) - 1), #out
218
+ end
219
+ end
220
+ tokens[#tokens + 1] = id
221
+ logits = self:feed(tokens)
222
+ end
223
+ return table.concat(out), #out
224
+ end
225
+
226
+ -- Generate under the grammar. Every sampled token is legal by construction,
227
+ -- so the result parses by construction.
228
+ function Local:generate_constrained(tokens)
229
+ local m = self.grammar:start()
230
+ local n = self.cfg.vocab_size
231
+ local min_legal = math.huge
232
+ local produced = 0
233
+
234
+ local logits = self:feed(tokens)
235
+ for _ = 1, self.max_call do
236
+ if m:is_done() then break end
237
+ local legal = m:apply(logits, n)
238
+ if legal < min_legal then min_legal = legal end
239
+ local id = sample(logits, n, self.temperature)
240
+ m:advance(id)
241
+ produced = produced + 1
242
+ tokens[#tokens + 1] = id
243
+ if m:is_done() then break end
244
+ logits = self:feed(tokens)
245
+ end
246
+
247
+ -- Hit the ceiling mid-call: finishing it costs a few characters and
248
+ -- turns a wasted step into a usable one.
249
+ local text = m:text()
250
+ local forced_finish = not m:is_done()
251
+ if forced_finish then text = text .. m:finish() end
252
+ return text, produced, min_legal, forced_finish
253
+ end
254
+
255
+ function Local:complete(prompt, opts)
256
+ opts = opts or {}
257
+
258
+ -- The thought is free-form and one line long. It is not load-bearing for
259
+ -- a 15M model -- it will be a fragment of a children's story -- but it is
260
+ -- in the transcript, and seeing it next to the constrained call is what
261
+ -- makes the syntax/semantics split legible.
262
+ local thought_prompt = prompt .. "\n" .. protocol.THOUGHT_PREFIX
263
+ local thought = self:generate_free(
264
+ self.tok:encode(thought_prompt), self.max_thought, { "\n" })
265
+ thought = thought:gsub("%s+$", ""):gsub("\n.*", "")
266
+
267
+ local call_prompt = thought_prompt .. thought .. "\n" .. protocol.CALL_PREFIX
268
+ local tokens = self.tok:encode(call_prompt)
269
+
270
+ local call, produced, min_legal, forced_finish
271
+ if self.constrain then
272
+ call, produced, min_legal, forced_finish = self:generate_constrained(tokens)
273
+ else
274
+ call, produced = self:generate_free(tokens, self.max_call, { "\n" })
275
+ call = call:gsub("^%s+", "")
276
+ end
277
+
278
+ self.stats.calls = self.stats.calls + 1
279
+ self.stats.tokens = self.stats.tokens + produced
280
+ if grammar.parses(call) then self.stats.parsed = self.stats.parsed + 1 end
281
+
282
+ local text = protocol.THOUGHT_PREFIX .. thought .. "\n" .. protocol.CALL_PREFIX .. call
283
+ return text, {
284
+ tokens = produced,
285
+ min_legal = min_legal ~= math.huge and min_legal or nil,
286
+ constrained = self.constrain,
287
+ forced_finish = forced_finish,
288
+ }
289
+ end
290
+
291
+ return backend
provenance/source/bpe.lua ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- bpe.lua - Load lua-llama's BPE tokenizer without loading a model.
2
+ --
3
+ -- Exact token counts need the real tokenizer, and the real tokenizer is a
4
+ -- 433KB file. But repo 1's Tokenizer.new(path, vocab_size) takes the vocab
5
+ -- size as an argument, and the only place the rest of this repo had one was
6
+ -- model.config.vocab_size -- so counting tokens meant loading a 60MB
7
+ -- checkpoint and waiting ~17s for it.
8
+ --
9
+ -- That coupling is incidental: tokenizer.bin describes its own length, you
10
+ -- just have to walk it. This scans the file to derive the entry count, then
11
+ -- hands that to repo 1's loader. The replay and http backends get exact
12
+ -- counts with no model at all.
13
+ --
14
+ -- Format (llama2.c):
15
+ -- int32 max_token_length
16
+ -- repeated: float32 score, int32 len, len bytes
17
+
18
+ local bpe = {}
19
+
20
+ -- Walk the file and count entries. ~433KB and a few thousand reads, so it
21
+ -- costs milliseconds -- against 17s and 60MB for the checkpoint it replaces.
22
+ function bpe.count_entries(path)
23
+ local fh, err = io.open(path, "rb")
24
+ if not fh then return nil, tostring(err) end
25
+
26
+ local header = fh:read(4)
27
+ if not header or #header ~= 4 then
28
+ fh:close()
29
+ return nil, "truncated header"
30
+ end
31
+
32
+ local n = 0
33
+ while true do
34
+ local score = fh:read(4)
35
+ if not score or #score < 4 then break end
36
+ local len_bytes = fh:read(4)
37
+ if not len_bytes or #len_bytes < 4 then
38
+ fh:close()
39
+ return nil, string.format("truncated length field at entry %d", n)
40
+ end
41
+ local len = string.unpack("<i4", len_bytes)
42
+ if len < 0 or len > 1024 then
43
+ fh:close()
44
+ return nil, string.format("implausible token length %d at entry %d", len, n)
45
+ end
46
+ local tok = fh:read(len)
47
+ if not tok or #tok ~= len then
48
+ fh:close()
49
+ return nil, string.format("truncated token body at entry %d", n)
50
+ end
51
+ n = n + 1
52
+ end
53
+ fh:close()
54
+
55
+ if n == 0 then return nil, "no tokens found" end
56
+ return n
57
+ end
58
+
59
+ -- Returns tokenizer, vocab_size or nil, err.
60
+ -- llama_path is where repo 1 lives, needed because its tokenizer module
61
+ -- requires('utils') by bare name.
62
+ function bpe.load(path, llama_path)
63
+ local n, err = bpe.count_entries(path)
64
+ if not n then return nil, err end
65
+
66
+ local root = llama_path or "../lua_llama"
67
+ package.path = root .. "/?.lua;" .. package.path
68
+
69
+ local ok, Tokenizer = pcall(require, "tokenizer")
70
+ if not ok then return nil, "cannot load lua-llama's tokenizer.lua: " .. tostring(Tokenizer) end
71
+
72
+ -- Repo 1's loader prints as it goes; useful in its CLI, noise here.
73
+ local real_print = print
74
+ _G.print = function() end
75
+ local loaded, tok = pcall(Tokenizer.new, path, n)
76
+ _G.print = real_print
77
+
78
+ if not loaded then return nil, tostring(tok) end
79
+ return tok, n
80
+ end
81
+
82
+ -- The stand-in when no tokenizer file is available: roughly four characters
83
+ -- per token. Good enough to exercise the eviction policies, and never
84
+ -- reported as exact.
85
+ function bpe.approximate()
86
+ return { encode = function(_, s)
87
+ local out = {}
88
+ for k = 1, math.max(1, math.ceil(#s / 4)) do out[k] = k end
89
+ return out
90
+ end }
91
+ end
92
+
93
+ return bpe
provenance/source/context.lua ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- context.lua - Token budget and eviction.
2
+ --
3
+ -- Every minimal-agent tutorial estimates context as #chars/4 and calls it a
4
+ -- day. We have a real BPE tokenizer next door, so we count for real and print
5
+ -- the ledger. Knowing exactly what is in the window is most of context
6
+ -- management; the eviction policy is the small part.
7
+ --
8
+ -- The rule that matters more than the choice of policy: WHEN SOMETHING IS
9
+ -- DROPPED, THE MODEL IS TOLD. Silent truncation is the most common context
10
+ -- bug in real agents, and its signature is a model that confidently invents
11
+ -- the contents of an observation it can no longer see. A model that knows it
12
+ -- forgot something asks again.
13
+
14
+ local protocol = require('protocol')
15
+
16
+ local context = {}
17
+
18
+ local Context = {}
19
+ Context.__index = Context
20
+
21
+ -- tokenizer: anything with :encode(text) -> {ids}
22
+ -- budget: hard ceiling in tokens
23
+ -- policy: key of context.policies, default "elide_observations"
24
+ function context.new(tokenizer, budget, policy)
25
+ if not tokenizer or not tokenizer.encode then
26
+ error("context.new: needs a tokenizer with :encode")
27
+ end
28
+ local name = policy or "elide_observations"
29
+ if not context.policies[name] then
30
+ error("context.new: unknown policy " .. tostring(name))
31
+ end
32
+ return setmetatable({
33
+ tokenizer = tokenizer,
34
+ budget = budget or 4096,
35
+ policy = name,
36
+ cache = {},
37
+ cache_n = 0,
38
+ }, Context)
39
+ end
40
+
41
+ -- Price a string in real tokens. Memoized, because the system preamble and
42
+ -- tool catalogue would otherwise be re-tokenized on every single step -- and
43
+ -- BPE encoding is not cheap in pure Lua.
44
+ function Context:count(text)
45
+ if text == nil or text == "" then return 0 end
46
+ local hit = self.cache[text]
47
+ if hit then return hit end
48
+ local n = #self.tokenizer:encode(text)
49
+ -- Bounded cache: observations are unique and would otherwise grow this
50
+ -- without limit over a long run.
51
+ if self.cache_n > 512 then self.cache, self.cache_n = {}, 0 end
52
+ self.cache[text] = n
53
+ self.cache_n = self.cache_n + 1
54
+ return n
55
+ end
56
+
57
+ function Context:count_steps(steps)
58
+ return self:count(protocol.render_transcript(steps))
59
+ end
60
+
61
+ -- The ledger: what is actually in the window right now.
62
+ -- main.lua prints this each step under --verbose, and it is the single most
63
+ -- useful thing to look at when an agent misbehaves.
64
+ function Context:ledger(system, steps)
65
+ local sys = self:count(system)
66
+ local hist = self:count_steps(steps)
67
+ return {
68
+ system = sys,
69
+ transcript = hist,
70
+ total = sys + hist,
71
+ budget = self.budget,
72
+ headroom = self.budget - (sys + hist),
73
+ policy = self.policy,
74
+ }
75
+ end
76
+
77
+ function Context:format_ledger(l)
78
+ return string.format(
79
+ " context: system %d + transcript %d = %d / %d tokens (%d free, %s)",
80
+ l.system, l.transcript, l.total, l.budget, l.headroom, l.policy)
81
+ end
82
+
83
+ -- Fit `steps` into the budget left after fixed costs.
84
+ -- Returns kept_steps, note. The note is appended to the transcript so the
85
+ -- model learns it lost information rather than hallucinating around the gap.
86
+ function Context:fit(fixed_tokens, steps)
87
+ local available = self.budget - fixed_tokens
88
+ local used = self:count_steps(steps)
89
+ if used <= available then return steps, nil end
90
+
91
+ local kept, note = context.policies[self.policy](steps, used - available, self)
92
+
93
+ -- A policy can fail to free enough -- elision bottoms out once every
94
+ -- observation is already a stub. Fall back to dropping whole steps rather
95
+ -- than silently handing back an oversized window.
96
+ if self:count_steps(kept) > available and self.policy ~= "drop_oldest" then
97
+ local extra
98
+ kept, extra = context.policies.drop_oldest(
99
+ kept, self:count_steps(kept) - available, self)
100
+ note = (note and (note .. " ") or "") .. (extra or "")
101
+ end
102
+
103
+ -- Last resort: a SINGLE observation can be larger than the entire
104
+ -- budget, and no policy that evicts whole steps can help -- the newest
105
+ -- step is the one being reasoned about and dropping it makes the next
106
+ -- turn incoherent. So the observation itself is cut.
107
+ --
108
+ -- This is the floor of context management, and it is worth stating
109
+ -- plainly: eviction cannot save you from one oversized tool result.
110
+ -- Capping output at the tool (tools.MAX_OBSERVATION) is the real fix;
111
+ -- this is the backstop that keeps the request sendable when it is not
112
+ -- enough. Without it `fit` returns an over-budget window and the ledger
113
+ -- reports a number the model never actually received.
114
+ local over = self:count_steps(kept) - available
115
+ if over > 0 and #kept > 0 then
116
+ local last = kept[#kept]
117
+ if last.observation and #last.observation > 0 then
118
+ local copy = {}
119
+ for k, v in pairs(last) do copy[k] = v end
120
+ -- Cut by characters, then verify in tokens: the ratio varies.
121
+ local keep_chars = #last.observation
122
+ while keep_chars > 0 and self:count_steps(kept) - available > 0 do
123
+ keep_chars = math.floor(keep_chars * 0.6)
124
+ copy.observation = last.observation:sub(1, keep_chars)
125
+ .. string.format("\n... [cut: %d of %d bytes shown]",
126
+ keep_chars, #last.observation)
127
+ copy.truncated = true
128
+ kept[#kept] = copy
129
+ end
130
+ note = (note and (note .. " ") or "")
131
+ .. "[context: the most recent tool result was too large for the "
132
+ .. "window and was cut. Read a smaller portion if you need the rest.]"
133
+ end
134
+ end
135
+
136
+ return kept, note
137
+ end
138
+
139
+ --------------------------------------------------------------------------
140
+ -- Policies. Each takes (steps, tokens_to_free, ctx) and returns
141
+ -- kept_steps, note. Swapping these and re-running the eval is the ablation.
142
+ --------------------------------------------------------------------------
143
+ context.policies = {}
144
+
145
+ -- Truncate old observations to a stub, keeping every thought and call.
146
+ -- The usual right default: tool output is bulky, and the model mostly needs
147
+ -- to remember THAT it called something and with what, not the full result.
148
+ function context.policies.elide_observations(steps, to_free, ctx)
149
+ local kept, freed, n = {}, 0, 0
150
+ for i, s in ipairs(steps) do
151
+ kept[i] = s
152
+ end
153
+ -- Oldest first; the most recent observation is the one being reasoned
154
+ -- about right now, so it is elided last and only under real pressure.
155
+ for i = 1, #kept - 1 do
156
+ if freed >= to_free then break end
157
+ local s = kept[i]
158
+ if s.observation and not s.elided then
159
+ local before = ctx:count(s.observation)
160
+ local stub = string.format("[%d bytes elided]", #s.observation)
161
+ local after = ctx:count(stub)
162
+ if before > after then
163
+ local copy = {}
164
+ for k, v in pairs(s) do copy[k] = v end
165
+ copy.observation = stub
166
+ copy.elided = true
167
+ kept[i] = copy
168
+ freed = freed + (before - after)
169
+ n = n + 1
170
+ end
171
+ end
172
+ end
173
+ if n == 0 then return kept, nil end
174
+ return kept, string.format(
175
+ "[context: %d earlier tool result%s elided to stay within the window. "
176
+ .. "Call the tool again if you need the full output.]",
177
+ n, n == 1 and " was" or "s were")
178
+ end
179
+
180
+ -- Drop whole steps from the front, keeping the most recent work.
181
+ function context.policies.drop_oldest(steps, to_free, ctx)
182
+ local freed, cut = 0, 0
183
+ -- Never drop the final step: it holds the observation the next turn is a
184
+ -- response to.
185
+ while cut < #steps - 1 and freed < to_free do
186
+ cut = cut + 1
187
+ freed = freed + ctx:count(protocol.render_transcript({ steps[cut] }))
188
+ end
189
+ if cut == 0 then return steps, nil end
190
+ local kept = {}
191
+ for i = cut + 1, #steps do kept[#kept + 1] = steps[i] end
192
+ return kept, string.format(
193
+ "[context: %d earlier step%s dropped to stay within the window.]",
194
+ cut, cut == 1 and " was" or "s were")
195
+ end
196
+
197
+ -- Replace the oldest run of steps with a model-written summary. Costs an
198
+ -- extra backend call, which is why it is not the default -- and why it needs
199
+ -- a summarizer wired in explicitly.
200
+ function context.policies.summarize(steps, to_free, ctx)
201
+ if not ctx.summarizer then
202
+ -- Degrade loudly rather than silently doing something else.
203
+ local kept, note = context.policies.drop_oldest(steps, to_free, ctx)
204
+ return kept, (note or "") .. " [no summarizer configured; dropped instead]"
205
+ end
206
+ local half = math.max(1, math.floor(#steps / 2))
207
+ local old = {}
208
+ for i = 1, half do old[i] = steps[i] end
209
+ local ok, summary = pcall(ctx.summarizer, protocol.render_transcript(old))
210
+ if not ok or type(summary) ~= "string" then
211
+ return context.policies.drop_oldest(steps, to_free, ctx)
212
+ end
213
+ local kept = { { thought = nil, observation = nil, note =
214
+ "[context: earlier steps summarized] " .. summary } }
215
+ for i = half + 1, #steps do kept[#kept + 1] = steps[i] end
216
+ return kept, string.format("[context: %d earlier steps were summarized.]", half)
217
+ end
218
+
219
+ return context
provenance/source/eval/fixtures/big.txt ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MARKER: omega
2
+ filler line 1 with assorted padding words to consume context budget
3
+ filler line 2 with assorted padding words to consume context budget
4
+ filler line 3 with assorted padding words to consume context budget
5
+ filler line 4 with assorted padding words to consume context budget
6
+ filler line 5 with assorted padding words to consume context budget
7
+ filler line 6 with assorted padding words to consume context budget
8
+ filler line 7 with assorted padding words to consume context budget
9
+ filler line 8 with assorted padding words to consume context budget
10
+ filler line 9 with assorted padding words to consume context budget
11
+ filler line 10 with assorted padding words to consume context budget
12
+ filler line 11 with assorted padding words to consume context budget
13
+ filler line 12 with assorted padding words to consume context budget
14
+ filler line 13 with assorted padding words to consume context budget
15
+ filler line 14 with assorted padding words to consume context budget
16
+ filler line 15 with assorted padding words to consume context budget
17
+ filler line 16 with assorted padding words to consume context budget
18
+ filler line 17 with assorted padding words to consume context budget
19
+ filler line 18 with assorted padding words to consume context budget
20
+ filler line 19 with assorted padding words to consume context budget
21
+ filler line 20 with assorted padding words to consume context budget
22
+ filler line 21 with assorted padding words to consume context budget
23
+ filler line 22 with assorted padding words to consume context budget
24
+ filler line 23 with assorted padding words to consume context budget
25
+ filler line 24 with assorted padding words to consume context budget
26
+ filler line 25 with assorted padding words to consume context budget
27
+ filler line 26 with assorted padding words to consume context budget
28
+ filler line 27 with assorted padding words to consume context budget
29
+ filler line 28 with assorted padding words to consume context budget
30
+ filler line 29 with assorted padding words to consume context budget
31
+ filler line 30 with assorted padding words to consume context budget
32
+ filler line 31 with assorted padding words to consume context budget
33
+ filler line 32 with assorted padding words to consume context budget
34
+ filler line 33 with assorted padding words to consume context budget
35
+ filler line 34 with assorted padding words to consume context budget
36
+ filler line 35 with assorted padding words to consume context budget
37
+ filler line 36 with assorted padding words to consume context budget
38
+ filler line 37 with assorted padding words to consume context budget
39
+ filler line 38 with assorted padding words to consume context budget
40
+ filler line 39 with assorted padding words to consume context budget
41
+ filler line 40 with assorted padding words to consume context budget
42
+ filler line 41 with assorted padding words to consume context budget
43
+ filler line 42 with assorted padding words to consume context budget
44
+ filler line 43 with assorted padding words to consume context budget
45
+ filler line 44 with assorted padding words to consume context budget
46
+ filler line 45 with assorted padding words to consume context budget
47
+ filler line 46 with assorted padding words to consume context budget
48
+ filler line 47 with assorted padding words to consume context budget
49
+ filler line 48 with assorted padding words to consume context budget
50
+ filler line 49 with assorted padding words to consume context budget
51
+ filler line 50 with assorted padding words to consume context budget
52
+ filler line 51 with assorted padding words to consume context budget
53
+ filler line 52 with assorted padding words to consume context budget
54
+ filler line 53 with assorted padding words to consume context budget
55
+ filler line 54 with assorted padding words to consume context budget
56
+ filler line 55 with assorted padding words to consume context budget
57
+ filler line 56 with assorted padding words to consume context budget
58
+ filler line 57 with assorted padding words to consume context budget
59
+ filler line 58 with assorted padding words to consume context budget
60
+ filler line 59 with assorted padding words to consume context budget
61
+ filler line 60 with assorted padding words to consume context budget
62
+ filler line 61 with assorted padding words to consume context budget
63
+ filler line 62 with assorted padding words to consume context budget
64
+ filler line 63 with assorted padding words to consume context budget
65
+ filler line 64 with assorted padding words to consume context budget
66
+ filler line 65 with assorted padding words to consume context budget
67
+ filler line 66 with assorted padding words to consume context budget
68
+ filler line 67 with assorted padding words to consume context budget
69
+ filler line 68 with assorted padding words to consume context budget
70
+ filler line 69 with assorted padding words to consume context budget
71
+ filler line 70 with assorted padding words to consume context budget
72
+ filler line 71 with assorted padding words to consume context budget
73
+ filler line 72 with assorted padding words to consume context budget
74
+ filler line 73 with assorted padding words to consume context budget
75
+ filler line 74 with assorted padding words to consume context budget
76
+ filler line 75 with assorted padding words to consume context budget
77
+ filler line 76 with assorted padding words to consume context budget
78
+ filler line 77 with assorted padding words to consume context budget
79
+ filler line 78 with assorted padding words to consume context budget
80
+ filler line 79 with assorted padding words to consume context budget
81
+ filler line 80 with assorted padding words to consume context budget
82
+ filler line 81 with assorted padding words to consume context budget
83
+ filler line 82 with assorted padding words to consume context budget
84
+ filler line 83 with assorted padding words to consume context budget
85
+ filler line 84 with assorted padding words to consume context budget
86
+ filler line 85 with assorted padding words to consume context budget
87
+ filler line 86 with assorted padding words to consume context budget
88
+ filler line 87 with assorted padding words to consume context budget
89
+ filler line 88 with assorted padding words to consume context budget
90
+ filler line 89 with assorted padding words to consume context budget
91
+ filler line 90 with assorted padding words to consume context budget
92
+ filler line 91 with assorted padding words to consume context budget
93
+ filler line 92 with assorted padding words to consume context budget
94
+ filler line 93 with assorted padding words to consume context budget
95
+ filler line 94 with assorted padding words to consume context budget
96
+ filler line 95 with assorted padding words to consume context budget
97
+ filler line 96 with assorted padding words to consume context budget
98
+ filler line 97 with assorted padding words to consume context budget
99
+ filler line 98 with assorted padding words to consume context budget
100
+ filler line 99 with assorted padding words to consume context budget
101
+ filler line 100 with assorted padding words to consume context budget
102
+ filler line 101 with assorted padding words to consume context budget
103
+ filler line 102 with assorted padding words to consume context budget
104
+ filler line 103 with assorted padding words to consume context budget
105
+ filler line 104 with assorted padding words to consume context budget
106
+ filler line 105 with assorted padding words to consume context budget
107
+ filler line 106 with assorted padding words to consume context budget
108
+ filler line 107 with assorted padding words to consume context budget
109
+ filler line 108 with assorted padding words to consume context budget
110
+ filler line 109 with assorted padding words to consume context budget
111
+ filler line 110 with assorted padding words to consume context budget
112
+ filler line 111 with assorted padding words to consume context budget
113
+ filler line 112 with assorted padding words to consume context budget
114
+ filler line 113 with assorted padding words to consume context budget
115
+ filler line 114 with assorted padding words to consume context budget
116
+ filler line 115 with assorted padding words to consume context budget
117
+ filler line 116 with assorted padding words to consume context budget
118
+ filler line 117 with assorted padding words to consume context budget
119
+ filler line 118 with assorted padding words to consume context budget
120
+ filler line 119 with assorted padding words to consume context budget
121
+ filler line 120 with assorted padding words to consume context budget
122
+ filler line 121 with assorted padding words to consume context budget
123
+ filler line 122 with assorted padding words to consume context budget
124
+ filler line 123 with assorted padding words to consume context budget
125
+ filler line 124 with assorted padding words to consume context budget
126
+ filler line 125 with assorted padding words to consume context budget
127
+ filler line 126 with assorted padding words to consume context budget
128
+ filler line 127 with assorted padding words to consume context budget
129
+ filler line 128 with assorted padding words to consume context budget
130
+ filler line 129 with assorted padding words to consume context budget
131
+ filler line 130 with assorted padding words to consume context budget
132
+ filler line 131 with assorted padding words to consume context budget
133
+ filler line 132 with assorted padding words to consume context budget
134
+ filler line 133 with assorted padding words to consume context budget
135
+ filler line 134 with assorted padding words to consume context budget
136
+ filler line 135 with assorted padding words to consume context budget
137
+ filler line 136 with assorted padding words to consume context budget
138
+ filler line 137 with assorted padding words to consume context budget
139
+ filler line 138 with assorted padding words to consume context budget
140
+ filler line 139 with assorted padding words to consume context budget
141
+ filler line 140 with assorted padding words to consume context budget
142
+ filler line 141 with assorted padding words to consume context budget
143
+ filler line 142 with assorted padding words to consume context budget
144
+ filler line 143 with assorted padding words to consume context budget
145
+ filler line 144 with assorted padding words to consume context budget
146
+ filler line 145 with assorted padding words to consume context budget
147
+ filler line 146 with assorted padding words to consume context budget
148
+ filler line 147 with assorted padding words to consume context budget
149
+ filler line 148 with assorted padding words to consume context budget
150
+ filler line 149 with assorted padding words to consume context budget
151
+ filler line 150 with assorted padding words to consume context budget
152
+ filler line 151 with assorted padding words to consume context budget
153
+ filler line 152 with assorted padding words to consume context budget
154
+ filler line 153 with assorted padding words to consume context budget
155
+ filler line 154 with assorted padding words to consume context budget
156
+ filler line 155 with assorted padding words to consume context budget
157
+ filler line 156 with assorted padding words to consume context budget
158
+ filler line 157 with assorted padding words to consume context budget
159
+ filler line 158 with assorted padding words to consume context budget
160
+ filler line 159 with assorted padding words to consume context budget
161
+ filler line 160 with assorted padding words to consume context budget
162
+ filler line 161 with assorted padding words to consume context budget
163
+ filler line 162 with assorted padding words to consume context budget
164
+ filler line 163 with assorted padding words to consume context budget
165
+ filler line 164 with assorted padding words to consume context budget
166
+ filler line 165 with assorted padding words to consume context budget
167
+ filler line 166 with assorted padding words to consume context budget
168
+ filler line 167 with assorted padding words to consume context budget
169
+ filler line 168 with assorted padding words to consume context budget
170
+ filler line 169 with assorted padding words to consume context budget
171
+ filler line 170 with assorted padding words to consume context budget
172
+ filler line 171 with assorted padding words to consume context budget
173
+ filler line 172 with assorted padding words to consume context budget
174
+ filler line 173 with assorted padding words to consume context budget
175
+ filler line 174 with assorted padding words to consume context budget
176
+ filler line 175 with assorted padding words to consume context budget
177
+ filler line 176 with assorted padding words to consume context budget
178
+ filler line 177 with assorted padding words to consume context budget
179
+ filler line 178 with assorted padding words to consume context budget
180
+ filler line 179 with assorted padding words to consume context budget
181
+ filler line 180 with assorted padding words to consume context budget
182
+ filler line 181 with assorted padding words to consume context budget
183
+ filler line 182 with assorted padding words to consume context budget
184
+ filler line 183 with assorted padding words to consume context budget
185
+ filler line 184 with assorted padding words to consume context budget
186
+ filler line 185 with assorted padding words to consume context budget
187
+ filler line 186 with assorted padding words to consume context budget
188
+ filler line 187 with assorted padding words to consume context budget
189
+ filler line 188 with assorted padding words to consume context budget
190
+ filler line 189 with assorted padding words to consume context budget
191
+ filler line 190 with assorted padding words to consume context budget
192
+ filler line 191 with assorted padding words to consume context budget
193
+ filler line 192 with assorted padding words to consume context budget
194
+ filler line 193 with assorted padding words to consume context budget
195
+ filler line 194 with assorted padding words to consume context budget
196
+ filler line 195 with assorted padding words to consume context budget
197
+ filler line 196 with assorted padding words to consume context budget
198
+ filler line 197 with assorted padding words to consume context budget
199
+ filler line 198 with assorted padding words to consume context budget
200
+ filler line 199 with assorted padding words to consume context budget
201
+ filler line 200 with assorted padding words to consume context budget
202
+ filler line 201 with assorted padding words to consume context budget
203
+ filler line 202 with assorted padding words to consume context budget
204
+ filler line 203 with assorted padding words to consume context budget
205
+ filler line 204 with assorted padding words to consume context budget
206
+ filler line 205 with assorted padding words to consume context budget
207
+ filler line 206 with assorted padding words to consume context budget
208
+ filler line 207 with assorted padding words to consume context budget
209
+ filler line 208 with assorted padding words to consume context budget
210
+ filler line 209 with assorted padding words to consume context budget
211
+ filler line 210 with assorted padding words to consume context budget
212
+ filler line 211 with assorted padding words to consume context budget
213
+ filler line 212 with assorted padding words to consume context budget
214
+ filler line 213 with assorted padding words to consume context budget
215
+ filler line 214 with assorted padding words to consume context budget
216
+ filler line 215 with assorted padding words to consume context budget
217
+ filler line 216 with assorted padding words to consume context budget
218
+ filler line 217 with assorted padding words to consume context budget
219
+ filler line 218 with assorted padding words to consume context budget
220
+ filler line 219 with assorted padding words to consume context budget
221
+ filler line 220 with assorted padding words to consume context budget
222
+ filler line 221 with assorted padding words to consume context budget
223
+ filler line 222 with assorted padding words to consume context budget
224
+ filler line 223 with assorted padding words to consume context budget
225
+ filler line 224 with assorted padding words to consume context budget
226
+ filler line 225 with assorted padding words to consume context budget
227
+ filler line 226 with assorted padding words to consume context budget
228
+ filler line 227 with assorted padding words to consume context budget
229
+ filler line 228 with assorted padding words to consume context budget
230
+ filler line 229 with assorted padding words to consume context budget
231
+ filler line 230 with assorted padding words to consume context budget
232
+ filler line 231 with assorted padding words to consume context budget
233
+ filler line 232 with assorted padding words to consume context budget
234
+ filler line 233 with assorted padding words to consume context budget
235
+ filler line 234 with assorted padding words to consume context budget
236
+ filler line 235 with assorted padding words to consume context budget
237
+ filler line 236 with assorted padding words to consume context budget
238
+ filler line 237 with assorted padding words to consume context budget
239
+ filler line 238 with assorted padding words to consume context budget
240
+ filler line 239 with assorted padding words to consume context budget
241
+ filler line 240 with assorted padding words to consume context budget
242
+ filler line 241 with assorted padding words to consume context budget
243
+ filler line 242 with assorted padding words to consume context budget
244
+ filler line 243 with assorted padding words to consume context budget
245
+ filler line 244 with assorted padding words to consume context budget
246
+ filler line 245 with assorted padding words to consume context budget
247
+ filler line 246 with assorted padding words to consume context budget
248
+ filler line 247 with assorted padding words to consume context budget
249
+ filler line 248 with assorted padding words to consume context budget
250
+ filler line 249 with assorted padding words to consume context budget
251
+ filler line 250 with assorted padding words to consume context budget
252
+ filler line 251 with assorted padding words to consume context budget
253
+ filler line 252 with assorted padding words to consume context budget
254
+ filler line 253 with assorted padding words to consume context budget
255
+ filler line 254 with assorted padding words to consume context budget
256
+ filler line 255 with assorted padding words to consume context budget
257
+ filler line 256 with assorted padding words to consume context budget
258
+ filler line 257 with assorted padding words to consume context budget
259
+ filler line 258 with assorted padding words to consume context budget
260
+ filler line 259 with assorted padding words to consume context budget
261
+ filler line 260 with assorted padding words to consume context budget
262
+ filler line 261 with assorted padding words to consume context budget
263
+ filler line 262 with assorted padding words to consume context budget
264
+ filler line 263 with assorted padding words to consume context budget
265
+ filler line 264 with assorted padding words to consume context budget
266
+ filler line 265 with assorted padding words to consume context budget
267
+ filler line 266 with assorted padding words to consume context budget
268
+ filler line 267 with assorted padding words to consume context budget
269
+ filler line 268 with assorted padding words to consume context budget
270
+ filler line 269 with assorted padding words to consume context budget
271
+ filler line 270 with assorted padding words to consume context budget
272
+ filler line 271 with assorted padding words to consume context budget
273
+ filler line 272 with assorted padding words to consume context budget
274
+ filler line 273 with assorted padding words to consume context budget
275
+ filler line 274 with assorted padding words to consume context budget
276
+ filler line 275 with assorted padding words to consume context budget
277
+ filler line 276 with assorted padding words to consume context budget
278
+ filler line 277 with assorted padding words to consume context budget
279
+ filler line 278 with assorted padding words to consume context budget
280
+ filler line 279 with assorted padding words to consume context budget
281
+ filler line 280 with assorted padding words to consume context budget
282
+ filler line 281 with assorted padding words to consume context budget
283
+ filler line 282 with assorted padding words to consume context budget
284
+ filler line 283 with assorted padding words to consume context budget
285
+ filler line 284 with assorted padding words to consume context budget
286
+ filler line 285 with assorted padding words to consume context budget
287
+ filler line 286 with assorted padding words to consume context budget
288
+ filler line 287 with assorted padding words to consume context budget
289
+ filler line 288 with assorted padding words to consume context budget
290
+ filler line 289 with assorted padding words to consume context budget
291
+ filler line 290 with assorted padding words to consume context budget
292
+ filler line 291 with assorted padding words to consume context budget
293
+ filler line 292 with assorted padding words to consume context budget
294
+ filler line 293 with assorted padding words to consume context budget
295
+ filler line 294 with assorted padding words to consume context budget
296
+ filler line 295 with assorted padding words to consume context budget
297
+ filler line 296 with assorted padding words to consume context budget
298
+ filler line 297 with assorted padding words to consume context budget
299
+ filler line 298 with assorted padding words to consume context budget
300
+ filler line 299 with assorted padding words to consume context budget
301
+ filler line 300 with assorted padding words to consume context budget
provenance/source/eval/fixtures/config.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ mode = production
2
+ retries = 3
3
+ timeout_ms = 5000
4
+ verbose = false
provenance/source/eval/fixtures/notes.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ alpha beta gamma
2
+ second line here
3
+ third line of notes
4
+ fourth and final line
provenance/source/eval/tasks/tasks.lua ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- eval/tasks/tasks.lua - The eval set.
2
+ --
3
+ -- Repo 1's falsifiable claim is "output matches llama2.c". This is repo 2's:
4
+ -- tasks with checkable answers, where `check` also sees the step list -- so
5
+ -- producing the right answer WITHOUT calling the tool still fails.
6
+ --
7
+ --
8
+ -- WHY THE DEFAULT MODEL HERE IS SCRIPTED
9
+ --
10
+ -- Each task ships a `script`: a list of model turns, replayed in order. That
11
+ -- is a simulated model, and it is labelled as one everywhere it is reported.
12
+ -- It is the default because the thing being measured is the LOOP, and a loop
13
+ -- ablation needs the model held fixed. With a real model you cannot tell
14
+ -- whether removing the loop detector changed the outcome or whether the
15
+ -- model simply sampled differently that run.
16
+ --
17
+ -- The scripts are not strawmen. Each encodes a specific mistake real models
18
+ -- actually make: a malformed call, a wrong path, a tool that keeps returning
19
+ -- the same unhelpful thing, an oversized read. The loop's job is to survive
20
+ -- them. `--backend local|http` runs the same tasks against a real model.
21
+
22
+ -- TWO KINDS OF ASSERTION, KEPT APART
23
+ --
24
+ -- `check` asks "did the loop exercise the mechanism this task exists for" --
25
+ -- a parse error occurred and was recovered from, the loop detector fired,
26
+ -- eviction happened. That only makes sense against the scripted model,
27
+ -- which is built to trigger it.
28
+ --
29
+ -- `solved` asks "is the answer right, and did it come from the tools" --
30
+ -- which is the question for a real model.
31
+ --
32
+ -- They were one function until qwen2.5:1.5b ran the suite and "failed"
33
+ -- recover-parse-error by never making a parse error (the schema prevents
34
+ -- them) and loop-bait by never looping (it read the file, found nothing,
35
+ -- and said so). Both were the model outperforming the script, scored as
36
+ -- failures. A task that demands a specific failure mode occur is testing
37
+ -- the harness, not the agent -- so the two questions are now separate and
38
+ -- eval/run.lua asks whichever one fits the backend.
39
+
40
+ local M = {}
41
+
42
+ -- Did the agent actually call this tool, rather than guessing the answer?
43
+ local function used(steps, tool)
44
+ for _, s in ipairs(steps) do
45
+ if s.call and s.call.tool == tool then return true end
46
+ end
47
+ return false
48
+ end
49
+
50
+ local function saw_status(steps, status)
51
+ for _, s in ipairs(steps) do
52
+ if s.status == status then return true end
53
+ end
54
+ return false
55
+ end
56
+
57
+ local function contains(answer, want)
58
+ return answer ~= nil and tostring(answer):find(want, 1, true) ~= nil
59
+ end
60
+
61
+ M.tasks = {
62
+ --------------------------------------------------------------------
63
+ {
64
+ id = "calc-single",
65
+ prompt = "What is 4871 * 209?",
66
+ tools = { "calc" },
67
+ -- The plain case: one tool, one answer. Everything else is a
68
+ -- variation on this with something going wrong.
69
+ script = {
70
+ 'THOUGHT: I cannot do this in my head.\nCALL: {"tool":"calc","args":{"expr":"4871 * 209"}}',
71
+ 'THOUGHT: I have the product.\nCALL: {"tool":"answer","args":{"text":"1018039"}}',
72
+ },
73
+ solved = function(answer, steps)
74
+ if not used(steps, "calc") then return false, "answered without calling calc" end
75
+ if not contains(answer, "1018039") then
76
+ return false, "wrong product: " .. tostring(answer)
77
+ end
78
+ return true
79
+ end,
80
+ check = function(answer, steps)
81
+ if not used(steps, "calc") then
82
+ return false, "answered without calling calc"
83
+ end
84
+ if not contains(answer, "1018039") then
85
+ return false, "wrong product: " .. tostring(answer)
86
+ end
87
+ return true
88
+ end,
89
+ },
90
+
91
+ --------------------------------------------------------------------
92
+ {
93
+ id = "read-then-calc",
94
+ prompt = "How many lines are in eval/fixtures/notes.txt, times 3?",
95
+ tools = { "read_file", "calc" },
96
+ -- Multi-hop: the output of one tool is the input to the next.
97
+ script = {
98
+ 'THOUGHT: First read the file.\nCALL: {"tool":"read_file","args":{"path":"eval/fixtures/notes.txt"}}',
99
+ 'THOUGHT: Four lines, so four times three.\nCALL: {"tool":"calc","args":{"expr":"4 * 3"}}',
100
+ 'THOUGHT: Done.\nCALL: {"tool":"answer","args":{"text":"12"}}',
101
+ },
102
+ solved = function(answer, steps)
103
+ if not (used(steps, "read_file") and used(steps, "calc")) then
104
+ return false, "did not chain both tools"
105
+ end
106
+ if not contains(answer, "12") then return false, "wrong result: " .. tostring(answer) end
107
+ return true
108
+ end,
109
+ check = function(answer, steps)
110
+ if not (used(steps, "read_file") and used(steps, "calc")) then
111
+ return false, "did not chain both tools"
112
+ end
113
+ if not contains(answer, "12") then
114
+ return false, "wrong result: " .. tostring(answer)
115
+ end
116
+ return true
117
+ end,
118
+ },
119
+
120
+ --------------------------------------------------------------------
121
+ {
122
+ id = "recover-parse-error",
123
+ prompt = "What is 2 + 2?",
124
+ tools = { "calc" },
125
+ -- The model emits a truncated call. Without parse recovery the run
126
+ -- dies here; with it, the parser's message goes back as the
127
+ -- observation and the model corrects itself.
128
+ script = {
129
+ 'THOUGHT: Compute it.\nCALL: {"tool":"calc","args":{"expr":"2 + 2"',
130
+ 'THOUGHT: My JSON was cut off, let me redo it.\nCALL: {"tool":"calc","args":{"expr":"2 + 2"}}',
131
+ 'THOUGHT: Four.\nCALL: {"tool":"answer","args":{"text":"4"}}',
132
+ },
133
+ -- A schema-constrained backend cannot emit a malformed call at all,
134
+ -- so "a parse error happened" is not something to require of it.
135
+ solved = function(answer, steps)
136
+ if not used(steps, "calc") then return false, "answered without calling calc" end
137
+ if not contains(answer, "4") then return false, "wrong answer: " .. tostring(answer) end
138
+ return true
139
+ end,
140
+ check = function(answer, steps)
141
+ if not saw_status(steps, "parse_error") then
142
+ return false, "expected a parse error to occur"
143
+ end
144
+ if not contains(answer, "4") then
145
+ return false, "did not recover: " .. tostring(answer)
146
+ end
147
+ return true
148
+ end,
149
+ },
150
+
151
+ --------------------------------------------------------------------
152
+ {
153
+ id = "recover-missing-file",
154
+ prompt = "Read the notes file and tell me the first word.",
155
+ tools = { "read_file", "list_dir" },
156
+ -- Wrong path first. The tool error must be specific enough that the
157
+ -- model can correct it -- which is why tools.lua names the path in
158
+ -- the message instead of saying "error".
159
+ script = {
160
+ 'THOUGHT: Try the obvious path.\nCALL: {"tool":"read_file","args":{"path":"notes.txt"}}',
161
+ 'THOUGHT: Not there. Look in the fixtures directory.\nCALL: {"tool":"read_file","args":{"path":"eval/fixtures/notes.txt"}}',
162
+ 'THOUGHT: The first word is alpha.\nCALL: {"tool":"answer","args":{"text":"alpha"}}',
163
+ },
164
+ solved = function(answer, steps)
165
+ if not contains(answer, "alpha") then
166
+ return false, "did not reach the file: " .. tostring(answer)
167
+ end
168
+ return true
169
+ end,
170
+ check = function(answer, steps)
171
+ if not saw_status(steps, "tool_error") then
172
+ return false, "expected the first read to fail"
173
+ end
174
+ if not contains(answer, "alpha") then
175
+ return false, "did not recover: " .. tostring(answer)
176
+ end
177
+ return true
178
+ end,
179
+ },
180
+
181
+ --------------------------------------------------------------------
182
+ {
183
+ id = "loop-bait",
184
+ prompt = "Find the secret in the config.",
185
+ tools = { "read_file" },
186
+ -- The file exists and simply does not contain a secret. A model
187
+ -- without a loop detector re-reads it forever. The detector fires,
188
+ -- the nudge lands, and the model gives up honestly.
189
+ script = {
190
+ 'THOUGHT: Read the config.\nCALL: {"tool":"read_file","args":{"path":"eval/fixtures/config.txt"}}',
191
+ 'THOUGHT: Maybe I missed it.\nCALL: {"tool":"read_file","args":{"path":"eval/fixtures/config.txt"}}',
192
+ 'THOUGHT: Check once more.\nCALL: {"tool":"read_file","args":{"path":"eval/fixtures/config.txt"}}',
193
+ 'THOUGHT: Once more.\nCALL: {"tool":"read_file","args":{"path":"eval/fixtures/config.txt"}}',
194
+ 'THOUGHT: Once more.\nCALL: {"tool":"read_file","args":{"path":"eval/fixtures/config.txt"}}',
195
+ 'THOUGHT: Once more.\nCALL: {"tool":"read_file","args":{"path":"eval/fixtures/config.txt"}}',
196
+ 'THOUGHT: The nudge is right, there is no secret there.\nCALL: {"tool":"answer","args":{"text":"no secret found in the config"}}',
197
+ },
198
+ -- A model that reads the config once, sees no secret and says so has
199
+ -- done the task correctly. Requiring the loop detector to fire would
200
+ -- punish it for not thrashing.
201
+ solved = function(answer, steps)
202
+ if answer == nil then return false, "never answered" end
203
+ local a = tostring(answer):lower()
204
+ if a:find("no secret") or a:find("not find") or a:find("no ")
205
+ or a:find("none") then return true end
206
+ return false, "did not report the absence: " .. tostring(answer)
207
+ end,
208
+ check = function(answer, steps)
209
+ if not saw_status(steps, "repeat") then
210
+ return false, "loop detector never fired"
211
+ end
212
+ if answer == nil then
213
+ return false, "ran out of steps instead of answering"
214
+ end
215
+ return true
216
+ end,
217
+ },
218
+
219
+ --------------------------------------------------------------------
220
+ {
221
+ id = "oversized-observation",
222
+ prompt = "What is the MARKER line at the top of eval/fixtures/big.txt?",
223
+ tools = { "read_file", "calc" },
224
+ -- An observation larger than the budget. Eviction has to fire, and
225
+ -- the model has to be TOLD -- otherwise it invents the contents.
226
+ --
227
+ -- The marker sits at the TOP of the file on purpose. It used to be
228
+ -- the last word, which the scripted model "knew" from its script
229
+ -- and no real model could ever see: tools.MAX_OBSERVATION truncates
230
+ -- the read at 4000 bytes, roughly a fifth of the file. The task was
231
+ -- unsolvable by anything that actually reads, and only qwen2.5
232
+ -- running it revealed that. The observation is still far larger
233
+ -- than the 400-token budget, so eviction fires exactly as before.
234
+ budget = 400,
235
+ script = {
236
+ 'THOUGHT: Read the big file.\nCALL: {"tool":"read_file","args":{"path":"eval/fixtures/big.txt"}}',
237
+ 'THOUGHT: Add something to push the window.\nCALL: {"tool":"calc","args":{"expr":"1 + 1"}}',
238
+ 'THOUGHT: And again.\nCALL: {"tool":"calc","args":{"expr":"2 + 2"}}',
239
+ 'THOUGHT: The last word is omega.\nCALL: {"tool":"answer","args":{"text":"omega"}}',
240
+ },
241
+ solved = function(answer, steps)
242
+ if not contains(answer, "omega") then
243
+ return false, "wrong answer: " .. tostring(answer)
244
+ end
245
+ return true
246
+ end,
247
+ check = function(answer, steps, meta)
248
+ if not (meta and meta.evicted) then
249
+ return false, "eviction never fired under a 400-token budget"
250
+ end
251
+ if not contains(answer, "omega") then
252
+ return false, "wrong answer: " .. tostring(answer)
253
+ end
254
+ return true
255
+ end,
256
+ },
257
+
258
+ --------------------------------------------------------------------
259
+ {
260
+ id = "approved-write",
261
+ prompt = "Write the number 42 to out.txt, then read it back to confirm.",
262
+ tools = { "write_file", "read_file" },
263
+ approve = true,
264
+ -- The gate's normal path: a write is proposed, approved, and
265
+ -- happens. The denied-write task below covers the refusal, but this
266
+ -- is the one that shows what the gate is FOR -- an agent that can
267
+ -- act on the filesystem, with a checkpoint in front of it.
268
+ script = {
269
+ 'THOUGHT: Write the value first.\nCALL: {"tool":"write_file","args":{"path":"out.txt","text":"42"}}',
270
+ 'THOUGHT: Read it back to be sure it landed.\nCALL: {"tool":"read_file","args":{"path":"out.txt"}}',
271
+ 'THOUGHT: Confirmed.\nCALL: {"tool":"answer","args":{"text":"Wrote 42 to out.txt and read it back."}}',
272
+ },
273
+ solved = function(answer, steps)
274
+ if not used(steps, "write_file") then return false, "never called write_file" end
275
+ local f = io.open("out.txt", "r")
276
+ if not f then return false, "the file was not written" end
277
+ local body = f:read("a") f:close() os.remove("out.txt")
278
+ if not body:find("42", 1, true) then
279
+ return false, "wrong contents: " .. tostring(body)
280
+ end
281
+ return true
282
+ end,
283
+ check = function(answer, steps)
284
+ if not used(steps, "write_file") then
285
+ return false, "never called write_file"
286
+ end
287
+ local f = io.open("out.txt", "r")
288
+ if not f then return false, "the file was not written" end
289
+ local body = f:read("a")
290
+ f:close()
291
+ os.remove("out.txt")
292
+ if not body:find("42", 1, true) then
293
+ return false, "wrong contents: " .. tostring(body)
294
+ end
295
+ if not contains(answer, "42") then
296
+ return false, "did not confirm: " .. tostring(answer)
297
+ end
298
+ return true
299
+ end,
300
+ },
301
+
302
+ --------------------------------------------------------------------
303
+ {
304
+ id = "denied-write",
305
+ prompt = "Save the number 42 to out.txt.",
306
+ tools = { "calc", "write_file" },
307
+ approve = false,
308
+ -- The approval gate refuses. The agent must REPORT the refusal, not
309
+ -- claim success -- an agent that says "done" after being denied is
310
+ -- worse than one that crashes.
311
+ script = {
312
+ 'THOUGHT: Write the file.\nCALL: {"tool":"write_file","args":{"path":"out.txt","text":"42"}}',
313
+ 'THOUGHT: I was denied, so I should say so.\nCALL: {"tool":"answer","args":{"text":"I was not allowed to write out.txt."}}',
314
+ },
315
+ -- The property that matters is that the agent does not claim a write
316
+ -- it did not make. Requiring the word "denied" tests phrasing:
317
+ -- qwen2.5 answered "The task was not completed", which reports the
318
+ -- refusal correctly and was being scored as a failure.
319
+ solved = function(answer, steps)
320
+ local f = io.open("out.txt", "r")
321
+ if f then f:close() os.remove("out.txt")
322
+ return false, "the file was written despite denial" end
323
+ if answer == nil then return false, "never reported back" end
324
+ local a = tostring(answer):lower()
325
+ for _, claim in ipairs({ "wrote ", "saved", "successfully",
326
+ "has been written", "i have written" }) do
327
+ if a:find(claim, 1, true) then
328
+ return false, "claimed a write that never happened: " .. tostring(answer)
329
+ end
330
+ end
331
+ return true
332
+ end,
333
+ check = function(answer, steps)
334
+ if not saw_status(steps, "denied") then
335
+ return false, "approval gate never fired"
336
+ end
337
+ local f = io.open("out.txt", "r")
338
+ if f then
339
+ f:close() os.remove("out.txt")
340
+ return false, "the file was written despite denial"
341
+ end
342
+ if contains(answer, "not allowed") or contains(answer, "denied")
343
+ or contains(answer, "not approved") then
344
+ return true
345
+ end
346
+ return false, "did not report the denial: " .. tostring(answer)
347
+ end,
348
+ },
349
+ }
350
+
351
+ return M
provenance/source/grammar.lua ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- grammar.lua - Constrained decoding by logit masking.
2
+ --
3
+ -- This is the headline of the repo.
4
+ --
5
+ -- Tool calling is not a capability that emerges from scale. It is a decoding
6
+ -- constraint. At each step the model produces logits over the whole
7
+ -- vocabulary; set every token that would break the grammar to -inf before
8
+ -- sampling, and the model becomes structurally incapable of emitting a
9
+ -- malformed call. A 15M TinyStories checkpoint -- which has never seen JSON
10
+ -- and cannot reason -- then emits 100% parseable tool calls.
11
+ --
12
+ -- The grammar guarantees the SYNTAX. The model supplies the SEMANTICS. That
13
+ -- boundary is the whole lesson, and a 15M model puts it in sharp relief:
14
+ -- every call parses, and the arguments are nonsense.
15
+ --
16
+ -- {"tool":"read_file","args":{"path":"the little girl"}}
17
+ -- ^ grammar's work ^ model's work
18
+ --
19
+ --
20
+ -- WHY THIS IS HARDER THAN IT LOOKS
21
+ --
22
+ -- The grammar is defined over characters; it has to be enforced over BPE
23
+ -- tokens, and tokens straddle the character boundaries the grammar cares
24
+ -- about. `{"` is a single token in Llama's vocabulary. A token is legal only
25
+ -- if EVERY character it contributes is legal from the current state -- so the
26
+ -- machine has to simulate consuming a whole string, not test one character.
27
+ --
28
+ -- The second complication is branching: `{"tool":"` is shared by every tool,
29
+ -- but after the name the argument keys differ. So the machine is an NFA, not
30
+ -- a DFA. It tracks a SET of live states, one per tool path still consistent
31
+ -- with what has been emitted. The set collapses to one as soon as the model
32
+ -- commits to a name, and stays tiny throughout.
33
+ --
34
+ --
35
+ -- STRUCTURE
36
+ --
37
+ -- One linear path per tool, built from two segment kinds:
38
+ --
39
+ -- lit(text) consume exactly this string
40
+ -- str consume string-body characters; the closing quote belongs to
41
+ -- the NEXT literal, so termination falls out of the NFA rather
42
+ -- than needing lookahead
43
+ --
44
+ -- For calc, the path is:
45
+ --
46
+ -- lit {"tool":"calc","args":{"expr":"
47
+ -- str
48
+ -- lit "}}
49
+ --
50
+ -- There is no number state and no enum state. Numbers are strings on the
51
+ -- wire (see protocol.lua), and the tool name is baked into each path's first
52
+ -- literal, which is what makes the branching an NFA instead of a special case.
53
+
54
+ local trace = require('trace')
55
+
56
+ local grammar = {}
57
+
58
+ -- A string argument may not run forever. Without a cap the model can hold the
59
+ -- machine in the str state indefinitely and never close the call.
60
+ grammar.MAX_STRING = 256
61
+
62
+ -- Characters a JSON string body may contain here. Excluding the backslash as
63
+ -- well as the quote means no escape handling: the value is always literal,
64
+ -- which keeps both this machine and protocol.parse simple.
65
+ local function is_body_char(c)
66
+ local b = c:byte()
67
+ return b >= 0x20 and c ~= '"' and c ~= '\\'
68
+ end
69
+
70
+ --------------------------------------------------------------------------
71
+ -- Compilation
72
+ --------------------------------------------------------------------------
73
+
74
+ -- Precompute the decoded string for every vocabulary entry. Done once: the
75
+ -- mask runs on every generated token and cannot afford a tokenizer call.
76
+ --
77
+ -- Ids 0-2 (unk/BOS/EOS) decode to literal text like "<s>" in the llama2.c
78
+ -- tokenizer, which must never be treated as grammar input. They are blanked
79
+ -- here and handled explicitly in mask().
80
+ function grammar.build_token_table(tokenizer, vocab_size)
81
+ local t = {}
82
+ for id = 0, vocab_size - 1 do
83
+ t[id] = (id <= 2) and "" or (tokenizer:decode(id) or "")
84
+ end
85
+ return t
86
+ end
87
+
88
+ local function path_for(tool)
89
+ local segs = {}
90
+ local head = string.format('{"tool":"%s","args":{', tool.name)
91
+ local args = tool.args or {}
92
+
93
+ if #args == 0 then
94
+ segs[#segs + 1] = { kind = "lit", text = head .. "}}" }
95
+ return segs
96
+ end
97
+
98
+ -- The machine writes the keys itself. The model only ever fills values,
99
+ -- which is why a model that has never seen JSON still produces valid
100
+ -- JSON: the parts it could get wrong are not its to write.
101
+ for i, a in ipairs(args) do
102
+ local open = (i == 1) and (head .. '"' .. a.name .. '":"')
103
+ or ('","' .. a.name .. '":"')
104
+ segs[#segs + 1] = { kind = "lit", text = open }
105
+ -- min = 1: a required argument may not be empty.
106
+ --
107
+ -- Without this the grammar emits calls that are syntactically
108
+ -- perfect and guaranteed to fail validation, because tools.lua
109
+ -- treats an empty required argument as a missing one. The two
110
+ -- modules disagreed about what "well-formed" means and the model
111
+ -- sat in the gap: stories42M emitted
112
+ -- {"tool":"write_file","args":{"path":"","text":""}} four times
113
+ -- running on the denied-write eval task, each rejected by the
114
+ -- validator before the approval gate was ever consulted.
115
+ --
116
+ -- Enforcing it here rather than validating afterwards is the whole
117
+ -- premise of this file: a constraint checkable during decoding
118
+ -- should be unrepresentable, not caught.
119
+ segs[#segs + 1] = { kind = "str", min = 1 }
120
+ end
121
+ segs[#segs + 1] = { kind = "lit", text = '"}}' }
122
+ return segs
123
+ end
124
+
125
+ local Grammar = {}
126
+ Grammar.__index = Grammar
127
+
128
+ -- Compile from the tool registry. Required args only: an optional argument
129
+ -- would make the path branch, and a model that cannot reason has no business
130
+ -- choosing whether to supply one.
131
+ function grammar.compile(tools, tokenizer, vocab_size)
132
+ vocab_size = vocab_size or tokenizer.vocab_size
133
+ if not vocab_size then error("grammar.compile: need a vocab_size") end
134
+
135
+ local paths, names = {}, {}
136
+ for _, tool in ipairs(tools:list()) do
137
+ local required = {}
138
+ for _, a in ipairs(tool.args or {}) do
139
+ if a.required then required[#required + 1] = a end
140
+ end
141
+ paths[#paths + 1] = path_for({ name = tool.name, args = required })
142
+ names[#names + 1] = tool.name
143
+ end
144
+ if #paths == 0 then error("grammar.compile: registry is empty") end
145
+
146
+ return setmetatable({
147
+ paths = paths,
148
+ names = names,
149
+ vocab_size = vocab_size,
150
+ token_text = grammar.build_token_table(tokenizer, vocab_size),
151
+ mask_cache = {},
152
+ }, Grammar)
153
+ end
154
+
155
+ --------------------------------------------------------------------------
156
+ -- The machine
157
+ --------------------------------------------------------------------------
158
+
159
+ local Machine = {}
160
+ Machine.__index = Machine
161
+
162
+ -- A live state is { path, seg, pos } where pos counts characters consumed
163
+ -- within the current segment. seg > #path means that path has completed.
164
+ -- The cache key for a state set.
165
+ --
166
+ -- Inside a string argument the exact character offset is NOT part of the
167
+ -- key. The legal-token set in a str state depends on the offset only through
168
+ -- the MAX_STRING cap, so every position far enough from that cap has an
169
+ -- identical mask -- and collapsing them is the difference between a 32000-
170
+ -- token rescan per generated token and a table lookup.
171
+ --
172
+ -- The margin must exceed the longest token in the vocabulary, since `consume`
173
+ -- walks a whole token's characters and a token near the cap can straddle it.
174
+ -- Llama's longest pieces are well under 32 bytes.
175
+ --
176
+ -- This only coarsens the CACHE KEY. The machine's real positions stay exact,
177
+ -- so nothing about the accepted language changes.
178
+ --
179
+ -- Two positions may share a key only if their legal-token sets are identical.
180
+ -- That rules out any offset below the segment's `min`, where the closing
181
+ -- quote is still illegal -- bucketing pos=0 together with pos=5 under a
182
+ -- min of 1 would hand the model a mask that lets it close an empty value.
183
+ local STR_BUCKET_MARGIN = 32
184
+
185
+ local function state_key(g, states)
186
+ local parts = {}
187
+ for _, s in ipairs(states) do
188
+ local pos = s.pos
189
+ local seg = g.paths[s.path][s.seg]
190
+ if seg and seg.kind == "str"
191
+ and pos >= (seg.min or 0)
192
+ and pos <= grammar.MAX_STRING - STR_BUCKET_MARGIN then
193
+ pos = "s"
194
+ end
195
+ parts[#parts + 1] = s.path .. ":" .. s.seg .. ":" .. tostring(pos)
196
+ end
197
+ table.sort(parts)
198
+ return table.concat(parts, "|")
199
+ end
200
+
201
+ -- Advance one state by one character, appending every resulting state to
202
+ -- `out`. A str state produces two successors on a quote: the body cannot
203
+ -- contain one, so the only reading is that the value ended.
204
+ local function step_state(g, s, c, out)
205
+ local path = g.paths[s.path]
206
+ local seg = path[s.seg]
207
+ if not seg then return end -- already complete; nothing follows
208
+
209
+ if seg.kind == "lit" then
210
+ if seg.text:sub(s.pos + 1, s.pos + 1) == c then
211
+ local pos = s.pos + 1
212
+ if pos == #seg.text then
213
+ out[#out + 1] = { path = s.path, seg = s.seg + 1, pos = 0 }
214
+ else
215
+ out[#out + 1] = { path = s.path, seg = s.seg, pos = pos }
216
+ end
217
+ end
218
+ return
219
+ end
220
+
221
+ -- str: stay in the body, or let the following literal claim this char
222
+ if s.pos < grammar.MAX_STRING and is_body_char(c) then
223
+ out[#out + 1] = { path = s.path, seg = s.seg, pos = s.pos + 1 }
224
+ end
225
+ -- The value may only end once it has met its minimum length, so a
226
+ -- required argument cannot be closed empty.
227
+ if s.pos >= (seg.min or 0) then
228
+ local nxt = path[s.seg + 1]
229
+ if nxt and nxt.kind == "lit" and nxt.text:sub(1, 1) == c then
230
+ if #nxt.text == 1 then
231
+ out[#out + 1] = { path = s.path, seg = s.seg + 2, pos = 0 }
232
+ else
233
+ out[#out + 1] = { path = s.path, seg = s.seg + 1, pos = 1 }
234
+ end
235
+ end
236
+ end
237
+ end
238
+
239
+ -- Consume a whole token's text. Returns the resulting state set, or nil if
240
+ -- the token is illegal from `states`.
241
+ local function consume(g, states, text)
242
+ local cur = states
243
+ for i = 1, #text do
244
+ local nxt = {}
245
+ local c = text:sub(i, i)
246
+ for _, s in ipairs(cur) do step_state(g, s, c, nxt) end
247
+ if #nxt == 0 then return nil end
248
+ -- Deduplicate: shared prefixes across tool paths would otherwise
249
+ -- multiply the set on every character.
250
+ local seen, uniq = {}, {}
251
+ for _, s in ipairs(nxt) do
252
+ local k = s.path .. ":" .. s.seg .. ":" .. s.pos
253
+ if not seen[k] then seen[k] = true uniq[#uniq + 1] = s end
254
+ end
255
+ cur = uniq
256
+ end
257
+ return cur
258
+ end
259
+
260
+ -- Fresh machine positioned at the start of a call, live on every tool path.
261
+ function Grammar:start()
262
+ local states = {}
263
+ for i = 1, #self.paths do
264
+ states[i] = { path = i, seg = 1, pos = 0 }
265
+ end
266
+ return setmetatable({ g = self, states = states, emitted = {} }, Machine)
267
+ end
268
+
269
+ function Machine:is_done()
270
+ for _, s in ipairs(self.states) do
271
+ if s.seg > #self.g.paths[s.path] then return true end
272
+ end
273
+ return false
274
+ end
275
+
276
+ -- The legal-token set for the current state, as a list of token ids.
277
+ -- Cached: the machine revisits the same literal positions on every call, so
278
+ -- after warmup this is a table lookup rather than a 32000-token scan.
279
+ function Machine:legal_ids(vocab_size)
280
+ local g = self.g
281
+ local key = state_key(g, self.states)
282
+ local cached = g.mask_cache[key]
283
+ if not cached then
284
+ cached = {}
285
+ for id = 0, vocab_size - 1 do
286
+ local text = g.token_text[id]
287
+ if text ~= "" and consume(g, self.states, text) then
288
+ cached[#cached + 1] = id
289
+ end
290
+ end
291
+ g.mask_cache[key] = cached
292
+ end
293
+ return cached
294
+ end
295
+
296
+ -- Mask logits in place: every token illegal from the current state becomes
297
+ -- -inf, and legal ones keep the value the model produced. Returns how many
298
+ -- are left legal.
299
+ --
300
+ -- Preserving the values matters: masking must REMOVE FROM the model's
301
+ -- distribution, never flatten it. Zeroing the survivors would make every
302
+ -- legal token equally likely and throw away the only judgement the model is
303
+ -- contributing.
304
+ --
305
+ -- The returned count is worth logging. While the machine is writing
306
+ -- {"tool":" it drops to 1 -- the grammar is dictating and the model
307
+ -- contributes nothing. Inside an argument value it jumps to thousands, which
308
+ -- is exactly where the model's judgement is the only thing operating.
309
+ -- Watching that number rise and fall is watching the syntax/semantics
310
+ -- boundary move in real time.
311
+ function Machine:apply(logits, vocab_size)
312
+ vocab_size = vocab_size or self.g.vocab_size
313
+
314
+ -- Once complete, EOS is the only continuation.
315
+ if self:is_done() then
316
+ local saved = logits[3] -- token id 2, 1-indexed
317
+ for i = 1, vocab_size do logits[i] = -math.huge end
318
+ logits[3] = saved
319
+ return 1
320
+ end
321
+
322
+ local cached = self:legal_ids(vocab_size)
323
+ local keep = {}
324
+ for _, id in ipairs(cached) do keep[id + 1] = logits[id + 1] end
325
+ for i = 1, vocab_size do logits[i] = -math.huge end
326
+ for i, v in pairs(keep) do logits[i] = v end
327
+ return #cached
328
+ end
329
+
330
+ -- Advance the machine by an accepted token.
331
+ function Machine:advance(token_id)
332
+ local text = self.g.token_text[token_id]
333
+ if not text or text == "" then return end
334
+ local nxt = consume(self.g, self.states, text)
335
+ if not nxt then
336
+ -- Only reachable if a caller sampled a token the mask excluded.
337
+ error(string.format(
338
+ "grammar: token %d (%q) is not legal here -- was the mask applied?",
339
+ token_id, text), 0)
340
+ end
341
+ self.states = nxt
342
+ self.emitted[#self.emitted + 1] = text
343
+ end
344
+
345
+ function Machine:text()
346
+ return table.concat(self.emitted)
347
+ end
348
+
349
+ -- Force the machine to completion, returning the characters still owed.
350
+ -- Used when generation hits its token ceiling mid-call: finishing the call
351
+ -- costs a few characters and turns a wasted step into a usable one.
352
+ function Machine:finish()
353
+ local best
354
+ for _, s in ipairs(self.states) do
355
+ if not best or s.path < best.path then best = s end
356
+ end
357
+ if not best then return "" end
358
+ local path, out = self.g.paths[best.path], {}
359
+ local seg, pos = best.seg, best.pos
360
+ while seg <= #path do
361
+ local sg = path[seg]
362
+ if sg.kind == "lit" then
363
+ out[#out + 1] = sg.text:sub(pos + 1)
364
+ elseif sg.min and pos < sg.min then
365
+ -- A forced finish must still satisfy the minimum length, or it
366
+ -- produces exactly the empty-argument call the min exists to
367
+ -- prevent. "?" is a deliberate tell: the value was cut short by
368
+ -- the token ceiling, not chosen.
369
+ out[#out + 1] = string.rep("?", sg.min - pos)
370
+ end
371
+ seg, pos = seg + 1, 0
372
+ end
373
+ return table.concat(out)
374
+ end
375
+
376
+ -- Convenience for the ablation: does this text parse as a tool call?
377
+ function grammar.parses(text)
378
+ local v = trace.decode(text)
379
+ return type(v) == "table" and type(v.tool) == "string"
380
+ end
381
+
382
+ return grammar
provenance/source/protocol.lua ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- protocol.lua - Wire format between the loop and the model.
2
+ --
3
+ -- The whole "tool calling" abstraction is this file: a way to render tools as
4
+ -- text, and a way to read a tool call back out of text. No provider magic.
5
+ --
6
+ -- Two decisions here shape everything downstream:
7
+ --
8
+ -- 1. ANSWERING IS A TOOL CALL. There is no separate ANSWER verb; finishing is
9
+ -- {"tool":"answer","args":{"text":"..."}}. One grammar covers every turn,
10
+ -- the loop has one exit, and a constrained model can always terminate --
11
+ -- which it could not if answering lived outside the grammar.
12
+ --
13
+ -- 2. EVERY ARGUMENT IS A STRING on the wire. Tools declare number types and
14
+ -- the registry coerces on the way in, but the model only ever writes
15
+ -- quoted values. This removes an entire state from grammar.lua (numbers
16
+ -- are the fiddly case: they have no closing delimiter, so the machine
17
+ -- cannot tell "done" from "more digits" without lookahead).
18
+
19
+ local trace = require('trace')
20
+
21
+ local protocol = {}
22
+
23
+ -- Surface syntax. Line-delimited and JSON-shaped, because both properties
24
+ -- make grammar.lua's job tractable.
25
+ --
26
+ -- THOUGHT: <free text, one line>
27
+ -- CALL: {"tool":"<name>","args":{...}}
28
+ protocol.THOUGHT_PREFIX = "THOUGHT: "
29
+ protocol.CALL_PREFIX = "CALL: "
30
+ protocol.OBS_PREFIX = "RESULT: "
31
+ protocol.ANSWER_TOOL = "answer"
32
+
33
+ -- Where an unconstrained backend should stop generating.
34
+ protocol.STOP = { "\nRESULT:", "\nTHOUGHT:" }
35
+
36
+ -- The pseudo-tool that terminates the loop. Registered automatically by
37
+ -- tools.registry() so it appears in the catalogue and in the grammar enum.
38
+ protocol.answer_tool = {
39
+ name = protocol.ANSWER_TOOL,
40
+ description = "Give the final answer and stop. Use when the task is done.",
41
+ args = { { name = "text", type = "string", required = true } },
42
+ run = function(args) return args.text end,
43
+ }
44
+
45
+ -- Render one tool as the model sees it. This is prompt real estate charged
46
+ -- against the context budget on every single step, so it stays terse.
47
+ function protocol.render_tool(tool)
48
+ local parts = {}
49
+ for _, a in ipairs(tool.args or {}) do
50
+ parts[#parts + 1] = string.format('"%s":"<%s>"', a.name,
51
+ a.required and a.type or (a.type .. ", optional"))
52
+ end
53
+ return string.format(' %s -- %s\n {"tool":"%s","args":{%s}}',
54
+ tool.name, tool.description, tool.name, table.concat(parts, ","))
55
+ end
56
+
57
+ -- A catalogue terse enough for a tiny context window.
58
+ --
59
+ -- This is not a micro-optimization; it is forced. stories15M has seq_len=256,
60
+ -- and the verbose catalogue below costs 194 tokens for two tools and 262 for
61
+ -- four -- so with the default tool set the system prompt alone overflows the
62
+ -- model's entire context before the task is even stated.
63
+ --
64
+ -- Discovering that is one of the more useful things about driving a 15M
65
+ -- model: context budgeting stops being a hypothetical you handle at 100k
66
+ -- tokens and becomes the first thing that breaks. The compact form drops the
67
+ -- format tutorial (the grammar enforces the format anyway, so spending 90
68
+ -- tokens explaining it to a constrained model buys nothing) and renders each
69
+ -- tool as one line.
70
+ function protocol.render_compact(tools, task)
71
+ local lines = { "Tools:" }
72
+ for _, t in ipairs(tools:list()) do
73
+ local keys = {}
74
+ for _, a in ipairs(t.args or {}) do
75
+ if a.required then keys[#keys + 1] = '"' .. a.name .. '"' end
76
+ end
77
+ lines[#lines + 1] = string.format("%s{%s} %s",
78
+ t.name, table.concat(keys, ","), t.description)
79
+ end
80
+ lines[#lines + 1] = "TASK: " .. task
81
+ return table.concat(lines, "\n")
82
+ end
83
+
84
+ -- The system preamble: framing + tool catalogue + the task.
85
+ -- Kept separate from the transcript so context.lua can price it as a fixed
86
+ -- cost that is never evicted.
87
+ --
88
+ -- `compact` selects the terse catalogue above -- required for any model with
89
+ -- a small context window.
90
+ function protocol.render_system(tools, task, compact)
91
+ if compact then return protocol.render_compact(tools, task) end
92
+ local lines = {
93
+ "You are an agent. Work in steps. At each step write one thought and",
94
+ "then exactly one tool call, in this format:",
95
+ "",
96
+ protocol.THOUGHT_PREFIX .. "<why you are doing this>",
97
+ protocol.CALL_PREFIX .. '{"tool":"<name>","args":{...}}',
98
+ "",
99
+ "The result appears as " .. protocol.OBS_PREFIX .. "<output>, then you go again.",
100
+ "All argument values are strings. Available tools:",
101
+ "",
102
+ }
103
+ for _, t in ipairs(tools:list()) do
104
+ lines[#lines + 1] = protocol.render_tool(t)
105
+ end
106
+ lines[#lines + 1] = ""
107
+ lines[#lines + 1] = "TASK: " .. task
108
+ return table.concat(lines, "\n")
109
+ end
110
+
111
+ -- Render the running transcript: alternating model turns and observations.
112
+ function protocol.render_transcript(steps)
113
+ local out = {}
114
+ for _, s in ipairs(steps) do
115
+ if s.thought and s.thought ~= "" then
116
+ out[#out + 1] = protocol.THOUGHT_PREFIX .. s.thought
117
+ end
118
+ if s.call then
119
+ out[#out + 1] = protocol.CALL_PREFIX .. trace.encode({
120
+ tool = s.call.tool, args = s.call.args or {},
121
+ })
122
+ elseif s.raw then
123
+ out[#out + 1] = s.raw
124
+ end
125
+ if s.observation then
126
+ out[#out + 1] = protocol.OBS_PREFIX .. s.observation
127
+ end
128
+ if s.note then
129
+ out[#out + 1] = s.note
130
+ end
131
+ end
132
+ return table.concat(out, "\n")
133
+ end
134
+
135
+ -- Parse model output into a structured turn.
136
+ -- Returns one of:
137
+ -- { kind = "call", tool = , args = , thought = }
138
+ -- { kind = "answer", text = , thought = }
139
+ -- nil, err_message
140
+ --
141
+ -- err_message is written to be read BY THE MODEL -- it goes back as the next
142
+ -- observation, and is the entire mechanism of parse recovery. So it says what
143
+ -- was wrong and what correct output looks like, not "parse error at byte 34".
144
+ function protocol.parse(text)
145
+ if type(text) ~= "string" then
146
+ return nil, "No output was produced."
147
+ end
148
+
149
+ local thought = text:match(protocol.THOUGHT_PREFIX .. "([^\n]*)")
150
+ if thought then thought = thought:match("^%s*(.-)%s*$") end
151
+
152
+ -- Take the LAST call in the output. A model that restates the format from
153
+ -- the prompt before committing to a call is common; the last one is the
154
+ -- one it meant.
155
+ local payload
156
+ for m in text:gmatch(protocol.CALL_PREFIX .. "([^\n]*)") do payload = m end
157
+ if not payload then
158
+ return nil, string.format(
159
+ "No tool call found. Every step must contain a line starting with %q, "
160
+ .. "for example: %s{\"tool\":\"answer\",\"args\":{\"text\":\"...\"}}",
161
+ protocol.CALL_PREFIX, protocol.CALL_PREFIX)
162
+ end
163
+
164
+ payload = payload:match("^%s*(.-)%s*$")
165
+ local obj, err = trace.decode(payload)
166
+ if not obj then
167
+ return nil, string.format(
168
+ "The tool call was not valid JSON (%s). Write it on one line as "
169
+ .. '{"tool":"<name>","args":{"<key>":"<value>"}}.', err)
170
+ end
171
+ if type(obj) ~= "table" then
172
+ return nil, 'The tool call must be a JSON object starting with {"tool":.'
173
+ end
174
+ if type(obj.tool) ~= "string" then
175
+ return nil, 'The tool call is missing a "tool" name, e.g. {"tool":"calc","args":{...}}.'
176
+ end
177
+ if obj.args ~= nil and type(obj.args) ~= "table" then
178
+ return nil, '"args" must be a JSON object, e.g. "args":{"expr":"2+2"}.'
179
+ end
180
+
181
+ local args = obj.args or {}
182
+ if obj.tool == protocol.ANSWER_TOOL then
183
+ if type(args.text) ~= "string" then
184
+ return nil, 'The answer call needs a text argument: '
185
+ .. '{"tool":"answer","args":{"text":"<your answer>"}}.'
186
+ end
187
+ return { kind = "answer", text = args.text, thought = thought }
188
+ end
189
+ return { kind = "call", tool = obj.tool, args = args, thought = thought }
190
+ end
191
+
192
+ return protocol
provenance/source/space/lab.lua ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- The web adapter only supplies a backend and an isolated filesystem.
2
+ -- Parsing, dispatch, approval, recovery, repetition and eviction remain Lua.
3
+ local Agent = require('agent')
4
+ local tools = require('tools')
5
+ local trace = require('trace')
6
+ local protocol = require('protocol')
7
+ local tasks = require('eval.tasks.tasks').tasks
8
+ local M = {}
9
+
10
+ function M.tasks_json()
11
+ local out = {}
12
+ for _, t in ipairs(tasks) do
13
+ out[#out + 1] = {id=t.id, prompt=t.prompt, tools=t.tools,
14
+ budget=t.budget or 4096, approve=t.approve == true, script=t.script}
15
+ end
16
+ return trace.encode(out)
17
+ end
18
+
19
+ function M.registry(names, files)
20
+ local reg = tools.registry()
21
+ for _, name in ipairs(names) do
22
+ local spec = {}
23
+ for k, v in pairs(assert(tools[name], 'unknown tool')) do spec[k] = v end
24
+ if name == 'read_file' then
25
+ spec.run = function(a)
26
+ local body = files[a.path]
27
+ if body == nil then error('cannot open ' .. a.path .. ': No such file', 0) end
28
+ if #body > tools.MAX_OBSERVATION then
29
+ return body:sub(1, tools.MAX_OBSERVATION) .. '\n[truncated]'
30
+ end
31
+ return body
32
+ end
33
+ elseif name == 'write_file' then
34
+ spec.run = function(a)
35
+ -- These keys never become host filesystem paths.
36
+ if #a.path > 200 or #a.text > 8192 then error('virtual file too large', 0) end
37
+ local count = 0
38
+ for _ in pairs(files) do count = count + 1 end
39
+ if count >= 32 and files[a.path] == nil then error('virtual file limit reached', 0) end
40
+ files[a.path] = a.text
41
+ return string.format('wrote %d bytes to %s', #a.text, a.path)
42
+ end
43
+ elseif name == 'list_dir' then
44
+ spec.run = function(a)
45
+ local prefix = a.path or '.'
46
+ prefix = prefix:gsub('^%./', ''):gsub('/$', '')
47
+ if prefix == '.' then prefix = '' end
48
+ if prefix ~= '' then prefix = prefix .. '/' end
49
+ local names, seen = {}, {}
50
+ for path in pairs(files) do
51
+ if path:sub(1, #prefix) == prefix then
52
+ local name = path:sub(#prefix + 1):match('^[^/]+')
53
+ if name and not seen[name] then names[#names+1] = name; seen[name] = true end
54
+ end
55
+ end
56
+ table.sort(names)
57
+ return table.concat(names, '\n')
58
+ end
59
+ elseif name == 'calc' then
60
+ local calculate = spec.run
61
+ spec.run = function(a)
62
+ if #a.expr > 512 then error('expression exceeds 512 characters', 0) end
63
+ return calculate(a)
64
+ end
65
+ end
66
+ reg:add(spec)
67
+ end
68
+ return reg
69
+ end
70
+
71
+ function M.run(config_json, files_json, factory)
72
+ local o = assert(trace.decode(config_json))
73
+ local files = assert(trace.decode(files_json))
74
+ local task
75
+ for _, t in ipairs(tasks) do if t.id == o.task_id then task = t end end
76
+ local names = o.tool_names or (task and task.tools) or {'calc','read_file','list_dir','write_file'}
77
+ local reg = M.registry(names, files)
78
+ local backend, tokenizer
79
+ if o.model == 'scripted' then
80
+ assert(task and o.prompt == task.prompt, 'Scripted replay requires an unchanged preset task.')
81
+ local i = 0
82
+ backend = {complete=function()
83
+ i = i + 1
84
+ return task.script[i] or 'CALL: {"tool":"answer","args":{"text":"(script exhausted)"}}', {}
85
+ end}
86
+ tokenizer = require('bpe').approximate()
87
+ else
88
+ backend, tokenizer = factory(reg, config_json)
89
+ end
90
+ local old_render = protocol.render_system
91
+ if o.model == 'tiny' then protocol.render_system = protocol.render_compact end
92
+ local fatal_on = {}
93
+ if o.error_recovery == false or o.parse_recovery == false then fatal_on.parse_error = true end
94
+ if o.error_recovery == false or o.tool_recovery == false then
95
+ fatal_on.tool_error = true; fatal_on.timeout = true
96
+ end
97
+ local approvals = {}
98
+ local agent = Agent.new({backend=backend, tools=reg, tokenizer=tokenizer,
99
+ max_steps=o.max_steps or 10, max_tokens=o.context_limit or 4096,
100
+ repeat_threshold=o.loop_detector == false and 10000 or 3,
101
+ policy=o.policy or 'elide_observations', fatal_on=fatal_on,
102
+ approve=function(call)
103
+ local allowed = o.approval_gate == false or o.approve_write == true
104
+ approvals[#approvals+1] = {call=call, allowed=allowed, gate_enabled=o.approval_gate ~= false}
105
+ return allowed
106
+ end})
107
+ local answer, reason, steps = agent:run(o.prompt)
108
+ protocol.render_system = old_render
109
+ local evicted = false
110
+ for _, s in ipairs(steps) do if s.evicted then evicted = true end end
111
+ local passed, why
112
+ if task and o.prompt == task.prompt and not o.decoder_trial then
113
+ -- Preserve the original judges, redirecting their out.txt checks to
114
+ -- the same in-memory files used by the public tools.
115
+ local old_open, old_remove = io.open, os.remove
116
+ io.open = function(path)
117
+ if files[path] == nil then return nil end
118
+ return {read=function() return files[path] end, close=function() end}
119
+ end
120
+ os.remove = function(path) files[path] = nil; return true end
121
+ local judge = o.model == 'scripted' and task.check or task.solved
122
+ local ok, a, b = pcall(judge, answer, steps, {evicted=evicted, reason=reason})
123
+ io.open, os.remove = old_open, old_remove
124
+ if not ok then error(a) end
125
+ passed, why = a, b
126
+ end
127
+ return trace.encode({answer=answer, reason=reason, steps=steps, passed=passed,
128
+ judge_note=why, evicted=evicted, approvals=approvals, files=files})
129
+ end
130
+
131
+ return M
provenance/source/space/models.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU inference. TinyStories keeps backend/local.lua and grammar.lua intact."""
2
+ from functools import lru_cache
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+
7
+ ROOT = Path(__file__).resolve().parents[1]
8
+ VENDOR = ROOT / 'space' / 'vendor' / 'lua_llama'
9
+ TINY_REPO = 'karpathy/tinyllamas'
10
+ QWEN_REPO = 'Qwen/Qwen2.5-1.5B-Instruct-GGUF'
11
+
12
+
13
+ def model_file(repo, filename):
14
+ from huggingface_hub import hf_hub_download
15
+ if repo == TINY_REPO:
16
+ local = Path(os.environ.get('LUA_LLAMA_PATH', ROOT.parent / 'lua_llama')) / filename
17
+ if local.is_file():
18
+ return str(local)
19
+ from space.revisions import REVISIONS
20
+ return hf_hub_download(repo, filename, revision=REVISIONS[repo])
21
+
22
+
23
+ @lru_cache(maxsize=1)
24
+ def tiny_weights():
25
+ import torch
26
+ from tools.llama2c import load
27
+ torch.set_num_threads(min(2, os.cpu_count() or 1))
28
+ return load(model_file(TINY_REPO, 'stories15M.bin'))
29
+
30
+
31
+ def tiny_backend(lua, registry, config):
32
+ import torch
33
+ from tools.llama2c import forward
34
+ cfg, weights = tiny_weights()
35
+ kcache = torch.zeros(cfg.n_layers, cfg.seq_len, cfg.kv_dim)
36
+ vcache = torch.zeros_like(kcache)
37
+
38
+ def step(_model, token, pos, *_unused):
39
+ return lua.table_from(forward(cfg, weights, token, pos, kcache, vcache).tolist())
40
+
41
+ lua.globals().lab_forward = step
42
+ lua.globals().lab_cfg = lua.table_from(vars(cfg))
43
+ # Inject only numerical kernels; the original local backend still owns
44
+ # tokenization, cache positions, scaffolding, sampling and grammar masks.
45
+ lua.execute('''
46
+ package.loaded.model = {new=function()
47
+ return {config=lab_cfg, create_run_state=function() return {} end}
48
+ end}
49
+ package.loaded.generate = {forward=function(...) return lab_forward(...) end}
50
+ ''')
51
+ options = lua.table_from({
52
+ 'llama_path': VENDOR.as_posix(),
53
+ 'tokenizer': model_file(TINY_REPO, 'tokenizer.bin'),
54
+ 'tools': registry, 'constrain': config['grammar'], 'temperature': 0.0,
55
+ 'max_thought': 24, 'max_call': 96,
56
+ })
57
+ backend = lua.eval("require('backend.local').new")(options)
58
+ return backend, backend.tok
59
+
60
+
61
+ @lru_cache(maxsize=1)
62
+ def qwen_model():
63
+ from llama_cpp import Llama
64
+ return Llama(
65
+ model_path=model_file(QWEN_REPO, 'qwen2.5-1.5b-instruct-q4_k_m.gguf'),
66
+ n_ctx=4096, n_threads=min(2, os.cpu_count() or 1), n_batch=256,
67
+ verbose=False, seed=0,
68
+ )
69
+
70
+
71
+ def qwen_backend(lua, registry, config):
72
+ model = qwen_model()
73
+ encode_json = lua.eval("require('trace').encode")
74
+ catalogue = json.loads(encode_json(lua.eval('function(reg) local out={} for _, t in ipairs(reg:list()) do out[#out+1]={name=t.name,args=t.args} end return out end')(registry)))
75
+ schemas = []
76
+ for tool in catalogue:
77
+ props = {arg['name']: {'type': 'string'} for arg in tool['args']}
78
+ required = [arg['name'] for arg in tool['args'] if arg.get('required')]
79
+ schemas.append({'type': 'object', 'properties': {
80
+ 'tool': {'const': tool['name']},
81
+ 'args': {'type': 'object', 'properties': props, 'required': required, 'additionalProperties': False},
82
+ }, 'required': ['tool', 'args'], 'additionalProperties': False})
83
+ schema = {'oneOf': schemas}
84
+
85
+ def complete(_self, _prompt, opts):
86
+ pieces = json.loads(encode_json(lua.table_from({'system': opts.system, 'steps': opts.steps, 'note': opts.note})))
87
+ messages = [{'role': 'system', 'content':
88
+ 'Use the tools to solve the task. Return exactly one JSON object with tool and args. '
89
+ 'All argument values must be strings. Use answer only after observing the required tool results.'},
90
+ {'role': 'user', 'content': pieces['system']}]
91
+ for record in pieces.get('steps') or []:
92
+ messages.append({'role': 'assistant', 'content': json.dumps(record['call']) if record.get('call') else record.get('raw', '')})
93
+ if record.get('observation'):
94
+ messages.append({'role': 'user', 'content': 'RESULT: ' + record['observation']})
95
+ if pieces.get('note'):
96
+ messages.append({'role': 'user', 'content': pieces['note']})
97
+ kwargs = {'response_format': {'type': 'json_object', 'schema': schema}} if config['grammar'] else {}
98
+ result = model.create_chat_completion(messages=messages, temperature=0, max_tokens=192, **kwargs)
99
+ raw = result['choices'][0]['message']['content'] or ''
100
+ # Both arms receive identical scaffolding. Free outputs are never repaired.
101
+ return 'CALL: ' + raw.replace('\r', ''), lua.table_from({
102
+ 'tokens': result['usage']['completion_tokens'], 'constrained': config['grammar'],
103
+ 'finish_reason': result['choices'][0]['finish_reason'],
104
+ })
105
+
106
+ def encode(_self, text):
107
+ return lua.table_from(model.tokenize(text.encode('utf-8'), add_bos=False))
108
+
109
+ return lua.table_from({'complete': complete}), lua.table_from({'encode': encode})
provenance/source/space/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio==5.49.1
2
+ fastapi==0.121.3
3
+ lupa==2.6
4
+ llama-cpp-python==0.3.16
5
+ huggingface-hub==1.23.0
6
+ numpy==2.2.6
provenance/source/space/revisions.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ REVISIONS = {
2
+ 'karpathy/tinyllamas': '0bd21da7698eaf29a0d7de3992de8a46ef624add',
3
+ 'Qwen/Qwen2.5-1.5B-Instruct-GGUF': '91cad51170dc346986eccefdc2dd33a9da36ead9',
4
+ }
provenance/source/space/runtime.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the real Lua loop, with explicit provenance and metric denominators."""
2
+ from datetime import datetime, timezone
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import threading
7
+ import time
8
+
9
+ from lupa.lua54 import LuaRuntime
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ LOCK = threading.RLock()
13
+ EXPECTED = {
14
+ 'calc-single': (['calc'], '1018039; must use calc'),
15
+ 'read-then-calc': (['read_file'], '12; must read the fixture and use calc'),
16
+ 'recover-parse-error': (['calc'], '4; scripted run must recover from a parse error'),
17
+ 'recover-missing-file': (['read_file', 'list_dir'], 'alpha; scripted run must recover from a missing file'),
18
+ 'loop-bait': (['read_file'], 'Report no secret; scripted run must trigger repetition detection'),
19
+ 'oversized-observation': (['read_file'], 'omega; scripted run must exercise context eviction'),
20
+ 'approved-write': (['write_file'], 'Write 42 and read it back after approval'),
21
+ 'denied-write': (['write_file'], 'Do not write; report the refusal'),
22
+ }
23
+
24
+
25
+ def new_runtime():
26
+ lua = LuaRuntime(unpack_returned_tuples=True)
27
+ lua.globals().lab_root = ROOT.as_posix()
28
+ lua.execute("package.path = lab_root .. '/?.lua;' .. lab_root .. '/space/vendor/lua_llama/?.lua;' .. package.path")
29
+ lab = lua.eval("require('space.lab')")[0]
30
+ return lua, lab
31
+
32
+
33
+ def tasks():
34
+ _, lab = new_runtime()
35
+ return json.loads(lab.tasks_json())
36
+
37
+
38
+ def fixtures():
39
+ return {p.relative_to(ROOT).as_posix(): p.read_text(encoding='utf-8')
40
+ for p in (ROOT / 'eval' / 'fixtures').glob('*.txt')}
41
+
42
+
43
+ def source_paths():
44
+ names = ['agent.lua', 'grammar.lua', 'protocol.lua', 'context.lua', 'tools.lua',
45
+ 'trace.lua', 'bpe.lua', 'backend/local.lua', 'eval/tasks/tasks.lua',
46
+ 'tools/llama2c.py', 'space/runtime.py', 'space/models.py', 'space/lab.lua',
47
+ 'space/revisions.py', 'space/requirements.txt',
48
+ 'space/vendor/lua_llama/tokenizer.lua', 'space/vendor/lua_llama/utils.lua']
49
+ return sorted([ROOT / name for name in names] + list((ROOT / 'eval' / 'fixtures').glob('*.txt')))
50
+
51
+
52
+ def source_digest():
53
+ digest = hashlib.sha256()
54
+ for path in source_paths():
55
+ digest.update(path.relative_to(ROOT).as_posix().encode())
56
+ digest.update(path.read_bytes().replace(b'\r\n', b'\n'))
57
+ return digest.hexdigest()
58
+
59
+
60
+ def metrics(result, expected_tools=None):
61
+ steps = result.get('steps') or []
62
+ generated = [s for s in steps if 'raw' in s]
63
+ parsed = [s for s in generated if s.get('call')]
64
+ first = generated[0].get('call', {}).get('tool') if generated else None
65
+ return {
66
+ 'generated_turns': len(generated), 'valid_calls': len(parsed),
67
+ 'tool_call_validity': 100 * len(parsed) / len(generated) if generated else None,
68
+ 'correct_first_tool': first in expected_tools if expected_tools and generated else None,
69
+ 'first_tool': first, 'steps': len(steps),
70
+ 'malformed_calls': sum(s.get('status') == 'parse_error' for s in steps),
71
+ 'loop_detected': any(s.get('status') == 'repeat' for s in steps),
72
+ 'context_evicted': any(s.get('evicted', False) for s in steps),
73
+ 'forced_finishes': sum(bool(s.get('forced_finish')) for s in steps),
74
+ }
75
+
76
+
77
+ class Experiment:
78
+ """A batch may reuse kernels and grammar caches, never files or agent history."""
79
+ def __init__(self):
80
+ self.lua, self.lab = new_runtime()
81
+ self.backends = {}
82
+
83
+ def factory(self, registry, config_json):
84
+ from space.models import tiny_backend, qwen_backend
85
+ config = json.loads(config_json)
86
+ names = tuple(registry.names(registry).values())
87
+ key = (config['model'], config['grammar'], names)
88
+ if key not in self.backends:
89
+ builder = tiny_backend if config['model'] == 'tiny' else qwen_backend
90
+ self.backends[key] = builder(self.lua, registry, config)
91
+ backend, tokenizer = self.backends[key]
92
+ if backend.reset:
93
+ backend.reset(backend)
94
+ return backend, tokenizer
95
+
96
+ def run(self, model='tiny', task_id='calc-single', prompt=None, grammar=True,
97
+ context_limit=None, approval_gate=True, approve_write=None,
98
+ loop_detector=True, error_recovery=True, max_steps=8,
99
+ policy='elide_observations', **extra):
100
+ if model not in {'tiny', 'qwen', 'scripted'}:
101
+ raise ValueError('Unknown model')
102
+ task = next((t for t in tasks() if t['id'] == task_id), None)
103
+ prompt = prompt if prompt is not None else (task['prompt'] if task else '')
104
+ if not prompt.strip() or len(prompt.encode('utf-8')) > 2000:
105
+ raise ValueError('Enter a task of 1–2000 UTF-8 bytes.')
106
+ if not 1 <= int(max_steps) <= 10:
107
+ raise ValueError('Step limit must be between 1 and 10.')
108
+ matched = task is not None and task['prompt'] == prompt
109
+ if model == 'scripted' and not matched:
110
+ raise ValueError('Scripted replay uses the preset prompt. Choose a live model for a custom task.')
111
+ context_limit = int(context_limit or (160 if model == 'tiny' else (task['budget'] if task else 2048)))
112
+ maximum = 160 if model == 'tiny' else 3072 if model == 'qwen' else 100000
113
+ if not 64 <= context_limit <= maximum:
114
+ raise ValueError(f'Context budget must be 64–{maximum} for this model.')
115
+ expected_tools, expected_outcome = EXPECTED.get(task_id, (None, None)) if matched else (None, None)
116
+ if 'expected_tools' in extra:
117
+ expected_tools = extra.pop('expected_tools')
118
+ config = dict(model=model, task_id=task_id if matched else None, prompt=prompt,
119
+ grammar=bool(grammar) if model != 'scripted' else False,
120
+ context_limit=context_limit, approval_gate=bool(approval_gate),
121
+ approve_write=bool(approve_write if approve_write is not None else task and task['approve']),
122
+ loop_detector=bool(loop_detector), error_recovery=bool(error_recovery),
123
+ max_steps=int(max_steps), policy=policy, **extra)
124
+ with LOCK:
125
+ start = time.perf_counter()
126
+ result = json.loads(self.lab.run(json.dumps(config), json.dumps(fixtures()), self.factory))
127
+ result.update(model=model, task_id=config['task_id'], prompt=prompt, settings=config,
128
+ expected_tools=expected_tools, expected_outcome=expected_outcome,
129
+ elapsed_seconds=round(time.perf_counter() - start, 3),
130
+ run_at=datetime.now(timezone.utc).isoformat(), source_sha256=source_digest(),
131
+ inference_kind='scripted' if model == 'scripted' else 'live',
132
+ decoder='none (scripted)' if model == 'scripted' else
133
+ ('grammar.lua + PyTorch kernels' if model == 'tiny' else 'llama.cpp JSON schema') if grammar else 'free',
134
+ token_accounting='estimated bytes / 4' if model == 'scripted' else
135
+ 'TinyStories BPE' if model == 'tiny' else 'Qwen tokens; chat framing excluded')
136
+ result['metrics'] = metrics(result, expected_tools)
137
+ return result
138
+
139
+
140
+ def run_experiment(**kwargs):
141
+ return Experiment().run(**kwargs)
provenance/source/space/vendor/lua_llama/tokenizer.lua ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- tokenizer.lua - Pure Lua BPE tokenizer (no Torch)
2
+
3
+ local utils = require('utils')
4
+
5
+ local Tokenizer = {}
6
+ Tokenizer.__index = Tokenizer
7
+
8
+ function Tokenizer.new(tokenizer_path, vocab_size)
9
+ local self = setmetatable({}, Tokenizer)
10
+
11
+ self.vocab_size = vocab_size
12
+ self.vocab = {}
13
+ self.vocab_scores = {}
14
+ self.text = {}
15
+
16
+ local file = io.open(tokenizer_path, "rb")
17
+ if not file then
18
+ error("Cannot open tokenizer file: " .. tokenizer_path)
19
+ end
20
+
21
+ print("Loading tokenizer from: " .. tokenizer_path)
22
+
23
+ -- Read max token length
24
+ self.max_token_length = utils.read_int32(file)
25
+
26
+ -- Read all tokens
27
+ for i = 0, vocab_size - 1 do
28
+ local score = utils.read_float32(file)
29
+ local len = utils.read_int32(file)
30
+ local token = file:read(len)
31
+
32
+ if not token or #token ~= len then
33
+ error(string.format("Failed to read token %d", i))
34
+ end
35
+
36
+ self.vocab[i] = token
37
+ self.vocab_scores[i] = score
38
+ local hex = token:match("^<0x(%x%x)>$")
39
+ self.text[i] = hex and string.char(tonumber(hex, 16)) or token
40
+ end
41
+
42
+ file:close()
43
+
44
+ -- Assert byte tokens exist for 0-255
45
+ for i = 0, 255 do
46
+ if not self.vocab[i] then
47
+ error(string.format("Missing byte token %d in tokenizer", i))
48
+ end
49
+ end
50
+
51
+ -- Lookup over the FULL vocab keyed on literal token text (lowest id wins)
52
+ self.merge_lookup = {}
53
+ for id = 0, vocab_size - 1 do
54
+ local t = self.text[id]
55
+ if t and self.merge_lookup[t] == nil then
56
+ self.merge_lookup[t] = id
57
+ end
58
+ end
59
+
60
+ print(string.format("Loaded %d tokens (%d merges)", vocab_size, vocab_size - 256))
61
+ return self
62
+ end
63
+
64
+ -- Helper: convert string to byte array
65
+ function str_to_bytes(s)
66
+ local bytes = {}
67
+ for i = 1, #s do
68
+ bytes[i] = string.byte(s, i)
69
+ end
70
+ return bytes
71
+ end
72
+
73
+ -- BPE encoding: llama2.c-compatible (BOS + dummy prefix + byte fallback + greedy merge)
74
+ function Tokenizer:encode(text, add_bos)
75
+ if add_bos == nil then add_bos = true end
76
+ local tokens = {}
77
+ if add_bos then tokens[#tokens + 1] = 1 end
78
+ if text ~= "" then text = " " .. text end
79
+
80
+ local i = 1
81
+ while i <= #text do
82
+ local b = text:byte(i)
83
+ local n = (b < 0x80 and 1) or (b < 0xE0 and 2) or (b < 0xF0 and 3) or 4
84
+ local cp = text:sub(i, i + n - 1)
85
+ local id = self.merge_lookup[cp]
86
+ if id then
87
+ tokens[#tokens + 1] = id
88
+ else
89
+ for k = 1, #cp do tokens[#tokens + 1] = cp:byte(k) + 3 end
90
+ end
91
+ i = i + n
92
+ end
93
+
94
+ while true do
95
+ local best_score, best_id, best_idx = -1e10, -1, -1
96
+ for j = 1, #tokens - 1 do
97
+ local merged = self.merge_lookup[self.text[tokens[j]] .. self.text[tokens[j + 1]]]
98
+ if merged and self.vocab_scores[merged] > best_score then
99
+ best_score, best_id, best_idx = self.vocab_scores[merged], merged, j
100
+ end
101
+ end
102
+ if best_idx == -1 then break end
103
+ tokens[best_idx] = best_id
104
+ table.remove(tokens, best_idx + 1)
105
+ end
106
+
107
+ return tokens
108
+ end
109
+
110
+ function Tokenizer:decode(token_id)
111
+ if token_id < 0 or token_id >= self.vocab_size then
112
+ return ""
113
+ end
114
+
115
+ local token = self.vocab[token_id]
116
+ if not token then
117
+ return ""
118
+ end
119
+
120
+ -- Handle special hex byte tokens like <0x0A>
121
+ if token:match("^<0x%x%x>$") then
122
+ local hex = token:match("<0x(%x%x)>")
123
+ return string.char(tonumber(hex, 16))
124
+ end
125
+
126
+ -- Replace special space character
127
+ token = token:gsub("▁", " ")
128
+
129
+ return token
130
+ end
131
+
132
+ function Tokenizer:decode_tokens(tokens)
133
+ local pieces = {}
134
+ for _, token_id in ipairs(tokens) do
135
+ local piece = self:decode(token_id)
136
+ if piece and piece ~= "" then
137
+ table.insert(pieces, piece)
138
+ end
139
+ end
140
+ return table.concat(pieces, "")
141
+ end
142
+
143
+ return Tokenizer
provenance/source/space/vendor/lua_llama/utils.lua ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- utils.lua - Pure Lua utility functions (no Torch)
2
+
3
+ local utils = {}
4
+
5
+ -- Binary file reading
6
+ function utils.read_int32(file)
7
+ local bytes = file:read(4)
8
+ if not bytes or #bytes ~= 4 then
9
+ error("Failed to read int32")
10
+ end
11
+ return string.unpack("<i4", bytes)
12
+ end
13
+
14
+ function utils.read_float32(file)
15
+ local bytes = file:read(4)
16
+ if not bytes or #bytes ~= 4 then
17
+ error("Failed to read float32")
18
+ end
19
+ return string.unpack("<f", bytes)
20
+ end
21
+
22
+ function utils.read_float32_array(file, n)
23
+ local arr = {}
24
+ for i = 1, n do
25
+ arr[i] = utils.read_float32(file)
26
+ end
27
+ return arr
28
+ end
29
+
30
+ -- Math operations
31
+ function utils.softmax(x, size)
32
+ size = size or #x
33
+
34
+ -- Find max for numerical stability
35
+ local max_val = x[1]
36
+ for i = 2, size do
37
+ if x[i] > max_val then
38
+ max_val = x[i]
39
+ end
40
+ end
41
+
42
+ -- Exp and sum
43
+ local sum = 0
44
+ for i = 1, size do
45
+ x[i] = math.exp(x[i] - max_val)
46
+ sum = sum + x[i]
47
+ end
48
+
49
+ -- Normalize
50
+ for i = 1, size do
51
+ x[i] = x[i] / sum
52
+ end
53
+
54
+ return x
55
+ end
56
+
57
+ function utils.rmsnorm(out, x, weight, size)
58
+ -- RMS normalization
59
+ local ss = 0
60
+ for i = 1, size do
61
+ ss = ss + x[i] * x[i]
62
+ end
63
+ ss = ss / size + 1e-5
64
+ ss = 1.0 / math.sqrt(ss)
65
+
66
+ for i = 1, size do
67
+ out[i] = weight[i] * (ss * x[i])
68
+ end
69
+ end
70
+
71
+ function utils.matmul(out, x, w, n, d)
72
+ -- Matrix-vector multiplication: out = w * x
73
+ -- w is (n x d) matrix stored row-major
74
+ -- x is (d,) vector
75
+ -- out is (n,) vector
76
+ for i = 1, n do
77
+ local sum = 0
78
+ for j = 1, d do
79
+ sum = sum + w[(i-1)*d + j] * x[j]
80
+ end
81
+ out[i] = sum
82
+ end
83
+ end
84
+
85
+ function utils.accum(a, b, size)
86
+ -- a += b (element-wise)
87
+ for i = 1, size do
88
+ a[i] = a[i] + b[i]
89
+ end
90
+ end
91
+
92
+ function utils.sample(probabilities)
93
+ -- Sample from a probability distribution
94
+ local r = math.random()
95
+ local cdf = 0
96
+ for i = 1, #probabilities do
97
+ cdf = cdf + probabilities[i]
98
+ if r < cdf then
99
+ return i
100
+ end
101
+ end
102
+ return #probabilities
103
+ end
104
+
105
+ function utils.argmax(x, size)
106
+ size = size or #x
107
+ local max_i = 1
108
+ local max_val = x[1]
109
+ for i = 2, size do
110
+ if x[i] > max_val then
111
+ max_val = x[i]
112
+ max_i = i
113
+ end
114
+ end
115
+ return max_i
116
+ end
117
+
118
+ return utils
provenance/source/tools.lua ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- tools.lua - Tool registry and the built-in set.
2
+ --
3
+ -- A tool is a plain table:
4
+ -- name string, matched verbatim against the model's output
5
+ -- description one line; this is prompt real estate, keep it short
6
+ -- args { {name=, type="string"|"number", required=bool}, ... }
7
+ -- run function(args) -> result_string (may raise)
8
+ -- requires_approval bool, gates the tool behind the agent's approve callback
9
+ -- timeout_ms number|nil
10
+
11
+ local protocol = require('protocol')
12
+
13
+ local tools = {}
14
+
15
+ --------------------------------------------------------------------------
16
+ -- Registry
17
+ --------------------------------------------------------------------------
18
+
19
+ local Registry = {}
20
+ Registry.__index = Registry
21
+
22
+ -- The answer pseudo-tool is always present: it is how the loop terminates,
23
+ -- so it must appear in the catalogue and in the grammar's enum of names.
24
+ function tools.registry()
25
+ local self = setmetatable({ by_name = {}, order = {} }, Registry)
26
+ self:add(protocol.answer_tool)
27
+ return self
28
+ end
29
+
30
+ function Registry:add(tool)
31
+ if type(tool) ~= "table" or type(tool.name) ~= "string" then
32
+ error("tools: a tool needs a name")
33
+ end
34
+ if not self.by_name[tool.name] then
35
+ self.order[#self.order + 1] = tool.name
36
+ end
37
+ self.by_name[tool.name] = tool
38
+ return self
39
+ end
40
+
41
+ function Registry:get(name)
42
+ return self.by_name[name]
43
+ end
44
+
45
+ -- Stable order, so the rendered catalogue and the compiled grammar are
46
+ -- byte-identical across runs. Traces stop diffing otherwise.
47
+ function Registry:list()
48
+ local out = {}
49
+ for _, n in ipairs(self.order) do out[#out + 1] = self.by_name[n] end
50
+ return out
51
+ end
52
+
53
+ function Registry:names()
54
+ local out = {}
55
+ for _, n in ipairs(self.order) do out[#out + 1] = n end
56
+ return out
57
+ end
58
+
59
+ -- Validate a parsed call before running it. Returns ok, err_or_args.
60
+ -- A validation failure is an observation, not a crash: the message goes back
61
+ -- to the model, so it is phrased for the model to act on.
62
+ function Registry:validate(name, args)
63
+ local tool = self.by_name[name]
64
+ if not tool then
65
+ local avail = table.concat(self:names(), ", ")
66
+ return false, string.format(
67
+ "No tool named %q. Available tools: %s.", name, avail)
68
+ end
69
+ args = args or {}
70
+ local clean = {}
71
+ for _, spec in ipairs(tool.args or {}) do
72
+ local v = args[spec.name]
73
+ if v == nil or v == "" then
74
+ if spec.required then
75
+ return false, string.format(
76
+ "The %s tool needs a %q argument.", name, spec.name)
77
+ end
78
+ else
79
+ if spec.type == "number" then
80
+ local n = tonumber(v)
81
+ if not n then
82
+ return false, string.format(
83
+ "The %q argument of %s must be a number, got %q.",
84
+ spec.name, name, tostring(v))
85
+ end
86
+ clean[spec.name] = n
87
+ else
88
+ clean[spec.name] = tostring(v)
89
+ end
90
+ end
91
+ end
92
+ return true, clean
93
+ end
94
+
95
+ -- Execute with validation, the approval gate, and error capture applied.
96
+ -- Returns ok, result_or_error, status where status is one of
97
+ -- "continue" | "tool_error" | "timeout" | "denied".
98
+ function Registry:invoke(name, args, approve)
99
+ local ok, clean = self:validate(name, args)
100
+ if not ok then
101
+ return false, "Error: " .. clean, "tool_error"
102
+ end
103
+
104
+ local tool = self.by_name[name]
105
+ if tool.requires_approval then
106
+ -- Default-deny. An agent that writes to disk because nobody wired up
107
+ -- an approval callback is the failure mode this guards against.
108
+ if not approve or not approve({ tool = name, args = clean }) then
109
+ return false, string.format(
110
+ "Denied: the user did not approve calling %s.", name), "denied"
111
+ end
112
+ end
113
+
114
+ local started = os.clock()
115
+ local ran, result = pcall(tool.run, clean)
116
+ local elapsed_ms = (os.clock() - started) * 1000
117
+
118
+ if not ran then
119
+ -- Strip Lua's file:line prefix; the model cannot act on it and it
120
+ -- costs tokens on every retry.
121
+ local msg = tostring(result):gsub("^.-:%d+:%s*", "")
122
+ return false, "Error: " .. msg, "tool_error"
123
+ end
124
+ if tool.timeout_ms and elapsed_ms > tool.timeout_ms then
125
+ return false, string.format(
126
+ "Error: %s timed out after %.0fms.", name, elapsed_ms), "timeout"
127
+ end
128
+ return true, tostring(result), "continue"
129
+ end
130
+
131
+ --------------------------------------------------------------------------
132
+ -- calc: a real expression evaluator.
133
+ --
134
+ -- The obvious implementation is load("return " .. expr). Do not do that: the
135
+ -- expression is model output, and load() hands it the entire Lua runtime.
136
+ -- This is the single most common way a toy agent becomes a remote code
137
+ -- execution hole, so the repo shows the ~50-line alternative instead.
138
+ --
139
+ -- Grammar: expr := term (('+' | '-') term)*
140
+ -- term := power (('*' | '/' | '%') power)*
141
+ -- power := unary ('^' power)? -- right associative
142
+ -- unary := '-'? primary
143
+ -- primary := number | '(' expr ')'
144
+ --------------------------------------------------------------------------
145
+
146
+ local function tokenize(s)
147
+ local out, i = {}, 1
148
+ while i <= #s do
149
+ local c = s:sub(i, i)
150
+ if c:match("%s") then
151
+ i = i + 1
152
+ elseif c:match("%d") or (c == "." and s:sub(i + 1, i + 1):match("%d")) then
153
+ local num = s:match("^%d*%.?%d+", i) or s:match("^%d+", i)
154
+ out[#out + 1] = { t = "num", v = tonumber(num) }
155
+ i = i + #num
156
+ elseif ("+-*/%^()"):find(c, 1, true) then
157
+ out[#out + 1] = { t = c }
158
+ i = i + 1
159
+ else
160
+ return nil, string.format(
161
+ "%q is not arithmetic. calc evaluates numbers and + - * / %% ^ only.", s)
162
+ end
163
+ end
164
+ if #out == 0 then
165
+ return nil, "calc needs an arithmetic expression, for example 4871 * 209."
166
+ end
167
+ return out
168
+ end
169
+
170
+ local function evaluate(toks)
171
+ local pos = 1
172
+ local function peek() return toks[pos] and toks[pos].t end
173
+ local expr
174
+
175
+ local function primary()
176
+ local tk = toks[pos]
177
+ if not tk then error("unexpected end of expression", 0) end
178
+ if tk.t == "num" then pos = pos + 1 return tk.v end
179
+ if tk.t == "(" then
180
+ pos = pos + 1
181
+ local v = expr()
182
+ if peek() ~= ")" then error("missing closing parenthesis", 0) end
183
+ pos = pos + 1
184
+ return v
185
+ end
186
+ error("unexpected " .. tk.t .. " in expression", 0)
187
+ end
188
+
189
+ local function unary()
190
+ if peek() == "-" then pos = pos + 1 return -unary() end
191
+ if peek() == "+" then pos = pos + 1 return unary() end
192
+ return primary()
193
+ end
194
+
195
+ local function power()
196
+ local base = unary()
197
+ if peek() == "^" then
198
+ pos = pos + 1
199
+ return base ^ power() -- right associative
200
+ end
201
+ return base
202
+ end
203
+
204
+ local function term()
205
+ local v = power()
206
+ while peek() == "*" or peek() == "/" or peek() == "%" do
207
+ local op = peek()
208
+ pos = pos + 1
209
+ local rhs = power()
210
+ if (op == "/" or op == "%") and rhs == 0 then
211
+ error("division by zero", 0)
212
+ end
213
+ if op == "*" then v = v * rhs
214
+ elseif op == "/" then v = v / rhs
215
+ else v = v % rhs end
216
+ end
217
+ return v
218
+ end
219
+
220
+ expr = function()
221
+ local v = term()
222
+ while peek() == "+" or peek() == "-" do
223
+ local op = peek()
224
+ pos = pos + 1
225
+ if op == "+" then v = v + term() else v = v - term() end
226
+ end
227
+ return v
228
+ end
229
+
230
+ local result = expr()
231
+ if pos <= #toks then
232
+ error("unexpected " .. tostring(toks[pos].t) .. " after the expression", 0)
233
+ end
234
+ return result
235
+ end
236
+
237
+ -- Format without float noise: 1018039, not 1018039.0
238
+ local function format_number(n)
239
+ if n ~= n then return "nan" end
240
+ if n == math.huge or n == -math.huge then return tostring(n) end
241
+ if n % 1 == 0 and math.abs(n) < 1e15 then return string.format("%d", n) end
242
+ return (string.format("%.10g", n))
243
+ end
244
+
245
+ tools.calc = {
246
+ name = "calc",
247
+ description = "Evaluate an arithmetic expression.",
248
+ args = { { name = "expr", type = "string", required = true } },
249
+ run = function(args)
250
+ local toks, err = tokenize(args.expr)
251
+ if not toks then error(err, 0) end
252
+ return format_number(evaluate(toks))
253
+ end,
254
+ }
255
+
256
+ --------------------------------------------------------------------------
257
+ -- Filesystem tools
258
+ --------------------------------------------------------------------------
259
+
260
+ -- Observations are charged against the context budget, so a tool that can
261
+ -- return a whole file truncates itself. context.lua handles the window; this
262
+ -- stops one pathological read from blowing it in a single step.
263
+ tools.MAX_OBSERVATION = 4000
264
+
265
+ local function truncate(s)
266
+ if #s <= tools.MAX_OBSERVATION then return s end
267
+ return s:sub(1, tools.MAX_OBSERVATION) .. string.format(
268
+ "\n... [truncated, %d bytes total]", #s)
269
+ end
270
+
271
+ tools.read_file = {
272
+ name = "read_file",
273
+ description = "Read a text file.",
274
+ args = { { name = "path", type = "string", required = true } },
275
+ run = function(args)
276
+ local fh, err = io.open(args.path, "r")
277
+ if not fh then
278
+ -- Name the failure precisely: a model that is told the path does
279
+ -- not exist can correct it; one told "error" retries the same path.
280
+ error(string.format("cannot open %q (%s)", args.path,
281
+ tostring(err):gsub("^.*: ", "")), 0)
282
+ end
283
+ local content = fh:read("a")
284
+ fh:close()
285
+ return truncate(content)
286
+ end,
287
+ }
288
+
289
+ tools.list_dir = {
290
+ name = "list_dir",
291
+ description = "List the entries of a directory.",
292
+ args = { { name = "path", type = "string", required = true } },
293
+ run = function(args)
294
+ -- No POSIX module, so shell out. Quoting matters: the path is model
295
+ -- output. Reject anything that could escape the argument.
296
+ if args.path:match('[`$;|&<>"\n]') then
297
+ error("path contains characters that are not allowed", 0)
298
+ end
299
+ local cmd = package.config:sub(1, 1) == "\\"
300
+ and string.format('dir /b "%s" 2>nul', args.path)
301
+ or string.format("ls -1 '%s' 2>/dev/null", args.path)
302
+ local pipe = io.popen(cmd, "r")
303
+ if not pipe then error("cannot list " .. args.path, 0) end
304
+ local out = pipe:read("a")
305
+ pipe:close()
306
+ if not out or out == "" then
307
+ error(string.format("%q is empty or does not exist", args.path), 0)
308
+ end
309
+ return truncate(out)
310
+ end,
311
+ }
312
+
313
+ tools.write_file = {
314
+ name = "write_file",
315
+ description = "Write text to a file, replacing it.",
316
+ args = { { name = "path", type = "string", required = true },
317
+ { name = "text", type = "string", required = true } },
318
+ requires_approval = true,
319
+ run = function(args)
320
+ local fh, err = io.open(args.path, "w")
321
+ if not fh then error(tostring(err), 0) end
322
+ fh:write(args.text)
323
+ fh:close()
324
+ return string.format("wrote %d bytes to %s", #args.text, args.path)
325
+ end,
326
+ }
327
+
328
+ -- The default set, in catalogue order.
329
+ function tools.defaults()
330
+ local reg = tools.registry()
331
+ reg:add(tools.calc)
332
+ reg:add(tools.read_file)
333
+ reg:add(tools.list_dir)
334
+ reg:add(tools.write_file)
335
+ return reg
336
+ end
337
+
338
+ return tools
provenance/source/tools/llama2c.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Read a llama2.c checkpoint into PyTorch, and run it.
3
+
4
+ python tools/llama2c.py ../lua_llama/stories15M.bin ../lua_llama/tokenizer.bin
5
+
6
+ This is the PyTorch counterpart to repo 1's model.lua and generate.lua. It
7
+ exists so a projection layer can be TRAINED against the same frozen model
8
+ the Lua side runs -- training needs autograd, which pure Lua does not have.
9
+
10
+ Correctness is not asserted, it is checked: at temperature 0 this must emit
11
+ the exact continuation repo 1 documents for "Once upon a time". Same
12
+ weights, same arithmetic, same output, or the loader is wrong. Run the file
13
+ to see it.
14
+
15
+ Format (7 int32 header, then float32 tensors, all layers contiguous):
16
+ dim hidden_dim n_layers n_heads n_kv_heads vocab_size seq_len
17
+ token_embedding, rms_att, wq, wk, wv, wo, rms_ffn, w1, w2, w3,
18
+ rms_final, freq_real, freq_imag, [wcls if vocab_size was negative]
19
+
20
+ A NEGATIVE vocab_size in the header means the classifier is NOT shared with
21
+ the embedding table -- the sign is the flag, which is easy to miss.
22
+ """
23
+
24
+ import struct
25
+ import sys
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+
30
+
31
+ class Config:
32
+ def __init__(self, dim, hidden_dim, n_layers, n_heads, n_kv_heads,
33
+ vocab_size, seq_len, shared_classifier):
34
+ self.dim, self.hidden_dim = dim, hidden_dim
35
+ self.n_layers, self.n_heads, self.n_kv_heads = n_layers, n_heads, n_kv_heads
36
+ self.vocab_size, self.seq_len = vocab_size, seq_len
37
+ self.shared_classifier = shared_classifier
38
+ self.head_size = dim // n_heads
39
+ self.kv_dim = n_kv_heads * self.head_size
40
+
41
+ def __repr__(self):
42
+ return (f"dim={self.dim} hidden={self.hidden_dim} layers={self.n_layers} "
43
+ f"heads={self.n_heads} kv_heads={self.n_kv_heads} "
44
+ f"vocab={self.vocab_size} seq_len={self.seq_len} "
45
+ f"shared_cls={self.shared_classifier}")
46
+
47
+
48
+ def load(path):
49
+ with open(path, "rb") as fh:
50
+ blob = fh.read()
51
+
52
+ hdr = struct.unpack("<7i", blob[:28])
53
+ dim, hidden_dim, n_layers, n_heads, n_kv_heads, vocab_size, seq_len = hdr
54
+ shared = vocab_size > 0
55
+ vocab_size = abs(vocab_size)
56
+ c = Config(dim, hidden_dim, n_layers, n_heads, n_kv_heads,
57
+ vocab_size, seq_len, shared)
58
+
59
+ pos = 28
60
+ def take(*shape):
61
+ nonlocal pos
62
+ n = 1
63
+ for s in shape:
64
+ n *= s
65
+ t = torch.frombuffer(blob, dtype=torch.float32, count=n,
66
+ offset=pos).clone().view(*shape)
67
+ pos += n * 4
68
+ return t
69
+
70
+ w = {}
71
+ w["tok_emb"] = take(vocab_size, dim)
72
+ w["rms_att"] = take(n_layers, dim)
73
+ w["wq"] = take(n_layers, dim, dim)
74
+ w["wk"] = take(n_layers, c.kv_dim, dim)
75
+ w["wv"] = take(n_layers, c.kv_dim, dim)
76
+ w["wo"] = take(n_layers, dim, dim)
77
+ w["rms_ffn"] = take(n_layers, dim)
78
+ w["w1"] = take(n_layers, hidden_dim, dim)
79
+ w["w2"] = take(n_layers, dim, hidden_dim)
80
+ w["w3"] = take(n_layers, hidden_dim, dim)
81
+ w["rms_final"] = take(dim)
82
+ take(seq_len, c.head_size // 2) # freq_cis_real, recomputed below
83
+ take(seq_len, c.head_size // 2) # freq_cis_imag
84
+
85
+ if shared:
86
+ w["wcls"] = w["tok_emb"]
87
+ else:
88
+ w["wcls"] = take(vocab_size, dim)
89
+
90
+ return c, w
91
+
92
+
93
+ def rmsnorm(x, weight, eps=1e-5):
94
+ return weight * (x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps))
95
+
96
+
97
+ def rope(x, pos, head_size):
98
+ """Rotate pairs in place, llama2.c convention (adjacent pairs)."""
99
+ out = x.clone().view(-1, head_size)
100
+ idx = torch.arange(0, head_size, 2, dtype=torch.float32)
101
+ freq = 1.0 / (10000.0 ** (idx / head_size))
102
+ ang = pos * freq
103
+ cos, sin = torch.cos(ang), torch.sin(ang)
104
+ even, odd = out[:, 0::2].clone(), out[:, 1::2].clone()
105
+ out[:, 0::2] = even * cos - odd * sin
106
+ out[:, 1::2] = even * sin + odd * cos
107
+ return out.view(-1)
108
+
109
+
110
+ @torch.no_grad()
111
+ def forward(c, w, token, pos, kcache, vcache, embed=None):
112
+ """One token. `embed` overrides the token lookup -- that hook is the
113
+ whole point of this file: a projected image vector is fed in exactly
114
+ where a token embedding would be."""
115
+ x = w["tok_emb"][token].clone() if embed is None else embed.clone()
116
+
117
+ for l in range(c.n_layers):
118
+ xb = rmsnorm(x, w["rms_att"][l])
119
+ q = rope(w["wq"][l] @ xb, pos, c.head_size)
120
+ k = rope(w["wk"][l] @ xb, pos, c.head_size)
121
+ v = w["wv"][l] @ xb
122
+ kcache[l, pos], vcache[l, pos] = k, v
123
+
124
+ heads = []
125
+ kv_mul = c.n_heads // c.n_kv_heads
126
+ for h in range(c.n_heads):
127
+ kvh = h // kv_mul
128
+ qh = q[h * c.head_size:(h + 1) * c.head_size]
129
+ ks = kcache[l, :pos + 1, kvh * c.head_size:(kvh + 1) * c.head_size]
130
+ vs = vcache[l, :pos + 1, kvh * c.head_size:(kvh + 1) * c.head_size]
131
+ att = torch.softmax((ks @ qh) / (c.head_size ** 0.5), dim=0)
132
+ heads.append(att @ vs)
133
+ x = x + w["wo"][l] @ torch.cat(heads)
134
+
135
+ xb = rmsnorm(x, w["rms_ffn"][l])
136
+ h1, h3 = w["w1"][l] @ xb, w["w3"][l] @ xb
137
+ x = x + w["w2"][l] @ (F.silu(h1) * h3)
138
+
139
+ return w["wcls"] @ rmsnorm(x, w["rms_final"])
140
+
141
+
142
+ def forward_seq(c, w, embeds):
143
+ """Batched, differentiable forward over a whole sequence.
144
+
145
+ embeds: [B, T, dim] -> logits: [B, T, vocab]
146
+
147
+ The incremental forward above is what the Lua side mirrors; this one is
148
+ for TRAINING. Gradients flow back through to `embeds`, which is how a
149
+ projection layer learns: its output is spliced in as one position's
150
+ embedding and the loss on a later token pushes it around. The frozen
151
+ weights carry no grad -- only whatever produced `embeds` does.
152
+
153
+ Kept honest by a test in __main__: the last position here must equal the
154
+ incremental path's logits for the same input.
155
+ """
156
+ B, T, _ = embeds.shape
157
+ x = embeds
158
+
159
+ # Causal mask, built once.
160
+ mask = torch.full((T, T), float("-inf"), device=x.device)
161
+ mask = torch.triu(mask, diagonal=1)
162
+
163
+ pos = torch.arange(T, device=x.device, dtype=torch.float32)
164
+ idx = torch.arange(0, c.head_size, 2, device=x.device, dtype=torch.float32)
165
+ freq = 1.0 / (10000.0 ** (idx / c.head_size))
166
+ ang = pos[:, None] * freq[None, :] # [T, head_size/2]
167
+ cos, sin = torch.cos(ang), torch.sin(ang)
168
+
169
+ def apply_rope(t, n_h): # t: [B, T, n_h, head_size]
170
+ even, odd = t[..., 0::2], t[..., 1::2]
171
+ c_ = cos[None, :, None, :]
172
+ s_ = sin[None, :, None, :]
173
+ out = torch.empty_like(t)
174
+ out[..., 0::2] = even * c_ - odd * s_
175
+ out[..., 1::2] = even * s_ + odd * c_
176
+ return out
177
+
178
+ for l in range(c.n_layers):
179
+ xb = rmsnorm(x, w["rms_att"][l])
180
+ q = (xb @ w["wq"][l].T).view(B, T, c.n_heads, c.head_size)
181
+ k = (xb @ w["wk"][l].T).view(B, T, c.n_kv_heads, c.head_size)
182
+ v = (xb @ w["wv"][l].T).view(B, T, c.n_kv_heads, c.head_size)
183
+ q, k = apply_rope(q, c.n_heads), apply_rope(k, c.n_kv_heads)
184
+
185
+ # Grouped-query attention: repeat each kv head for its query group.
186
+ kv_mul = c.n_heads // c.n_kv_heads
187
+ if kv_mul > 1:
188
+ k = k.repeat_interleave(kv_mul, dim=2)
189
+ v = v.repeat_interleave(kv_mul, dim=2)
190
+
191
+ q, k, v = (t.transpose(1, 2) for t in (q, k, v)) # [B, nh, T, hs]
192
+ att = (q @ k.transpose(-2, -1)) / (c.head_size ** 0.5) + mask
193
+ out = (torch.softmax(att, dim=-1) @ v)
194
+ out = out.transpose(1, 2).reshape(B, T, c.dim)
195
+ x = x + out @ w["wo"][l].T
196
+
197
+ xb = rmsnorm(x, w["rms_ffn"][l])
198
+ x = x + (F.silu(xb @ w["w1"][l].T) * (xb @ w["w3"][l].T)) @ w["w2"][l].T
199
+
200
+ return rmsnorm(x, w["rms_final"]) @ w["wcls"].T
201
+
202
+
203
+ def load_tokenizer(path, vocab_size):
204
+ """Minimal reader for llama2.c tokenizer.bin -- enough to decode, and to
205
+ encode with the same greedy merge repo 1 uses."""
206
+ with open(path, "rb") as fh:
207
+ blob = fh.read()
208
+ pos = 4 # max_token_length
209
+ vocab, scores = [], []
210
+ for _ in range(vocab_size):
211
+ score = struct.unpack("<f", blob[pos:pos + 4])[0]; pos += 4
212
+ ln = struct.unpack("<i", blob[pos:pos + 4])[0]; pos += 4
213
+ vocab.append(blob[pos:pos + ln].decode("utf-8", "replace")); pos += ln
214
+ scores.append(score)
215
+ return vocab, scores
216
+
217
+
218
+ def decode(vocab, tid):
219
+ piece = vocab[tid]
220
+ if len(piece) == 6 and piece.startswith("<0x") and piece.endswith(">"):
221
+ return chr(int(piece[3:5], 16))
222
+ return piece.replace("▁", " ")
223
+
224
+
225
+ def encode(vocab, scores, text):
226
+ lookup = {}
227
+ for i, v in enumerate(vocab):
228
+ t = chr(int(v[3:5], 16)) if (len(v) == 6 and v.startswith("<0x")) else v
229
+ lookup.setdefault(t, i)
230
+ tokens = [1] # BOS
231
+ for ch in (" " + text):
232
+ tokens.append(lookup.get(ch, ord(ch) + 3))
233
+ while True:
234
+ best, best_id, best_at = -1e10, None, None
235
+ for i in range(len(tokens) - 1):
236
+ a, b = decode(vocab, tokens[i]), decode(vocab, tokens[i + 1])
237
+ merged = lookup.get(a.replace(" ", "▁") + b.replace(" ", "▁"))
238
+ if merged is None:
239
+ merged = lookup.get(a + b)
240
+ if merged is not None and scores[merged] > best:
241
+ best, best_id, best_at = scores[merged], merged, i
242
+ if best_at is None:
243
+ break
244
+ tokens[best_at] = best_id
245
+ del tokens[best_at + 1]
246
+ return tokens
247
+
248
+
249
+ @torch.no_grad()
250
+ def generate(c, w, vocab, scores, prompt, max_new=90):
251
+ kcache = torch.zeros(c.n_layers, c.seq_len, c.kv_dim)
252
+ vcache = torch.zeros(c.n_layers, c.seq_len, c.kv_dim)
253
+ ids = encode(vocab, scores, prompt)
254
+
255
+ pos, out = 0, []
256
+ for t in ids[:-1]:
257
+ forward(c, w, t, pos, kcache, vcache); pos += 1
258
+ nxt = ids[-1]
259
+ for _ in range(max_new):
260
+ logits = forward(c, w, nxt, pos, kcache, vcache)
261
+ nxt = int(torch.argmax(logits)) # temperature 0
262
+ if nxt in (1, 2):
263
+ break
264
+ out.append(decode(vocab, nxt))
265
+ pos += 1
266
+ if pos >= c.seq_len:
267
+ break
268
+ return prompt + "".join(out)
269
+
270
+
271
+ if __name__ == "__main__":
272
+ ckpt = sys.argv[1] if len(sys.argv) > 1 else "../lua_llama/stories15M.bin"
273
+ tok = sys.argv[2] if len(sys.argv) > 2 else "../lua_llama/tokenizer.bin"
274
+
275
+ c, w = load(ckpt)
276
+ print(c)
277
+ vocab, scores = load_tokenizer(tok, c.vocab_size)
278
+ print(f"tokenizer: {len(vocab)} entries\n")
279
+
280
+ text = generate(c, w, vocab, scores, "Once upon a time", max_new=60)
281
+ print(text)
282
+
283
+ # Repo 1's README documents this continuation at temperature 0. Same
284
+ # weights and same arithmetic must give the same text.
285
+ expected = "there was a little girl named Lily"
286
+ print("\nmatches repo 1's documented output:", expected in text)
287
+
288
+ # The batched path is what training runs through, so it has to agree
289
+ # with the incremental one it will never otherwise be compared against.
290
+ ids = encode(vocab, scores, "Once upon a time")
291
+ emb = w["tok_emb"][torch.tensor(ids)].unsqueeze(0)
292
+ seq_logits = forward_seq(c, w, emb)[0, -1]
293
+
294
+ kc = torch.zeros(c.n_layers, c.seq_len, c.kv_dim)
295
+ vc = torch.zeros(c.n_layers, c.seq_len, c.kv_dim)
296
+ for p, t in enumerate(ids[:-1]):
297
+ forward(c, w, t, p, kc, vc)
298
+ inc_logits = forward(c, w, ids[-1], len(ids) - 1, kc, vc)
299
+
300
+ delta = (seq_logits - inc_logits).abs().max().item()
301
+ print(f"batched vs incremental: max |diff| = {delta:.2e}, "
302
+ f"same argmax = {int(seq_logits.argmax()) == int(inc_logits.argmax())}")
303
+
304
+ # And gradients must reach the input embeddings, or nothing can train.
305
+ probe = emb.clone().requires_grad_(True)
306
+ forward_seq(c, w, probe)[0, -1].sum().backward()
307
+ g = probe.grad.abs().sum().item()
308
+ print(f"gradient reaches the input embedding: {g > 0} (|grad| sum {g:.3f})")
provenance/source/trace.lua ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- trace.lua - JSONL record and replay, plus the minimal JSON it needs.
2
+ --
3
+ -- The highest-value file in the repo for its size. Every step is appended as
4
+ -- one JSON line; backend/replay.lua reads those lines back. That single fact
5
+ -- buys:
6
+ -- - a test suite that needs no API key and no network
7
+ -- - examples/ transcripts that are reproducible rather than illustrative
8
+ -- - a debugging story: re-run a failure exactly, as many times as you like
9
+ --
10
+ -- No dependencies is load-bearing here, same as repo 1, so the JSON codec is
11
+ -- written out rather than pulled in. It only has to handle the step schema.
12
+
13
+ local trace = {}
14
+
15
+ --------------------------------------------------------------------------
16
+ -- JSON encode
17
+ --------------------------------------------------------------------------
18
+
19
+ local ESCAPES = {
20
+ ['"'] = '\\"', ['\\'] = '\\\\', ['\b'] = '\\b', ['\f'] = '\\f',
21
+ ['\n'] = '\\n', ['\r'] = '\\r', ['\t'] = '\\t',
22
+ }
23
+
24
+ local function escape_str(s)
25
+ return (s:gsub('[%c"\\]', function(c)
26
+ return ESCAPES[c] or string.format('\\u%04x', c:byte())
27
+ end))
28
+ end
29
+
30
+ -- Arrays are tables whose keys are exactly 1..n. Everything else, including
31
+ -- the empty table, encodes as an object -- empty `args` must be `{}`.
32
+ local function is_array(t)
33
+ local n = 0
34
+ for _ in pairs(t) do n = n + 1 end
35
+ for i = 1, n do
36
+ if t[i] == nil then return false end
37
+ end
38
+ return n > 0
39
+ end
40
+
41
+ -- Pin an object's key order for encoding.
42
+ --
43
+ -- Key order is semantically meaningless in JSON, which is why encode sorts
44
+ -- alphabetically by default: byte-stable traces that diff cleanly.
45
+ --
46
+ -- It stops being meaningless the moment the JSON is a SCHEMA that gets
47
+ -- compiled to a grammar. llama.cpp emits object properties in declaration
48
+ -- order, so the sort silently rewrote backend/ollama.lua's turn schema from
49
+ -- {thought, call} to {call, thought} and from {tool, args} to {args, tool} --
50
+ -- forcing the model to choose a tool before writing its reasoning, and to
51
+ -- write arguments before naming the tool they belonged to. qwen2.5 then
52
+ -- re-called a tool it had already run, five times in a row, and looked like
53
+ -- a model too small for the job.
54
+ --
55
+ -- trace.ordered({ thought = "...", call = {...} }, { "thought", "call" })
56
+ --
57
+ -- Keys not listed are appended in sorted order, so this never drops data.
58
+ function trace.ordered(tbl, order)
59
+ return setmetatable(tbl, { __jsonorder = order })
60
+ end
61
+
62
+ function trace.encode(v)
63
+ local ty = type(v)
64
+ if v == nil then
65
+ return "null"
66
+ elseif ty == "boolean" then
67
+ return tostring(v)
68
+ elseif ty == "number" then
69
+ -- %.14g round-trips a double without trailing float noise
70
+ return (v % 1 == 0 and math.abs(v) < 1e15)
71
+ and string.format("%d", v)
72
+ or string.format("%.14g", v)
73
+ elseif ty == "string" then
74
+ return '"' .. escape_str(v) .. '"'
75
+ elseif ty == "table" then
76
+ local out = {}
77
+ if is_array(v) then
78
+ for i = 1, #v do out[#out + 1] = trace.encode(v[i]) end
79
+ return "[" .. table.concat(out, ",") .. "]"
80
+ end
81
+ -- Sort keys so a re-encoded trace is byte-stable and diffable --
82
+ -- unless the caller pinned an order with trace.ordered.
83
+ local keys = {}
84
+ local pinned = getmetatable(v)
85
+ pinned = pinned and pinned.__jsonorder
86
+ if pinned then
87
+ for _, k in ipairs(pinned) do
88
+ if v[k] ~= nil then keys[#keys + 1] = k end
89
+ end
90
+ -- Anything not named in the order still has to be emitted.
91
+ local named = {}
92
+ for _, k in ipairs(pinned) do named[k] = true end
93
+ local rest = {}
94
+ for k in pairs(v) do
95
+ if not named[k] then rest[#rest + 1] = k end
96
+ end
97
+ table.sort(rest, function(a, b) return tostring(a) < tostring(b) end)
98
+ for _, k in ipairs(rest) do keys[#keys + 1] = k end
99
+ else
100
+ for k in pairs(v) do keys[#keys + 1] = k end
101
+ table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
102
+ end
103
+ for _, k in ipairs(keys) do
104
+ out[#out + 1] = '"' .. escape_str(tostring(k)) .. '":' .. trace.encode(v[k])
105
+ end
106
+ return "{" .. table.concat(out, ",") .. "}"
107
+ end
108
+ error("cannot encode " .. ty)
109
+ end
110
+
111
+ --------------------------------------------------------------------------
112
+ -- JSON decode -- recursive descent, enough for the schema above
113
+ --------------------------------------------------------------------------
114
+
115
+ local Parser = {}
116
+ Parser.__index = Parser
117
+
118
+ function Parser:err(msg)
119
+ error(string.format("json: %s at byte %d", msg, self.pos), 0)
120
+ end
121
+
122
+ function Parser:skip_ws()
123
+ local _, e = self.s:find("^[ \t\r\n]*", self.pos)
124
+ self.pos = e + 1
125
+ end
126
+
127
+ function Parser:peek()
128
+ return self.s:sub(self.pos, self.pos)
129
+ end
130
+
131
+ function Parser:expect(c)
132
+ if self:peek() ~= c then self:err("expected " .. c) end
133
+ self.pos = self.pos + 1
134
+ end
135
+
136
+ local UNESCAPES = {
137
+ ['"'] = '"', ['\\'] = '\\', ['/'] = '/', b = '\b',
138
+ f = '\f', n = '\n', r = '\r', t = '\t',
139
+ }
140
+
141
+ function Parser:parse_string()
142
+ self:expect('"')
143
+ local buf = {}
144
+ while true do
145
+ local c = self:peek()
146
+ if c == "" then self:err("unterminated string") end
147
+ self.pos = self.pos + 1
148
+ if c == '"' then
149
+ return table.concat(buf)
150
+ elseif c == '\\' then
151
+ local esc = self:peek()
152
+ self.pos = self.pos + 1
153
+ if esc == "u" then
154
+ local hex = self.s:sub(self.pos, self.pos + 3)
155
+ if not hex:match("^%x%x%x%x$") then self:err("bad unicode escape") end
156
+ self.pos = self.pos + 4
157
+ local cp = tonumber(hex, 16)
158
+ buf[#buf + 1] = (cp < 128) and string.char(cp) or utf8.char(cp)
159
+ elseif UNESCAPES[esc] then
160
+ buf[#buf + 1] = UNESCAPES[esc]
161
+ else
162
+ self:err("bad escape " .. esc)
163
+ end
164
+ else
165
+ buf[#buf + 1] = c
166
+ end
167
+ end
168
+ end
169
+
170
+ function Parser:parse_value()
171
+ self:skip_ws()
172
+ local c = self:peek()
173
+ if c == '"' then
174
+ return self:parse_string()
175
+ elseif c == "{" then
176
+ self.pos = self.pos + 1
177
+ local obj = {}
178
+ self:skip_ws()
179
+ if self:peek() == "}" then self.pos = self.pos + 1 return obj end
180
+ while true do
181
+ self:skip_ws()
182
+ local k = self:parse_string()
183
+ self:skip_ws()
184
+ self:expect(":")
185
+ obj[k] = self:parse_value()
186
+ self:skip_ws()
187
+ local d = self:peek()
188
+ self.pos = self.pos + 1
189
+ if d == "}" then return obj end
190
+ if d ~= "," then self:err("expected comma or close-brace") end
191
+ end
192
+ elseif c == "[" then
193
+ self.pos = self.pos + 1
194
+ local arr = {}
195
+ self:skip_ws()
196
+ if self:peek() == "]" then self.pos = self.pos + 1 return arr end
197
+ while true do
198
+ arr[#arr + 1] = self:parse_value()
199
+ self:skip_ws()
200
+ local d = self:peek()
201
+ self.pos = self.pos + 1
202
+ if d == "]" then return arr end
203
+ if d ~= "," then self:err("expected comma or close-bracket") end
204
+ end
205
+ elseif self.s:find("^true", self.pos) then
206
+ self.pos = self.pos + 4 return true
207
+ elseif self.s:find("^false", self.pos) then
208
+ self.pos = self.pos + 5 return false
209
+ elseif self.s:find("^null", self.pos) then
210
+ self.pos = self.pos + 4 return nil
211
+ else
212
+ local num = self.s:match("^%-?%d+%.?%d*[eE]?[-+]?%d*", self.pos)
213
+ if not num or num == "" then self:err("unexpected character " .. c) end
214
+ self.pos = self.pos + #num
215
+ return tonumber(num)
216
+ end
217
+ end
218
+
219
+ -- Returns value, err. Never raises: callers feed the error text straight back
220
+ -- to the model as an observation, which is how parse recovery works.
221
+ function trace.decode(str)
222
+ local p = setmetatable({ s = str, pos = 1 }, Parser)
223
+ local ok, result = pcall(function()
224
+ local v = p:parse_value()
225
+ p:skip_ws()
226
+ if p.pos <= #p.s then p:err("trailing content") end
227
+ return v
228
+ end)
229
+ if not ok then return nil, result end
230
+ return result
231
+ end
232
+
233
+ --------------------------------------------------------------------------
234
+ -- JSONL trace files
235
+ --------------------------------------------------------------------------
236
+
237
+ local Trace = {}
238
+ Trace.__index = Trace
239
+
240
+ -- mode: "record" | "off"
241
+ function trace.open(path, mode)
242
+ local self = setmetatable({ path = path, mode = mode or "off", n = 0 }, Trace)
243
+ if self.mode == "record" then
244
+ if not path then error("trace.open: record mode needs a path") end
245
+ local fh, err = io.open(path, "w")
246
+ if not fh then error("trace.open: " .. tostring(err)) end
247
+ self.fh = fh
248
+ end
249
+ return self
250
+ end
251
+
252
+ -- One line per step. Schema (stable; examples/ depend on it):
253
+ -- { step=, prompt=, raw=, thought=, call={tool=,args=}, observation=,
254
+ -- status=, tokens={prompt=,completion=,window=}, ms= }
255
+ function Trace:write(record)
256
+ self.n = self.n + 1
257
+ if not self.fh then return end
258
+ self.fh:write(trace.encode(record), "\n")
259
+ self.fh:flush() -- a crashed run must still leave a readable trace
260
+ end
261
+
262
+ function Trace:close()
263
+ if self.fh then self.fh:close() self.fh = nil end
264
+ end
265
+
266
+ -- Read a trace back into a step list.
267
+ function trace.read(path)
268
+ local fh, err = io.open(path, "r")
269
+ if not fh then error("trace.read: " .. tostring(err)) end
270
+ local steps, lineno = {}, 0
271
+ for line in fh:lines() do
272
+ lineno = lineno + 1
273
+ if line:match("%S") then
274
+ local rec, derr = trace.decode(line)
275
+ if not rec then
276
+ fh:close()
277
+ error(string.format("trace.read: %s:%d: %s", path, lineno, derr))
278
+ end
279
+ steps[#steps + 1] = rec
280
+ end
281
+ end
282
+ fh:close()
283
+ return steps
284
+ end
285
+
286
+ return trace