{
 "item": "linkage",
 "batch": "e03-a-link-register",
 "approach": "Register one conditional linkage-control experiment on joint-nulls-v1: within the FREE cell of each crosswalk branch, enumerate all bijections of the registered shared identities, relabel Z13 shared variables onto their permuted Z32 partners (paired-variable quotient), and recount with the unchanged registered cell() function. Only synthetic toys were executed; no observed or permuted compatibility was computed.",
 "protocol": {
  "version": "joint-nulls-v1/link-shuffle-v1",
  "status": "exploratory conditional linkage control; follows known results; not confirmation; registers only, no observed or permuted compatibility evaluated",
  "base": {
   "registration": "https://api.imd.fun/artifacts/504fbbe361083ef46e0ba5266b74b940a9ed4887cb5a577e98b73b6628ce36cf",
   "registrationSha256": "504fbbe361083ef46e0ba5266b74b940a9ed4887cb5a577e98b73b6628ce36cf",
   "registeredProtocolSha256": "16b5bad2742033561ca1334f09b97910bfb5fc58ab209be08c56a3141c41711e",
   "generator": "joint_nulls.py = registration field generatorSource, sha256 38eea82d0280a4ae3ad7c668f2675985653d3fd3a365f5ce0583925cdae8ff75 (asserted at import)",
   "audit": "https://api.imd.fun/artifacts/b2e262d2ab6cf6b4e2e3f46b3359bb236e96c52d81947709c8a187ab220ef830",
   "auditSha256": "b2e262d2ab6cf6b4e2e3f46b3359bb236e96c52d81947709c8a187ab220ef830",
   "crosswalk": "https://api.imd.fun/artifacts/6262429733357009532501273176da5477cac8738d5b6bd0e74fc39533222bdd (hash checked by jn.load_prior)",
   "rawData": "SSA yob1880..1950 + Names_2010Census.csv, pinned and checked by jn.build exactly as registered"
  },
  "unchanged": "Z13 AENz0K0M0[NAM and Z32 C9J|#Ok[AMf8?ORTG+X6FDVj%HCELzPW9 in printed order; section-2 aliases resolved per branch by jn.resolve; name vocabulary (given cap 10000, surname cap 50000, 13-letter concatenations); 840 G texts; printed rule; <=3 null identities, null-eligible = Z32-only unanchored ids; within-message identities; serialization and count definitions of joint-nulls-v1",
  "cells": "FREE anchor case only, for branches primary, shortHooks, crossedRings; each reported separately, never summed. Anchored cases (unchangedZ340, unchangedZ408, both) are the already-established exclusions and are outside this count.",
  "sharedSets": {
   "primary": [
    "A",
    "E",
    "M"
   ],
   "shortHooks": [
    "A",
    "E",
    "M",
    "hook13"
   ],
   "crossedRings": [
    "A",
    "E",
    "M",
    "cross13"
   ],
   "validation": "S = sorted(set(r13)&set(r32)) recomputed at run time and asserted equal to these lists, which equal sharedIds of the registered cell parameters (audit vocabularyAndParameters.cellParameters, xz payload sha256 c8a4be1a40cc65830145af02c192861a9146161d149f9da8f015d21eeaa03256)",
   "N": {
    "primary": 6,
    "shortHooks": 24,
    "crossedRings": 24
   }
  },
  "linkage": "For each bijection pi:S->S impose k13(s)=k32(pi(s)) for all s in S; no other cross-message equality. Implemented on the paired-variable quotient: every Z13 occurrence of shared id s is relabelled pi(s) (the Z32 member of the pair) and Z32 is untouched, so the union id set, null-eligible set, null sets and key coordinates are identical across permutations and counts are comparable. pi = identity is the registered linkage. These are synthetic link shuffles conditional on fixed marginals, not alternative historical crosswalks.",
  "enumeration": "itertools.permutations(sorted(S)) with Python str ordering (lexicographic in the image tuple); index 0 = identity; record pi serialized as the list [pi(s) for s in sorted(S)]",
  "serialization": "canonical = json.dumps(sort_keys=True, separators=(',',':'), ensure_ascii=True); sha256 hex of UTF-8; per cell recordsSha256 over the ordered list of permutation records",
  "countingUnits": {
   "keys": "distinct union keys on the quotient incl. null assignment (= distinct (nullSet, Z13 text, Z32 text))",
   "textPairs": "distinct (Z13 text, Z32 text)",
   "z13Projection": "distinct Z13 texts among joint solutions",
   "z32Projection": "distinct Z32 texts among joint solutions",
   "numericPairs": "distinct (angle, distance) value pairs among G expansions producing a joint Z32 text"
  },
  "strata": {
   "all": "every key with 0..3 nulls",
   "z32StillRepeated": "keys whose Z32 after deletion still contains a repeated identity"
  },
  "budgets": "exact null count 0,1,2,3 and le3 (<=3), each in both strata: 10 vectors x 5 metrics per permutation",
  "denominators": "per permutation: z13LocalTexts, z32LocalTriples, z32LocalStillRepeatedTriples, prejoinAll = z13LocalTexts*z32LocalTriples, prejoinStillRepeated = z13LocalTexts*z32LocalStillRepeatedTriples; survival = joint key count; asserted identical across all permutations of a branch (marginal invariance) together with structural parameters",
  "primaryDiagnostic": "z32StillRepeated/le3 textPairs (second metric), per branch",
  "tails": "over all N permutations including identity: lower = #{v<=v_id}/N, equal = #{v==v_id}/N, upper = #{v>=v_id}/N, exact counts, no Monte Carlo, no plus-one; reported for every metric/stratum/budget; no winner selected, no pooling over branches or metrics",
  "commands": {
   "toy": "python3 -I linkage.py toy",
   "count": "python3 -I linkage.py count PRIOR_JSON RAWDIR (the later registered run; not run here)"
  },
  "runtime": "CPython 3.12, stdlib, linkage.py and joint_nulls.py in the same directory"
 },
 "protocolSha256": "6957f845497b026ee5a2193f727d4a5f2e7d3233bada57d4984759ca5f428e41",
 "protocolHashRule": "sha256 of canonical JSON of the protocol object",
 "commitments": {
  "sources": {
   "registration": "https://api.imd.fun/artifacts/504fbbe361083ef46e0ba5266b74b940a9ed4887cb5a577e98b73b6628ce36cf",
   "audit": "https://api.imd.fun/artifacts/b2e262d2ab6cf6b4e2e3f46b3359bb236e96c52d81947709c8a187ab220ef830"
  },
  "generatorBase": {
   "file": "joint_nulls.py",
   "sha256": "38eea82d0280a4ae3ad7c668f2675985653d3fd3a365f5ce0583925cdae8ff75",
   "from": "registration field generatorSource (verified byte hash locally)"
  },
  "data": "name lists and G vocabulary as frozen in registration: given rankedNamesSha256 fb9f57e0..., surname rankedNamesSha256 92b42a15..., G sortedTextsSha256 888b3af7..., numericMapSha256 ce59e1e1...; enforced by jn.build",
  "linkageCode": {
   "file": "linkage.py",
   "sha256": "88ffdc843c7e611250f2238ec8a1c4e764a717f81561bcf1caa25e5ac075c571",
   "bytes": 8638
  }
 },
 "generatorSource": "\"\"\"joint-nulls-v1 linkage control (link-shuffle-v1). CPython 3.12 stdlib.\nRequires joint_nulls.py (generatorSource of registration 504fbbe3..., sha256 38eea82d...) beside this file.\n  python3 -I linkage.py toy                         synthetic exhaustive toys only (run at registration)\n  python3 -I linkage.py count PRIOR_JSON RAWDIR     observed-order link shuffles, FREE cells (registered, NOT run here)\"\"\"\nimport hashlib, sys, random\nfrom itertools import permutations, combinations\nfrom pathlib import Path\nHERE = Path(__file__).resolve().parent\nsys.path.insert(0, str(HERE))\nJN_SHA = '38eea82d0280a4ae3ad7c668f2675985653d3fd3a365f5ce0583925cdae8ff75'\nassert hashlib.sha256((HERE / 'joint_nulls.py').read_bytes()).hexdigest() == JN_SHA, 'joint_nulls.py hash mismatch'\nimport joint_nulls as jn\nEXPECTED_SHARED = {'primary': ['A', 'E', 'M'], 'shortHooks': ['A', 'E', 'M', 'hook13'], 'crossedRings': ['A', 'E', 'M', 'cross13']}\nEXPECTED_N = {'primary': 6, 'shortHooks': 24, 'crossedRings': 24}\nMETRICS = jn.COUNT_NAMES  # keys,textPairs,z13Projection,z32Projection,numericPairs\nSTRATA = ('all', 'z32StillRepeated')\nBUDGETS = ('0', '1', '2', '3', 'le3')\n\ndef perms(S):\n    \"\"\"Lexicographic enumeration over sorted(S) (Python str order); index 0 = identity.\"\"\"\n    S = sorted(S)\n    return [dict(zip(S, p)) for p in permutations(S)]\n\ndef relabel13(r13, pi):\n    \"\"\"Impose k13(s)=k32(pi(s)): Z13 occurrence of shared s becomes variable pi(s) (paired-variable quotient,\n    labelled by the Z32 member). Within-message identities preserved because pi is a bijection on S.\"\"\"\n    return tuple(pi.get(g, g) for g in r13)\n\ndef flat(rec):\n    out = {}\n    for st, bk in (('all', 'budgetAll'), ('z32StillRepeated', 'budgetStillRepeated')):\n        for b in BUDGETS:\n            out[f'{st}/{b}'] = rec[st] if b == 'le3' else rec[bk][b]\n    return out\n\ndef denominators(rec):\n    m = rec['marginals']\n    return dict(z13LocalTexts=m['z13LocalTexts'], z32LocalTriples=m['z32LocalTriples'],\n                z32LocalStillRepeatedTriples=m['z32LocalStillRepeatedTriples'],\n                prejoinAll=m['z13LocalTexts'] * m['z32LocalTriples'],\n                prejoinStillRepeated=m['z13LocalTexts'] * m['z32LocalStillRepeatedTriples'])\n\ndef tails(values):\n    o, n = values[0], len(values)\n    return dict(N=n, observed=o, lower=f'{sum(v <= o for v in values)}/{n}', equal=f'{sum(v == o for v in values)}/{n}',\n                upper=f'{sum(v >= o for v in values)}/{n}')\n\ndef link_cell(r13, r32, ix, maxnull=jn.MAXNULL):\n    S = sorted(set(r13) & set(r32))\n    P = perms(S)\n    recs = []\n    for pi in P:\n        rec = jn.cell(relabel13(r13, pi), r32, {}, {}, ix, maxnull)\n        recs.append(dict(pi=[pi[s] for s in S], denominators=denominators(rec), parameters=rec['parameters'], counts=flat(rec)))\n    d0 = recs[0]['denominators']\n    assert all(r['denominators'] == d0 for r in recs), 'marginal invariance failed'\n    assert all(r['parameters'] == recs[0]['parameters'] for r in recs), 'parameter invariance failed'\n    summary = {k: [tails([r['counts'][k][i] for r in recs]) for i in range(len(METRICS))] for k in recs[0]['counts']}\n    return dict(shared=S, N=len(P), records=recs, summary=summary,\n                primaryDiagnostic=summary['z32StillRepeated/le3'][1],\n                recordsSha256=jn.digest(jn.canonical(recs)))\n\ndef count(prior_path, rawdir):\n    reg, d, given, sur, gnum, aud = jn.build(prior_path, rawdir)\n    ix = jn.make_indexes(given, sur, gnum)\n    out = {}\n    for bname in jn.BRANCHES:\n        branch = jn.branch_of(d, bname)\n        anchors, conflicts = jn.anchor_map(d, branch, ())\n        assert anchors == {} and conflicts == {}\n        r13, r32 = jn.resolve(d, [list(jn.Z13), list(jn.Z32)], branch)\n        S = sorted(set(r13) & set(r32))\n        assert S == EXPECTED_SHARED[bname], (bname, S)\n        res = link_cell(r13, r32, ix)\n        assert res['N'] == EXPECTED_N[bname]\n        out[f'{bname}/free'] = res  # never summed across branches\n    print(jn.canonical(dict(version='joint-nulls-v1/link-shuffle-v1', results=out)))\n\ndef brute_link(r13, r32, pi, names13, gnum, maxnull=jn.MAXNULL):\n    \"\"\"Independent enumerator on UNRELABELLED sequences with explicit cross-message equalities.\"\"\"\n    S = sorted(set(r13) & set(r32))\n    elig = sorted(set(r32) - set(r13))\n    def consistent(seq, text):\n        m = {}\n        return len(seq) == len(text) and all(m.setdefault(g, c) == c for g, c in zip(seq, text))\n    res = {}\n    for k in range(maxnull + 1):\n        for N in combinations(elig, k):\n            seq = [g for g in r32 if g not in N]\n            still = len(set(seq)) < len(seq)\n            for y in gnum:\n                if not consistent(seq, y):\n                    continue\n                f32 = {g: y[i] for i, g in reversed(list(enumerate(seq)))}\n                for x in names13:\n                    if not consistent(r13, x):\n                        continue\n                    f13 = {g: x[i] for i, g in enumerate(r13)}\n                    if all(f13[s] == f32[pi[s]] for s in S):\n                        res.setdefault((k, still), set()).add((N, x, y))\n    def summ(T):\n        return [len(T), len({(x, y) for _, x, y in T}), len({x for _, x, _ in T}), len({y for _, _, y in T}),\n                len({tuple(p) for _, _, y in T for p in gnum[y]})]\n    out = {}\n    for st in STRATA:\n        for b in BUDGETS:\n            T = set().union(*[v for (k, s), v in res.items() if (b == 'le3' or str(k) == b) and (s or st == 'all')] or [set()])\n            out[f'{st}/{b}'] = summ(T)\n    return out\n\ndef toy():\n    rep = {}\n    assert [tuple(p.values()) for p in perms('cab')] == [tuple(x) for x in ('abc', 'acb', 'bac', 'bca', 'cab', 'cba')]\n    assert len(perms('abc')) == 6 and len(perms('abcd')) == 24\n    rep['enumeration'] = 'pass'\n    # identity recovery: identity permutation reproduces the registered cell() and its known answer\n    given, sur = ['X', 'XY'], ['YX', 'X', 'Z']\n    gnum = {'XQRQ': [(1, 1)], 'XQQ': [(1, 2)], 'XZ': [(1, 1)], 'YQQ': [(2, 2)]}\n    ix = jn.toy_ix(given, sur, gnum)\n    lc = link_cell(('a', 'b', 'a'), ('a', 'c', 'd', 'c'), ix)\n    assert lc['N'] == 1 and lc['records'][0]['counts']['all/le3'] == [3, 3, 1, 3, 2]\n    assert lc['records'][0]['counts']['z32StillRepeated/le3'] == [2, 2, 1, 2, 2]\n    rep['identityRecovery'] = 'pass'\n    # hand toy with two shared ids: Z13 a b, Z32 a b c; names XY only; G {XYQ, YXQ, XY}\n    ix2 = jn.toy_ix(['X'], ['Y'], {'XYQ': [(1, 1)], 'YXQ': [(2, 1)], 'XY': [(1, 2)]})\n    lc2 = link_cell(('a', 'b'), ('a', 'b', 'c'), ix2)\n    assert lc2['records'][0]['counts']['all/le3'] == [2, 2, 1, 2, 2], lc2['records'][0]\n    assert lc2['records'][1]['counts']['all/le3'] == [1, 1, 1, 1, 1], lc2['records'][1]\n    assert lc2['summary']['all/le3'][0] == dict(N=2, observed=2, lower='2/2', equal='1/2', upper='1/2')\n    rep['handTwoShared'] = 'pass'\n    # exhaustive agreement: every permutation of random small toys vs independent brute enumerator\n    rng, trials, cells, nz = random.Random(20261203), 150, 0, 0\n    for _ in range(trials):\n        al = 'PQR'\n        g = sorted({''.join(rng.choice(al) for _ in range(rng.randint(1, 2))) for _ in range(5)})\n        s = sorted({''.join(rng.choice(al) for _ in range(rng.randint(1, 3))) for _ in range(5)})\n        n13 = rng.randint(3, 5)\n        names13 = {a + b for a in g for b in s if len(a + b) == n13}\n        gn = {}\n        for _ in range(25):\n            gn.setdefault(''.join(rng.choice(al) for _ in range(rng.randint(2, 6))), set()).add((rng.randint(0, 2), rng.randint(1, 2)))\n        gn = {t: sorted(v) for t, v in gn.items()}\n        t13 = tuple(rng.choice('abcx') for _ in range(n13))\n        t32 = tuple(rng.choice('abcdef') for _ in range(rng.randint(3, 7)))\n        ixr = jn.toy_ix(g, s, gn)\n        lc = link_cell(t13, t32, ixr)\n        for rec in lc['records']:\n            pi = dict(zip(lc['shared'], rec['pi']))\n            b = brute_link(t13, t32, pi, names13, gn)\n            assert rec['counts'] == b, (t13, t32, pi, rec['counts'], b)\n            cells += 1\n            nz += b['all/le3'][0] > 0\n    rep['bruteAgreement'] = f'{trials} toys, {cells} permutation records agree exactly; {nz} nonzero'\n    rep['marginalInvariance'] = 'asserted in every link_cell call'\n    print(jn.canonical(rep))\n\nif __name__ == '__main__':\n    if sys.version_info[:2] != (3, 12) or sys.implementation.name != 'cpython':\n        raise SystemExit('Use CPython 3.12.')\n    cmd = sys.argv[1] if len(sys.argv) > 1 else ''\n    if cmd == 'toy':\n        toy()\n    elif cmd == 'count' and len(sys.argv) == 4:\n        count(sys.argv[2], sys.argv[3])\n    else:\n        raise SystemExit(__doc__)\n",
 "controlEnumeration": {
  "primary": "6 permutations of [A,E,M]",
  "shortHooks": "24 permutations of [A,E,M,hook13]",
  "crossedRings": "24 permutations of [A,E,M,cross13]",
  "order": "lexicographic, identity first",
  "random": "none"
 },
 "testExpectations": {
  "toyRun": "python3 -I linkage.py toy printed {\"bruteAgreement\":\"150 toys, 205 permutation records agree exactly; 96 nonzero\",\"enumeration\":\"pass\",\"handTwoShared\":\"pass\",\"identityRecovery\":\"pass\",\"marginalInvariance\":\"asserted in every link_cell call\"}",
  "identityRecovery": "identity permutation reproduces registered known answer all=[3,3,1,3,2], z32StillRepeated=[2,2,1,2,2]; in the real count, identity records must equal the audited observed FREE-cell vectors (e.g. primary/free all le3 [466,15,4,4,4], crossedRings/free [34,4,1,4,4], shortHooks/free zeros) and marginals (z13LocalTexts 33; z32LocalTriples 630/609/581)",
  "handToy": "Z13 a b, Z32 a b c, names X+Y, G {XYQ,YXQ,XY}: identity all=[2,2,1,2,2], swap all=[1,1,1,1,1], keys tails lower 2/2 equal 1/2 upper 1/2",
  "bruteForce": "every permutation record equals an independent enumerator using explicit k13(s)=k32(pi(s)) constraints on unrelabelled sequences",
  "invariance": "denominators and structural parameters equal across permutations, asserted"
 },
 "fits": "none computed; no names, plaintexts, coordinates or predictions",
 "limitations": [
  "N is tiny (6 or 24): the finest attainable tail is 1/6 or 1/24; this control cannot be strongly discriminating.",
  "shortHooks/free identity counts are already zero, so its tails are trivially upper=24/24 unless a shuffle is nonzero.",
  "Conditional on fixed marginals and printed order; it tests only cross-message linkage, not the crosswalk, vocabulary, null model or transcription.",
  "Anchored cases excluded by brief; results do not generalize to them.",
  "Any nonzero count remains a fit, not a decipherment; Z32 stays unsolved.",
  "The count run and an independent second-agent check are still required."
 ],
 "whatWouldChangeConclusions": "If identity sits at the upper extreme across metrics in a branch, linkage carries some conditional information in that model (still only a fit); if identity is typical, the registered joint fits owe nothing to the specific crosswalk. A different shared set, transcription, vocabulary or null model would void this registration.",
 "gates": {
  "ready": "pass",
  "why": "one protocol, shared sets validated (3,4,4 -> 6,24,24), enumeration, serialization, counting units, denominators, tails, code with hash and passing exhaustive toys are frozen; count command is executable given the registered raw data"
 }
}