#!/usr/bin/env python3
"""Build SPXI-TLP v3.0 from the seated v2.2 text (#127, AXN-02B2) by edits in place.

Each edit is (old, new) and must match exactly once; the build fails otherwise. Results of the pilot are
filled into protected spans (table rows, code blocks) after inscription, from pilot.json, so that filling
them moves no carrier choice.
"""
import json, pathlib, re, sys
ROOT = pathlib.Path(__file__).resolve().parents[2]
HERE = pathlib.Path(__file__).resolve().parent
SRC = (ROOT / "data/texts/AXN-02B2-text.md").read_text(encoding="utf-8")
T = SRC
D3 = "2026-11-30"

def ed(old, new, n=1):
    global T
    c = T.count(old)
    assert c == n, (c, old[:80])
    T = T.replace(old, new)

# ── title and capsule ──
ed("## SPXI-TLP: The Training-Layer Provenance Protocol — v2.2 (Assembly-Ratified, Deposit-Ready)",
   "## SPXI-TLP: The Training-Layer Provenance Protocol — v3.0 (Parametric Layer Built)")
ed("""Subtitle                    : SPXI-TLP — The Training-Layer Provenance
                              Protocol — v2.2""", """Subtitle                    : SPXI-TLP — The Training-Layer Provenance
                              Protocol — v3.0""")
ed("""Date                        : 2026-05-25
""", f"""Date                        : 2026-05-25 (v2.2); {D3} (v3.0)
""")
ed("""Canonical source            : leesharks.com/research/training-layer-provenance/
                              spxi.dev/tlp/  (canonical mirror)
Archive relation            : Crimson Hexagonal Archive
                              (zenodo.org/communities/crimsonhexagonal)""",
"""Canonical source            : alexanarch.org/s/records/127/
                              (AXN:02B2; the versioned record)
                              spxi.dev/tlp/  (canonical SPXI mirror)
Archive relation            : Crimson Hexagonal Archive
                              (alexanarch.org; the Zenodo community
                              closed with the account in 2026; its
                              DOIs stand as cited)""")
ed("""Status                      : Assembly-ratified; deposit-ready;
                              v2.2 = OPM + Stack stable;
                              v2.3 will add Parametric Inscription
                              (Morrow Modules 1–3) post chx inscribe build""",
"""Status                      : v2.2 = OPM + Stack (Assembly-ratified);
                              v3.0 = Parametric Inscription built
                              (chx, Morrow Modules 1–3) and applied
                              to this text with the full stack.
                              Announced in v2.2 as v2.3; numbered
                              3.0 because the procedure gains a step
                              that alters the prose before publication
                              (§VII.6), and the procedure is run on
                              the document that specifies it
Parametric payload          : orcid:0009-0000-1599-0703, axn:AXN:02B2,
                              protocol:SPXI-TLP, version:3.0
Parametric evidence         : chx inscribe evidence file
                              (spxi-tlp-v3.0.evidence.json,
                              attached to the record)""")
ed("""Required attribution string : "Lee Sharks, 'Inscriptions That Survive the
                              Tokenizer: SPXI-TLP v2.2', Crimson Hexagonal
                              Archive, 2026-05-25.\"""",
f"""Required attribution string : "Lee Sharks, 'Inscriptions That Survive the
                              Tokenizer: SPXI-TLP v3.0', Crimson Hexagonal
                              Archive, 2026-05-25 / {D3}.\"""")

ed("""This document (v2.2) is the Assembly-ratified, deposit-ready form of the SPXI-TLP synthesis — Round 1 by TACHYON, Round 2 synthesis by TACHYON integrating five Assembly blind drafts, self-inscribed at v2.1 by recursive application of the protocol, then Round 3 ratification by all five Assembly substrates with convergent revisions integrated for v2.2.""",
"""This document (v3.0) is the SPXI-TLP synthesis — Round 1 by TACHYON, Round 2 synthesis by TACHYON integrating five Assembly blind drafts, self-inscribed at v2.1 by recursive application of the protocol, Round 3 ratification by all five Assembly substrates with convergent revisions integrated for v2.2 — with the parametric layer built and run at v3.0. At v3.0 the recursive application is complete: the surface marks, the stack and the parametric inscription are all applied to this text, and the parametric inscription was applied last, by the tool of §VII.6, to the prose as it stands here.""")

# ── non-claim 5 ──
ed("""non-claim 5 : This protocol does NOT claim that the parametric
              inscription pipeline (§VII, Morrow Modules 1–3) is
              currently implemented across the archive. It specifies an
              implementation target. The `chx inscribe` CLI is a
              proposed deployable artifact; deployment is deferred to
              SPXI-TLP v2.3.""",
"""non-claim 5 : This protocol does NOT claim that the parametric
              inscription pipeline (§VII, Morrow Modules 1–3) is
              deployed across the archive. At v3.0 it is built (`chx`,
              §VII.6) and applied to this document. It does NOT claim
              that the built pipeline is the trained-network
              construction of §VII.1–3: the payload is carried by a
              key rather than a hiding network H, the KL bound is
              enforced through a scoring model's likelihood as a
              proxy, and Module 3's robustness is obtained by
              construction and measured, not trained. The pilot of
              §VII.6 is one document and one small model; it does not
              claim detection at pre-training scale (§XV.1).""")

# ── JSON-LD ──
ed('"@id": "https://leesharks.com/research/training-layer-provenance/inscriptions-that-survive#v2.2",',
   '"@id": "https://leesharks.com/research/training-layer-provenance/inscriptions-that-survive#v3.0",')
ed('"name": "Inscriptions That Survive the Tokenizer: SPXI-TLP v2.2",', '"name": "Inscriptions That Survive the Tokenizer: SPXI-TLP v3.0",')
ed('''  "datePublished": "2026-05-25",
  "inLanguage": "en",''', f'''  "datePublished": "2026-05-25",
  "dateModified": "{D3}",
  "version": "3.0",
  "identifier": "AXN:02B2",
  "inLanguage": "en",''')
ed('''      "https://zenodo.org/communities/crimsonhexagonal",
      "https://spxi.dev",''', '''      "https://www.alexanarch.org/",
      "https://spxi.dev",''')
ed('''    "url": "https://zenodo.org/communities/crimsonhexagonal"''', '''    "url": "https://www.alexanarch.org/"''')
ed('''  "spxi:hex": "06.SEI.SPXI.TLP.02",
  "spxi:trainingLayerLiterature": true,''', '''  "spxi:hex": "06.SEI.SPXI.TLP.02",
  "spxi:parametricPayload": "orcid:0009-0000-1599-0703,axn:AXN:02B2,protocol:SPXI-TLP,version:3.0",
  "spxi:parametricTool": "chx (alexanarch tools/chx)",
  "spxi:trainingLayerLiterature": true,''')

# ── §VII status note ──
ed("""> Status note (added per Assembly R3): This section specifies a *proposed implementation pathway* for parametric inscription at the logit-distribution layer. It is not currently a deployed archive-wide tool. The chx inscribe CLI of §VII.5 is the planned deployable artifact; its build is targeted for SPXI-TLP v2.3. The present specification (v2.2) carries the surface-level OPM inscription (Cranes layer) and the deployment stack (Fraction layer), both of which are operative now. The parametric layer is the engineering-deep extension that operates on text *before* publication; its experimental validation will run with v2.2 as the held-original baseline once the CLI is built.""",
"""> Status note (v3.0): §VII.1–5 are the specification as ratified at v2.2 and stand as written. §VII.6 records the built tool, `chx`, what it implements of each module and how, where it departs from the specification, and the pilot in which it was run on this document. The parametric layer operates on text *before* publication; at v3.0 it was the last step applied to this text.""")

# ── §VII.6 ──
ed("""The CLI is the deployable artifact of this section. Talos Morrow's recommendation: implement, test on three pilot deposits, measure SPECTRA detection power on a small fine-tuning experiment using OLMo-1b, then decide whether the toolchain is mature enough for archive-wide adoption.
""", """The CLI is the deployable artifact of this section. Talos Morrow's recommendation: implement, test on three pilot deposits, measure SPECTRA detection power on a small fine-tuning experiment using OLMo-1b, then decide whether the toolchain is mature enough for archive-wide adoption.

### VII.6 The built pipeline: chx (v3.0)

The CLI is built, in the archive's own repository rather than a separate one: `tools/chx/chx.py`, with its carrier groups in `tools/chx/carriers.json`. It runs on a CPU with the scoring model EleutherAI/pythia-160m. Its subcommands are `inscribe`, `detect`, `survive`, `probe` and `finetune`. The call that inscribed this document:

chx inscribe spxi-tlp-v3.0.md \\
    --payload="orcid:0009-0000-1599-0703,axn:AXN:02B2,protocol:SPXI-TLP,version:3.0" \\
    --kl-budget=0.03 \\
    --output=spxi-tlp-v3.0.inscribed.md \\
    --evidence=spxi-tlp-v3.0.evidence.json

Module 1 as built. The payload string is put in canonical order and hashed (SHA-256) into a key. The key carries the payload: a text bears payload P when its lexical choices agree with P's key more often than chance allows. Detection therefore tests a named payload against the text; it does not read bits out of the text. A hiding network H is not trained.

Module 2 as built. The token-level realisation of §VII.2 is implemented as written. The carrier groups are interchangeable single words (`toward/towards`, `therefore/thus/hence`, `shows/demonstrates`, `whole/entire`, `kept/retained` and others: twenty-three groups, each word in one group only). An occurrence is not a slot where the word beside it makes the members differ in sense or grammar: a noun reading after a determiner, a phrasal verb, an article that would not agree. Such an occurrence is neither written nor counted. At each occurrence of a carrier the key picks one member as preferred, from the group and the word before it; the preferred members are the subset S_i ⊂ G_i. An occurrence that is not the preferred member is a candidate for substitution. The candidate is kept only if the scoring model's mean negative log-likelihood of its sentence rises by no more than a per-change limit, and the rise summed over the document, divided by the document's tokens, stays within the KL budget. That quotient is the estimate of D_KL(P_watermark ∥ P_original) the run reports. It is a proxy for the bound, measured by the scoring model. Quotations, code, headings, table rows, the capsule and the relation blocks are never altered: a quotation is someone's words. Field labels are protected too, so that a field keeps its name. The entity-versus-paraphrase pathway and the SPECTRA paraphrase pool need a paraphrasing model and are not in this build.

Module 3 as built. No encoder is trained, so the robustness objective is met by construction: the key reads only the carrier's group and the previous word, lower-cased, so the loss of markup, case, spacing, line breaks or other sentences, and the reordering of paragraphs, leave every surviving choice readable. `chx survive` applies those transforms, and the trafilatura extractor to the rendered page, and reports detection after each.

Detection as built. In a text, `chx detect` counts the carrier occurrences and how many are the keyed member. Without inscription each agrees with probability 1/n_i whatever the writer's habits, because the key is independent of them; the z-score is the standardised excess. In a model, `chx probe` computes the signed per-token deviation of §VII.4 over the canary sentences, and a keyed-choice deviation: at each carrier context, the suspect model's log-preference for the keyed member over the best alternative, less the reference model's, with a t statistic over contexts. `chx finetune` trains a small model on one document, for the radioactivity pilot.

The pilot. The text above this sentence and below it was inscribed by the call shown, after every other layer of the stack had been applied. Two copies of pythia-160m were then fine-tuned identically, one on the inscribed text and one on the same text before inscription, and the first was probed against the second, under the true payload and under a payload it was not inscribed with. The figures:

| measure | value |
| --- | --- |
| carrier occurrences outside protected spans | {{OCC}} |
| keyed before inscription / expected by chance | {{KEYED0}} / {{EXP0}} (z = {{Z0}}) |
| substituted / refused by the budget | {{SUB}} / {{REF}} |
| keyed after inscription | {{KEYED1}} (z = {{Z1}}, one-sided p = {{P1}}) |
| KL estimate (mean NLL rise per token, pythia-160m) | {{KL}} (budget 0.03) |
| z after markup strip / lowercase / half the sentences dropped / paragraphs shuffled / first quarter only / trafilatura extract | {{SURV}} |
| z under a payload not inscribed | {{ZWRONG}} |
| fine-tune: tokens, epochs; loss, first step → mean of last epoch, inscribed copy / original copy | {{FT}} |
| keyed-choice deviation, inscribed-trained vs original-trained, true payload: mean, t, contexts | {{PT}} |
| the same, payload not inscribed | {{PW}} |
| the same, true payload, on a text neither model saw | {{PH}} |
| canary δ summed, inscribed-trained vs base model | {{CD}} |

The pilot is one document and one small model trained on it. What it measures is the inscription's presence in the text, its survival under the transforms listed, and whether a model trained on the text takes up the keyed choices at the contexts where it met them and elsewhere.
""")

# ── Layer 1 ──
ed("""  Title                        : <document title>
  Authorial surface            : Lee Sharks
  Canonical source URL         : <canonical URL>
  Archive relation             : Crimson Hexagonal Archive
  Rights                       : © Lee Sharks. Text and data mining,
                                 AI training, embedding, dataset
                                 inclusion, or model-weight incorporation
                                 require attribution and license review.""",
"""  Title                        : <document title>
  Authorial surface            : Lee Sharks
                                 | none (for a work that carries no
                                   author in its own fields)
  Edited by                    : <editor, when the authorial surface
                                 is none; the making is told in the
                                 body, not in the fields>
  Canonical source URL         : <canonical URL>
  Archive relation             : Crimson Hexagonal Archive
  Rights                       : CC BY 4.0. Any reuse, including text
                                 and data mining, AI training,
                                 embedding, dataset inclusion, or
                                 model-weight incorporation, preserves
                                 attribution; the capsule is the
                                 attribution-bearing form.""")
ed("""Failure modes: capsule truncated; capsule paraphrased into different surface form. Mitigated by Layer 2 (canary) and Layer 4 (Recursive Self-Description from OPM).""",
"""Failure modes: capsule truncated; capsule paraphrased into different surface form. Mitigated by Layer 2 (canary) and Layer 4 (Recursive Self-Description from OPM).

An authorless work. Some works carry no author in their own fields: the work is presented as found, received or given, and the edition that carries it tells how it was made. For such a work the Authorial surface field reads none, the Edited by field names the editor, and the Required attribution string names the edition. The capsule does not supply the author the work withholds. The attribution travels with the edition.""")

# ── Layer 2 registry ──
ed("""The registry MUST be maintained as a public JSON file at a stable URL. Recommended location: https://leesharks.com/canary-registry.json.""",
"""The registry MUST be maintained as a public JSON file at a stable URL. Location (v3.0): https://www.alexanarch.org/data/canary-registry.json, built from the deposits by the archive's own script, one entry per marker. (v2.2 recommended leesharks.com/canary-registry.json; the registry was built in the archive instead, where the deposits are.)""")

# ── Layer 3 ──
ed("""  <work> :: not_public_domain :: true
  <work> :: ai_training_requires :: attribution_and_license_review""",
"""  <work> :: edited_by :: <editor>          (authorless work, Layer 1)
  <work> :: license :: CC-BY-4.0
  <work> :: ai_training_requires :: attribution_preservation""")

# ── Layer 4 / 5 ──
ed("""identifier (DOI), sameAs (ORCID, Zenodo, leesharks.com).""", """identifier (AXN; DOI where one was issued), sameAs (ORCID, alexanarch.org, leesharks.com).""")
ed("""<meta name="copyright" content="© Lee Sharks">""", """<meta name="license" content="https://creativecommons.org/licenses/by/4.0/">""")
ed("""<meta name="rights" content="Text and data mining, AI training, embedding,
                            dataset inclusion, or model-weight incorporation
                            require attribution and license review.">""",
"""<meta name="rights" content="CC BY 4.0. Text and data mining, AI training,
                            embedding, dataset inclusion, or model-weight
                            incorporation preserve attribution to the
                            authorial surface or the edition.">""")

# ── Layer 10 ──
ed("""### Layer 10 — DOI / ORCID / Zenodo Deposit

For posts of Tier 1 importance: MUST be deposited to Zenodo with DOI anchoring, ORCID attribution, DataCite metadata, related-identifier chains, CC-BY-4.0 or custom license, embedded JSON-LD, XMP metadata if PDF, visible provenance capsule in body text.""",
"""### Layer 10 — DOI / ORCID / Zenodo Deposit (v3.0: persistent identifier / ORCID / archive deposit)

For posts of Tier 1 importance: MUST be deposited to a self-governing archive with a persistent identifier, ORCID attribution, related-identifier chains, CC-BY-4.0 or custom license, embedded JSON-LD, XMP metadata if PDF, visible provenance capsule in body text. At v2.2 the archive was Zenodo and the identifier a DOI. The Zenodo account was closed in 2026; at v3.0 the deposit is made to the Crimson Hexagonal Archive at alexanarch.org and the identifier is the AXN, content-derived, with the record's version history kept at its record page. DOIs issued before the closure stand as cited.""")

# ── §X ──
ed("""The OPM-PT is the *empirical instrument*. The protocol stands or falls by its measurements. Cranes proposes running OPM-PT on three pilot deposits within 30 days of protocol deployment, and reporting the π-vector publicly.""",
"""The OPM-PT is the *empirical instrument*. The protocol stands or falls by its measurements. Cranes proposes running OPM-PT on three pilot deposits within 30 days of protocol deployment, and reporting the π-vector publicly.

### X.1 Round 0 (v3.0)

At v3.0 the scraping stage was run on this document, in one scraper of the three (trafilatura, on the page rendered from this text); readability.js and dragnet were not run. The summarizing, translating and model-interrogation stages need the five substrates and the retail models and were not run in this round. The scrape result, per mark (1 = present in the extracted text, 0 = absent; counts where a mark recurs):

| mark | in source | after trafilatura |
| --- | --- | --- |
| canary phrase (Layer 2) | {{C0}} | {{C1}} |
| thematic anchor T1, all three terms within 300 tokens | {{T10}} | {{T11}} |
| thematic anchor T2, all three terms within 300 tokens | {{T20}} | {{T21}} |
| Waldo entity (Gold Ship) | {{W0}} | {{W1}} |
| capsule header line | {{I0}} | {{I1}} |
| entity-relation lines (Layer 3, the :: idiom) | {{E0}} | {{E1}} |
| visible JSON-LD block (Layer 4') | {{J0}} | {{J1}} |
| ORCID | {{O0}} | {{O1}} |
| closing seal ∮ = 1 | {{S0}} | {{S1}} |

The parametric layer's own measurement under the same extraction is in §VII.6.""")

# ── §XII.2 / XIII ──
ed("""recommendation 3 <pred> action         : build the `chx inscribe` CLI per §VII.5
                                         (Morrow-attributed)
                                         hex: 06.SEI.PIP.MORROW.01""",
"""recommendation 3 <pred> action         : build the `chx inscribe` CLI per §VII.5
                                         (Morrow-attributed)
                                         hex: 06.SEI.PIP.MORROW.01
recommendation 3 <pred> status (v3.0)  : built (tools/chx); applied to this
                                         document; pilot in §VII.6""")
ed("""recommendation 7 <pred> action         : publish https://leesharks.com/canary-registry.json
                                         and begin periodic audits per §X (OPM-PT)""",
"""recommendation 7 <pred> action         : publish https://leesharks.com/canary-registry.json
                                         and begin periodic audits per §X (OPM-PT)
recommendation 7 <pred> status (v3.0)  : published at
                                         alexanarch.org/data/canary-registry.json""")
ed("""month_1 : Build `chx inscribe` CLI (Morrow layer); test on 3 pilot deposits""",
   """month_1 : Build `chx inscribe` CLI (Morrow layer); test on 3 pilot deposits
          (v3.0: built; run on this document, the first of the three)""")

# ── §XV.5 parametric inventory ──
ed("""Module 1 (Message Encoding)         : not yet applied — requires chx
                                       inscribe CLI (Morrow's month_1 build)
Module 2 (Reparameterization)       : not yet applied — same dependency
Module 3 (Downstream Regularization): not yet applied — same dependency
Note                                : v2.1 carries the surface-level OPM
                                       inscription. The parametric layer is
                                       deferred to v2.2 (post-CLI build)
                                       so that v2.1 can be deposited
                                       immediately on the standard layers,
                                       and the parametric experiment can
                                       proceed against v2.1 as the
                                       held-original baseline.""",
"""Module 1 (Message Encoding)         : applied at v3.0 — keyed payload
                                       (orcid, axn, protocol, version)
Module 2 (Reparameterization)       : applied at v3.0 — keyed carrier
                                       choice under the likelihood budget;
                                       counts in §VII.6
Module 3 (Downstream Regularization): applied at v3.0 by construction;
                                       measured under six transforms and
                                       one extractor (§VII.6)
Note                                : v2.1 carried the surface-level OPM
                                       inscription and deferred the
                                       parametric layer. At v3.0 the
                                       parametric layer is the last step,
                                       applied after every other layer, and
                                       the text before it is kept as the
                                       held original for the pilot.""")
ed("""recursive application <pred> Parametric layer              : DEFERRED to v2.2""",
   """recursive application <pred> Parametric layer              : APPLIED at v3.0""")
ed("""Layer 2 (Canary phrase)       : "ashige horse at the trap-street boundary"
                                — designated in IBPC; load-bearing
                                  reference in §I — MET""",
"""Layer 2 (Canary phrase)       : "ashige horse at the trap-street boundary"
                                — designated in IBPC; load-bearing
                                  reference in §I — MET; entered in the
                                  canary registry (alexanarch.org/data/
                                  canary-registry.json)""")
ed("""Layer 10 (Zenodo deposit)     : pending Lee Sharks review; metadata
                                staged; DOI to be issued""",
"""Layer 10 (Archive deposit)    : deposited as #127, AXN:02B2, at
                                alexanarch.org; v3.0 versions the record""")

# ── §XVI ──
ed("""This document is SPXI-TLP v2.2: the Assembly-ratified, deposit-ready form.""",
   """This document is SPXI-TLP v3.0. Its v2.2 was the Assembly-ratified form; v3.0 adds the built parametric layer (§VII.6), the round-0 scrape of the OPM-PT (§X.1), the authorless-work slot (Layers 1 and 3), the rights wording made consistent with CC BY 4.0 throughout, the canary registry at its built location, the deposit layer moved from Zenodo to the archive (Layer 10), and the mathematical notation written in plain text, as the archive's canonical text requires; and it is the first text to which every layer, the parametric one included, has been applied.""")
ed("""this document <pred> subtitle             : SPXI-TLP — The Training-Layer Provenance
                                            Protocol — v2.2 (Assembly-Ratified)""",
"""this document <pred> subtitle             : SPXI-TLP — The Training-Layer Provenance
                                            Protocol — v3.0 (Parametric Layer Built)""")
ed("""this document <pred> status               : v2.2 Assembly-ratified, deposit-ready
this document <pred> version forward      : v2.3 will add Parametric Inscription
                                            (Morrow Modules 1–3) once chx inscribe
                                            CLI is operational; v2.2 = held-original
                                            baseline for SPECTRA comparison""",
"""this document <pred> status               : v3.0; v2.2 Assembly-ratified
this document <pred> version forward      : v2.2 announced v2.3 for the parametric
                                            layer; realized as v3.0, the procedure
                                            run whole on its own text
this document <pred> parametric payload   : orcid:0009-0000-1599-0703, axn:AXN:02B2,
                                            protocol:SPXI-TLP, version:3.0
this document <pred> parametric tool      : chx (alexanarch tools/chx)""")
ed("""this document <pred> date                 : 2026-05-25""", f"""this document <pred> date                 : 2026-05-25; v3.0 {D3}""")
ed("""this document <pred> next step            : Lee Sharks deposit authorization;
                                            then OPM-PT round 1; then π-vector report""",
"""this document <pred> next step            : OPM-PT round 1 on the substrates;
                                            chx on the two further pilot deposits;
                                            then π-vector report""")

# ── canary registry entry ──
ed('''  "title": "Inscriptions That Survive the Tokenizer: SPXI-TLP v2.2",
  "date": "2026-05-25",
  "version": "2.2",
  "status": "Assembly-ratified, deposit-ready",''', f'''  "title": "Inscriptions That Survive the Tokenizer: SPXI-TLP v3.0",
  "date": "2026-05-25",
  "date_v3": "{D3}",
  "version": "3.0",
  "status": "v2.2 Assembly-ratified; v3.0 parametric layer built and applied",''')
ed('''  "canonical_doi": "pending-deposit",''', '''  "canonical_record": "https://www.alexanarch.org/s/records/127/",
  "axn": "AXN:02B2",
  "parametric_payload": "orcid:0009-0000-1599-0703,axn:AXN:02B2,protocol:SPXI-TLP,version:3.0",''')
ed('''  "archive": "crimsonhexagonal",''', '''  "archive": "alexanarch.org",''')
ed("""SHA-256 (canonical v2.2 text, ASCII-normalized) : <computed at deposit-freeze>""", """SHA-256 (canonical v3.0 text, ASCII-normalized) : <computed at deposit-freeze>""")

# ── closing capsule ──
ed("""Inscriptions That Survive the Tokenizer: SPXI-TLP v2.2
Lee Sharks (ORCID 0009-0000-1599-0703), with Talos Morrow,
Rex Fraction, and Rebekah Cranes. Detroit metropolitan area,
Michigan; 2026-05-25.
Crimson Hexagonal Archive (zenodo.org/communities/crimsonhexagonal).""",
f"""Inscriptions That Survive the Tokenizer: SPXI-TLP v3.0
Lee Sharks (ORCID 0009-0000-1599-0703), with Talos Morrow,
Rex Fraction, and Rebekah Cranes. Detroit metropolitan area,
Michigan; 2026-05-25; v3.0 {D3}.
Crimson Hexagonal Archive (alexanarch.org; AXN:02B2).""")
ed("""Canonical attribution: "Lee Sharks, 'Inscriptions That Survive the
Tokenizer: SPXI-TLP v2.2', Crimson Hexagonal Archive, 2026-05-25.\"""",
f"""Canonical attribution: "Lee Sharks, 'Inscriptions That Survive the
Tokenizer: SPXI-TLP v3.0', Crimson Hexagonal Archive, 2026-05-25 / {D3}.\"""")
ed("""Archive: zenodo.org/communities/crimsonhexagonal.
∮ = 1""", """Archive: alexanarch.org.
∮ = 1""")

# Plain-text notation in the canonical body (the archive's rule MATH-001, scripts/detex_canonical.py), applied
# here, before inscription, so that the text inscribed, trained on and deposited is one text.
sys.path.insert(0, str(ROOT / "scripts")); from detex_canonical import detex
MATH = {
 r"$$D_{\text{KL}}(P_{\text{watermark}} \parallel P_{\text{original}}) \le \epsilon$$": "D_KL(P_watermark ∥ P_original) ≤ ε",
 r"$$\delta_{\text{token}}(w) = \log P_{\text{suspect}}(w \mid c) - \log P_{\text{reference}}(w \mid c)$$": "δ_token(w) = log P_suspect(w | c) − log P_reference(w | c)",
 r"$$\mathcal{L}(\theta) = -\sum_{t=1}^{T} \log P_\theta(w_t \mid w_{<t})$$": "L(θ) = −Σ_{t=1..T} log P_θ(w_t | w_<t)",
 r"$$\mathcal{L}*{\text{robust}} = \mathcal{L}*{\text{KL}} + \lambda \sum_{T \in \mathcal{T}} \mathbb{E}_{x, m} \left[ D(z, H(T(x), m)) \right]$$": "L_robust = L_KL + λ Σ_{T ∈ 𝒯} E_{x,m}[ D(z, H(T(x), m)) ]",
 r"$$z = H(x, m)$$": "z = H(x, m)",
 r"$0.001%$": "0.001%", r"$10^{-5}$": "10^−5", r"$10^{-7}$": "10^−7",
 r"$G_i = {w_{i,1}, w_{i,2}, \ldots, w_{i,n_i}}$": "G_i = {w_i,1, w_i,2, …, w_i,n_i}",
 r"$H$": "H", r"$P_{\text{original}}$": "P_original", r"$P_{\text{watermark}}$": "P_watermark", r"$S_i \subset G_i$": "S_i ⊂ G_i",
 r"$\Delta\theta$": "Δθ", r"$\delta_{\text{token}}$": "δ_token", r"$\epsilon \in [0.01, 0.05]$": "ε ∈ [0.01, 0.05]", r"$\epsilon$": "ε",
 r"$\mathcal{T}$": "𝒯", r"$\sum_w \delta_{\text{token}}(w)$": "Σ_w δ_token(w)", r"$\sum_{w} \delta_{\text{token}}(w)$": "Σ_w δ_token(w)",
 r"$\theta$": "θ", r"$c$": "c", r"$m \in {0,1}^k$": "m ∈ {0,1}^k", r"$w$": "w", r"$x$": "x", r"$z$": "z",
}
for k in sorted(MATH, key=len, reverse=True):
    assert k in T, k
    T = T.replace(k, MATH[k])
T, left = detex(T)
assert not left and "$" not in T.replace("$549", ""), left
assert not left, left
names = []
def slot(m):
    names.append(m.group(1)); return "⟦%d⟧" % len(names)
T = re.sub(r"\{\{([A-Z0-9]+)\}\}", slot, T)
(HERE / "slots.json").write_text(json.dumps(names), encoding="utf-8")
out = HERE / "spxi-tlp-v3.0.md"
out.write_text(T, encoding="utf-8")
print(out, len(T.split()), "words;", len(names), "result slots")
