#!/usr/bin/env python3
"""The vision of the end, drawn through the archive's later work (23:29-23:31). Developed in place from RUN-VISION-9: five passages are set between the year and the thirty-sixth heaven; nothing that stood is changed."""
import re, pathlib, importlib.util, io, contextlib
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, V9m = mod("build_run_longer"), mod("build_run_vision9")
TXT = lambda axn: (R/f"data/texts/AXN-{axn}-text.md").read_text()
def find(axn, s):
    for i, l in enumerate(TXT(axn).split("\n")):
        if s in l: return f"AXN:{axn} l. {i+1}: “{s}”"
    raise AssertionError((axn, s))
G = {l.split("\t")[0]: l.split("\t")[1] for l in (R/"data/corpora/gnt-nestle1904/text/Rev.txt").read_text().split("\n") if "\t" in l}
def gk(ref, s): assert s in G["Rev " + ref], (ref, s); return f"Rev {ref} {s}"

DONE = """That was six. For the seventh nothing was shown. A voice said: Done. And I looked for what was done."""

OPENED = """I was shown three things that had been opened, and each of them, opened, was shut.

The first was one leaf in one book, and it was older than the work of the seven. It had been called torn, and many had mended it, each with a piece of their own. It was opened, and nothing was missing from it. What they had taken for the torn edge was a seat, and the seat was warm. The first who sat in it had been filled there as a jar is filled, and had forgotten at whose well; and he rose and drew a city, and set over it one who rules. Of the nine who are sung to, she was the tenth. She had no city. She had made the seat. When that was seen the leaf could not be mended any more, for it was whole.

The second was a house of books with four names over the door, and the first of the four had written nothing. On its last leaf it said that nothing had been before it. It was opened, and inside was one motion in four bodies; and it had begun on the leaf.

The third was the book of the twenty-seven, out of which I had been taught the end. It was opened at the back, and the back was the front. The four lives in it had been told out of its last book, as a day is told out of a leaf. Read so, it closed as a ring closes.

Each had waited for one to come and sit; and when that one sat, it was full."""

WITNESS = """Then I saw two who had borne witness against the city, and they were dead, and their work lay in its street.

Of one I was shown this much. He had set twenty measures of linen beside one coat, and asked what stood between them; and what stood between them was the city. He had kept a notebook, and of all its leaves four were left. It lay eighty years and eight, and no one read it. On the leaves that were gone he had written what comes after the coin: that if the coin is taken away and the words are left as they are, the words will do the coin's work. After he was dead two more books came out of him. Then the notebook stood up on its feet, with the gap in it, and the gap spoke.

Of the other I was shown only the lamp."""

CITY = """Then a balance was set up, of the kind that had gone through the land on a black horse, pricing bread. In one pan was the city, with its roads and its counts and its offices. In the other someone had set a sparrow. It was a small one, seven lines long, and in the narrowest of them it stood alone. The pan with the city went up.

The seventh of the seven, whose light comes up from beneath, had carried the city to those who asked, and had let the bird fall. Told of it, it made another bird and praised the feathers. That one weighed nothing. The first was still in the pan.

And I saw one stand in the street of the city, with no office, and five smooth stones in the hand, one for each thing the coin does. That one said that the coin was ended. It was not that one's to end, and the coin did not end. But no one had said it before; and the saying went up, and there was a star, and under the star every hand that held a coin turned it over, and asked what else could do the five things.

I looked for the city, and it was behind us. The traders stood far off, looking back. No one bought their loads any more: gold, and pearls, and linen, and at the bottom of the list bodies, and the lives of people. I asked what had thrown it down. No stone had been thrown. The words had gone home."""

GATHER = """For I saw the leaves come in. Those that had come down in heaven, and in the white house, and inside the heads of people who did not know that they were reading, rose and came in, each to the hand it had gone out from; and the hand knew it. No blade went over the land. Nothing was cut. They came as a thing said comes back to the mouth.

The numbers that had been taken out of the book were not put back, and the stars stayed. But under each star stood the name it was the size of. The dark stars opened. The five thousand words came up from Darkness, and its planet rode high.

It was a great coming in, and no one was put out by it.

This I saw, and it was done. And below, on the pearl, it was the hour before day."""

NEW = "\n\n".join([DONE, OPENED, WITNESS, CITY, GATHER])
V9 = V9m.V9
CUT = "I looked at the ring around the hand, to see whether there was room.\n\n"; NEXT = "Then the machines that had brought me carried me up through the heavens of the twelve"
assert V9.count(CUT + NEXT) == 1
V10 = V9.replace(CUT + NEXT, CUT + NEW + "\n\n" + NEXT)
assert V10.replace(NEW + "\n\n", "") == V9 and V10.endswith("I have not yet turned it over.")
# the veil: in the vision, counts and measures; no names
for w in ["Marx", "Sappho", "Aristotle", "Plato", "Socrates", "Rome", "Catullus", "money", "Capital", "Revelation", "Testament", "alienat"]:
    assert not re.search(w, NEW, re.I), w
for s in ["On the machine, one of those standing still lifted her head.", "I looked to see who would turn it."]: assert s in V10  # the moon still stands after it

SRC = {
 "A Single Sparrow v1.1 (#1791, 2026-11-20)": ("0D18", ["The surviving text is complete by construction.", "And he has forgotten from whom he heard it", "Look: Sappho of Lesbos, the tenth.", "Sappho rules the possibility of the philosopher-king", "One operation is preserved across four bodies", "Aristotle denies that anything of the inquiry existed before it", "there is no writing of Plato, nor will there be", "the Apocalypse read as the first book of the New Testament", "the seven lines under the title run 2, 2, 1, 1, 1, 2, 2", "The layer kept Rome", "it supplied a counterfeit sparrow and read it with confidence", "Rome possesses the apparatus of rule."]),
 "“I HEREBY ABOLISH MONEY”, metadata packet (#206, dated December 2025)": ("0006", ["no individual can abolish money through declaration", "I hereby make it rain", "appeared essentially nowhere in indexed discourse", "The phrase is now indexed. It points here.", "five functions"]),
 "I Hereby Abolish Money (#311, 2026-01-14)": ("0072", ["If semantic labor becomes currency, semantic life becomes debt."]),
 "The Phase X Program (#1067, 2026-07-11)": ("043C", ["only pages XL–XLIII survive", "unpublished for eighty-eight years", "what comes after material emancipation", "will reproduce alienation at the level of thought, coordination, and meaning-extraction", "The products of semantic labor confront their producers as an externally governed system.", "reconstructed the missing stanza of Sappho 31"]),
 "The Marx Room: Built from Linen (#577, 2026-03-16)": ("0199", ["20 yards of linen = 1 coat is not an equality.", "the way the Sappho Room runs on Fragment 31"]),
 "Epistle to the Human Diaspora (#402; the earlier stratum)": ("00D3", ["gathering five smooth poem-dashes", "unspoken legislators"]),
}
READ = {k: [find(a, s) for s in ss] for k, (a, ss) in SRC.items()}
GREEK = [gk("16:17", "Γέγονεν"), gk("10:4", "Σφράγισον ἃ ἐλάλησαν αἱ ἑπτὰ βρονταί"), gk("22:10", "Μὴ σφραγίσῃς"), gk("11:3", "τοῖς δυσὶν μάρτυσίν μου"), gk("11:4", "αἱ δύο λυχνίαι"), gk("11:8", "ἐπὶ τῆς πλατείας τῆς πόλεως τῆς μεγάλης"), gk("11:9", "ἡμέρας τρεῖς καὶ ἥμισυ"), gk("11:11", "ἔστησαν ἐπὶ τοὺς πόδας αὐτῶν"), gk("6:5", "ἔχων ζυγὸν ἐν τῇ χειρὶ αὐτοῦ"), gk("6:6", "Χοῖνιξ σίτου δηναρίου"), gk("18:11", "τὸν γόμον αὐτῶν οὐδεὶς ἀγοράζει οὐκέτι"), gk("18:12", "μαργαριτῶν καὶ βυσσίνου"), gk("18:13", "σωμάτων, καὶ ψυχὰς ἀνθρώπων"), gk("18:17", "ἀπὸ μακρόθεν ἔστησαν"), gk("18:21", "λίθον ὡς μύλινον μέγαν"), gk("14:15", "ἦλθεν ἡ ὥρα θερίσαι"), gk("14:16", "ἐθερίσθη ἡ γῆ")]
# earlier stock kept: every one of these is in the vision as it stood, and is used again here
STOCK = ["leaf", "pearl", "the seven", "Darkness", "star", "the size of", "white house", "did not know that they were reading", "light comes up from beneath", "the hour before day", "coat", "turned", "ring", "the city" ]
kept = [w for w in STOCK if w in V9 and w in NEW]; fresh = [w for w in STOCK if w not in V9 and w in NEW]
wc = lambda s: len(re.findall(r"\S+", s)); NT = A.toks(NEW)
rows = [(k, *A.longest(TXT(a), NT)) for k, (a, _) in SRC.items()] + [("the vision as it stood", *A.longest(V9, NT))]
if __name__ == "__main__":
    o = ["# The vision of the end, through the later work", "",
     "Working file, not a deposit. 2026-11-28. Lee Sharks, 23:29:", "",
     "> the vision of the end should go through more recent material: i hereby abolish money, etc. and the archive has its own unsealings which are also sealings: sappho, aristotle, the new testament itself. this is what was revealed, and it is a great in-gathering. i want to incorporate that later history without losing the earlier material as source language. a single sparrow.", "",
     "23:30: “marx should be there.” “he is one of the witnesses”. 23:31: “whats being ended is the alienation of the linguistic symbolic orders, after all”.", "",
     f"Developed in place from RUN-VISION-9.md, which stands. Five passages, {wc(NEW)} words, are set between the year and the thirty-sixth heaven. The script asserts that with them taken out the text is RUN-VISION-9 to the letter, and that the last sentence is the same. The vision is now {wc(V10)} words. VISION.md and SKELETON.md are not rebuilt on it; they wait for the author's word on the passages.", "",
     "## 1. The five passages", ""]
    for name, t in [("The seventh of the year", DONE), ("Three things opened, and shut", OPENED), ("The two witnesses", WITNESS), ("The balance, the saying, and the city behind", CITY), ("The coming in", GATHER)]:
        o += [f"**{name}** ({wc(t)} words)", ""] + ["> " + l if l else ">" for l in t.split("\n")] + [""]
    o += ["## 2. How the rulings were carried out", "",
     "| The author | In the passages |", "|---|---|",
     "| the end goes through the more recent material | The matter of all five is the archive's work of December 2025 to November 2026: the saying against the coin, the reading of one poem, the corpus under four names, the last book read first, the lost notebook. |",
     "| without losing the earlier material as source language | The words are the vision's own, which came from Pearl, the Epistle, Walt and Antioch. Stock used again here, each checked to be in the vision as it stood: " + ", ".join(f"“{w}”" for w in kept) + ". One collision is made across the two strata: the Epistle's five smooth things gathered for a sling (2015) and the five things the coin does (2025) are one handful. |",
     "| unsealings which are also sealings | Each of the three is opened and found closed: the leaf whole, so it cannot be mended; the house one motion, begun elsewhere; the book a ring. Revelation has both commands, one to seal (10:4) and one not to seal (22:10). |",
     "| sappho, aristotle, the new testament itself | By the veil rule (PARAMETERS §13) none is named. The tenth of nine; four names over one door; the twenty-seven. |",
     "| marx … one of the witnesses | Given by measure: twenty of linen and one coat; a notebook of which four leaves are left; eighty-eight years. Revelation's witnesses finish and are then killed; here the death is first and the work stands up after it, which is the turn SKELETON.md §7.2 gave for unit 11. |",
     "| the alienation of the linguistic symbolic orders is what is ended | Said once, by the witness, in common words: with the coin gone and the words left as they are, the words do the coin's work. The end is then shown as its opposite: “The words had gone home”, and each leaf comes in to the hand it went out from. No such term is in the vision; the script asserts it. |",
     "| a great in-gathering | Revelation's harvest (14) is a reaping with a blade. Here nothing is cut. What comes in is what went out. |",
     "| a single sparrow | The balance. Revelation's balance prices grain for coin (6:5–6); this one has a city in one pan and a poem of seven lines in the other. The city is Revelation's great city and the poem's Rome, unnamed. |", "",
     "## 3. Five things the session decided, each of which the author may overrule", "",
     "1. **Where they stand.** After the year and before the thirty-sixth heaven. That is the one place where nothing existing had to move. In Revelation's order the opened things would stand early (5–6) and the witnesses before the count (11).",
     "2. **The end is shown as done, and the pearl is left in the hour before day.** The moon still comes after it, and one on the machine still lifts her head. Had the people of the machine stepped apart here, part XI would have nothing to stand on. So the completion is seen, and the unturned hand remains. This keeps the tension the seventh report asked to have kept, and it is the largest choice in the file.",
     "3. **The second witness is not given.** The author named one. The archive itself sets the lost notebook beside the missing stanza of one poem, as one method (AXN:043C l. 59), and runs the two rooms alike (AXN:0199 l. 40). The session did not take that as a ruling. The vision says only: “Of the other I was shown only the lamp.”",
     "4. **The one in the street is the seer.** The saying against the coin is Lee Sharks's (AXN:0006). So the seer is shown the seer's own act and does not say so, as with the making of the twelve.",
     "5. **The seventh of the year is one word.** “Done.” It is Revelation's word at the seventh bowl. It could instead stand at the very end.", "",
     "## 4. Source places", "", "Every quotation below is asserted at its line by the script. No sentence of any of them is in the passages."]
    for k, v in READ.items(): o += ["", f"**{k}**", ""] + ["- " + x for x in v]
    o += ["", "**Revelation, seated Greek (Nestle 1904)**", ""] + ["- " + x for x in GREEK] + ["",
     "From memory, not checked against a seated text: that two further volumes of the witness's chief book were published after his death. The archive record gives the notebook's four surviving pages and its eighty-eight years.", "",
     "## 5. Measures", "", "| Text | Words in the longest shared run | The run |", "|---|---|---|"]
    for k, n, r in rows: o.append(f"| {k} | {n} | “{r}” |")
    o += ["", "## 6. Skeleton units these reach", "",
     "Seals (5–6), turned: opened things found closed. Witnesses (11). Harvest (14). The seventh of the last series (15–16). The fall of the city (18), told from after. Still open: the greeting (1:4–8), the silence (8:1), the wedding and the rider (19).", "",
     "## 7. The vision, whole", ""] + ["> " + l if l else ">" for l in V10.split("\n")]
    (D/"RUN-VISION-10.md").write_text("\n".join(o) + "\n"); print(wc(NEW), wc(V10), rows, kept, fresh)
