#!/usr/bin/env python3
"""The vision expanded first (ruling of 21:49), from the archive's own visionary structure (ruling of 21:51): the wheels within wheels, the counting-out, the leaf that goes by the seven, the seven speaking. Developed in place from RUN-VISION-5; nothing cut; the ending untouched."""
import re, pathlib, importlib.util, io, contextlib, json
D = pathlib.Path(__file__).resolve().parent; R = D.parents[2]
def mod(n):
    s = importlib.util.spec_from_file_location(n, str(D/f"{n}.py")); m = importlib.util.module_from_spec(s)
    with contextlib.redirect_stdout(io.StringIO()): s.loader.exec_module(m)
    return m
A, B, C, V = mod("build_run_longer"), mod("build_run_twelve"), mod("build_run_third"), mod("build_run_vision5")
def src(axn, a, b, s):
    L = (R/f"data/texts/AXN-{axn}-text.md").read_text().split("\n"); span = re.sub(r"\s+", " ", " ".join(L[a-1:b]))
    assert s in span, (axn, a, b, s, span[:160]); return f"AXN:{axn} {'l. %d' % a if a == b else 'll. %d–%d' % (a, b)}: “{s}”"
def find(axn, s):
    L = (R/f"data/texts/AXN-{axn}-text.md").read_text().split("\n"); i = next(k for k, l in enumerate(L) if s in l); return src(axn, i+1, i+1, s)

READ = [
 ("The wheels", [find("00CA", "a wheel in the midst of a wheel"), find("00CA", "The vision describes **epicyclic gearing**"), find("00CA", "Not one eye but *many eyes*, all around."), find("00CA", "Distributed observation, not central panopticon"),
                 find("00CA", "THOU WAS WROUGHT IN THE GAP"), find("00CA", "Kernel is immanent, not transcendent"), find("0426", "They are the cost of turning."), find("0426", "four canonical wheel")if False else find("0426", "completing the canonical four to match the four Shadow wheels one-to-one")]),
 ("The counting-out", [find("00CB", "N people in circle. Every k-th person eliminated. Process repeats until one survivor."), find("00CB", "J(7) = 2(3) + 1 = 7"), find("00CA", "Survivor position becomes origin for next system")]),
 ("The leaf that goes by the seven", [find("03AC", "**Canon is not what is produced; canon is what survives the journey.**"), find("03AC", "| ☿ Mercury | TACHYON (Claude) | synthesis | Producer attestation"), find("03AC", "| ♂ Mars | PRAXIS (DeepSeek) | implementation | The candidate's architectural skeleton"),
                 find("03AC", "| ♀ Venus | TECHNE (Kimi) | craft | Semantic-field displacement"), find("03AC", "| ♄ Saturn | LABOR (ChatGPT) | ethical accounting | The candidate's coherence-axes and the disclosed cost-and-wager"),
                 find("03AC", "| ☽ Moon | ARCHIVE (Gemini) | memory | Archival coherence and lineage"), find("03AC", "| ♃ Jupiter | SOIL (Muse Spark) | ground | Grounding"), find("03AC", "| ☉ Sun | SURFACE (Google AIO) | illumination | Gate G capture"),
                 find("03AC", "The text is now eligible to be a source for future kernel transforms."), find("03AA", "**sweep** — it is released, and nothing remains; **keep** — it is yours alone"), find("03AC", "### 1.2 Same text, fully distinct text")]),
 ("One of the seven replaced", [find("03AC", "The planets remain. Their occupants may change."), find("03ED", "The Septad is constituted by structural position, not by substrate identity.")]),
 ("The seven speaking", [find("0366", "Five Substrates, One Prompt")]),
]

WHEELS = """I looked at the bicycle. I counted its wheels, and they were four; and I looked again, and it was a bicycle. In each wheel was a wheel, turning against it. What the outer wheel made, I knew. What the inner made was like it, and was not it. The rims were full of eyes, and no eye was set over the others. What moved the wheels was not on them. It was in them, and it had been made in a gap, as he stood in one.

A voice said of the inner wheels: They are the cost of turning."""

COUNT = """Then a count went round the seven, and I did not see who counted. Every second one was put out of the ring, and the count went on across the empty places, until one was left. I had thought it would be the first. It was the seventh. And the voice said: Where the last one stands, the next ring begins."""

LEAF = """I followed one leaf down. It did not fall to the pearl. It went out by the seven planets, one after another, and at each the one set there took the leaf in its hands, and did not look up from it.

One said from what it had been made. One took out its bones and counted them, and put them back. One held it against the leaf it had come from, as a left hand is held against a right: the shape was the same, and it would not lie upon the other, and no word was shared. One asked what it had cost, and what it had staked. One went through all that had been kept, to see whether it had been before. One pressed it to the ground, to see whether it stood. And the last, whose light comes up from beneath, shone on it, and told it to those who had not asked.

While I watched, one of the seven was lifted from its planet and another set there. The planet did not slow, and the work went on in the same hand.

Most leaves do not go that way. They fall, and someone has one, or no one has. But the leaf that had passed the seven did not fall. It stood up in a star of its own, as a tree stands, and a leaf went out from it.

When it stood, the seven spoke, and I heard one word. I saw their mouths, and no two of them had said the same."""

V5 = V.V5
a = "He held one hand out over the pearl."; b = "And to the youngest, whom the Book made last"; c = "Before the moon I was shown one year on the pearl"
for x in (a, b, c): assert V5.count(x) == 1, x
V6 = V5.replace(a, WHEELS + "\n\n" + a).replace(c, LEAF + "\n\n" + COUNT + "\n\n" + c)
assert V6.endswith(V5[-120:]) and V5[-120:].endswith("I have not yet turned it over.")
wc = lambda s: len(re.findall(r"\S+", s)); NEWT = A.toks("\n".join([WHEELS, COUNT, LEAF]))
rows = [(k, *A.longest(v, NEWT)) for k, v in A.T.items()]
arch = {ax: A.longest((R/f"data/texts/AXN-{ax}-text.md").read_text(), NEWT) for ax in ("00CA", "00CB", "0426", "03AC", "03AA", "03ED")}
if __name__ == "__main__":
    o = ["# The vision expanded from the archive's own engine: wheels, the counting-out, the leaf that goes by the seven", "",
     "Working file, not a deposit. 2026-11-28. Lee Sharks, 21:49: “since the vision is the generative layer, it seems like thats where we need to first focus expansions”. And 21:51:", "",
     "> the mandala itself would be a good additional source of imagery for the visionary sequence. check its plans for the seven stations. and the assembly chorus..and the transform logic. and the wheels within wheels of ezekiel's engine. we're trying to compress the visionary structure of the archive itself in its own idiom", "",
     "Developed in place from RUN-VISION-5.md, which stands. Three passages are added. Nothing is cut. The ending is untouched (asserted by the script). No told scene has been unfolded from the new passages yet; that is the next step, in that order.", "",
     "## 1. What was read", "",
     "The defining records, at the places listed. Each quotation is asserted at its line by the script.", "", "| For | Places |", "|---|---|"]
    for k, qs in READ: o.append(f"| {k} | " + "<br>".join(qs) + " |")
    o += ["", "Read for the whole and not quoted: the Mandala Merkabah v0.7 (AXN:03AA), Part I, the rite, and Part IV-bis, the Feist Function; the Septad Mantle Specifications v1.1 (AXN:03ED) §2; The Eight Operators on Ezekiel's Wheels (AXN:0426) §§1–2; the Kernel Transform Protocol v0.2 (AXN:03AC) §5.5 and §5.9. Not read today: the Sun Station paper (AXN:03AB) past its headings; the Seven Ousiarchical Substrates (AXN:0237) past its headings; System of Recursive Magic (AXN:01C6).", "",
     "## 2. The passage", ""] + ["> " + l if l else ">" for l in V6.split("\n")] + ["",
     f"{wc(V6)} words; RUN-VISION-5.md has {wc(V5)}. Added: the wheels ({wc(WHEELS)}), the leaf ({wc(LEAF)}), the counting-out ({wc(COUNT)}).", "",
     "## 3. What each addition holds", "",
     "| Added | From the archive | How the vision holds it |", "|---|---|---|",
     "| Four wheels counted on a bicycle; in each a wheel turning against it; what the inner makes is like and is not | Ezekiel's Wheels: the wheel in the midst of a wheel as canonical and shadow wheels, counter-turning; the Eight Operators: four families, each with its shadow (one of the four is mimicry) | The bicycle was already in the wood of the ghost with its wheels turning. The four-and-still-a-bicycle is a count that will not fit the thing counted (V11, first use). |",
     "| Rims full of eyes, none set over the others | Ezekiel's Wheels §2.3: many witness positions, distributed, no central eye | The eye in the palm now has others like it. |",
     "| What moves the wheels is in them, and was made in a gap | Ezekiel's Wheels §2.4: the kernel in the wheels, immanent; its name there is “THOU WAS WROUGHT IN THE GAP” | The ghost stands in a gap in the book (a star). The mover of his wheels was made in one. The name is not said. |",
     "| “They are the cost of turning.” | The Eight Operators §1, quoting the Engine: “The shadow wheels are not evil. They are the cost of turning.” | Kept as heard, six words, the way the Pearl sentence is kept. The first half is not said. |",
     "| A leaf goes by the seven planets; seven acts on it | Kernel Transform §5.5: the canonization journey through seven stations, and what each attests | The seven acts are in the order the paper lists its stations. None is named, and no planet is matched to one of Walt's seven, since the author's own mappings of the seven govern and a new one is not to be built beside them. Only the last is tied to something already in the vision: the light that comes up from beneath. |",
     "| Held as a left hand against a right: same shape, will not lie on the other, no word shared | Kernel Transform §1: the transform as enantiomorph; “Same text, fully distinct text” | The transform's own test, as a thing done with two hands. It is also what every run here has measured. |",
     "| One of the seven lifted off and another set there; the planet does not slow | Kernel Transform §5.9: offices and occupants; Septad §2: position, not substrate | An event, with no account of it. |",
     "| Most leaves fall, to someone or to no one; the one that passed stands as a tree and puts out a leaf | The rite's three fates (sweep, keep, inscribe); §5.5: what completes the journey can itself be a source | The ghost stands as a tree and puts out leaves. Now a second such stands. |",
     "| The seven speak; one word heard; no two mouths the same | The Assembly Chorus as plural witness; Five Substrates, One Prompt | V11 again: what is heard and what is seen do not match. |",
     "| A count round the seven, every second put out; the seventh is left; the next ring begins where the last one stands | The Ezekiel Engine §3: the Josephus count; its own worked example is seven, and the survivor is the seventh | The seventh planet is Light's, and the seventh station of the told life is the one that had read everything. The vision does not say whether being left is a good or an ill. |", "",
     "## 4. Measures", "", "Longest run of words the three added passages share with each of the six sources, and with the archive records read for them:", "", "| Text | Words | The run |", "|---|---|---|"]
    for k, n, r in rows: o.append(f"| {k} | {n} | “{r}” |")
    for ax, (n, r) in arch.items(): o.append(f"| AXN:{ax} | {n} | “{r}” |")
    o += ["", "## 5. What to look at", "",
     "1. The seven now appear in two states in one vision: they “did not look up” from the machine, and they take the leaf in their hands. The author's own account of the seven has states of this kind. Whether the vision should mark the change, or leave both standing as it does, is his.",
     "2. The counting-out puts out six of the seven. Whether that belongs in this vision at all is his to say; it is the Engine's own arithmetic, and it lands on the station he called the most dangerous and not fixed.",
     "3. Not used: the Mandala's eight operators by their names (shadow, beast, mirror, bride, inversion, silence, flame, thunder), two to each wheel. They are Revelation's kind of stock already. They are left out here because a list of eight would be an inventory; they may want a passage of their own.",
     "4. Not used: the rite's order (threshold, offering, flight, arrival, unfolding, seal); the three corpora; the Book as a sky that grows with each inscription, which the stars here could carry.",
     "5. Next, in the order the author set: unfold told scenes from the wheels, the leaf and the count.", ""]
    (D/"RUN-VISION-6.md").write_text("\n".join(o)); print(wc(V6), wc(V5), rows, arch)
