# Tally: a language in which every number is a count of something

Version 0.3.0, 17 November 2026. The interpreter is `tally.py` (standard library only). `python3 verify.py` runs the regression tests, language self-check, strict accuracy example, physics programs and premise audit. These are executable checks of documented behavior, not a proof of every possible program.

A number on its own is just a symbol. In Tally a number may only appear as a count of a declared kind, made by a declared procedure, on a declared bench, in a declared window, at a declared resolution. Anything else is rejected, usually with the question "8 of what?".

## The rules the interpreter enforces

1. **Meaning comes from acts.** A word means something only if its definition reaches acts someone can perform. Words must be defined from words already defined. Declared acts, definitions and scales keep their meaning and role throughout the run: changing or cross-shadowing one is rejected. Exact duplicate declarations are idempotent and do not reset scale conversions.
2. **Every number is a count.**
   - An integer in a program is a compressed tally: `8` stands for `||||||||`.
   - Positions and times are counts of steps of a declared scale. Scales relate by counted pairing (`relate 1000 ms = 1 s`), like gears.
   - There are no bare numbers, no decimals (write 500 ms, not 0.5 s) and no negative numbers.
3. **A zero needs a positive control:** a record in which the same procedure, on the same bench, did mark the kind.
4. **Resolution decides how many.**
   - Marks closer than the resolution are one mark.
   - Recounting coarser is allowed; finer than the record is refused.
   - A resolution plateau is reported where the count stays flat over two or more doublings. Stability under that detector model is not independent experimental certification.
5. **Arithmetic is acts:**

   | Operation | Act | Result |
   |---|---|---|
   | `a + b` | join | windows apart: exact sum. Same window: the joined marks are recounted, so 8 + 8 can be 8. Without marks: a range |
   | `a - b` | pair off | a difference with a direction ("the first has 6 more"), never below nothing |
   | `a * b` | count pairs, one of each | a new kind `(a × b)` |
   | `a / b`, same kind | part of a whole | a band from none to all of the whole |
   | `a / b`, different kinds | so many per so many | a rate |

6. **Values retain their sources.** Settings, theory and apparatus/cited/simulated records remain distinguishable. A derived value can carry both a model and one or several record categories, such as `derived from cited and simulated records with theory`. Comparisons say `against theory`. Provenance is propagated conservatively through arithmetic, calls and control flow; it does not authenticate a bench declaration.
7. **Prospective claim checks.** A claim freezes its program, recursive imports, language runtime and configuration in a ledger. A later unchanged run can check new file contents on a named bench. A cited record remains observed, never prospectively certified. The ledger cannot establish when an external measurement occurred or whether its file came from physical apparatus.

## Settings and observations (new in 0.2)

Some numbers are not observed: they count acts you perform yourself, such as trials prepared, phase steps turned, loop passes, ways of arranging. These are **settings**: declared with `setting`, exact, with no window and no bench, and a zero of a setting needs no control (you know you did nothing). Observed counts keep every rule above. The two do not mix in `+`, `-` or comparisons.

`lib/core.tly` is loaded before every program and declares the settings the built-in functions use: `trial`, `seed`, `item`, `way` and `sixteenth` (one sixteenth of a full turn of a phase plate or polarizer).

## Amplitudes and chances (new in 0.2)

An **amplitude** is an exact arrow on a 16-step phase ratchet: a sum of whole numbers of arrows ζ^k (ζ = one sixteenth of a turn, ζ⁸ = the reversed arrow), divided by a power of two. Arrows add and compose exactly; nothing is rounded. A **chance** is |amplitude|² (the conditional rate argument requires the universal coherent-mixer and regularity premises in `BORN_PREMISES.md`) and is checked to lie between none and all. A **weight** is the same square with no such limit, for sizes that are not chances. Both print with an exact form in 1, √2, k₁ = 2cos(π/8) and k₃ = 2cos(3π/8).

| Function | Gives |
|---|---|
| `arrow(k sixteenth)`, `turn(a, k sixteenth)`, `nothing()` | an arrow; a turned amplitude; the empty amplitude |
| `split(a)` | a × 1/√2, a balanced splitter's share |
| `cos_turn(k sixteenth)`, `sin_turn(k sixteenth)` | (ζ^k + ζ^-k)/2 and (ζ^k − ζ^-k)/2i |
| `chance(a)`, `weight(a)` | |a|², as a chance (≤ all) or a weight |
| `conj(a)` | the mirror arrow (each ζ^k becomes ζ^-k) |
| `quarter(a)`, `opposite(a)` | a turned a quarter turn (× i) or half a turn (× −1), on whatever ratchet is in use |
| `draw(chance, n trial, s seed)` | a simulated bench: how many of n trials clicked (seeded, repeatable) |
| `within_noise(count, chance, n trial)` | yes if the count is within 5 standard deviations of n × chance |

A ratio of records compares with an exact chance or weight by its range. Chances compare exactly with each other and with bands (`chance(cos_turn(2 sixteenth)) == 1 trial / 2 trial`). Every amplitude is theory until a draw or a record is compared with it.

Each interpreter owns its phase ratchet and phase-count kind. `ratchet` must precede amplitude construction in that interpreter; another interpreter's activity cannot change this guard or its phase settings. Amplitudes retain their field size, and adding or multiplying amplitudes from different ratchet sizes is refused. Intrinsic quarter-turns, half-turns and splitting use the operand's field. This permits interleaved embedded interpreters without changing the meaning of existing amplitudes.

**Exact means exact for decisions.** Rational comparisons use integer/fraction arithmetic. For real cyclotomic amplitudes, `exact_order.py` bounds the appropriate half-angle square roots with integer arithmetic, evaluates outward-rounded intervals, and refines until the sign is certified. Equality is decided in the exact coefficient basis. Near-equal values are never declared equal by a tolerance, and chance bounds use the same exact comparison. Refinement may be expensive for adversarial inputs; the language does not promise constant-time comparisons.

The `about` display, seeded `draw` sampler and `within_noise` statistical diagnostic are approximations. Fraction previews round directly from exact integers to six significant decimal digits with ties to even, without passing through binary floating point; very large and very small fractions remain printable. Real cyclotomic values are converted by refining rigorous intervals until both endpoints round to the same float; this avoids catastrophic cancellation in the conversion. The sampler still has finite random-bit resolution, and a five-standard-deviation diagnostic is not an exact binomial confidence calculation. Approximate simulation does not turn an exact model into an exact experimental prediction.

Native atomic polynomial kernels preserve exact fractions on their declared domain. Polynomial lists must be nonempty, exponential decay parameters must be strictly positive, and a multipole order must be a nonnegative integer. `poly_multipole` requires both polynomial densities to have zero coefficients below degree `k+1`; it rejects unsupported terms rather than silently truncating them. This restricted formula does not claim that every integral outside its domain diverges. Native/reference equivalence tests cover stated cases, not every possible input.

## Statements

One statement per line; `#` starts a comment.

| Statement | Meaning |
|---|---|
| `act click "a detector registers one event"` | a primitive act: done, never defined |
| `kind click_A = click` | a countable kind; must reach acts |
| `procedure tally = click, mark` | a way of counting; must reach `mark` (one mark per instance) |
| `scale ms = tick "one millisecond on the stopwatch"` | positions are counts of one step of an act |
| `relate 1000 ms = 1 s` | 1,000 steps of one scale pair off with 1 step of another |
| `relate 299792458 m = 1 s by light` | a gear between scales counted by different acts, through the act that links them; without `by`, refused |
| `bench desk simulated "…"` / `bench kitchen apparatus "…"` / `bench thorn2004 cited "…"` | where records are made: an apparatus, a simulation, or a published record with its source (observed, never certified) |
| `context window 0..10 s resolution 1 ms on desk procedure tally` | defaults for the lines that follow |
| `record a = tally click_A marks [500, 1500] ms` | marks written in the program |
| `record a = tally click_A file "data/a.txt" ms` | marks read from a file, one position per line |
| `record r = read_meter lux window 0..5 s file "data/r.txt" reading` | a display's reading: one number, or the lowest and highest seen; a count of the display's smallest step |
| `record r = pair_marks rod window 0..100 cm resolution 1 cm count 3` | a count without positions |
| `record z = tally click_A count 0 control a` | a zero, with its positive control |
| `expect guess = 8 click_A` | a prediction: theory |
| `let x = a + b` | names a value |
| `show expression` | prints a value with all its context |
| `claim id: expression == expression` (also `<=`, `>=`) | freezes a prediction in `program.ledger.json` |
| `certify id` | checks a frozen claim against records made since |
| `assess id: prediction against reference within tolerance scope "..." bounds enclosure assuming ["..."] unresolved []` | exact scalar discrepancy report with explicit premises; `coverage` and `unknown` are other bound interpretations |
| `require_accuracy id` | accepts only a within-tolerance report with declared enclosures and no declared unresolved issue; conditional acceptance, not a truth certificate |
| `setting trial = prepare` | a kind counted by acts you perform: exact, no window |
| `fn name(a, b)` … `return expr` … `end` | a function |
| `repeat k from 1 trial to 10 trial` … `end` | a loop; the bounds are settings of one kind (`below` excludes the end) |
| `for x in list` … `end` | a loop over a list |
| `if comparison` … `else` … `end` | a branch; an undecided comparison is an error, not a guess |
| `check comparison "what it shows"` | stops the program unless the answer is yes; prints ✓ and how it was decided |
| `import "file.tly"` | runs another file once, found beside the program |
| `import "walk"` | a bare name loads the standard library's `lib/walk.tly`: 2×2 matrices (`mm`), `overlap`, `empty(n)`, a balanced `splitter` |
| `import "atom"` | `lib/atom.tly`: exact integrals for atomic clouds P(r)·e^(−αr): polynomials as lists of fractions, kinetic energy, attraction, densities, `coulomb` and `multipole` repulsions, `orthogonal` clouds (Cramer's rule), `relativity` (Pauli). Inner loops run as native kernels (`poly_int`, `poly_mul`, `poly_multipole`), each with its Tally-written definition kept beside it and checked equal |
| `import "si"` | `lib/si.tly`: SI units as counts |
| `import "qed"` | `lib/qed.tly`: exact 4×4 amplitude coefficient matrices, Dirac gamma matrices, Minkowski contractions and slash operators; expects well-formed four-component inputs and the default phase ratchet. See `QED.md` for physical premises, reference units and limitations |
| `import "operational"` | `lib/operational.tly`: exact signed rational vector pairing, addition, scaling, matrix action, transpose, tensor coordinates, identity and rank. Shapes and fraction entries are checked; state/effect positivity and physical dynamics are separate model obligations. See `OPERATIONAL_MODELS.md` |
| `ratchet 128 step` | a finer phase ratchet: 128 steps a turn, counted in `step`; must come before any amplitude |
| `note "text"` | prints a line |

Expressions: a literal `8 click_A` (an expectation, using the context) or `3 trial` (a setting), names, `+ - * /`, `n times x` (repeat x exactly n times), `band(a, b)`, `ratio(a, b)`, `ladder x`, `x at 4 ms`, a length or duration `3 m` (a span, when `m` is a scale) and `x in ns` (shown in another related scale), comparisons `== != <= >= < >`, `and`, `or`, `not`, lists `[a, b]`, calls, and parentheses.

Lists compare item by item: `[a, b] == [c, d]`. **Balances** hold signed amounts without negative numbers: `balance(2 third, 0 third)` is +2 thirds, `balance(0 third, 1 third)` is −1 third; they add, repeat (`n times b`), multiply (minus times minus lands on the plus side), compare by cross-pairing, and `flip(b)` swaps the sides. **Exact fractions** are balances of kind part: `fraction(3 trial, 4 trial)` (from two exact counts, settings or records), divided with `share(x, y)`; with `factorial(n)` they compute the integrals of atomic clouds exactly. Real amplitudes (no sideways part) can be ordered with `<` and `>`. Other built-ins: `len`, `item(list, k)` (counted from 0), `ring_item(list, k)` (going round), `append`, `replace(list, k, value)`, `sum`, `choose(n, k)` and `assignments(items, places)` (counts of ways), `every(list of comparisons)`, and `possible(comparison)` (yes unless the records rule it out).

**Provenance follows control flow conservatively.** Branch assignments and returned values carry the condition's dependencies. Loop bounds, iterable lists, selected functions and list indices also contribute dependencies; a skipped assignment can leave a value dependent on its branch or loop condition. User-function arguments contribute through expressions and decisions that use them; merely passing an unused record argument does not make it evidence for a constant result. A skipped local assignment retains its control dependency locally without changing the global value it shadows. This is executable metadata tracking, not a proof of noninterference or a security sandbox.

Record and bench names are single-assignment within an interpreter run, including records waiting for a file. Reusing a name would let old values point to new evidence, so it is rejected. Use distinct names for distinct acquisitions. Every `draw` has its own immutable provenance ID even when its seed and returned count repeat; the internal simulated bench cannot be relabelled as apparatus or cited evidence. Acts, kinds, settings, procedures and scales likewise reject changed meanings or roles; exact duplicates are allowed. Ordinary value variables may still be reassigned.

Record files use UTF-8, with an optional initial byte-order mark. Each nonblank line contains one nonnegative integer written with ASCII digits; surrounding whitespace and `#` comments are allowed. Negative numbers, decimal readings, extra columns, trailing text and invalid UTF-8 are rejected with the file and line where available. A malformed reading is never silently shortened to a numeric prefix. Choose a finer declared scale to represent a decimal physical reading as an integer count.

**Ratios across kinds are laws.** A band is a part of one whole, so bands of different kinds never line up. A ratio counts how many times one count fits into another, so ratios of different kinds can be compared, and that comparison is a physical law: `ratio(t100 * t100, t25 * t25) == ratio(l100, l25)` says the square of a pendulum's period goes as its length. Ranged records can refute such a law, or leave it `possible`; they never prove it exact.

## Reference-relative accuracy (new in 0.3)

[ACCURACY.md](ACCURACY.md) defines native `assess` contracts for compatible count intervals, exact signed balances and same-origin scale quantities. Given prediction P and reference R, the interpreter encloses P−R and its absolute distance using exact rational arithmetic. The result is `within`, `outside` or `unresolved` relative to the supplied tolerance. A report is not an ordinary `Truth` and cannot be silently used by `check`, `if` or `certify`.

Every contract declares its scope, bound interpretation, assumptions and unresolved issues. `require_accuracy` requires the complete distance interval within tolerance, `bounds enclosure` and an empty unresolved list. `bounds coverage` is probabilistic interval information, not a hard guarantee; `bounds unknown` remains unsettled. Declaring no unresolved issue does not establish that the author found every issue.

`python3 tally.py --strict-accuracy file.tly` also gates the journal of every executed assessment and requires at least one. Rebinding a report variable cannot hide an earlier failure. The journal exists for one run; strict mode neither assesses every output automatically nor proves complete branch coverage or physical truth. Invalid CLI arguments exit nonzero without running the program.

Spans retain original scale/act identity through display conversion, scalar repetition and addition. A length converted through a light-travel relation cannot pass an accuracy comparison to a duration; mixed-origin sums are rejected. Related scales with the same origin act normalize exactly. Observed counts retain the existing kind and record-context checks, but matching labels do not establish identical apparatus or physical comparability.

Python embedding is a trusted boundary. `Balance` requires exact `int` or `Fraction` inputs, excluding Boolean and float values; malformed or unsupported assessment values are rejected. Snapshot values preserve declared numeric inputs and metadata, not independently authenticated physical facts.

## What a run looks like (`examples/numbers.tly`)

```
show a + b               → 16 click_A  [window 0–10 s; resolved to 1 ms; tally; on desk]  (derived from simulated records)
show (a + b) at 4 ms     → 8 click_A   [… resolved to 4 ms …]  — recounted at a coarser resolution
show ladder (a + b)      → 1 ms: 16 · 2 ms: 8 · … · 512 ms: 8 · 1024 ms: 1 …
                           resolution plateaus: 8 for 2 ms–512 ms; 1 for 1024 ms–8192 ms (presence only)
show p + q   (no marks)  → between 8 and 16 click_A — exact only where nothing merges
show a - later           → the first has 6 more click_A
show rods * later        → 6 (click_A × rod)  — each pair: one of each, taken together
show band(first4, a)     → 4 of 8 click_A: a band from none (0) to all (8) of that whole
show a / ten == first4 / five → yes: by cross pairs (the gear rule): 8×5 against 4×10
show a == guess          → yes: by pairing off  (theory)
```

The desk bench in this example is declared `simulated`, so every value says so.

`examples/rubber_band.tly` shows two bands: 20 of 40 mm released, and 130 of 180 coin·mm of energy released. It then refuses to equate them, by design: *part of mm_step and part of coin_mm do not line up: half of one is not half of the other.*

## What it refuses

These are the self-check's own rejections:

| Written | Tally says |
|---|---|
| `show 8` | 8 of what? A number needs a kind |
| `show 3 nothing` | "nothing" is not defined, so it reaches no act and means nothing |
| `kind lfhlaskfh = oafhuowihf` | "oafhuowihf" is not defined, so it reaches no act and means nothing |
| a declared word assigned a different definition | already declared with a different definition or role; its earlier meaning cannot be changed |
| `record z = … count 0` | 0 with no positive control: nothing shows it could have been marked |
| `show 0.5` | a decimal is not a count: write a count on a finer scale, or a band |
| `show -3 click_A` | a negative number is not a count: pair off two counts instead |
| `procedure look = compare` | leaves no mark per instance |
| `a + rods` | click_A and rod are different kinds |
| `x at 1 ms` after `x at 1 s` | cannot resolve finer than the record |
| a mark outside its window | refused |
| `band(h, a) == band(r1, r2)` | part of click_A and part of rod do not line up |
| `3 trial / 2 trial` | a part cannot exceed its whole; use `ratio` |
| `fn f(x)` with no `end` | a block was opened but never closed |
| `repeat k from 1 sixteenth to 3 trial` | the bounds must be counts of one kind |
| `arrow(1 trial)` | a phase is a count of sixteenth |
| `chance(2 trial times arrow(0 sixteenth))` | not a chance: more than all; use `weight` |
| `check 1 trial == 2 trial` | check failed |

## Certification, step by step (`examples/drips.tly`)

1. Write the complete program and prediction (`claim enough: drips >= 10 drip`) and run. The ledger freezes the expression, the entire program, recursive imports (including imports after the claim or in unexecuted branches), core/runtime Python sources, runtime configuration (including this interpreter's phase step count and kind), and fingerprints of existing referenced data files. The source passed to `run_text` must match these source files.
2. Do the experiment: count a tap's drips for 60 s, writing the second of each drop in `data/drips.txt`.
3. Run again. You get one of these:

| Result | When |
|---|---|
| certified on apparatus | prediction met; the unchanged program read new file contents from an apparatus-labelled bench |
| refuted on apparatus | prediction failed under those same conditions |
| waiting | the record file does not exist yet |
| frozen in this run | run again after recording |
| observed, not certified | inline data, unchanged data already present at freeze, or any cited record |
| undecided | ranges overlap |
| claim cannot be verified | source/configuration changed, executed source differs from disk, or the old ledger lacks a supported source snapshot |

A frozen claim cannot be edited indirectly by changing a variable, function, import or interpreter. The snapshot is deliberately conservative: even a comment-only source edit, a changed Python patch version or a relocated source path invalidates it. Use a **new program and ledger** to freeze a revised experiment, and preserve the old ledger as history. Ledgers from earlier Tally versions lack the required snapshot and must not be retrospectively upgraded to certified claims.

The host, ledger, clock, measurement files and bench labels are trusted. A changed data file may contain old measurements; Tally cannot establish measurement chronology or authenticity. `certified` therefore means the stated prospective software check passed under those trust assumptions, never that a physical law has been proven. A git commit provides a versioned record but is not independent laboratory certification. Mixed apparatus/simulation records are labelled as mixed, and cited measurements cannot acquire certification by being copied into a new file.

## Scales, units, and the quanta quantum physics keeps repeating

**Units are gears between counts.** Since 2019 every SI unit is defined by fixing a count, and `import "si"` writes those definitions as Tally scales:

| Unit | Defined by |
|---|---|
| the second | 9,192,631,770 cycles of caesium-133 |
| the metre | the distance light covers in 1/299,792,458 s; the gear is `relate 299792458 m = 1 s by light` |

The library adds prefixes from fm to km and from fs to days. A length or duration is then an exact value: `3 m`, `10 ns`, `1 day`. These compare exactly (`check 3 m > 10 ns`), add, repeat (`4 times 1 s`), and show in any related scale (`show 1 ns in cm` gives "exactly 299792458 nm; about 30 cm"). A display leads with "about" when the exact value is not a whole count.

Lengths and times can be compared only because a gear links them, and Tally insists that the gear be named. Linking metres and seconds without saying `by light` is refused, because a ruler and a clock are different acts. `examples/units.tly` runs these checks and calibrates the walk of programs 11 to 23: at one tick per femtosecond, one site is exactly 299,792,458 fm, about 300 nm.

**The pattern in quantum values.** Nearly every number that recurs in quantum physics is a count of one of a handful of quanta, or the cos² of a whole number of phase steps:

| What | Counted in | Where Tally meets it |
|---|---|---|
| phase | steps of a turn (16 to a turn by default) | every amplitude |
| chance | cos² of a whole number of steps, or a power of ½ from splitters | printed by name: (2 + √2)/4 shows as "= cos² 22.5°" |
| charge | whole units of e | program 22: the Aharonov–Bohm period counts it |
| magnetic flux | turns of link phase; one whole turn is h/e, and h/2e for charge-2 carriers (the flux quantum of superconducting rings) | program 22 |
| angular momentum | half-units of ħ: spin ½ for the walk's quanta, helicity ±1 for photons; a polarization pattern repeats every half turn ÷ helicity | programs 05 and 18 |
| energy of light | quanta hν of a mode, counted n = 0, 1, 2, … | programs 08 and 24 |
| speed | one site per tick, the speed of light | programs 11 and 14; `examples/units.tly` |

h and c are gears, fixed by definition. What no current theory turns into counts is a short list of pure numbers: the fine-structure constant (about 1/137) and the ratios of particle masses.

## How it differs from ordinary numbers

| Ordinary arithmetic | Tally |
|---|---|
| `8` is complete | `8` is an error: 8 of what? |
| `0` is a number like the others | a zero is a record with a positive control |
| `0.5` | a band, `1 of 2 <kind>`, or a count on a finer scale |
| `-3` | a direction: "the second has 3 more" |
| `8 + 8 = 16` | 16 where nothing merges; a recount where marks coincide; a range without marks |
| ½ of a length = ½ of an energy | refused: bands of different kinds do not line up |
| a statement is true or false | it is a record, derived from records, theory, certified or refuted |

**Where ordinary arithmetic is still exact:** inside one kind, at one resolution, where nothing merges. Tally is built to say where that is, and to refuse numbers that don't.

## Limits

- **One ratchet per run.** A program may choose a finer ratchet (`ratchet 128 step`), but arrows on two ratchets never mix. Multiplying amplitudes costs the square of the ratchet's size.
- **Some names are taken.** `ladder` builds a scale ladder, so it cannot name a variable.
- **The interpreter walks the syntax tree.** Scanning 4096 polarizer settings takes about 2 seconds.
- **The exact number domain is restricted.** Integers, rational balances and power-of-two cyclotomic amplitudes are supported (including irrational values such as √2). Arbitrary real numbers and general transcendental functions are not exact language primitives.
- **Merging marks closer than the resolution is one detector model** (dead time). Other instruments merge differently.
- **The interpreter itself runs on Python's ordinary integers and fractions.** Tally restricts what a *program* may write, not what the machine does underneath.
- **Kind names are trusted.** Tally cannot check that two records called `click_A` came from the same detector; the bench and procedure fields carry that information.
- **The grounding rule is a design choice.** It cannot itself be grounded in an act.

## Run

```sh
python3 verify.py                             # regressions, self-check and all physics programs
python3 tally.py --check                       # the language's core self-check
python3 tally.py examples/numbers.tly          # the tour
python3 tally.py examples/rubber_band.tly      # stops at the last line, by design
python3 tally.py examples/drips.tly            # freeze your prediction; record; run again
python3 tally.py --test                        # all physics programs; reports the current check count
python3 tally.py examples/malus_kitchen.tly    # a photon law you can certify in a kitchen
python3 tally.py examples/units.tly            # SI units as counts; light delays; calibrating the walk
python3 tally.py                               # interactive: type statements, blocks run when closed with end
```
