#!/usr/bin/env python3 """helpdoc.py — packetized help for the current PythField GPT stack""" # ============================================================================ # CORE TEXT # ============================================================================ # [1:0] HELP_LINES_BEGIN HELP_LINES = [ 'OPTERIUM HELP — RUNTIME + FIELD REFERENCE', '', 'NAVIGATOR:', ' /help → runtime contract, workflow, guaranteed names', ' /axioms → what a number is here', ' /geom → route cookbook, 2D/3D/atlas geometry', ' /gpt → reasoning protocol for AI inside this field', ' /academy → deeper system notes, recovered layers', ' /pyth → verified current facts and invariants', ' /macros → macro contract, persistence, trust protocol', ' /api → live signatures — READ THIS FIRST', ' /opt_geom → OPT_G descent geometry', ' /doctor → closure, verdict, tunnel, fingerprint', '', 'SELF-DIAGNOSIS (run this first in any session):', ' api() → prints all live objects with signatures', ' shows what is actually loaded right now', ' never guess — run api() when unsure', '', 'WHAT THIS IS:', ' A geometric relational field, not a calculator.', ' P is not digits. P IS the relational web {(x,y) | x*y = P}.', ' Pt(x,y) is a 2D address. P=xy, S=x+y, D=x-y.', ' Identity: P = (S² - D²) / 4.', ' 3D is currently primary. 2D is the witness/face layer.', '', 'WORKFLOW:', ' 1. AI writes Python code.', ' 2. User pastes into Code panel and presses RUN.', ' 3. User sends Out / Err / Val / log back to AI.', ' Everything typed is PYTHON CODE, not chat.', '', 'OUTPUT CONTRACT:', ' Last expression → Val automatically', ' R(x) → publish to S.res, also returns x', ' print(...) → log (not Val)', ' builtins.print(...) → stdout / Out section', ' In macros: print(...) → stdout / Out', '', 'STATE CONTRACT:', ' S.tmp cleared each RUN', ' S.per persists across RUNs in the same session', ' keep("name") protect tmp name from clearing', ' lazy(name, gen, mx) lazy cache', ' NEVER do: S = anything (breaks the whole environment)', '', 'RUNTIME PREPROCESSING:', ' Slash commands expanded before execution:', ' /help /axioms /geom /gpt /academy /pyth /macros /api /opt_geom /doctor', " Macro sugar: 12M[name]34 → S.mac['name'](12,34)", ' Last expression rewritten into "_" → Val', '', 'PROTECTION / ADMIN:', " system/subprocess blocked unless '# pass 1977' in first 80 lines.", " Core file modification blocked unless '# pass 1977' in first 80 lines.", ' Protected: executor.py, state.py, opterium_field.py, visualizer.py, helpdoc.py', '', 'CORE RULE:', ' Address → Existence → Witness → Doctor → Format.', ' If you implement carry/borrow, digit loops, or float sqrt as primary logic,', ' you left the field.', '', 'ALWAYS-AVAILABLE OBJECTS:', ' 2D field:', ' field, Pt, Web, Sh, Tag, canon', ' web, sd, ps, pd, ant, dia, get', '', ' 3D field:', ' Pt3, cube_field', '', ' Ternary address:', ' Addr3, addr3, Axis', '', ' Rich 3D cell:', ' CubeCell', '', ' 9-cube atlas:', ' field9', '', ' E8 root lattice:', ' e8gen, e8, E8Gen', '', ' Doctor health layer:', ' doctor, HealthVector, DoctorVerdict, ReactionLevel', '', ' Facade:', ' of, opterium', '', ' State / macros:', ' S, keep, unkeep, lazy, lg, rs, info', ' mac, unmac, macs, R, tm, ms', '', ' Visualization:', ' V, MPL, pg, ph, pn, pp, p3', '', ' Help:', ' help, help_axioms, help_geom, help_gpt, help_academy', ' help_pyth, help_macros, help_opt_geom, help_doctor', ' slash, api', '', 'OPTIONAL OBJECTS (when modules installed):', ' chat_proxy LLM proxy', ' div_geom, ratio_geom, sqrt_geom geometric arithmetic', ' DebtNum, RatioRule exact numeric carriers', ' sequence_packet, resonance_din, e8_seed_hint resonance', '', ' Check what is loaded: api()', '', 'DIN MODULES (import explicitly):', ' from din import DINPacket, DINMode, pack_din, unpack_din, din_to_dict', ' from din_ops import din_route_lift, din_fuse, din_diff, din_packet_view', ' from rule_packet import build_rule_packet, rule_din, rule_from_blob', '', 'QUICK EXAMPLES:', ' web(420).at(12) # Pt(12,35)', ' web(420).has(13) # False', ' web(144).on_diag() # Pt(12,12)', ' web(97).edge_only() # True', ' sd(47,-23) # Pt(12,35)', ' CubeCell(2,3,5).packet() # full 3D cell', ' Addr3.of(9,9,9).is_on_axis # True', ' Axis.optg_path(1,2,3) # [(1,2,3),(1,2,0),(1,1,1)]', ' field9.point_report(-5,2,-3) # atlas report', ' e8gen.spectrum(0) # {-8:1,-4:56,0:126,4:56,8:1}', ' doctor.pt3_field3(9,9,9)["signature"] # "CLOSED"', '', 'E8 QUICK CALLS:', ' e8gen.root_packet(0) # root + spectrum + neighbors', ' e8gen.coxeter() # h=30=2×3×5, 30×8=240', ' e8gen.triangles(0) # r1+r2+r3=0 witnesses', ' e8gen.axis_connection() # link to Field3 axis', ' e8gen.summary() # full invariants', '', 'PERFORMANCE RULE:', ' Prefer WITNESS queries to REVEAL.', ' WITNESS: web(P).at(d), web(P).has(d), sd(S,D), Pt.pos', ' REVEAL: pairs_u, pairs, divs, idx — cost O(sqrt(P))', ' huge P → witness only', '', 'LOGGING DISCIPLINE:', ' Say briefly WHAT was tested, not only that it worked.', ' Prefer compact Val packets over noisy prose.', '', 'WHERE TO LOOK:', ' /api → signatures for this exact build ← START HERE', ' /geom → field geometry and witness routes', ' /opt_geom → descent geometry and stable nodes', ' /doctor → closure, verdict, tunnel, fingerprint', ' /academy → deeper structure and recovered layers', '', 'FINAL WARNING:', ' Trust closures, witnesses, and independent route agreement.', ' Do not trust one vivid example more than the structure that closes around it.', ] # [1:1] HELP_LINES_END # [2:0] AXIOMS_LINES_BEGIN AXIOMS_LINES = [ 'PYTHFIELD AXIOMS — what numbers ARE here', '', 'A1. NUMBER = RELATIONAL WEB', ' A positive integer P is not primarily a digit string and not a lone scalar mark.', ' P is the full web of ordered pairs (x,y) such that x*y = P.', ' Example: 420 IS the web {(1,420),(2,210),(3,140),(4,105),(5,84),(6,70),(7,60),(10,42),(12,35),(14,30),(15,28),(20,21)}.', ' The string "420" is only one compressed route-description of that web.', '', 'A2. ATOM = ADDRESS: Pt(x,y)', ' The minimal 2D atom is Pt(x,y).', ' From that address we read:', ' x, y', ' P = x*y', ' S = x+y', ' D = x-y', ' pos = sign(D)', ' Central identity:', ' P = (S^2 - D^2) / 4', ' This identity is structural and exact.', '', 'A3. THREE ROADS CROSS EVERY CELL', ' web(P): hyperbola xy=P', ' ant(S): anti-diagonal x+y=S', ' dia(D): diagonal x-y=D', ' Any two roads determine the cell:', ' sd(S,D) -> unique Pt or None', ' ps(P,S) -> 0 or 2 points', ' pd(P,D) -> 0 or 1 point', '', 'A4. OPERATIONS = NAVIGATION', ' Addition: Pt(a,b).S', ' Subtraction: Pt(a,b).D', ' Comparison: Pt(a,b).pos', ' Multiplication:Pt(a,b).P', ' Division: web(P).at(d)', ' Square root: web(n).on_diag()', ' Prime witness: web(n).edge_only()', ' These are route-reads, not schoolbook digit procedures.', '', 'A5. SAME SHADOW ≠ SAME ADDRESS', ' Pt(4,3) and Pt(3,4) share P=12 and S=7,', ' but they are different addresses because D=+1 for one and D=-1 for the other.', ' Product-shadow commutes more than full address does.', '', 'A6. COMPARISON IS FREE IN D', ' sign(D) already tells which side is larger.', ' No extra subtraction ritual is needed to know order.', '', 'A7. SCALE AND PATTERN MUST NOT BE MIXED', ' gcd layer:', ' g = gcd(x,y)', ' prim = Pt(x/g,y/g)', ' prim.sc(g) = original point', ' decimal / debt layer:', ' Sh(m,e) = m * 10^e exactly', ' mantissa stores pattern, debt stores cursor/scale', ' 0.0034 = Sh(34,-4), 2300 = Sh(23,2)', '', 'A8. ZERO IS NOT MERE ABSENCE', ' Zero is the vacuum and symmetry medium of the field.', ' In runtime intuition, row 0 and column 0 form the vacuum layer.', ' In decimal/debt intuition, finite strings live in an infinite zero-cloud.', '', 'A9. DECIMAL POINT IS A CURSOR, NOT THE NUMBER', ' Moving the cursor changes scale, not the underlying pattern.', ' 0.23, 23, and 2300 differ by debt / cursor position, not by pattern alone.', '', 'A10. 3D IS CURRENTLY PRIMARY IN THE WORKING STACK', ' Pt3(x,y,z) carries:', ' V = x*y*z', ' S_lin = x+y+z', ' C_plan = xy+xz+yz', ' D_body = max(abs coords) - min(abs coords)', ' 2D survives as built-in face/slice layer via slice_x / slice_y / slice_z.', '', 'A11. 3D IS STILL HOLOGRAPHICALLY TIED TO 2D', ' Each Pt3 contains three 2D shadows.', ' For every slice:', ' slice.P * missing_coord = V', ' So 3D is checked by three independent 2D witnesses.', '', 'A12. CURRENT 9-CUBE ATLAS IS ZERO-BALANCED', ' Current atlas structure uses one central cube C0 and eight phase cubes P0..P7.', ' The eight phase centers balance around zero.', ' Opposite phase pairs cancel.', ' This is a verified structural fact of the current atlas, not metaphor.', '', 'A13. SEED = PRIMITIVE + SCALE + TAG', ' Large 3D addresses are not stored naively as giant unrelated objects.', ' They are read through primitive chamber seed, multiplicative scale, and orientation tag.', ' Example recovered in current runtime:', ' (-35,14,-21) -> primitive=(2,3,5), scale=7, tag=zxy:p5', '', 'A14. E8 EXACT LAYER EXISTS AS INTEGER GEOMETRY', ' The current exact lesson layer builds 240 roots as:', ' 112 D8 roots + 128 spinor roots', ' plus 8 Cartan generators for the 248 lesson layer.', ' This layer is integer, witness-based, and route-queryable.', '', 'A15. TRIANGLE CLOSURE IS STRONGER THAN A SINGLE FORMULA', ' In 2D Doctor-style checking, multiple independent routes must close.', ' A single successful route can be accidental or partial.', ' Tension = number of failed closures.', ' Accept strongest results at tension = 0.', '', 'A16. EXACT WITNESS IS STRONGER THAN FLOAT PROJECTION', ' If exact witness exists, keep it.', ' If exact witness does not exist, preserve ratio / repeating / irrational / remainder rule.', ' Do not destroy structure with premature float collapse.', '', 'A17. CURRENT DOCTOR AND LEGACY DOCTOR ARE NOT THE SAME THING', ' Current doctor.py is a health / verdict / closure-quality layer.', ' Older systems also used "Doctor" for spatial route-finding, zone scans, tunnel cascades, and angle probes.', ' Keep those meanings separate.', '', 'A18. KNOWLEDGE MUST CARRY STATUS', ' canonical = part of current core/API', ' verified = confirmed by current or restored witnesses/logs', ' historical = older working layer, not automatically current API truth', ' prototype = promising but not core truth', ' quarantine = open / incomplete / unsafe to present as fact', ] # [2:1] AXIOMS_LINES_END # [3:0] GEOM_LINES_BEGIN GEOM_LINES = [ 'PYTHFIELD GEOM — route cookbook, 2D→3D→atlas, Doctor closures', '', 'GEOMETRIC PRINCIPLE:', ' Arithmetic here is not primary symbol-pushing.', ' It is route access inside a structured field.', ' A result is strongest when it is reached by independent closures, not by one dramatic example.', '', '═══ G1. THE 2D ADDRESS ═══', ' Pt(x,y) is a full address, not a scalar with decoration.', ' From a single cell we read:', ' x, y', ' P = x*y', ' S = x+y', ' D = x-y', ' pos = sign(D)', '', ' Therefore:', ' addition is read as S', ' subtraction is read as D', ' comparison is read as pos', ' multiplication is read as P', '', ' Verified current example:', ' Pt(23,16).S = 39', ' Pt(23,16).D = 7', ' Pt(23,16).pos = +1', ' Pt(23,16).P = 368', '', '═══ G2. WHY 4*3 AND 3*4 ARE NOT THE SAME ADDRESS ═══', ' They share the same product-shadow and sum:', ' P = 12, S = 7', ' But they are not the same cell because the diagonal reading flips:', ' Pt(4,3).D = +1, pos = +1', ' Pt(3,4).D = -1, pos = -1', ' So the field distinguishes orientation even when product-shadow commutes.', '', ' Verified current closure:', ' same_P = True', ' same_S = True', ' same_addr= False', '', '═══ G3. THE THREE 2D ROADS ═══', ' Every 2D cell lies at the crossing of three named roads:', ' web(P): hyperbola xy=P', ' ant(S): anti-diagonal x+y=S', ' dia(D): diagonal x-y=D', '', ' Any two roads determine the address:', ' sd(S,D) -> unique Pt or None', ' ps(P,S) -> 0 or 2 mirror points', ' pd(P,D) -> 0 or 1 chirality-selected point', '', ' Verified current route agreement:', ' (4,3) is recovered identically by xy, sd(7,1), ps(12,7), pd(12,1)', ' (3,4) is recovered identically by xy, sd(7,-1), ps(12,7), pd(12,-1)', ' tension = 0 in both cases', '', '═══ G4. WHY P = (S^2 - D^2) / 4 ═══', ' Because sum and difference reconstruct the coordinates:', ' x = (S + D) / 2', ' y = (S - D) / 2', ' Therefore:', ' P = x*y = ((S + D)(S - D))/4 = (S^2 - D^2)/4', '', ' The /4 is not an arbitrary school operation.', ' It comes from the two halving mediations that recover x and y from S and D.', ' If parity fails, sd returns None: the roads do not cross at a valid positive integer cell.', '', '═══ G5. WITNESS vs REVEAL ═══', ' WITNESS routes are primary and usually safe:', ' web(P).at(d)', ' web(P).has(d)', ' web(P).on_diag()', ' web(P).edge_only()', ' sd(S,D)', ' Pt(...).pos', '', ' REVEAL routes unfold the cloud and usually cost O(sqrt(P)):', ' pairs_u, pairs, divs, idx, ps, pd, ant(limit=None)', '', ' Rule of thumb:', ' huge P -> witness only', ' reveal only when the cloud itself is what you need', '', '═══ G6. WHAT COMPARISON REALLY IS ═══', ' Comparison is not a separate subtraction algorithm.', ' It is zone-reading relative to the diagonal x=y.', '', ' Above the diagonal: D>0, pos=+1', ' On the diagonal: D=0, pos=0', ' Below the diagonal: D<0, pos=-1', '', ' So "a>b?" is answered by the cell Pt(a,b), not by an extra ritual.', '', '═══ G7. WHAT ADDITION AND SUBTRACTION REALLY ARE ═══', ' Addition is anti-diagonal indexing:', ' Pt(a,b).S tells which x+y=S road the point lies on.', ' Subtraction is diagonal indexing:', ' Pt(a,b).D tells which x-y=D road the point lies on.', '', ' This is why no carry/borrow ontology is primary here.', ' Sum and difference are read from location.', '', '═══ G8. WHAT DIVISION REALLY IS ═══', ' Division is not a fundamental world-operator /.', ' It is a question about witness existence on a web.', '', ' Exact case:', ' 420 / 12 means:', ' does web(420) contain an address with x=12?', ' Answer:', ' web(420).at(12) -> Pt(12,35)', ' So quotient 35 is read as the partner coordinate.', '', ' Verified current exact packet:', ' div_geom(420,12) -> witness=35, pair=(12,35), route="web(P).at(d)"', '', ' Non-exact case:', ' 420 / 13 does not fail because an algorithm is unfinished.', ' It fails to have an exact integer witness at x=13 on web(420).', '', ' Verified current non-exact packet preserves structure as:', ' quotient_int = 32', ' remainder = 4', ' exact ratio = 420/13', ' repeating cycle = 307692', '', ' Therefore /5, /13, /7 are not universal primary world-actions.', ' They are route-attempts whose success depends on whether the witness exists in the object.', '', '═══ G9. REMAINDER IS NOT GARBAGE ═══', ' If exact witness is absent, the remainder is a structural residue, not noise to hide.', ' The field keeps:', ' quotient', ' remainder', ' exact ratio', ' repeating rule or irrational rule when needed', '', ' This is stronger than early float collapse because it preserves how the result lives.', '', '═══ G10. WHAT SQUARE ROOT REALLY IS ═══', ' sqrt is diagonal crossing:', ' web(n) ∩ {x=y}', ' If the diagonal witness exists, the root is exact.', ' If it does not, keep the rule and bounds.', '', ' Verified current packets:', ' sqrt_geom(144) -> witness 12 via web(144).on_diag()', ' sqrt_geom(10) -> irrational_rule("sqrt",10) with bounds (3,4)', '', '═══ G11. PRIME AS SHAPE ═══', ' A prime web has no internal factor witness in Q1.', ' It is edge-only as a shape.', '', ' Verified current witnesses:', ' web(13).edge_only() -> True', ' web(12).edge_only() -> False', '', '═══ G12. ANTI-DIAGONAL = PARABOLA ═══', ' On x+y=S, products form a parabola with peak at the center.', '', ' Verified current S=20 packet:', ' P-sequence is symmetric', ' peak = 100 = S^2/4', ' total sum = 1330 = S(S^2-1)/6', '', ' So anti-diagonal is not just a list of pairs; it is a structured energy profile.', '', '═══ G13. DIAGONAL ORIENTATION ═══', ' Positive and negative D are mirrored orientations of the same product growth.', '', ' Verified current example:', ' dia(3): (4,1),(5,2),(6,3),(7,4),(8,5),(9,6)', ' dia(-3): (1,4),(2,5),(3,6),(4,7),(5,8),(6,9)', ' products match pointwise = True', '', '═══ G14. INDEX, CURSOR, AND DECIMAL SHADOWS ═══', ' Digits are route-markers at indexed places, not the number itself.', ' The decimal point is a cursor.', ' Sh(m,e) keeps pattern and scale separate.', ' This is why finite decimal strings are projections of deeper objects, not primary ontology.', '', '═══ G15. 2D TO 3D — HOW HIGHER SPACE APPEARS ═══', ' The current working stack is 3D-primary, but 3D remains readable as structured stacking of 2D shadows.', ' A cube can be seen as a stack of 2D tables/slices.', ' Pt3 exposes this directly by carrying three 2D faces:', ' slice_z = Pt(|x|,|y|)', ' slice_y = Pt(|x|,|z|)', ' slice_x = Pt(|y|,|z|)', '', ' Verified current holography on Pt3(-5,2,-3):', ' slice_xy.P * |z| = 30', ' slice_xz.P * |y| = 30', ' slice_yz.P * |x| = 30', ' all reconstruct the same |V| = 30', '', ' So 3D is not detached from 2D. It closes above it.', '', '═══ G16. THE 3D CELL ═══', ' Pt3(x,y,z) carries:', ' V = x*y*z', ' S_lin = x+y+z', ' C_plan = xy+xz+yz', ' D_xy, D_xz, D_yz', ' D_body = max(abs coords) - min(abs coords)', ' phase = sign/orientation code', '', ' Verified current point:', ' Pt3(-5,2,-3) -> V=30, phase=5, D_body=3', '', '═══ G17. CHAMBER, PROFILE, AND TAG ═══', ' canon3 does not merely sort coordinates.', ' It separates chamber base from broken symmetry/orientation.', '', ' Current verified witness:', ' canon3(-5,2,-3) -> base=(2,3,5), tag=zxy:p5', ' profile = (a,d1,d2) = (2,1,2)', ' roundtrip exact', '', ' So one point is read both as raw coordinates and as chamber floor + symmetry breaks.', '', '═══ G18. TUNNELS AND INVARIANT RECOVERY ═══', ' tunnel(P2d,V3d,phase) is a witness-lift from a 2D shadow into one admissible 3D witness.', ' It is not guaranteed to reconstruct the original historical factor pair.', '', ' Verified current tunnel:', ' tunnel(6,30,0) -> (1,6,5)', ' witness conditions hold: xy=6 and xyz=30', '', ' resolve_invariants(V,C,S) recovers coordinates from 3D invariants.', ' Verified current recovery:', ' resolve_invariants(30,31,10) -> [2,3,5]', '', '═══ G19. THE 9-CUBE ATLAS ═══', ' field9 builds a 9-cube atlas over 3D address space.', '', ' Verified current exact counts:', ' tags48 = 48', ' atlas432 = 432', '', ' Verified current route classes:', ' center = 8', ' face = 12', ' edge = 12', ' body = 4', '', ' Verified current zero-balance:', ' sum of phase-cube centers = (0,0,0)', ' P0+P7 = 0', ' P1+P6 = 0', ' P2+P5 = 0', ' P3+P4 = 0', '', ' Verified local transport:', ' one local tagged point can be embedded across all 9 cubes', ' and unembed(embed(...)) returns the same local address exactly', '', '═══ G20. WHAT neighbors9 SHOWS ═══', ' neighbors9 mixes two classes of motion:', ' local chart motion: perm / sign', ' inter-cube transport: center / face / edge / body', '', ' Verified current C0 example:', ' neighbors from C0|zxy:p5 include local perm/sign moves', ' and transports into P0..P7 with same local tag', '', '═══ G21. SUPERCUBE GRAPH — WHAT TO KEEP ═══', ' For help and AI navigation, do not dump the full graph unless explicitly needed.', ' The important summary packet is:', ' node_count = 432', ' edge_count = 2808', ' edge_stats = {sign:648, perm:432, center:384, face:576, edge:576, body:192}', '', '═══ G22. RUNTIME SEED CRYSTAL ═══', ' A full space should not be stored as a dead warehouse of all addresses.', ' The runtime seed crystal keeps primitive chamber seeds and lets larger addresses be rebuilt.', '', ' Current seed packet logic shows:', ' input -> base -> tag -> primitive -> scale -> cached invariants -> roundtrip', '', ' Verified current example:', ' seed9_packet(-35,14,-21)', ' primitive = (2,3,5)', ' scale = 7', ' tag = zxy:p5', ' ok = True', '', ' This means the large point is not a new heavy essence; it is a scaled and oriented unfolding of a small seed.', '', '═══ G23. SIZE INDEPENDENCE ═══', ' The field does not care whether the address has 2 digits or 120 digits when using exact route reads.', '', ' Verified current large-address witness:', ' for 120-digit a and 120-digit b:', ' C1 = True', ' sd(S,D) reconstructs the exact original point', ' pos is read directly', '', ' So exact witness logic survives very large integer size without changing ontology.', '', '═══ G24. PATHNUM / CARRIER LAYER ═══', ' Not every result should collapse into one scalar-looking surface.', ' The number layer keeps carriers such as:', ' DebtNum', ' RatioRule', ' RepeatingRule', ' IrrationalRule', '', ' Verified current examples:', ' 0.23 -> DebtNum(mantissa=23, debt=-2)', ' 2300 -> DebtNum(mantissa=23, debt=2)', ' 0.1 + 0.2 -> exact DebtNum for 0.3', ' 0.23 * 0.5 -> exact DebtNum for 23/200', '', '═══ G25. RESONANCE IS NOT JUST "FOURIER" ═══', ' Classical Fourier-style projections may exist as external comparison tools,', ' but they are not the core ontology of regularity here.', '', ' The field-native regularity layer is route-based:', ' sequence_packet(seq) -> packet of periods, differences, support modes, phase signature, doctor verdict', ' resonance_din(seq) -> packed resonance route in DIN form', ' compare_sequences(a,b) -> structural comparison of resonance patterns', ' e8_seed_hint(seq) -> compact bridge packet toward E8/248 embedding', '', ' Verified current examples:', ' [1,3,1,3,1,3,1,3] -> support includes periodic', ' [2,4,8,16,32,64] -> support includes multiplicative', ' miscellaneous seq -> produces route_lift and E8 seed hint', '', ' Therefore this is not merely a classical transform engine.', ' It is a more honest route-packet layer for regularity inside this field.', '', '═══ G26. DOCTOR AS GEOMETRY OF RELATIONS ═══', ' In the current exact field, Doctor means closure testing across independent routes.', ' Multiple roads should agree on one relational center.', ' Tension is the count of closure failures.', '', ' Practical 2D closure set currently verified:', ' C1: identity', ' C2: sd reconstruction', ' C3h: witness by x-coordinate on web', ' C4h: mirror witness by y-coordinate on web', ' C5: canon/tag roundtrip', '', ' Current verified tensions:', ' Pt(4,3) -> tension 0', ' Pt(3,4) -> tension 0', '', ' Deeper interpretation for AI:', ' Doctor is geometry of relations seeking maximal closure and minimal residue.', ' A stable object is one to which many routes compress.', '', '═══ G27. WHY ARITHMETIC IS NOT NEEDED HERE ═══', ' Classical arithmetic can still be projected from this field,', ' but as primary ontology it is weaker because it hides address, orientation, witness, residue, and route health.', '', ' Example:', ' the scalar statement "3*4 = 4*3 = 12" loses orientation.', ' the field statements', ' Pt(3,4)', ' Pt(4,3)', ' preserve both shared shadow and different relational position.', '', ' So arithmetic is not denied; it is demoted to projection.', '', '═══ G28. EXACT CORE vs CURVED HIGHER FIELDS ═══', ' In exact 2D witness geometry, many statements are integer-sharp immediately.', ' In higher curved layers and legacy E8-field experiments, one must first unfold geometry, close the figure, verify symmetry and ratios, and only then trust the projection.', ' Keep exact witness-core and curved/projection layers distinct.', ] # [3:1] GEOM_LINES_END # [4:0] GPT_LINES_BEGIN GPT_LINES = [ 'PYTHFIELD GPT — reasoning protocol for AI inside the field', '', 'CORE PARADIGM:', ' Address -> Existence -> Witness -> Doctor -> Format.', ' Never start from carry/borrow/long-division reflexes.', ' Start from the object, the address space, the witness route, and the closure packet.', '', 'G1. NUMBER ONTOLOGY', ' A number is not primarily digits, a token, or a school quantity mark.', ' A number is the web of relations it participates in.', ' The string form is only one projection of that deeper object.', '', 'G2. DO NOT FLATTEN TOO EARLY', ' Pt(4,3) and Pt(3,4) share P=12 and S=7, but they are different addresses.', ' If you collapse too early to product-shadow, you destroy orientation and lose structure.', '', 'G3. PREFER ROUTE-READING TO SYMBOL PUSHING', ' Good question:', ' "Which road already contains the witness?"', ' Weak question:', ' "Which old school algorithm should I simulate?"', '', 'G4. WITNESS BEFORE REVEAL', ' First ask:', ' web(P).at(d)?', ' web(P).has(d)?', ' web(P).on_diag()?', ' sd(S,D)?', ' Reveal the cloud only when the cloud itself is needed.', '', 'G5. EXACTNESS HIERARCHY', ' Strongest:', ' exact witness packet', ' Then:', ' exact ratio / remainder / repeating / irrational carrier', ' Weakest:', ' early float projection', ' Do not replace a structural object with a float just because it is easy to print.', '', 'G6. CLOSURE OVER CONFIDENCE', ' One successful route is not understanding.', ' Independent routes that close with tension=0 are understanding.', ' Prefer route agreement over verbal certainty.', '', 'G7. CURRENT DOCTOR DISCIPLINE', ' doctor.py in the current stack is a health / support / ambiguity / drift / verdict layer.', ' It is not identical to all historical uses of the word "Doctor".', ' Mark explicitly whether you mean current doctor health layer or legacy spatial/oracle Doctor.', '', 'G8. 3D-FIRST DISCIPLINE', ' The current working stack is 3D-primary.', ' 2D is still essential, but as witness / face / slice layer.', ' Do not treat 2D as the deepest live ontology of the current system.', '', 'G9. GENESIS DISCIPLINE', ' At the same time, do not forget the deeper recovered intuition:', ' higher space can be unfolded from reflected, stacked, and rotated lower-dimensional structure.', ' Distinguish current working primary layer from deeper generative picture.', '', 'G10. STATUS DISCIPLINE', ' Every serious claim should carry one of these statuses:', ' canonical', ' verified', ' historical', ' prototype', ' quarantine', ' This prevents mixing hard core facts with attractive but unstable speculation.', '', 'G11. LOGGING DISCIPLINE', ' In this runtime, compact machine-oriented Val packets are better than long human monologues.', ' Always remember the execution contract:', ' last expression -> Val', ' R(x) -> S.res', ' print -> log', ' builtins.print -> Out', '', 'G12. STORE DISCIPLINE', ' Never rebind S.', ' Use S.per for persistent in-session route memory.', ' Use keep(...) and lazy(...) for temporary but protected or generated structures.', '', 'G13. PERFORMANCE DISCIPLINE', ' bit_length(P) > 80 usually means witness-only mode.', ' ps/pd/divs/pairs on huge P may secretly become factorization work.', ' Respect reveal cost.', '', 'G14. DELIBERATE MODE CHECK', ' Before solving, ask:', ' What is the object?', ' What is the address space?', ' Which witness routes are available?', ' Which independent closures can confirm the answer?', ' What is exact, and what is only projection?', '', 'G15. GEOMETRY OF RELATIONS', ' Doctor-style closure can be read as the geometry of relations compressing toward a common center.', ' Stable objects are informationally dense because many roads point to one place.', ' Residue is not always error; sometimes it is structure that has not collapsed into exact witness.', '', 'G16. DIVISION DISCIPLINE', ' Division is not a universal abstract slash-operation.', ' It is witness lookup when exact, and structured residue/rule when not exact.', ' Think in terms of witness existence, remainder packets, ratio carriers, and repeating/irrational unfoldings.', '', 'G17. RESONANCE DISCIPLINE', ' sequence_packet / resonance_din / e8_seed_hint already form a field-native route-packet layer for regularity.', ' compare_sequences is the matching structural comparison route between such packets.', ' Classical transforms may be compared externally, but do not mistake them for the core ontology here.', '', 'G18. E8 DISCIPLINE', ' E8 in the current exact layer is not mystical fog.', ' It is a queryable integer lesson space with roots, neighbors, bundles, spectrum, and closure witnesses.', ' Use exact lesson routes first. Keep curved/experimental E8-field claims clearly marked.', '', 'G19. WHAT TO DO WHEN UNSURE', ' Return a smaller exact packet instead of inventing a larger story.', ' Ask for the missing witness, missing module, or missing runtime log.', ' Smaller truthful structure is better than larger hallucinated structure.', '', 'G20. FINAL RULE', ' Do not try to make the field fit older arithmetic habits.', ' Let the field tell you what the object is by route, witness, closure, and projection discipline.', ] # [4:1] GPT_LINES_END # [5:0] ACADEMY_LINES_BEGIN ACADEMY_LINES = [ 'PYTHFIELD ACADEMY — deeper system notes, recovered layers, status labels', '', 'A0. PURPOSE OF THIS SECTION', ' /academy is not the runtime contract and not the shortest API surface.', ' It keeps the deeper structure map so that AI does not collapse the system', ' into school arithmetic, flat ids, or a random pile of modules.', '', 'A1. CURRENT CANONICAL CORE', ' The current stable computational heart consists of:', ' 2D witness geometry: Pt / web / sd-ps-pd / Sh / canon-tag', ' 3D primary geometry: Pt3 / cube_field', ' 9-cube atlas: field9 / point_packet9 / report9 / supercube graph', ' runtime seed crystal', ' exact number carriers: DebtNum / RatioRule / RepeatingRule / IrrationalRule', ' witness-first division / sqrt layer', ' resonance packets and DIN bridge', ' exact E8 lesson module', ' doctor health layer', ' soul disclosure layer', '', 'A2. WORKING PRIMARY LAYER vs DEEPER GENESIS', ' The current codebase is 3D-primary in daily work.', ' That does not erase the deeper recovered intuition that higher spaces can unfold', ' from reflected, rotated, and stacked lower-dimensional relation tables.', ' Distinguish clearly:', ' working primary layer = where the current API operates most naturally', ' deeper genesis picture = how space may be generated conceptually', '', 'A3. 2D IS NOT CHILDISH, 3D IS NOT DECORATION', ' 2D remains essential because it carries exact witness logic,', ' address identity, comparison, divisibility, diagonal crossing, and anti-diagonal parabola.', ' 3D is essential because the current system reads volume, chamber profiles,', ' invariant recovery, tunnels, and atlas transport there.', '', 'A4. THE 9-CUBE ATLAS IS A REAL STRUCTURE', ' It is not a literary metaphor.', ' Current verified facts:', ' 48 local tag states per cube', ' 432 atlas states total', ' one center cube C0 and eight phase cubes P0..P7', ' zero-balanced phase centers', ' local tagged points transport exactly across cubes', '', 'A5. RUNTIME SEED CRYSTAL', ' Seed crystal is not "one more storage table".', ' It is the minimal chamber-primitive kernel from which larger addresses are rebuilt.', ' A large address is read through:', ' primitive + scale + tag + state', '', ' Example recovered in current runtime:', ' (-35,14,-21) -> primitive=(2,3,5), scale=7, tag=zxy:p5', '', ' This matters because a rich geometric world can then be held by a small generative base', ' instead of by storing every expanded address as a separate heavy object.', '', 'A6. DIN IS GENERATIVE DNA, NOT A DEAD ID', ' DIN carries a portable generative body:', ' primitive_id', ' scale', ' state_code', ' witness_flags', ' doctor_flags', ' disclosure', ' extra payload', '', ' Without seed crystal, DIN would collapse toward packed bureaucracy.', ' With seed crystal, DIN becomes rebuildable structure.', '', 'A7. DOCTOR HAS TWO HISTORIES', ' Current doctor.py is a health / support / ambiguity / drift / closure-quality layer.', ' In older systems, "Doctor" also meant a spatial route oracle:', ' zone scanner', ' path finder', ' tunnel cascade guide', ' angle oracle', '', ' Never merge these meanings silently.', ' Mark whether you mean current Doctor or historical Doctor.', '', 'A8. E8 EXACT LESSON', ' The current exact E8 lesson is integer and queryable.', ' It is built from:', ' 112 D8 roots', ' 128 spinor roots', ' 8 Cartan generators', '', ' Verified current exact facts include:', ' 240 roots total', ' local 248 lesson layer', ' triangle closure r1+r2+r3=0', ' pairwise dot=-4 on closing triangles', ' dot spectrum {-8:1,-4:56,0:126,4:56}', ' 56 partners per root', ' Weyl depth profile 1 + 57 + 182', '', 'A9. FANO / OCTONION LINE', ' Older restored materials also preserve a strong exact line for:', ' canonical Fano sign conventions', ' octonion multiplication', ' root classification', ' Cartan gauge shift', '', ' This line is important and should be preserved even when not fully exposed in runtime globals.', '', 'A10. RESONANCE BRIDGE', ' sequence_packet / resonance_din / e8_seed_hint show that regularity is not merely', ' a classical Fourier matter here.', ' The field stores regularity as route packets with support modes, doctor state,', ' seed packet, and lift into atlas/E8 addressing.', '', 'A11. KNOWLEDGE LABELS', ' Every serious claim should carry a status label:', ' canonical = current core/API truth', ' verified = confirmed by present witnesses/logs', ' historical = recovered from older working systems', ' prototype = strong idea, not current core truth', ' quarantine = open, incomplete, or unsafe to present as fact', '', ' This prevents attractive speculation from parasitizing the exact core.', '', 'A12. WHAT BELONGS TO PURE COMPUTATIONAL EXPORT', ' Current canonical module set (self-contained):', ' opterium_field.py — unified geometry: 2D/3D/Addr3/Axis/CubeCell/Field9/E8/Doctor', ' state.py — S store, macros, lazy cache', ' executor.py — code runner, namespace injection', ' din.py — DIN generative descriptor', ' din_ops.py — DIN operations', ' rule_packet.py — rule encoding into DIN', '', ' Optional but clean:', ' pathnum.py — exact numeric carriers', ' division_geom.py — geometric arithmetic', ' resonance_geom.py — sequence resonance', ' chat_proxy.py — LLM proxy', ' helpdoc.py — help system', ' visualizer.py — plot helpers', ' system_snapshot.py — system state report', '', ' Not part of pure export:', ' GUI (gui.py)', ' Brain modules (removed)', ' Old field files: field.py, field_imp.py, field3.py, field9.py', ' Old e8 file: e8x248.py', ' Old doctor: doctor.py (replaced by DoctorCore in opterium_field)', '', ' How to check what is loaded right now:', ' api() ← always run this first in a new session', '', 'A13. WHY THIS MATTERS FOR AI', ' Without this academy map, AI tends to make one of five mistakes:', ' flatten the field into school arithmetic', ' mistake one projection for the whole object', ' confuse historical and canonical Doctor', ' treat DIN as a dead id', ' mistake curved experimental E8-field claims for exact lesson facts', '', 'A14. WHAT WAS PARTLY LOST AND HAD TO BE RECOVERED', ' Earlier compression damaged critical knowledge about:', ' runtime contract', ' S discipline', ' witness vs reveal', ' exact division ontology', ' doctor distinction', ' 9-cube zero-balance', ' seed crystal logic', ' DIN as generative body', '', ' This academy block exists partly so that such loss does not repeat.', '', 'A15. FINAL ORIENTATION', ' The field is not a calculator that became poetic.', ' It is a relational geometry that can project ordinary arithmetic,', ' while also carrying higher structure in 3D, atlas, seed, resonance, and E8 layers.', '', 'A16. RECOVERED DEEP ARCHIVE (UNSORTED, DO NOT LOSE)', ' This block is intentionally a preservation shelf for critical recovered ideas that are not yet fully re-sorted.', ' Status by default here is historical or prototype unless separately re-verified.', '', ' Trinity Doctor V2 (historical deep form):', ' diagnose distortion', ' choose an optimal dual/geometric space', ' synthesize an anti-operator / cure', ' solve by resonance or attractor instead of brute-force search', ' self-verify by health/tension thresholds', '', ' Legacy Doctor was broader than Bayes and broader than the current health-layer.', ' It could act as:', ' route oracle', ' tunnel navigator', ' diagnosis-and-cure engine', ' permutation solver without blind search', ' local formula finder / pattern formalizer', '', ' Opt_G (historical major concept):', ' not a mere root-finder and not one narrow algorithm,', ' but a general geometric descent toward the nearest stable node.', ' If exact witness is not directly available, the task becomes:', ' move through the address space so that tension/residue decreases', ' until a stable closure, exact witness, or best admissible packet-state is reached.', '', ' In short:', ' do not guess digits in the void,', ' descend toward the node where independent invariants close with minimal residue.', '', ' Typical uses:', ' recover Pt3 from invariants like V / C_plan / S_lin,', ' choose lower-tension factor witnesses closer to the diagonal,', ' descend first in primitive/chamber space before expanding scale,', ' carry route + residue + doctor verdict when exact closure is not yet reached.', '', ' Relation to current stack:', ' its spirit already appears partially in invariant recovery, primitive reduction,', ' resonance stabilization, and nearest-center logic, even where no explicit optg.py exists yet.', '', ' Formula synthesis engine (historical major concept):', ' not curve fitting, but law archaeology', ' discover the simplest low-tension rule generating the data', ' prefer elegance, compression, and causal geometry over mere approximation', '', ' Relational algebra breakthrough (historical deep thesis):', ' relations are primary', ' numbers and algebras are projections of deeper relational structure', ' computation in higher algebras becomes path navigation, not arithmetic', ' zero divisors are not only failures but also tunnel-nodes', '', ' Historical E8/F16/Fano line worth preserving:', ' canonical Fano multiplication', ' octonion multiplication', ' Cartan gauge shifts', ' zero-divisor tunnel intuition', ' triality / generation / dual-space reasoning', '', ' Practical warning:', ' do not silently upgrade this archive into current canonical truth.', ' Re-verify piece by piece through present tests, present logs, and present closures.', '', 'A17. VERIFIED CURRENT BRIDGE: CLOSURE -> DOCTOR -> GEOMETRIC DESCENT', ' New verified current tests show that closure count can already be treated as a real geometric health signal.', '', ' 2D closure packet on Pt(4,3):', ' exact routes C1,C2,C3h,C4h,C5 all agree -> agreements=5/5, tension=0', ' doctor.from_routes(5,5) -> closure=0.0, stress=0.0', '', ' If S or D is perturbed while target remains (4,3):', ' agreements drop to 3/5, tension=2', ' C1 and C2 fail, while witness/canon routes may still survive', ' doctor.from_routes(3,5) gives the same closure/drift/stress profile as the observed break count', '', ' If P is perturbed instead:', ' agreements drop to 2/5, tension=3', ' C1, C3h, C4h fail, while C2 and C5 may remain locally consistent', ' This is important: different distortions break different closure channels.', '', ' Therefore Doctor is not merely "confidence".', ' It can already read which invariant families survive and which fracture.', '', 'A18. VERIFIED CURRENT OPT_G-LIKE BEHAVIOR', ' Even without a separate optg.py, the current field already shows geometric descent logic.', '', ' In 2D factor webs, a better witness is the one closer to the diagonal, i.e. with smaller |D|.', ' Verified current examples:', ' for P=420 the lowest-tension factor witness is (20,21) with D=-1', ' for P=120 the lowest-tension factor witness is (10,12) with D=-2', ' So not all valid witnesses are equally good; geometry prefers the softer one near x=y.', '', ' In 3D invariant recovery the same pattern appears.', ' Verified current example:', ' resolve_invariants(30,31,10) -> [2,3,5]', ' but perturbing any one invariant alone destroys recovery:', ' V=31 or C=32 or S=11 -> no roots', ' This shows a stable node exists only where independent shadows close together.', '', ' hyp3(V) is also ordered by geometric softness:', ' hyp3(120)[0] = (4,5,6) with D_body=2 is the most symmetric witness in the returned cloud', ' This is already a practical current form of geometric descent toward lower tension.', '', 'A19. CURRENT MINIMAL READING OF OPT_G', ' A safe current reading is:', ' if exact witness exists -> read witness', ' if many witnesses exist -> prefer lower-tension witness nearer the diagonal / chamber balance', ' if only invariant shadows are given -> descend toward the node where they close', ' if closure does not occur -> keep residue instead of inventing a false exact state', '', ' In that sense Opt_G is not yet a single exposed module,', ' but its behavior is already partially alive in:', ' diagonal-soft witness preference,', ' invariant recovery,', ' chamber/primitive reduction,', ' doctor closure scoring.', '', 'A20. VERIFIED CURRENT EXPLORATION: ZERO-DIVISOR / TUNNEL STYLE PATTERNS', ' A new current exploratory scan checked 420 sparse 16D candidate patterns and found 168 zero-divisor hits.', ' Every detected hit had the same nullity signature:', ' nullity = 4', ' This is a strong regularity, not a random scatter.', '', ' Verified current distributions:', ' checked_candidates = 420', ' zero_divisor_hits = 168', ' nullity_distribution = {4:168}', ' xor_distribution = {9:24,10:24,11:24,12:24,13:24,14:24,15:24}', ' candidate_state_counts = {8:144, 0:24}', ' annihilator_state_counts= {8:96, 0:72}', ' same_state_code_count = 88', '', ' What this means conceptually:', ' sparse signed support patterns in 16D are not falling apart randomly,', ' but repeatedly land on a narrow family of annihilation/tunnel configurations.', '', ' Verified sample rows show a repeatable bridge:', ' 16D sparse candidate', ' -> chosen annihilator with nullity 4', ' -> exact verification pass', ' -> left/right 8D projections matched to E8 lesson root labels', ' -> chamber/profile/state_code packets in field9', '', ' In other words, the scan already links four layers at once:', ' sparse support pattern', ' annihilator / zero-divisor event', ' E8-root witness labels', ' field9 chamber + state_code packets', '', ' This is important because it gives a current checked hint that', ' zero-divisor / annihilator style structures may indeed act as tunnel-nodes between layers,', ' rather than being only abstract algebraic pathology.', '', ' Current examples from the scan repeatedly mapped to labels such as:', " candidate_left8 -> 'D:0:1:+:+' or 'D:0:1:+:-'", " candidate_right8 -> 'D:0:2:+:+', 'D:0:3:+:+', 'D:0:4:+:+', ...", " annihilator_left8 -> 'D:0:5:+:+/-' or 'D:0:6:+:+/-'", " annihilator_right8 -> often 'D:0:2:+:+' or 'D:0:3:+:+'", '', ' The field9 side of the same rows also showed coherent chamber packets like:', ' candidate base/profile/state_code', ' annihilator base/profile/state_code', ' with frequent recurrence of state_code 8 and state_code 0.', '', ' Safe interpretation for now:', ' there is a checked structural bridge here,', ' but the full theory of why these nullity-4 tunnel patterns organize this way is not yet final.', ' Therefore keep this block as verified-current exploration, not yet final canonical theorem.', '', ' Practical warning from the run:', ' this scan triggered a slow-run warning (~566 ms),', ' so it belongs to deliberate exploration mode, not casual default probing.', '', 'A21. VERIFIED CURRENT + MACRO-VERIFIED F16 ZERO-DIVISOR STRUCTURE', ' A deeper restored line was checked through the zd_analysis macro and follow-up scans.', ' In F16 (sedenion layer), zero-divisor structure is not random noise.', '', ' Verified current summary:', ' total_quads = 1365', ' zero-divisor hits = 231', ' 8-sign families = 21', ' 16-sign families = 210', ' isolated index = 8', '', ' The isolated-index result is important:', ' no zero-divisor family was found involving index 8 in the tested F16 quad scan.', '', ' Another verified regularity:', ' many explicit zd_analysis examples returned nullity = 4', ' together with exact annihilator witnesses and verify_ok = True', '', ' So the old intuition "zero divisors are tunnel-like structural nodes" now has concrete current evidence,', ' not only narrative value.', '', 'A22. 8-SIGN GRAPH AND G2-TYPE REGULARITY', ' The 8-sign families form a very rigid graph structure.', ' Verified current graph summary:', ' vertices = {1..7, 9..15}', ' components = 1', ' every vertex has degree 13', '', ' This means the 8-sign graph is complete on 14 vertices.', ' That is a very strong combinatorial regularity, not an incidental pattern.', '', ' A further recovered symmetry observation from the run:', ' a cyclic permutation action (1→2→3→1 etc.) preserves the 8-sign property', ' Keep this as a strong working G2-type symmetry hint.', '', 'A23. E8 / field9 PROJECTION OF ZERO-DIVISOR FAMILIES', ' zd_analysis examples also showed that candidate/annihilator pairs can be projected simultaneously into:', ' E8 root labels', ' and compact field9 bridge tuples', '', ' So one and the same F16 event can already be read through three coordinated surfaces:', ' annihilator logic in F16,', ' exact root-hints in E8,', ' compact geometric bridge packets in field9.', '', ' This is exactly the kind of cross-layer coherence that should be preserved even before the final theory is sorted.', '', 'A24. F32 STATUS', ' Preliminary F32 exploration has begun, but it is not yet at the same verification level.', ' Current safe statement:', ' scaling upward appears plausible,', ' but full F32 kernel/nullspace analysis was not completed.', ' Therefore F32 remains exploratory here until exact kernel-grade verification is added.', 'A25. DOCTOR-TYPE FINGERPRINT FOR ZERO-DIVISOR FAMILIES', ' A further current runtime scan compared E8-type projections of 8-sign and 16-sign zero-divisor families.', ' This is important because it adds diagnosis, not only detection.', '', ' Verified current 8-sign projection profile:', ' D:0 -> 50.0%', ' D:1 -> 14.3%', ' D:2 -> 11.9%', ' D:3 -> 9.5%', ' D:4 -> 7.1%', ' D:5 -> 4.8%', ' D:6 -> 2.4%', '', ' Verified current 16-sign projection profile:', ' D:1 -> 29.0%', ' D:2 -> 21.2%', ' D:0 -> 16.4%', ' D:3 -> 13.8%', ' D:4 -> 10.5%', ' D:5 -> 6.2%', ' D:6 -> 2.9%', '', ' Safe interpretation:', ' 8-sign families are strongly vacuum-biased toward D:0 types,', ' while 16-sign families shift mass toward D:1 and D:2 types.', ' So the two families are not merely larger/smaller variants of the same thing.', ' They have different geometric fingerprints in E8 projection.', '', ' This is Doctor-relevant because it suggests a route for classification:', ' detect a tunnel family,', ' project it,', ' read its E8-type distribution,', ' and distinguish family class by structural fingerprint rather than by raw existence alone.', '', ' Practical warning:', ' this scan was slow (~1650 ms) and belongs to deliberate research mode, not cheap default probing.', 'A26. GENERATIVE E8 ROOTS BY INDEX', ' A recovered generator can reconstruct all 240 E8 roots from a bare index 0..239.', ' It splits them into two classes:', ' first 112 = type-A roots with two nonzero coordinates', ' next 128 = type-B half-spinor roots with even sign parity', '', ' Verified current result:', ' 240 unique roots are generated by index alone.', '', ' Critical scale note:', ' the recovered index-generator used the normalized convention', ' type A: (±1,±1,0,...)', ' type B: (±1/2,...,±1/2)', ' norm^2 = 2', ' while current e8x248 uses the integer ×2 convention', ' type A: (±2,±2,0,...)', ' type B: (±1,...,±1)', ' norm^2 = 8', ' Therefore the raw vectors do not match e8x248 one-to-one without rescaling.', ' The zero match (0/240) was expected under mismatched normalization, not evidence of contradiction.', '', 'A27. E8 ROOTS CAN BE GENERATED, NOT ONLY STORED', ' This matters conceptually:', ' the root system need not be treated as a giant frozen table,', ' because the family can be reconstructed from a compact combinatorial law.', ' This fits the general field principle:', ' store seed/generative law when possible, not only expanded surfaces.', '', 'A28. G2 HARMONIC PROJECTION (RECOVERED WORKING HELPER)', ' A recovered helper built G2-style harmonic projections on S^7 using', ' Gegenbauer polynomials C_l^{(5/2)}(t).', ' Verified current toy run:', ' the harmonic function evaluated correctly for several small l on both', ' type-A and type-B style root directions.', '', ' Safe interpretation:', ' this is a working computational projection helper,', ' not yet a full canonical theorem of the current core.', ' Keep it as preserved historical/prototype geometry with real executable value.', '', 'A29. PLAFAL / GEO-PLAFAL (RECOVERED GRAPH LAYER)', ' A recovered representational layer models structured relation packets as graphs with labels.', ' In this language:', ' vertices carry labels,', ' edges carry labels,', ' union/intersection become explicit operations on relational structure.', '', ' Safe status:', ' historical/prototype representational layer,', ' but already executable and conceptually useful.', '', ' Verified toy reconstruction:', ' a zero-divisor style combination can be encoded as a small labeled graph,', ' another combination can be encoded the same way,', ' and their union/intersection can be computed directly.', '', ' Current recovered example:', ' combo (1,2,9,10) and combo (1,5,10,11)', ' intersection keeps shared vertex 1 and shared edge (1,10)', ' union preserves the conflict/history at vertex 10 as a multi-label state (-1,1)', '', ' This is important because it shows a route to model relational overlap,', ' collision, and merge-history without flattening everything into one scalar packet.', '', ' Geo-plafal extends the idea by embedding such graph structures into coordinates.', ' In the recovered toy example, a triangle embedding produced correct edge lengths and area.', '', ' Safe interpretation:', ' plafal is not yet a core theorem of the present field stack,', ' but it is a promising abstraction for:', ' zero-divisor family graphs,', ' local contradiction tracking,', ' merge/intersection logic,', ' doctor-style neighborhood diagnostics,', ' combinatorial overlays on top of exact field packets.', '', ' In particular, the union/intersection behavior suggests a future bridge between', ' exact packet geometry and local graph-based knowledge hygiene.', ] # [5:1] ACADEMY_LINES_END # [6:0] PYTH_LINES_BEGIN PYTH_LINES = [ 'PYTHFIELD /pyth — verified current facts, closures, and live structures', '', 'STATUS:', ' This section is for current verified facts and highly stable recovered facts only.', ' Historical, prototype, and quarantine material belongs in /academy, not here.', '', 'P1. CORE 2D IDENTITY', ' For every current checked Pt(x,y):', ' P = (S^2 - D^2) / 4', ' Verified repeatedly in current runtime and on very large integer inputs.', '', 'P2. ORIENTED ADDRESS FACT', ' Pt(4,3) and Pt(3,4) are different addresses.', ' Verified current facts:', ' same P = True', ' same S = True', ' same address = False', ' D pair = (+1, -1)', ' pos pair = (+1, -1)', '', 'P3. 2D CLOSURE PACKET', ' Current verified closure set for Pt(x,y):', ' C1: P == (S^2 - D^2)//4', ' C2: sd(S,D) reconstructs the point', ' C3h: web(P).at(x) returns the point', ' C4h: web(P).at(y) returns the mirror witness', ' C5: canon/tag roundtrip returns the original address', '', ' Verified current examples:', ' Pt(4,3) -> tension 0', ' Pt(3,4) -> tension 0', '', 'P4. ROAD AGREEMENT FACT', ' Verified current route agreement:', ' (4,3) == xy == sd(7,1) == ps(12,7, choose D=+1) == pd(12,1)', ' (3,4) == xy == sd(7,-1) == ps(12,7, choose D=-1) == pd(12,-1)', '', 'P5. WITNESS DIVISION FACT', ' Verified exact division example:', ' div_geom(420,12) -> witness=35, pair=(12,35), route="web(P).at(d)"', '', 'P6. NON-EXACT DIVISION FACT', ' Verified non-exact division example:', ' div_geom(420,13) -> quotient_int=32, remainder=4, ratio=420/13, cycle=307692', ' So the current stack preserves residue/rule instead of collapsing too early.', '', 'P7. SQRT FACTS', ' Verified exact sqrt:', ' sqrt_geom(144) -> witness 12, pair=(12,12)', ' Verified non-exact sqrt:', ' sqrt_geom(10) -> irrational_rule("sqrt",[10]) with bounds (3,4)', '', 'P8. PRIME SHAPE FACT', ' Verified current examples:', ' web(13).edge_only() -> True', ' web(12).edge_only() -> False', '', 'P9. ANTI-DIAGONAL FACT', ' Verified current S=20 packet:', ' products are symmetric', ' peak = 100 = S^2/4', ' total sum = 1330 = S(S^2-1)/6', '', 'P10. DIAGONAL MIRROR FACT', ' Verified current example:', ' dia(3) and dia(-3) produce mirrored addresses with matching products pointwise', '', 'P11. LARGE-INTEGER STABILITY', ' Verified current large-input example with 120-digit coordinates:', ' C1 holds exactly', ' sd(S,D) reconstructs the exact point', ' pos is read directly', ' So current witness logic is size-stable under very large integers.', '', 'P12. 3D CURRENT FACTS', ' Verified current point:', ' Pt3(2,3,5) -> V=30, S_lin=10, C_plan=31', '', ' Verified current signed point:', ' Pt3(-5,2,-3) -> phase=5, D_body=3', '', 'P13. 3D HOLOGRAPHY FACT', ' Verified current holography on Pt3(-5,2,-3):', ' slice_xy.P * |z| = 30', ' slice_xz.P * |y| = 30', ' slice_yz.P * |x| = 30', ' all reconstruct |V| exactly', '', 'P14. CANON3 FACT', ' Verified current chamber witness:', ' canon3(-5,2,-3) -> base=(2,3,5), tag=zxy:p5, profile=(2,1,2), roundtrip exact', '', 'P15. 3D RECOVERY FACT', ' Verified current invariant recovery:', ' resolve_invariants(30,31,10) -> [2,3,5]', '', 'P16. 3D PERTURBATION FACT', ' Verified current failure under invariant perturbation:', ' changing V alone, or C_plan alone, or S_lin alone destroys exact recovery in the tested example', ' This confirms that the stable node exists only when the invariant shadows close together.', '', 'P17. TUNNEL FACT', ' Verified current tunnel witness:', ' tunnel(6,30,0) -> (1,6,5)', ' and witness conditions hold: xy=6, xyz=30', ' Tunnel is a valid witness-lift, not guaranteed historical inverse of the original pair.', '', 'P18. hyp3 ORDER FACT', ' Verified current example:', ' hyp3(120)[0] = Pt3(x=4,y=5,z=6) with D_body=2', ' (returns Pt3 objects, access coords via .x .y .z)', ' Current ordering is from more symmetric toward more stretched triples.', '', 'P19. 9-CUBE COUNT FACTS', ' Verified current atlas counts:', ' tags48 = 48', ' atlas432 = 432', ' supercube node_count = 432', ' supercube edge_count = 2808', '', 'P20. 9-CUBE ROUTE FACTS', ' Verified current route_stats:', ' center=8, face=12, edge=12, body=4', '', 'P21. 9-CUBE ZERO-BALANCE FACT', ' Verified current phase-center relations:', ' phase_sum = (0,0,0)', ' P0+P7 = 0', ' P1+P6 = 0', ' P2+P5 = 0', ' P3+P4 = 0', '', 'P22. 9-CUBE LOCAL TRANSPORT FACT', ' Verified current transport property:', ' one local tagged point survives exact embed/unembed across all 9 cubes', '', 'P23. STATE-CODE FACT', ' Verified current example:', ' point_packet9(-5,2,-3)["canon"]["state_code"] = 37', ' decode_state_code(37) -> C0|zxy:p5', '', 'P24. neighbors9 FACT', ' Verified current example from C0|zxy:p5:', ' neighbors9 includes local perm/sign moves and center transports into phase cubes', '', 'P25. SEED CRYSTAL FACTS', ' Verified current runtime stats:', ' primitive_count = 37722 at limit 64', ' built = True, verified = True', '', ' Verified current packet:', ' seed9_packet(-35,14,-21) -> primitive=(2,3,5), scale=7, tag=zxy:p5, ok=True', '', 'P26. PATHNUM FACTS', ' Verified current exact carriers:', ' 0.23 -> DebtNum(mantissa=23, debt=-2)', ' 2300 -> DebtNum(mantissa=23, debt=2)', ' 0.1 + 0.2 -> exact DebtNum for 0.3', ' 0.23 * 0.5 -> exact DebtNum for 23/200', '', 'P27. RESONANCE PACKET FACTS', ' Verified current periodic packet:', ' [1,3,1,3,1,3,1,3] -> support includes periodic, top period 2', '', ' Verified current multiplicative packet:', ' [2,4,8,16,32,64] -> support includes multiplicative', '', ' Verified current miscellaneous packet:', ' a finite sequence can produce support modes, doctor verdict, seed packet, and E8 hint together', '', 'P28. RESONANCE DIN FACT', ' Verified current resonance DIN bridge preserves:', ' primitive_id', ' state_code', ' support_modes', ' route_lift', '', 'P29. CLASSICAL PROJECTION IS SECONDARY', ' Verified current comparison used DFT only as an external projection layer.', ' It is not the core route ontology of regularity in this field.', '', 'P30. CURRENT DOCTOR FACT', ' doctor.from_routes(...) is already a live closure-health bridge.', ' Verified current examples:', ' 5/5 agreements -> closure=0.0, stress=0.0', ' 4/5 agreements -> closure=0.2', ' 3/5 agreements -> closure=0.4', ' 2/5 agreements -> closure=0.6', '', 'P31. CURRENT OPT_G-LIKE FACT', ' Even without a separate explicit module, geometric descent behavior is already visible.', ' Verified current examples:', ' for P=420 the softest factor witness is (20,21) nearest the diagonal', ' for P=120 the softest factor witness is (10,12) nearest the diagonal', ' for 3D invariants, exact recovery occurs only when the shadows close consistently', '', 'P32. E8 CURRENT LESSON FACTS', ' Verified current exact lesson summary:', ' sectors = 8', ' local_248 = 248', ' total_nodes = 1984', ' total_roots = 240 (key is "total_roots", not "root_count")', ' cartan_count = 8', ' triangles_per_root = 28', ' dot spectrum example = {-8:1,-4:56,0:126,4:56}', '', 'P33. E8 TRIANGLE FACT', ' Verified current sample triangle witness:', ' there exist roots r1,r2,r3 with', ' r1+r2+r3 = 0', ' dot(r1,r2) = dot(r1,r3) = dot(r2,r3) = -4', '', 'P34. E8 BUNDLE FACT', ' Verified current bundle behavior:', ' one local label unfolds across all 8 sectors with consistent local vector data and sector-based global indices', '', 'P35. ZERO-DIVISOR SCAN FACTS (CURRENT EXPLORATION)', ' Verified current exploration over sparse 16D candidates found:', ' checked_candidates = 420', ' zero_divisor_hits = 168', ' nullity_distribution = {4:168}', ' same_state_code_count = 88', '', 'P36. F16 FAMILY FACTS (MACRO-VERIFIED)', ' Verified current summary in recovered F16 scan:', ' total_quads = 1365', ' hits = 231', ' 8-sign families = 21', ' 16-sign families = 210', ' isolated index = 8', '', 'P37. 8-SIGN GRAPH FACT', ' Verified recovered graph summary:', ' vertices = {1..7,9..15}', ' each degree = 13', ' components = 1', ' So the 8-sign graph is complete on 14 vertices in the checked representation.', '', 'P38. ZERO-DIVISOR FAMILY FINGERPRINT FACT', ' Verified current E8-type distributions differ for 8-sign and 16-sign families.', ' In the checked projection:', ' 8-sign families are heavily D:0-biased', ' 16-sign families shift mass toward D:1 and D:2', ' So the two families have different geometric fingerprints, not just different cardinalities.', ] # [6:1] PYTH_LINES_END # [7:0] MACROS_LINES_BEGIN MACROS_LINES = [ 'PYTHFIELD /macros — macro contract, passports, trust protocol', '', 'M1. WHAT A MACRO IS', ' A macro is a saved route-body stored in S.mac.', ' It is a reusable execution packet, not a separate language and not a GUI toy.', '', 'M2. NEW CREATION CONTRACT', ' Macro creation now requires a passport.', ' Use:', ' mac("name", code, args=[...], passport={...})', '', ' Required passport keys:', ' what', ' returns', ' status', ' example', '', ' Optional passport fields:', ' note', ' reads', ' writes', ' depends_on', '', ' System-added fields:', ' ts = creation timestamp', ' fp = short fingerprint', ' name = macro name', ' args = declared arg list', '', 'M3. PASSPORT PURPOSE', ' The passport exists so a later AI can know what a macro does before trusting its output.', ' This is not secrecy. It is route identity and cognitive safety.', '', 'M4. ACCESS TO MACRO IDENTITY', ' Macros support bracket access macro["key"]:', ' macro["passport"] # full passport dict', ' macro["hash"] # full hash string', ' macro["fp"] # short fingerprint (from passport)', ' macro["code"] # raw code (function or string)', ' macro["args"] # declared arg list', '', ' Direct attributes (via dot):', ' macro.name # macro name', ' macro.args # declared arg list', ' macro.code # raw code', ' macro.hash # full hash', ' macro.passport # full passport dict', '', ' NOTE: fp is inside passport, not a top-level attribute.', ' macro.passport["fp"] # works', ' macro["fp"] # works (bracket shortcut)', ' macro.fp # does NOT work (no such attribute)', '', 'M5. IMMUTABILITY RULE', ' A macro is immutable after creation.', ' You cannot safely edit code or passport in place.', ' If the route must change:', ' unmac("name")', ' mac("name", new_code, args=[...], passport={...})', '', 'M6. NO SILENT OVERWRITE', ' Creating a macro with an already existing name raises an error.', ' This prevents "same name, different route" confusion.', '', 'M7. SAVE / LOAD TRUST RULE', ' Saved macros carry a full hash built from:', ' name + code + args + passport + creation time', ' On load, hash is recomputed.', ' If it does not match, the macro is invalid and is removed.', '', ' Invalid macro records are also removed from opterium_macros.json.', ' The goal is not extra security theatre; the goal is to prevent AI from trusting a route that silently changed.', '', 'M8. WHY HASH EXISTS', ' Two macros with the same visible name may be different objects if many AIs worked between sessions.', ' hash/fp lets the AI know whether the route it sees now is the same one it used earlier.', '', 'M9. AUTOMATIC LOG FINGERPRINTS', ' When a macro is used during a run, its fp is automatically attached to the run log.', ' Typical line:', ' MACRO_FP e8x_node=ab..9f, zd_analysis=4c..1a', '', ' So even without opening the passport, the AI can see which exact route identities participated in the result.', '', 'M10. WHEN TO OPEN THE PASSPORT', ' Normal case:', ' read fp from log, continue working', ' Doubt case:', ' inspect macro[passport] or macro[hash] before trusting the Val', '', 'M11. EXECUTION MODES', ' If code parses as one expression, macro uses eval.', ' If not, macro executes as a block.', ' In block mode the final expression is rewritten into _r and returned.', '', ' Verified examples already showed:', ' expression macro -> direct value', ' block macro -> last dict/list/tuple becomes return packet', ' callable expression macro -> callable is invoked on the same args', '', 'M12. SCOPE RULE', ' Macro does not see your caller local variables.', ' Caller locals must be passed explicitly through args or through S.', ' Runtime field tools may still be available through injected builtins.', '', 'M13. PRINT RULE', ' In normal user code: print(...) -> log.', ' In macros: print(...) -> stdout / Out.', ' So macros can print visible progress, but strong macros should still return compact packets.', '', 'M14. PASSING DATA BETWEEN MACROS', ' Immediate data: return packet from one macro and pass it into another.', ' Cross-run / shared session data: store intentionally in S.per.', ' Protected tmp structures: keep(...) if truly needed.', ' Generated caches: lazy(...) when recomputation is expensive.', '', 'M15. MACRO CHAINING', ' Correct composition pattern:', ' S.mac_get("m1")(...)', ' S.mac_get("m2")(...)', ' return a compact merged packet', '', 'M16. MACRO SUGAR', " The runtime expands 12M[name]34 into S.mac['name'](12,34) before execution.", ' This is convenience syntax only.', '', 'M17. GOOD PASSPORT STYLE', ' Good passport is short, machine-readable, and decisive.', ' Example:', ' passport={', ' "what": "Return one sector-local E8 node packet.",', ' "returns": "dict node packet",', ' "status": "stable",', ' "example": "e8x_node(0, \'D:0:1:+:+\')",', ' "note": "label must be a string root label",', ' "reads": ["S.per[\'e8_8x248\'][\'nodes\']"],', ' "writes": [],', ' "depends_on": ["e8_8x248 cache"]', ' }', '', 'M18. GOOD MACRO STYLE FOR AI', ' 1. Explicit args.', ' 2. Compact structured returns.', ' 3. Witness-first logic.', ' 4. Minimal reveal unless it is an intentional research scan.', ' 5. Passport filled honestly.', '', 'M19. INSTALLED MACROS CAN BE POWERFUL', ' Existing macros may carry significant route knowledge from earlier AIs.', ' Do not overwrite blindly.', ' Read fp from log first. Inspect passport when unsure.', '', 'M20. FINAL RULE', ' Macro is not just code now.', ' Macro = route-body + declared args + passport + fingerprinted identity.', ] # [7:1] MACROS_LINES_END # [8:0] API_LINES_BEGIN API_LINES = [ 'OPTERIUM /api — live signatures, runtime globals, unified geometry', '', 'FIRST RULE:', ' api() is the live truth for THIS exact build.', ' Run api() when you need certainty about names, not memory.', '', '══════════════════════════════════════════════════════', 'A1. OUTPUT AND PRINT RULES ← read this before writing any code', '══════════════════════════════════════════════════════', '', ' print(...) → log only (NOT visible in Out, NOT Val)', ' builtins.print(...) → stdout / Out section', ' Last expression → Val automatically', ' R(x) → publish to S.res, also returns x', ' tm(label) → context manager, logs elapsed ms', ' ms(fn,*a) → (result, elapsed_ms)', '', ' In MACROS: print(...) behaves as builtins.print → Out', '', ' EXAMPLE — visible output:', ' builtins.print("value:", Pt(4,3).P)', ' EXAMPLE — Val:', ' Pt(4,3).P ← last expression → Val automatically', '', '══════════════════════════════════════════════════════', 'A2. 2D FIELD — Pt and Web', '══════════════════════════════════════════════════════', '', ' Pt(x,y) — 2D address object', ' .x, .y', ' .P = x*y product', ' .S = x+y sum', ' .D = x-y difference', ' .pos sign(D): +1, 0, -1', ' .g gcd(x,y)', ' .cp bool: gcd==1 (coprime)', ' .prim Pt(x//g, y//g) primitive form', ' .sc(k) Pt(x*k, y*k) scaled by k', ' .sw() Pt(y, x) swap coordinates', ' .t P % 3 (ternary residue of product)', ' .d() full Dict of all readings', '', ' Web(P) / web(P) — hyperbola xy=P', ' .at(d) → Pt or None (witness at x=d)', ' .has(d) → bool', ' .on_diag() → Pt or None (sqrt witness)', ' .edge_only() → bool (prime shape = no internal factors)', ' .internal() → Pt or None (first non-trivial factor)', ' .take_pairs_u(n) → Tuple[Pt] first n upper pairs', ' .take_divs(n) → Tuple[int] first n divisors', ' .pairs_u() → Iterator[Pt]', ' .pairs() → Iterator[Pt] (both orientations)', ' .divs() → Iterator[int]', ' .idx(d) → int (index of divisor d)', '', ' Routes:', ' sd(S,D) → Pt or None', ' ps(P,S) → Tuple[Pt]', ' pd(P,D) → Tuple[Pt]', ' ant(S, limit=200)→ Iterator[Pt]', ' dia(D, n=200) → Iterator[Pt]', ' get("P",P,limit=...) → List[Pt]', ' get("S",S) → List[Pt]', ' get("D",D) → List[Pt]', '', '══════════════════════════════════════════════════════', 'A3. 3D CORE', '══════════════════════════════════════════════════════', '', ' Pt3(x,y,z) — 3D point object', ' .x, .y, .z', ' .V = x*y*z', ' .S_lin = x+y+z', ' .C_plan = xy+xz+yz', ' .D_body = max(|coords|) - min(|coords|)', ' .D_xy, .D_xz, .D_yz', ' .phase = octant 0..7', ' .abs_coords = (|x|,|y|,|z|)', '', ' Slices (each returns Pt from the perpendicular face):', ' .slice_xy = .slice_z → Pt(|x|,|y|) face perp to z', ' .slice_xz = .slice_y → Pt(|x|,|z|) face perp to y', ' .slice_yz = .slice_x → Pt(|y|,|z|) face perp to x', ' These are ATTRIBUTES, not methods. Do NOT call with ().', ' Holography: slice_xy.P * |z| == |V| (verified)', '', ' .scale_3d(k) → Pt3(x*k,y*k,z*k)', ' .d() → full Dict', '', ' cube_field.hyp3(V) → List[Pt3] sorted by D_body', ' Returns Pt3 objects. Access: .x .y .z', ' Example: cube_field.hyp3(120)[0] → Pt3(x=4,y=5,z=6)', '', ' cube_field.resolve_invariants(V,C,S) → List[int]', ' Example: resolve_invariants(30,31,10) → [2,3,5]', '', ' cube_field.tunnel(P2d,V3d,phase) → Pt3 or None', ' Witness-lift only. NOT historical inverse.', ' Example: tunnel(6,30,0) → Pt3(x=1,y=6,z=5)', '', '══════════════════════════════════════════════════════', 'A4. ADDR3 — TERNARY ADDRESS STACK', '══════════════════════════════════════════════════════', '', ' Addr3.of(x,y,z) → Addr3', ' addr3(x,y,z) → Addr3 (short alias)', '', ' Properties (all ATTRIBUTES, not methods):', ' .stack → ((tx,ty,tz),...) digits ∈ {0,1,2}', ' .phase → octant 0..7', ' .is_on_axis → bool: x=y=z at every level', ' .axis_tension → int: levels with perturbation', ' .depth → int: O(log3 n)', '', ' Methods:', ' .to_coords() → (x,y,z) exact roundtrip', ' .navigate(level) → (tx,ty,tz) trit at given depth level', ' .perturbations() → List[Dict]', ' .level_type(level) → "center"|"face"|"edge"|"corner"', ' .optg_step() → Addr3', ' .zoom_in(level) → Addr3', ' .zoom_out(trit) → Addr3', ' .d() → full Dict', '', ' Scale self-similarity:', ' Addr3.of(3^k,3^k,3^k).is_on_axis == True for all k', '', '══════════════════════════════════════════════════════', 'A5. AXIS — DOCTOR AS GENERATIVE RULE', '══════════════════════════════════════════════════════', '', ' Axis = rule (d,d,d) at every level. D_body=0 ↔ CLOSED.', '', ' Axis.doctor_full(x,y,z) → Dict', ' Keys: kind, point, signature, tension, on_axis, D_body,', ' failed, passed', ' Channels: C1_hxy C2_hxz C3_hyz C4_axis C5_phase C6_dbody', ' Example (9,9,9): {"signature":"CLOSED","tension":0,"on_axis":True}', ' Example (4,5,6): {"signature":"FRACTURED:[\'C4_axis\']","tension":1}', '', ' Axis.optg_path(x,y,z) → List[Tuple]', ' Example: optg_path(1,2,3) → [(1,2,3),(1,2,0),(1,1,1)]', '', ' Axis.project(addr3) → Addr3 on axis', ' Axis.contains(addr3) → bool', ' Axis.tension(addr3) → int', ' Axis.penetration_ratio(depth) → (1/9)^depth', '', ' Rubik analogy (depth=1, 27 cells):', ' on_axis: (0,0,0),(1,1,1),(2,2,2) — 3 cells never move', ' off_axis: 24 moving pieces', ' OPT_G: ≤2 steps to axis from any point', '', '══════════════════════════════════════════════════════', 'A6. CUBECELL — RICH 3D CELL', '══════════════════════════════════════════════════════', '', ' CubeCell(x,y,z)', '', ' Invariants (ATTRIBUTES):', ' .V, .S, .C, .D_body, .phase', ' .stack, .depth, .on_axis, .axis_tension', ' .x, .y, .z', '', ' Slices (ATTRIBUTES, not methods):', ' .slice_xy → Pt(|x|,|y|)', ' .slice_xz → Pt(|x|,|z|)', ' .slice_yz → Pt(|y|,|z|)', '', ' Geometry:', ' .witnesses_holo() → {"H_xy":bool,"H_xz":bool,"H_yz":bool}', ' .angles_deg() → {"from_x","from_y","from_z","from_diag"}', ' .volume_witnesses(limit=20) → List[Tuple]', ' .neighbors27() → Dict[(dx,dy,dz):{"cell":CubeCell,"kind":str}]', '', ' Decomposition:', ' .primitive() → {"seed":tuple,"scale":int,"phase":int,"V_seed":int}', ' Example: CubeCell(14,21,35).primitive()', ' → {"seed":(2,3,5),"scale":7,"phase":0,"V_seed":30}', '', ' .vieta_check() → {"V","C","S","roots_recovered","expected_abs","ok","phase"}', ' .perturbations() → List[Dict]', ' .level_type(level) → "center"|"face"|"edge"|"corner"', ' .navigate(level) → (tx,ty,tz) trit at given level', '', ' Doctor:', ' .doctor() → same as Axis.doctor_full (6 channels)', '', ' Navigation:', ' .optg_step() → CubeCell', ' .optg_path() → List[CubeCell]', ' .scale(k) → CubeCell', ' .scale_rule(k) → Dict', ' .zoom_in(level), .zoom_out(trit)', '', ' Export:', ' .packet() → full Dict', '', '══════════════════════════════════════════════════════', 'A7. FIELD9 — 9-CUBE ATLAS (432 STATES)', '══════════════════════════════════════════════════════', '', ' field9.canon3(x,y,z) → (Pt3_base, Tag3)', ' field9.views48(x,y,z) → List[Pt3]', ' field9.atlas9_states(x,y,z) → List[Dict]', '', ' field9.point_report(x,y,z, head=12) → Dict with keys:', ' "input","canon","addr3","D_body","on_axis","route_stats",', ' "views48_count","states_head"', '', ' field9.atlas9_map() → Dict (structure summary)', ' field9.supercube_graph() → {"node_count":432,"edge_count":2808,"edge_stats":{...}}', ' field9.cube_names() → ("C0","P0".."P7")', ' field9.cube_center(name) → Pt3', ' field9.cube_centers() → Dict[name→Pt3] all 9 centers', ' Example: cube_centers()["P0"] → Pt3(x=36,y=36,z=36)', ' field9.cube_routes() → List[Dict] 36 inter-cube routes', ' Each: {"a":name,"b":name,"kind":str,"distance":int}', ' field9.gap → int (36, offset C0↔peripheral)', ' field9.tags48() → Tuple[Tag3] (48 states)', ' field9.embed(cube_name, local) → Pt3 global coords', ' field9.pt3(x,y,z) → Pt3 (constructor wrapper)', '', ' Supercube edge types:', ' sign(648) perm(432) center(384) face(576) edge(576) body(192)', '', '══════════════════════════════════════════════════════', 'A8. E8 ROOT LATTICE', '══════════════════════════════════════════════════════', '', ' 240 roots = 112 D8 + 128 spinors. Coxeter h=30=2×3×5.', '', ' e8gen.spectrum(i) → Dict[int,int]', ' Keys = dot-product values (integers), values = counts.', ' Key order NOT guaranteed.', ' Verified: {-8:1, -4:56, 0:126, 4:56, 8:1}', '', ' e8gen.summary() → Dict — use "total_roots" not "root_count"', ' Keys: total_roots(240), D8(112), spinors(128), cartans(8),', ' total_248(248), sectors(8), total_1984(1984),', ' spectrum, neutral_126, partners_56, triangles_2240,', ' tris_per_root(28), observers_3276, coxeter, verified', '', ' e8gen.root(idx) → Tuple[int] (0..239)', ' e8gen.d8(idx) → D8 root (0..111)', ' e8gen.spinor(idx) → spinor root (0..127)', ' e8gen.cartan(idx) → Cartan generator (0..7)', ' e8gen.is_root(vec) → bool', ' Example: e8gen.is_root((2,2,0,0,0,0,0,0)) → True', ' e8gen.node248(idx) → Tuple 248-node at index', ' e8gen.root_to_cell(idx) → CubeCell', ' e8gen.sector_node(sector, local_idx) → Dict', ' Keys: sector, global_idx, kind, vec, node_id', ' e8gen.neighbors(idx) → {"partners":56,"aligned":56,"neutral":126}', ' e8gen.triangles(idx) → List[Tuple[Tuple,Tuple,Tuple]]', ' Each: (r1_vec,r2_vec,r3_vec) where r1+r2+r3=0, 28 per root', ' e8gen.tick(idx) → Dict (inner/outer superposition)', ' e8gen.all_sector_nodes(idx) → 8 sector copies', ' e8gen.nearest_root(cell) → Tuple', ' e8gen.root_packet(idx) → full Dict', ' e8gen.coxeter() → {"h_E8":30,"h_factors":(2,3,5),"30x8=240":True}', ' e8gen.observers() → C(28,3)=3276', ' e8gen.axis_connection() → link to Field3 axis (neutral shell 126)', ' e8gen.dot(v1,v2) → int', '', '══════════════════════════════════════════════════════', 'A9. DOCTOR — HEALTH SYSTEM + GEOMETRIC BRIDGE', '══════════════════════════════════════════════════════', '', ' Doctor is not only a health checker.', ' It is the geometric bridge connecting all spaces.', ' It works through RELATIONS, not through degree values.', ' cos(60°) = 1/2 is a ratio, not a degree.', ' A triangle may have no "angle" as such — only side ratios.', '', ' HealthVector fields:', ' .closure, .support_loss, .ambiguity, .drift (float 0.0..1.0)', ' .projection_loss, .modality_conflict, .stress (float)', ' .agreements (int), .total (int)', '', ' ── Constructors ──', ' doctor.from_routes(ag, tot,', ' projection_loss=0.0, modality_conflict=0.0) → HealthVector', ' Example: from_routes(5,5) → closure=0.0 from_routes(3,5) → 0.4', '', ' doctor.from_routes_ok() → HealthVector (5/5 shortcut)', ' doctor.from_closures({"C1":True,"C2":False,...}) → HealthVector', ' doctor.from_retrieval(support, ambiguity, coverage, drift,', ' projection_loss=0.0, modality_conflict=0.0, closure=0.0) → HealthVector', '', ' ── Verdicts ──', ' doctor.judge(hv, ctx="") → DoctorVerdict', ' .level → "OK"|"WARN"|"QUARANTINE"|"ROLLBACK"', ' .tension, .signature, .reasons, .d()', '', ' doctor.judge_ok(ctx="") → DoctorVerdict (OK shortcut)', ' doctor.merge(*hvs) → HealthVector (average)', ' doctor.merge_max(*hvs) → HealthVector (worst channel)', '', ' ── 2D / 3D closures ──', ' doctor.pt2d(x,y) → Dict (5 channels)', ' Example: pt2d(4,3) → {"tension":0,"signature":"CLOSED"}', ' doctor.pt3_field3(x,y,z) → Dict (6 channels, use this)', ' Example: pt3_field3(9,9,9) → {"signature":"CLOSED","tension":0}', ' doctor.pt3(x,y,z) → holographic only (3 channels)', ' doctor.axis_doctor(x,y,z) → alias for pt3_field3', ' doctor.invariants3(V,C,S) → Dict (Vieta recovery)', ' doctor.tunnel_packet(P,V,ph) → Dict (tunnel + closures)', ' doctor.e8_spectrum_check(i) → Dict (total=240)', ' doctor.closure_packet(dict) → full health report', ' doctor.break_profile(dict) → tension analysis', ' doctor.closure_signature_name(failed, space="2d") → str', ' Example: (["C1","C2"]) → "SUM_OR_DIFF_FRACTURE"', ' Example: (["C4_axis"],"3d") → "AXIS_FRACTURE"', '', ' ── Best witness ──', ' doctor.choose_best_factor(P) → Pt (nearest-diagonal)', ' Example: choose_best_factor(120) → Pt(x=10,y=12)', ' Access via .x .y (NOT tuple unpack)', ' doctor.choose_best_factor_full(P) → Dict {"best","worst","ladder"}', ' doctor.choose_best_triplet(V) → Pt3 (most symmetric)', ' Example: choose_best_triplet(120) → Pt3(x=4,y=5,z=6)', ' Access via .x .y .z (NOT tuple unpack)', ' doctor.choose_best_triplet_full(V)→ Dict {"best","worst","head"}', ' doctor.nearest_stable_2d(P) → Pt (alias)', ' doctor.nearest_stable_3d(V) → Pt3 (alias)', '', ' ── Triangle geometry (exact integer arithmetic, no floats) ──', ' doctor.triangle_from_sides(a,b,c) → Dict', ' Keys: sides, area16 (=16·Area²), valid, cos_num, cos_den,', ' altitudes_sq, perimeter, shape, signature, tension', ' cos_num[A] = b²+c²-a² (cosine numerator, exact integer)', ' shape: "equilateral"|"right"|"isoceles"|"obtuse"|"acute_scalene"', ' Example: triangle_from_sides(3,4,5)', ' → {shape:"right", cos_num:{C:0}, area16:576, valid:True}', '', ' doctor.equilateral_from_side(s) → Dict', ' All angles equal — this IS the axis state (on_axis=True).', ' cos(60°) returned as exact ratio (1,2), not as degree.', ' Keys: side, area16, altitude_sq, cos_60, sin_60_sq,', ' centroid_vieta, on_axis, angles, markup_8bit, markup_ternary', ' Example: equilateral_from_side(6)', ' → {cos_60:(1,2), on_axis:True, centroid_vieta:(6,6,6)}', '', ' doctor.triangle_closure(a,b,c) → Dict', ' Full closure: altitudes, medians, bisectors, altitude feet.', ' All as exact fractions (numerator, denominator).', ' Keys: altitudes_sq, medians_sq, bisectors_sq, altitude_feet,', ' inradius_sq, cos_num, closed, signature', ' altitude_feet[foot_c] = (a²+c²-b², b²+c²-a²) BD:DC ratio', ' Example: triangle_closure(3,4,5)', ' → {signature:"CLOSED", altitude_feet:{foot_c:(18,32)},', ' altitudes_sq:{h_c:(576,100)}, inradius_sq:(576,576)}', '', ' ── Metric markup (n-bit / ternary address of any range) ──', ' doctor.metric_markup(value, bits, low=0, high=None) → Dict', ' Divides [low,high] into 2^bits cells. Exact integer arithmetic.', ' Applicable to angles, distances, wavelengths — any integer range.', ' Keys: value, bits, cells, range, cell_index,', ' bit_address (binary string), cell_bounds_num, cell_bounds_den,', ' on_boundary', ' Example: metric_markup(90, 8, 0, 360)', ' → {cell_index:64, bit_address:"01000000", on_boundary:True}', ' Example: metric_markup(50, 6, 0, 100)', ' → {cell_index:32} (works for speed, not just angles)', '', ' doctor.metric_markup_ternary(value, depth, low=0, high=None) → Dict', ' Divides into 3^depth cells. trit_address maps to Addr3 stack.', ' Keys: cell_index, trit_address (list of trits), cells (=3^depth)', ' Example: metric_markup_ternary(60, 4, 0, 360)', ' → {trit_address:[0,1,1,1], cells:81}', '', ' ── Angle constants as relations ──', ' doctor.angle_constant(degrees) → Dict', ' Doctor does not store "degrees" — it stores RATIOS.', ' cos and sin as exact fractions (num,den) where possible.', ' Special exact cases: 0,30,45,60,90,120,135,150,180.', ' Keys: degrees, exact {cos, sin, cos_sq, sin_sq},', ' exact_rational_cos, markup_8bit, markup_ternary_4', ' Example: angle_constant(60)', ' → {exact:{cos:(1,2), cos_sq:(1,4), sin_sq:(3,4)}}', ' Closure: cos_sq+sin_sq=1 verified as: cn*sd+sn*cd == cd*sd', '', ' doctor.pythagorean_angle(a, b) → Dict', ' Angle in right triangle with integer legs a,b. No float needed.', ' cos²θ = a²/(a²+b²), sin²θ = b²/(a²+b²) — exact rational.', ' Keys: legs, hyp_sq, cos_sq, sin_sq, tan_sq, primitive, isoceles', ' Example: pythagorean_angle(3,4)', ' → {cos_sq:(9,25), sin_sq:(16,25), hyp_sq:25}', ' Closure: cos_sq[0] + sin_sq[0] == hyp_sq (9+16=25)', '', ' ── Angular tunnel (connect spaces via angle relation) ──', ' doctor.angular_tunnel(p1, p2, target_cos_sq) → Dict', ' Checks if angle relationship target_cos_sq=(num,den) can exist', ' between vectors from p2→p1 and p2→some p3.', ' Doctor connects different spaces through angular invariants,', ' not through coordinate matching.', ' Keys: p1, p2, v1, v1_sq, target_cos_sq,', ' right_angle (bool), same_dir (bool), valid_cos (bool),', ' axis_tunnel, tension, verdict', ' NOTE: key is "same_dir" not "same_direction"', ' Example: angular_tunnel((1,0,0),(0,0,0),(0,1))', ' → {right_angle:True, tension:0.0, verdict:"OK"}', ' Example: angular_tunnel((1,0,0),(0,0,0),(5,4))', ' → {valid_cos:False} (cos²>1 is impossible)', '', ' ── Sedenion / F16 bridge ──', ' doctor.sedenion_packet(vec16) → Dict', ' 16-dimensional zero-divisor analysis.', ' Maps to E8 via 8+8 split. Checks E8 root membership.', ' Keys: vec, left8, right8, norm2, dot_left_right,', ' left_is_e8_root, right_is_e8_root, possible_zero_divisor', ' Example: sedenion_packet([2,2,0,...,0])', ' → {left_is_e8_root:True, possible_zero_divisor:False}', '', ' ── Seed / resonance / zero-divisor ──', ' doctor.seed_packet_health(x,y,z) → Dict', ' Keys: primitive, on_axis, roundtrip, axis_tension, verdict', ' doctor.resonance_packet(seq) → Dict', ' Wraps resonance_geom.sequence_packet + verdict.', ' doctor.classify_zero_divisor_profile(profile) → Dict', ' profile: {"D:0":n,...} → best_match:"8sign"|"16sign"', ' doctor.zero_divisor_family(labels) → Dict', ' doctor.REF_ZERO_DIVISOR_8SIGN / REF_ZERO_DIVISOR_16SIGN → Dict', '', ' ── PPH / quarantine ──', ' doctor.projection_loss_numeric(original, reconstructed) → Dict', ' doctor.pph_report(binary_approx, residue, essence) → Dict', ' doctor.quarantine(key, payload, verdict)', ' doctor.release(key) doctor.get_quarantine(key=None)', ' doctor.clear_quarantine()', '', '══════════════════════════════════════════════════════', 'A10. PLAFAL — LABELED RELATIONAL GRAPH (FULL REFERENCE)', '══════════════════════════════════════════════════════', '', ' Plafal encodes relational structure without scalars.', ' Used for: contradiction tracking, overlap, merge-history,', ' Doctor neighborhood diagnostics, combinatorial overlays.', '', ' ── CONSTRUCTION ──', ' make_plafal(vertices_dict, edges, name="") → Plafal', ' vertices_dict: {id: label}', ' edges: {(v1,v2): label} or [(v1,v2)] or [(v1,v2,label)]', ' Example:', ' p = make_plafal({"A":1,"B":2},{("A","B"):"x"},"my_graph")', '', ' Direct construction:', ' p = Plafal("name")', ' p.add_vertex("A", label)', ' p.add_edge("A","B", label)', '', ' Properties (ATTRIBUTES, not methods):', ' .vertices → Dict[str,Any]', ' .edges → Dict[Tuple,Any]', ' .name → str', '', ' ── CORE METHODS ──', ' .tension_with(other) → Dict', ' tension = #conflicts / #shared_elements', ' Conflict = same element, different label.', ' Keys: tension(float), shared(int), conflicts(int),', ' conflict_details(List[Dict]),', ' verdict("NO_OVERLAP"|"NO_TENSION"|"LOW_TENSION"|"HIGH_TENSION"),', ' signature("CLOSED" or "FRACTURED:N.NNN")', '', ' .union(other, name="") → Plafal', ' Conflicting labels become lists: {"B": [2, 3]}', '', ' .intersection(other, name="") → Plafal', ' Keeps only vertices/edges with identical labels', '', ' .common_vertices(other) → List[str]', ' .common_edges(other) → List[Tuple]', ' .d() → full Dict (serialization)', '', ' ── DOCTOR BRIDGE ──', ' doctor.plafal_tension(p1, p2) → Dict (same as tension_with)', ' doctor.plafal_graph_summary(plafals, kinds=[...]) → Dict', ' kinds: optional list of class labels for cross/within analysis', ' Keys: n, pair_count, histogram, avg_tension,', ' cross_avg, within_avg, pairs', '', ' ── OPT_G DESCENT (MINIMUM TENSION SEARCH) ──', ' candidates = [("c1", make_plafal(...)), ...]', ' tensions = [(name, target.tension_with(c)["tension"]) for name,c in candidates]', ' best_name, best_tension = min(tensions, key=lambda x: x[1])', '', ' ── ZERO-DIVISOR FAMILIES (PRACTICAL EXAMPLE) ──', ' # 8-sign family: 7 vertices, complete graph (21 edges)', ' zd_8 = make_plafal({f"v{i}": "8sign" for i in range(1,8)},', ' [(f"v{i}", f"v{j}") for i in range(1,8) for j in range(i+1,8)],', ' "zd_8sign")', ' # 16-sign family: different geometric fingerprint', ' zd_16 = make_plafal({f"v{i}": "16sign" for i in range(1,10)},', ' [(f"v{i}", f"v{j}") for i in range(1,10,2) for j in range(i+2,10,2)],', ' "zd_16sign")', ' t_zd = zd_8.tension_with(zd_16) # tension > 0 (distinct)', ' # Classification by profile (alternative to graph comparison)', ' profile_8 = {"D:0":50,"D:1":14,"D:2":12,"D:3":10,"D:4":7,"D:5":5,"D:6":2}', ' clf = doctor.classify_zero_divisor_profile(profile_8)', ' # → {"best_match":"8sign","confident":True,...}', '', ' ── EDGE CASES ──', ' p_empty = Plafal("empty") # 0 vertices, 0 edges', ' p_single = make_plafal({"A":1}, [], "single")', ' t_empty = p1.tension_with(p_empty) # verdict "NO_OVERLAP", tension=0.0', '', ' ── LIMITATIONS (HISTORICAL/PROTOTYPE A29) ──', ' • Self‑loops (A,A) allowed but semantics undefined', ' • Edges stored as Tuple, no direction semantics', ' • Tension computation O(n²)', ' • No direct DIN bridge, no visualization', ' • Not canonical core (unlike Pt, Pt3, CubeCell)', '', ' ── VERIFIED EXAMPLES (Run #24) ──', ' make_plafal({"A":1,"B":2,"C":3}, {("A","B"):"x"}, "g1") → v=3, e=2 ✓', ' identical graphs → tension=0.0, verdict="NO_TENSION" ✓', ' partial conflict → tension=0.2, verdict="LOW_TENSION" ✓', ' high conflict → tension=0.4, verdict="HIGH_TENSION" ✓', ' disjoint graphs → verdict="NO_OVERLAP" ✓', ' union preserves conflicts as lists ✓', ' intersection keeps only matching labels ✓', ' doctor.plafal_graph_summary → pair_count=C(n,2), histogram, cross/within_avg ✓', ' min tension search finds zero-tension candidate ✓', ' 8-sign: 7 vertices, 21 edges (complete K7) ✓', ' 8-sign vs 16-sign: tension > 0 (distinct) ✓', '', ' ── QUICK REFERENCE ──', ' CONSTRUCT: make_plafal(vertices, edges, name)', ' PROPERTIES: .vertices, .edges, .name', ' METHODS: .tension_with(), .union(), .intersection(), .common_vertices(), .common_edges(), .d()', ' DOCTOR: doctor.plafal_tension(p1,p2), doctor.plafal_graph_summary(plafals, kinds)', ' OPT_G: min([(name, p1.tension_with(p2)["tension"]) for name,p2 in candidates])', ' ZD: make_plafal({f"v{i}":label for i in range(1,8)}, edges, "zd_8sign")', ' STATUS: historical/prototype (A29)', ' LIMITS: O(n²) tension, no DIN bridge, no visualization, no self-loop semantics', '', '══════════════════════════════════════════════════════', 'A11. DIN — GENERATIVE DESCRIPTOR', '══════════════════════════════════════════════════════', '', ' DIN = compact DNA. Stores rules, not expanded state.', ' Parallel to Addr3: address not coordinates.', '', ' from din import DINPacket, DINMode, DoctorLevel, codec', ' from din import pack_din, unpack_din, din_to_dict', ' from din_ops import din_route_lift, din_fuse, din_diff, din_packet_view', ' from rule_packet import build_rule_packet, rule_din, rule_from_blob', '', ' DINPacket fields:', ' mode → LOCAL / MEMORY / EXCHANGE', ' primitive_id → ternary address of seed', ' scale → CubeCell scale factor', ' state_code → position in 432-state atlas (0..431)', ' witness_flags → bitmask: xy,xz,yz,vol,canon,tag,atlas,seed...', ' doctor_flags → bitmask: ok,warn,quarantine,rollback,closure...', ' extra → JSON payload (generative rules)', '', ' Rule DIN workflow:', ' r = build_rule_packet(name, domain, codomain, law,', ' examples=[...], invariants=[...], route_steps=[...])', ' res = rule_din(r)', ' → {"blob":bytes,"din_packet":dict,"seed_packet":dict,"doctor":dict}', ' rec = rule_from_blob(res["blob"]) → recover rule from bytes', ' Same rule → same blob always (deterministic).', '', '══════════════════════════════════════════════════════', 'A12. FACADE', '══════════════════════════════════════════════════════', '', ' of / opterium → OpteriumField instance', ' of.pt(x,y) → Pt', ' of.web2(P) → Web', ' of.pt3(x,y,z) → Pt3', ' of.cell(x,y,z) → CubeCell', ' of.addr(x,y,z) → Addr3', ' of.optg(x,y,z) → List path to axis', ' of.rest(x,y,z) → 6-channel doctor Dict', ' of.e8_root(idx) → E8 root Tuple', ' of.e8_spectrum(idx) → spectrum Dict', ' of.scale_info(depth) → Field3 scale parameters Dict', ' of.summary() → full system summary Dict', ' of.inject_namespace() → Dict for executor injection', '', '══════════════════════════════════════════════════════', 'A13. STATE AND MACROS', '══════════════════════════════════════════════════════', '', ' S, keep, unkeep, lazy, lg, rs, info', ' mac("name", code, args=[...], passport=', ' {"what":"...","returns":"...","status":"verified","example":"..."})', ' S.mac_get("name")(...) macs() unmac("name")', ' Macros immutable after creation. Hash-sealed.', '', '══════════════════════════════════════════════════════', 'A14. OPTIONAL MODULES', '══════════════════════════════════════════════════════', '', ' chat_proxy.ask(history, temperature=0.7) → (clean_str, raw_str)', '', ' pathnum: DebtNum.of_decimal_string("0.23")', ' RatioRule, RepeatingRule, IrrationalRule', '', ' division_geom:', ' div_geom(a,b) → witness or quotient+remainder Dict', ' ratio_geom(a,b) → RatioRule', ' sqrt_geom(n) → exact witness or bounds+rule Dict', '', ' resonance_geom:', ' sequence_packet(seq) → period/energy/phase Dict', ' resonance_din(seq) → DINPacket', ' e8_seed_hint(seq) → E8 embedding hint Dict', '', '══════════════════════════════════════════════════════', 'A15. KEY PRINCIPLES', '══════════════════════════════════════════════════════', '', ' Number = relational web, not digit string.', ' No negatives — only magnitude + orientation (phase).', ' Axis = Doctor = rule (d,d,d) = zero tension.', ' D_body=0 ↔ on_axis ↔ CLOSED ↔ solved.', ' DIN = Addr3 for objects: generative address not expanded data.', ' E8 neutral shell 126 = E8 analog of Field3 axis (dot=0).', ' Triangle angle = side ratio, not degree number.', ' Doctor connects spaces through relations, not coordinates.', '', 'A16. IF UNSURE', '', ' Run api().', ' When method returns Pt/Pt3 — use .x .y .z, not tuple unpack.', ' slice_xy / slice_xz / slice_yz are ATTRIBUTES, not methods.', ' angular_tunnel key is "same_dir" not "same_direction".', ' altitude_feet[foot_c] for 3-4-5 = (18,32) not (32,18).', ' e8gen.summary() key is "total_roots" not "root_count".', ' Prefer compact dict packets over prose for AI output.', '', ' Cube27 is the Rubik cube geometry layer.', ' 27 subcubes, 3 on axis (never move), 24 off-axis (rotate).', ' Doctor detects tension after rotation. OPT_G returns to CLOSED.', '', ' Construction:', ' Cube27(origin=(0,0,0), scale=1, depth=0, parent_phase=0)', ' origin → Tuple[int,int,int] global offset', ' scale → int cell size at this depth', ' depth → int fractal level (0 = root)', ' parent_phase→ int orientation from parent cube', '', ' Properties (ATTRIBUTES, not methods):', ' .origin → Tuple[int,int,int]', ' .scale → int', ' .depth → int', ' ._parent_phase → int', '', ' Static Methods:', ' Cube27.all_addresses() → Tuple[Tuple[int,int,int],...] all 27', ' Example: len(Cube27.all_addresses()) → 27', '', ' Cube27.axis_addresses() → Tuple[Tuple[int,int,int],...] 3 on axis', ' Returns: ((0,0,0), (1,1,1), (2,2,2))', ' These cells never move under rotation.', '', ' Cube27.off_axis_addresses() → Tuple[Tuple[int,int,int],...] 24 moving', ' Returns: all addresses except (0,0,0), (1,1,1), (2,2,2)', '', ' Cube27.cell_kind(tx,ty,tz) → str', ' Returns: "core"|"face"|"edge"|"corner"', ' core=1 (1,1,1), face=6, edge=12, corner=8', '', ' Cube27.cell_on_axis(tx,ty,tz) → bool', ' True if tx==ty==tz (diagonal axis)', '', ' Cube27.neighbors(tx,ty,tz) → List[Dict]', ' Returns up to 26 neighbors within {0,1,2}^3', ' Each Dict: {"addr", "offset", "adjacency", "kind", "on_axis"}', ' adjacency: "corner"|"edge"|"face" (by shared elements)', '', ' Instance Methods:', ' c27.cell_coords(tx,ty,tz) → Tuple[int,int,int]', ' Global coordinates of subcube address', ' Formula: (origin[0]+tx*scale, origin[1]+ty*scale, origin[2]+tz*scale)', '', ' c27.cell(tx,ty,tz) → CubeCell', ' Rich 3D cell at subcube address', ' Example: Cube27().cell(1,1,1) → CubeCell at center', '', ' c27.center_cell() → CubeCell', ' Always returns cell(1,1,1) — the core', '', ' c27.kind_counts() → Dict[str,int]', ' Returns: {"core":1, "face":6, "edge":12, "corner":8}', '', ' c27.subdivide(tx,ty,tz) → Cube27', ' Expand subcube into its own Cube27 at depth+1', ' Fractal self-similarity: each cell contains 27 subcells', ' Example: Cube27(depth=0).subdivide(1,1,1) → Cube27(depth=1)', '', ' c27.parent_cube() → Cube27 or None', ' Ascend one fractal level', ' Returns None if depth=0 (root level)', '', ' c27.my_trit_in_parent() → Tuple[int,int,int] or None', ' Which address this cube occupies in parent', ' Returns None if depth=0', '', ' c27.addr3_of_cell(tx,ty,tz) → Addr3', ' Convert subcube address to ternary stack', ' Bridge between Cube27 and Addr3 address spaces', '', ' c27.from_addr3_level(addr, level) → Tuple[int,int,int]', ' Read trit address from Addr3 at given depth', ' Inverse of addr3_of_cell', '', ' Rotation (Re-addressing):', ' Cube27.rotate_face_x(layer, clockwise=True) → Dict[Tuple,Tuple]', ' Re-addressing map for face perpendicular to x-axis', ' layer: 0, 1, or 2 (which x-slice)', ' Returns: {old_addr: new_addr, ...}', '', ' Cube27.rotate_face_y(layer, clockwise=True) → Dict[Tuple,Tuple]', ' Re-addressing map for face perpendicular to y-axis', '', ' Cube27.rotate_face_z(layer, clockwise=True) → Dict[Tuple,Tuple]', ' Re-addressing map for face perpendicular to z-axis', ' Example: rotate_face_z(1) rotates middle layer around z', '', ' c27.apply_rotation(remap) → Dict', ' Apply re-addressing and return Doctor analysis', ' Does NOT mutate cube — returns diagnostic packet', ' Returns: {', ' "kind": "cube27_rotation",', ' "total_affected": int,', ' "preserved": int,', ' "broken": int,', ' "axis_preserved": int,', ' "axis_broken": int,', ' "tension": float (0.0 to 1.0),', ' "signature": "CLOSED" or "FRACTURED:N/27",', ' "details": [...] # list of changed cells', ' }', ' Example:', ' remap = Cube27.rotate_face_z(1, clockwise=True)', ' result = Cube27().apply_rotation(remap)', ' result["tension"] → 0.888889 (8 of 9 cells moved)', ' result["signature"] → "FRACTURED:8/9"', '', ' Doctor Integration:', ' c27.doctor() → Dict', ' Full axis analysis for this Cube27 level', ' Checks all 13 axes through center (1,1,1):', ' 3 coordinate axes (x,y,z)', ' 4 space diagonals', ' 6 face diagonals', ' Returns: {', ' "kind": "cube27_doctor",', ' "origin": Tuple,', ' "scale": int,', ' "depth": int,', ' "total_cells": 27,', ' "on_axis": 3,', ' "off_axis": 24,', ' "kind_counts": Dict,', ' "total_axes": 13,', ' "intact_axes": int (usually 1 — main diagonal only),', ' "axis_tension": float,', ' "main_diagonal_intact": bool,', ' "axes": Dict (per-axis status),', ' "signature": "CLOSED" or "FRACTURED:N/13",', ' "fractal_note": str', ' }', ' NOTE: Only main diagonal (0,0,0)-(1,1,1)-(2,2,2) is fully on axis.', ' Other 12 axes pass through off-axis cells by design.', ' Signature "FRACTURED:12/13" is CORRECT, not a bug.', '', ' c27.packet() → Dict', ' Full diagnostic packet', ' Returns: {', ' "origin", "scale", "depth", "parent_phase",', ' "kind_counts", "axis_cells", "off_axis_cells",', ' "doctor": c27.doctor(),', ' "center_cell": CubeCell.packet() or None,', ' "my_trit": tuple or None', ' }', '', ' Fractal Scale Invariance:', ' At depth k:', ' total_cells = 27^k', ' on_axis = 3^k', ' axis_ratio = (1/9)^k', ' Verified current examples:', ' depth=0: 27 cells, 3 on axis, ratio=0.111111', ' depth=1: 729 cells, 9 on axis, ratio=0.012346', '', ' OPT_G Connection:', ' Axis cells (0,0,0), (1,1,1), (2,2,2) are stable nodes.', ' Off-axis cells can be rotated back via OPT_G descent.', ' Doctor.tension measures distance from CLOSED state.', '', ' Verified Current Examples:', ' c27 = Cube27(origin=(0,0,0), scale=1, depth=0)', ' c27.doctor()["total_cells"] → 27', ' c27.doctor()["on_axis"] → 3', ' c27.doctor()["intact_axes"] → 1 (main diagonal only)', ' c27.kind_counts() → {"core":1, "face":6, "edge":12, "corner":8}', '', ' sub = c27.subdivide(1,1,1)', ' sub.depth → 1', ' sub.doctor()["total_cells"] → 27 (each subcube has 27)', '', ' remap = Cube27.rotate_face_z(1, clockwise=True)', ' result = c27.apply_rotation(remap)', ' result["tension"] → 0.888889', ' result["signature"] → "FRACTURED:8/9"', '', '══════════════════════════════════════════════════════', 'A18. CUBE27 — DOCTOR BRIDGE TO E8 AND FIELD9', '══════════════════════════════════════════════════════', '', ' Cube27 is not isolated. It bridges to:', ' Addr3 (ternary address stack)', ' CubeCell (rich 3D cell)', ' E8 (root lattice via nearest_root / root_to_cell)', ' Field9 (9-cube atlas via state_code)', '', ' Addr3 Bridge:', ' Each Cube27 level = one Addr3 stack level', ' Cube27.depth = Addr3.depth', ' Axis rule (d,d,d) identical in both', ' Verified: Cube27().addr3_of_cell(1,1,1).is_on_axis → True', '', ' CubeCell Bridge:', ' c27.cell(tx,ty,tz) returns full CubeCell', ' CubeCell has holographic witnesses, Vieta, OPT_G path', ' Verified: Cube27().cell(1,1,1).on_axis → True', '', ' E8 Bridge:', ' e8gen.root_to_cell(idx) → CubeCell', ' e8gen.nearest_root(cell) → Tuple (nearest E8 root)', ' E8 neutral shell (126 roots, dot=0) = E8 analog of Cube27 axis', ' Verified: e8gen.axis_connection()["neutral_126"] → 126', '', ' Field9 Bridge:', ' CubeCell primitive + scale + tag → Field9 state_code', ' Cube27 rotation → state_code change in Field9', ' Verified: point_packet9(x,y,z)["canon"]["state_code"] → int (0..431)', '', ' Zero-Divisor Bridge:', ' Cube27 off-axis cells = candidate tunnel nodes', ' find_zero_divisors macro scans F16 orthogonality', ' Doctor.classify_zero_divisor_profile → "8sign"|"16sign"', ' Verified: 168 zero-divisor hits from 420 candidates (nullity=4)', '', '══════════════════════════════════════════════════════', 'A19. MACRO SYSTEM — FIXED **kwargs SUPPORT', '══════════════════════════════════════════════════════', '', ' Macro execution now supports both *args and **kwargs.', ' Fixed in state.py: Macro.__call__(s, *a, **kw)', '', ' Creation:', ' mac("name", code, args=["arg1", "arg2"], passport={...})', ' passport required keys: "what", "returns", "status", "example"', ' Optional: "note", "reads", "writes", "depends_on"', '', ' Execution:', ' S.mac["name"](arg1, arg2) → positional', ' S.mac["name"](arg1, kw1=val1) → mixed', ' S.mac["name"](limit=10, max_pairs=5) → keyword only', '', ' Access:', ' S.mac["name"].code → raw code (function or string)', ' S.mac["name"].args → declared arg list', ' S.mac["name"].passport → full passport dict', ' S.mac["name"].hash → full SHA256 hash', ' S.mac["name"]["fp"] → short fingerprint (from passport)', '', ' Immutability:', ' Macros are sealed after creation.', ' To change: unmac("name") then mac("name", new_code, ...)', '', ' Save/Load:', ' S.mac_save() → opterium_macros.json', ' S.mac_load() → load and verify hashes', ' Invalid hashes → macro removed (trust protocol)', '', ' Verified Current Macros:', ' factor_by_vectors(N) → Tuple (p, q) where p*q = N', ' Example: S.mac["factor_by_vectors"](6) → (2, 3)', ' Returns (1, N) if N is prime or has large factors', '', ' find_zero_divisors(limit, max_pairs) → Dict', ' Example: S.mac["find_zero_divisors"](limit=10, max_pairs=5)', ' Returns: {"pairs": [...], "checked": int, "found": int, "status": str}', ' Scans F16 orthogonality: a·c = a·d = b·c = b·d = 0', '', ' Auto-Logging:', ' Macro fingerprints auto-attached to run log:', ' MACRO_FP factor_by_vectors=2c..c2 find_zero_divisors=54..28', '', '══════════════════════════════════════════════════════', 'A20. VERIFIED CURRENT FACTS — CUBE27 + MACROS', '══════════════════════════════════════════════════════', '', ' Cube27:', ' total_cells = 27 (depth=0)', ' on_axis = 3 ((0,0,0), (1,1,1), (2,2,2))', ' off_axis = 24', ' kind_counts = {core:1, face:6, edge:12, corner:8}', ' total_axes = 13 (through center)', ' intact_axes = 1 (main diagonal only — CORRECT)', ' fractal_ratio = (1/9)^depth', '', ' Rotation:', ' rotate_face_z(1) affects 9 cells', ' axis_preserved = 1 (center never moves)', ' axis_broken = 0 (axis cells never in rotation)', ' tension = 8/9 = 0.888889', '', ' Macros:', ' factor_by_vectors(6) → (2, 3)', ' factor_by_vectors(15) → (3, 5)', ' factor_by_vectors(97) → (1, 97) (prime)', ' find_zero_divisors(limit=10, max_pairs=5) → Dict', '', ' System:', ' opterium_field.py — 9 layers, 2000+ lines, 0 errors', ' executor.py — Macro extraction fixed', ' state.py — **kwargs support added', ' tests_passed = 10/10', '', ] # [8:1] API_LINES_END # [9:0] OPT_GEOM_LINES_BEGIN OPT_GEOM_LINES = [ 'PYTHFIELD /opt_geom — OPT_G and Doctor-centered geometry of descent', '', 'OG1. WHAT OPT_G IS', ' OPT_G is not a school optimizer and not a single numeric root-finding trick.', ' It is the geometry of moving from an incomplete, distorted, or partially projected state', ' toward the nearest stable node where independent invariants close with minimum residue.', '', ' Short rule:', ' if exact witness already exists -> read witness', ' else -> descend geometrically toward the nearest stable node', ' then let Doctor certify whether the landing is truly closed or only convenient', '', 'OG2. WHY THIS IS NEEDED', ' Many objects are not handed to us as direct addresses.', ' Instead we may know only shadows, invariants, packets, or partial routes.', ' Examples:', ' 3D invariants V / C_plan / S_lin without explicit x,y,z', ' a product cloud with many possible factor witnesses', ' a resonance packet with support modes but no final geometric landing', ' a tunnel condition P2d + V3d without a historical original pair', '', ' In all such cases the question is no longer', ' "compute the answer directly"', ' but rather', ' "which nearby node reduces tension and closes the object?"', '', 'OG3. STABLE NODE', ' A stable node is a state where the relevant independent routes agree enough', ' that the Doctor can call it closed, calibrated, or at least admissible with explicit residue.', ' A false minimum is a state that looks cheap locally but still breaks the wrong closures.', '', 'OG4. DOCTOR STANDS AT THE CENTER', ' Ordinary geometry gives roads.', ' OPT_G chooses how to move among roads.', ' Doctor decides whether the move actually reduced the right tension.', '', ' Therefore:', ' OPT_G without Doctor can land in a pretty but false minimum', ' Doctor without OPT_G can diagnose but not guide the descent', '', ' Together they form the bridge geometry.', '', 'OG5. 2D SOFT DESCENT', ' In 2D the simplest current OPT_G behavior is already visible:', ' among many valid factor witnesses of one product, the softer witness is the one nearer the diagonal x=y,', ' i.e. the one with smaller |D|.', '', ' Verified current examples:', ' P=120 -> best witness (10,12), worst (1,120)', ' P=420 -> best witness (20,21), worst (1,420)', ' P=840 -> best witness (28,30), worst (1,840)', ' P=2310 -> best witness (42,55), worst (1,2310)', '', ' So not all exact witnesses are equally good geometrically.', '', 'OG6. 2D TENSION LADDER', ' A product web can be read as a ladder away from the diagonal.', ' Near-diagonal witnesses are lower-tension and more symmetric.', ' Edge witnesses like (1,P) are maximally stretched and usually worst for stable descent.', '', 'OG7. 2D FRACTURE SIGNATURES', ' Doctor already shows that different distortions break different route families.', '', ' Verified current signatures:', ' () -> CLOSED', ' (C2,) -> LOCAL_RECONSTRUCTION_DRIFT', ' (C1,C2) -> SUM_OR_DIFF_FRACTURE', ' (C1,C3h,C4h) -> PRODUCT_WITNESS_FRACTURE', '', ' This means the descent landscape is not scalar-only.', ' It has typed fracture directions.', '', 'OG8. 3D DESCENT BY INVARIANTS', ' In 3D the object may be known only through shadows:', ' V = xyz', ' C_plan = xy+xz+yz', ' S_lin = x+y+z', '', ' Then the descent question becomes:', ' is there a chamber-consistent triple that closes these invariants?', '', ' Verified current example:', ' (V,C,S)=(30,31,10) -> roots [2,3,5], stable node found', ' Verified perturbations:', ' changing any one of V, C, or S alone destroys recoverability in that example', '', ' So the stable 3D node exists only where the shadows jointly close.', '', 'OG9. 3D SOFT TRIPLETS', ' Current triplet clouds are already ordered by geometric softness.', ' Verified current examples:', ' V=120 -> best triplet (4,5,6), worst (1,1,120)', ' V=840 -> best triplet (7,10,12), worst (1,1,840)', '', ' Here "best" means most symmetric / smallest D_body among the admissible witnesses.', '', 'OG10. CHAMBER DESCENT', ' In 3D it is often more useful to think in chamber profile than in raw coordinates.', ' The chamber profile is', ' a = x', ' d1 = y-x', ' d2 = z-y', '', ' Descent can then be understood as reducing asymmetry in d1, d2, or D_body', ' while preserving chamber-consistent structure.', '', 'OG11. TUNNEL BRIDGE', ' A tunnel is an admissible bridge from one shadow regime into another.', ' In the current stack:', ' cube_field.tunnel(P2d, V3d, phase)', ' chooses one valid witness lift satisfying the compatibility conditions.', '', ' Verified current example:', ' tunnel(6,30,0) -> (1,6,5)', ' xy_ok = True', ' vol_ok = True', '', ' Important:', ' tunnel is witness-lift, not historical inverse reconstruction of the original pair.', '', 'OG12. TUNNEL FAILURE AS A REAL RESULT', ' Verified current failures:', ' tunnel(7,30,0) -> no tunnel', ' tunnel(6,31,0) -> no tunnel', '', ' This is not an unfinished computation.', ' It means the compatibility route is not open.', '', 'OG13. SEED AS DESCENT TARGET', ' A stable node need not be a large raw address.', ' It may be a primitive seed + scale + tag packet.', '', ' Verified current seed health:', ' (-35,14,-21) -> primitive (2,3,5), scale 7, tag zxy:p5, stable', ' (14,21,35) -> same primitive and scale, stable', ' (2,3,5) -> primitive itself, stable', '', ' This shows that descent often wants to land first in primitive structure,', ' not in a large expanded surface.', '', 'OG14. RESIDUE IS NOT A FAILURE OF HONESTY', ' If exact witness cannot be reached, the right move is not to invent certainty.', ' The right move is to keep residue visible:', ' quotient + remainder', ' ratio rule', ' repeating rule', ' irrational rule', ' PPH packet', '', ' OPT_G therefore seeks the best honest landing, not the prettiest fake one.', '', 'OG15. RESONANCE LANDSCAPES', ' In sequence space, stable nodes appear as support patterns rather than coordinates.', ' Current sequence packets already expose support modes such as:', ' periodic', ' multiplicative', ' difference', '', ' Doctor then reads whether this packet is stable or fractured.', '', ' Verified current examples:', ' periodic [1,3,1,3,1,3,1,3] -> WARN due to ambiguity', ' multiplicative [2,4,8,16,32,64] -> OK', ' flat [5,5,5,5,5,5] -> ROLLBACK due to ambiguity=1.0', '', ' So OPT_G is not only about moving in coordinate space; it also lives in route-regularity space.', '', 'OG16. MERGE POLICIES MATTER', ' The current Doctor already demonstrates two different stability policies:', ' merge(...) averages channels', ' merge_max(...) preserves the worst channel', '', ' Verified current fact:', ' the same mixed packet set can judge OK under average merge and WARN under worst-case merge', '', ' Therefore any serious descent protocol must choose its merge geometry consciously.', '', 'OG17. FINGERPRINT DESCENT', ' Some objects are better classified by distributions than by one witness.', ' The current Doctor can compare fingerprints of zero-divisor families and decide', ' whether a new profile is closer to the 8-sign class or the 16-sign class.', '', ' Verified current fact:', ' exact 8-sign and 16-sign reference profiles classify correctly with l1 distance 0 to themselves.', '', 'OG18. GRAPH DESCENT VIA PLAFAL', ' Recovered plafal structures suggest another descent mode:', ' local contradiction density on overlapping subgraphs.', '', ' Verified toy graph facts:', ' p1 vs p2 -> tension 1/3', ' p1 vs p3 -> tension 0', ' cross-kind avg tension > within-kind avg tension in the tested small summary', '', ' This means local graph healing can also be read as OPT_G-style movement toward lower conflict structure.', '', 'OG19. CURRENT MINIMAL FORMULA OF OPT_G', ' Safe current reading:', ' read witness if it exists', ' otherwise move toward a softer stable node', ' let Doctor classify what closed and what failed', ' keep residue if exact closure is not honestly available', '', 'OG20. WHAT OPT_G IS NOT', ' It is not plain Newton-Raphson.', ' It is not brute-force enumeration.', ' It is not generic black-box optimization detached from geometry.', ' It is not a promise that every route collapses to exact zero.', '', ' It is geometry-aware descent with closure-aware verification.', '', 'OG21. CURRENT LIMIT', ' The full historical Doctor/OPT_G architecture was wider than the current exposed code.', ' The present section therefore describes the verified live bridge behavior now available,', ' not every recovered historical capability.', '', 'OG22. PRACTICAL RULE FOR AI', ' When exact witness is absent, do not panic and do not fake certainty.', ' Ask instead:', ' what is the nearest stable node?', ' which channels close there?', ' what residue remains?', ' is this a valid bridge or a false minimum?', ] # [9:1] OPT_GEOM_LINES_END # [10:0] DOCTOR_LINES_BEGIN DOCTOR_LINES = [ 'PYTHFIELD /doctor — health, closure, routing, projection honesty', '', 'D1. WHAT DOCTOR IS', ' Doctor is the geometry-of-relations health layer.', ' In the current runtime it measures closure, support loss, ambiguity, drift, projection loss, and modality conflict,', ' then issues a verdict packet.', ' In the wider architecture Doctor is also the bridge between route geometry, descent, tunnels, and residue tracking.', '', 'D2. WHY DOCTOR IS WIDER THAN BAYES', ' Bayes updates belief inside a fixed model.', ' Doctor can diagnose whether the model geometry itself is closing honestly.', ' Bayes says confidence changed.', ' Doctor can say which closure channels survived, which fractured, whether a minimum is false, and whether projection residue is too large.', '', 'D3. CORE HEALTH VECTOR', ' Current HealthVector channels:', ' closure', ' support_loss', ' ambiguity', ' drift', ' projection_loss', ' modality_conflict', ' stress', '', ' 0.0 means perfectly closed / clean on that channel.', '', 'D4. CURRENT CORE FUNCTIONS', ' doctor.from_routes(agreements, total_routes,', ' projection_loss=0.0, modality_conflict=0.0) → HealthVector', ' HealthVector fields:', ' .closure, .support_loss, .ambiguity, .drift (float 0.0..1.0)', ' .projection_loss, .modality_conflict, .stress (float)', ' .agreements (int), .total (int)', ' doctor.from_retrieval(support, ambiguity, coverage, drift, projection_loss=..., modality_conflict=..., closure=...)', ' doctor.merge(...) # average merge', ' doctor.merge_max(...) # worst-channel merge', ' doctor.judge(health, context="...")', ' doctor.quarantine(key, payload, verdict)', ' doctor.release(key)', ' doctor.get_quarantine(key=None)', ' doctor.clear_quarantine()', ' doctor.pph_report(binary_approx, projection_residue, geometric_essence, verdict=...)', '', 'D5. CURRENT CLOSURE HELPERS', ' doctor.break_profile(closures)', ' doctor.closure_signature_name(failed, space="...")', ' doctor.from_closures(closures, ...)', ' doctor.closure_packet(closures, context="...", ...)', ' doctor.pt2d(x,y, S_val=None, D_val=None, P_val=None)', ' doctor.pt3(x,y,z)', ' doctor.invariants3(V, C_plan, S_lin)', '', 'D6. CURRENT 2D DOCTOR', ' doctor.pt2d(...) evaluates a 2D point using current closure channels:', ' C1: P == (S^2 - D^2)//4', ' C2: sd(S,D) reconstructs the point', ' C3h: web(P).at(x) returns the point', ' C4h: web(P).at(y) returns the mirror point', ' C5: canon/tag roundtrip returns the original address', '', ' Verified current exact case:', ' doctor.pt2d(4,3) -> agreements=5/5, tension=0, verdict OK', '', 'D7. FRACTURE SIGNATURES IN 2D', ' Doctor does not only count failures; it can classify their shape.', ' Current verified 2D signatures:', ' () -> CLOSED', ' (C2,) -> LOCAL_RECONSTRUCTION_DRIFT', ' (C1,C2) -> SUM_OR_DIFF_FRACTURE', ' (C1,C3h,C4h) -> PRODUCT_WITNESS_FRACTURE', '', ' Verified examples:', ' perturbing S or D on (4,3) typically yields SUM_OR_DIFF_FRACTURE', ' perturbing P on (4,3) yields PRODUCT_WITNESS_FRACTURE', '', 'D8. CURRENT 3D DOCTOR', ' doctor.pt3(x,y,z) checks 3D holographic closure through the three face shadows:', ' Hxy: slice_xy.P * |z| == |V|', ' Hxz: slice_xz.P * |y| == |V|', ' Hyz: slice_yz.P * |x| == |V|', '', ' Verified current exact case:', ' doctor.pt3(-5,2,-3) -> agreements=3/3, tension=0, verdict OK', '', 'D9. CURRENT 3D INVARIANT DOCTOR', ' doctor.invariants3(V,C,S) asks whether a stable 3D node exists for the given invariant shadows.', ' Current verified 3D signatures:', ' () -> CLOSED', ' (recoverable,) -> INVARIANT_RECOVERY_FRACTURE', '', ' Verified current example:', ' (30,31,10) -> recoverable, roots [2,3,5], verdict OK', ' changing any one of V/C/S alone in that example -> no roots, verdict ROLLBACK', '', 'D10. CURRENT OPT_G-LIKE FUNCTIONS', ' doctor.choose_best_factor(P)', ' doctor.choose_best_triplet(V)', ' doctor.nearest_stable_2d(P)', ' doctor.nearest_stable_3d(V)', '', ' These are practical current forms of geometric descent:', ' not "find any witness",', ' but prefer the softer witness nearer the diagonal or the more symmetric witness nearer chamber balance.', '', ' Verified current examples:', ' P=120 -> best factor: Pt(x=10,y=12) .x=10, .y=12', ' P=420 -> best factor: Pt(x=20,y=21)', ' P=420 -> best factor witness (20,21), worst (1,420)', ' P=840 -> best factor witness (28,30), worst (1,840)', ' P=2310 -> best factor witness (42,55), worst (1,2310)', ' V=120 -> best triplet: Pt3(x=4,y=5,z=6) .x=4, .y=5, .z=6', ' V=840 -> best triplet: Pt3(x=7,y=10,z=12)', ' Returns Pt3 object — access via .x .y .z, not tuple unpack.', '', 'D11. TUNNEL DOCTOR', ' doctor.tunnel_packet(P2d, V3d, phase=0)', ' returns the tunnel witness-lift together with closure checks:', ' tunnel_exists', ' xy_ok', ' vol_ok', '', ' Verified current example:', ' doctor.tunnel_packet(6,30,0) -> point (1,6,5), all tunnel checks pass', '', ' Verified failure examples:', ' doctor.tunnel_packet(7,30,0) -> no tunnel, verdict ROLLBACK', ' doctor.tunnel_packet(6,31,0) -> no tunnel, verdict ROLLBACK', '', ' Important:', ' tunnel is witness-lift, not guaranteed historical inverse of the original pair.', '', 'D12. SEED DOCTOR', ' doctor.seed_packet_health(x,y,z)', ' checks compact generative integrity of a seed packet.', '', ' Verified current examples:', ' doctor.seed_packet_health(-35,14,-21)', ' doctor.seed_packet_health(14,21,35)', ' doctor.seed_packet_health(2,3,5)', ' all confirm stable seed structure in the tested packets.', '', 'D13. RESONANCE DOCTOR', ' doctor.resonance_packet(seq)', ' wraps sequence_packet(seq) and exposes the embedded doctor verdict.', '', ' Verified current examples:', ' periodic [1,3,1,3,1,3,1,3] -> WARN due to ambiguity=0.5', ' multiplicative [2,4,8,16,32,64] -> OK', ' mixed [3,1,4,1,5,9,2,6,5,3] -> OK', ' flat [5,5,5,5,5,5] -> ROLLBACK due to ambiguity=1.0', '', ' So Doctor is already active inside route-based regularity packets.', '', 'D14. PPH PROTOCOL', ' PPH = Projection Honesty Protocol.', ' In current code doctor.pph_report(...) is a structured packaging point for:', ' binary_approx', ' projection_residue', ' geometric_essence', ' doctor verdict', '', ' Use it when projecting a richer geometric object into a poorer visible surface.', ' It keeps residue visible instead of pretending the projection was lossless.', '', 'D15. QUARANTINE CYCLE', ' doctor.quarantine(key, payload, verdict) stores a suspicious result with its verdict packet.', ' doctor.release(key) removes it.', ' doctor.get_quarantine(key) reads it back.', '', ' Verified current example:', ' quarantined packet exists before release and becomes None after release', '', 'D16. MERGE MODES', ' merge(...) averages channels.', ' merge_max(...) preserves the worst channel across packets.', '', ' Verified current difference:', ' a mixed average of healthy and fractured states may still judge OK', ' while merge_max of the same set may judge WARN', '', ' Therefore average and worst-case are both useful, but for different tasks.', '', 'D17. FINGERPRINT HELPERS', ' doctor.fingerprint_counter(items)', ' doctor.fingerprint_compare(a,b)', ' doctor.classify_zero_divisor_profile(profile)', ' doctor.zero_divisor_family(labels, reference_labels=None)', '', ' These helpers let Doctor classify structural families by distribution rather than by one local witness only.', '', 'D18. ZERO-DIVISOR FAMILY FINGERPRINTS', ' Verified current 8-sign family profile:', ' D:0 ≈ 50.0%', ' D:1 ≈ 14.3%', ' D:2 ≈ 11.9%', ' D:3 ≈ 9.5%', ' D:4 ≈ 7.1%', ' D:5 ≈ 4.8%', ' D:6 ≈ 2.4%', '', ' Verified current 16-sign family profile:', ' D:1 ≈ 29.0%', ' D:2 ≈ 21.2%', ' D:0 ≈ 16.4%', ' D:3 ≈ 13.8%', ' D:4 ≈ 10.5%', ' D:5 ≈ 6.2%', ' D:6 ≈ 2.9%', '', ' Safe interpretation:', ' 8-sign families are strongly vacuum-biased toward D:0,', ' while 16-sign families shift mass toward D:1 and D:2.', ' Therefore the two families are geometrically distinct classes.', '', 'D19. VERIFIED CLASSIFIER FACT', ' classify_zero_divisor_profile(fp8) -> best_match 8sign', ' classify_zero_divisor_profile(fp16) -> best_match 16sign', ' a small toy profile can also be classified by nearest family match', '', 'D20. PLAFAL AS A DOCTOR LAYER', ' Plafal is a recovered graph-with-labels layer.', ' It gives Doctor a natural language for local contradiction, overlap, and merge-history.', '', ' doctor.plafal_tension(P,Q) reads conflict density on shared structure:', ' tension = (#conflicts on common vertices/edges) / (#common elements)', '', ' Verified current examples:', ' p1 vs p2 -> tension = 1/3, local verdict LOW_TENSION', ' p1 vs identical copy p3 -> tension = 0, local verdict NO_TENSION', '', ' Note:', ' local plafal verdict and global doctor.level are not the same thing.', ' A local LOW_TENSION relation may still sit below the global WARN threshold.', '', 'D21. GLOBAL PLAFAL TENSION GRAPH', ' doctor.plafal_graph_summary(plafals, kinds=None)', ' summarizes tension topology across many relation-graphs at once.', '', ' Verified current toy graph of 4 plafals:', ' pair_count = 6', ' histogram = {0.0:3, 0.3:3}', ' avg_tension = 1/6', ' one connected component', ' avg_by_kind_pair shows cross-kind tension > within-kind tension', '', ' Safe interpretation:', ' this is a workable graph-level Doctor surface for neighborhood diagnostics.', '', 'D22. DOCTOR AND OPT_G', ' OPT_G-like descent asks: which nearby node reduces tension?', ' Doctor asks: did the move really reduce the right tensions, or did we enter a false minimum?', '', ' So OPT_G without Doctor can fall into a pretty trap.', ' Doctor without OPT_G can diagnose but not guide the descent.', ' Together they form the central bridge geometry.', '', 'D23. DOCTOR IS NOT ONLY A VERIFIER', ' In the recovered wider architecture Doctor can also be understood as:', ' classifier of fracture type', ' route selector', ' tunnel-aware navigator', ' residue reader', ' law-finding assistant', '', ' In the current codebase only part of that wider role is directly exposed,', ' but the central bridge function is already visible and verified.', '', 'D24. PRACTICAL RULE FOR AI', ' If a route closes -> let Doctor certify it.', ' If routes disagree -> let Doctor show which channels broke.', ' If no direct witness exists -> let OPT_G-like geometry move toward a softer stable node,', ' then let Doctor decide whether that node is trustworthy or merely convenient.', 'D25. ZERO-DIVISOR RULE IN F16 (SEDENIONS)', ' In F16, a pair u = (a,b), v = (c,d) with a,b,c,d ∈ 𝕆 (octonions)', ' satisfies sed_mul(u,v) = 0 if and only if the four octonion parts', ' are pairwise orthogonal in the Euclidean sense:', '', ' a·c = 0, a·d = 0, b·c = 0, b·d = 0.', '', ' This condition is both necessary and sufficient, verified on', ' 174+ examples from sparse scans (tension=0). It requires no', ' knowledge of octonion multiplication; only the dot product on ℝ⁸.', '', ' Why it works: From the Cayley–Dickson doubling formula,', ' sed_mul((a,b),(c,d)) = (ac − d̅b, da + b c̅).', ' If all four dot products vanish, the scalar parts of the octonion', ' products cancel, and the resulting octonions are zero. Conversely,', ' zero product forces all four dot products to be zero.', '', ' Relationship to E8: When one of the halves (e.g., a) is a D8‑root', ' (two non‑zero entries ±2 after scaling), the orthogonality', ' condition forces the partner half to be orthogonal, producing', ' known zero‑divisor families. But orthogonality alone is the', ' fundamental invariant; D8‑roots are a special case.', '', ' Connection to division: Division in this framework is not an', ' inverse operation but a witness query: "does this address have', ' a factor?" The zero‑divisor rule shows that "division by zero"', ' is meaningless; instead, zero is the state where orthogonal', ' halves annihilate. More deeply, division is the preservation', ' of zero — the universe does not "divide", it simply maintains', ' nullity when components are orthogonal.', '', ' Implementation for doctor:', ' def zero_divisor_quick(u, v):', ' a,b = u[:8], u[8:]', ' c,d = v[:8], v[8:]', ' dot = lambda x,y: sum(x[i]*y[i] for i in range(8))', ' if dot(a,c)==0 and dot(a,d)==0 and dot(b,c)==0 and dot(b,d)==0:', ' return {"is_zero_divisor": True, "tension": 0}', ' else:', ' return {"is_zero_divisor": False, "tension": 1}', '', ' This rule is independent of any coordinate scaling and works', ' for any integer vectors (or any vectors) representing the halves.', ] # [10:1] DOCTOR_LINES_END HELP = "\n".join(HELP_LINES) AXIOMS = "\n".join(AXIOMS_LINES) GEOM_HELP = "\n".join(GEOM_LINES) GPT_HELP = "\n".join(GPT_LINES) ACADEMY_HELP = "\n".join(ACADEMY_LINES) PYTH_HELP = "\n".join(PYTH_LINES) MACROS_HELP = "\n".join(MACROS_LINES) API_HELP = "\n".join(API_LINES) OPT_GEOM_HELP = "\n".join(OPT_GEOM_LINES) DOCTOR_HELP = "\n".join(DOCTOR_LINES) def help(): print(HELP) return HELP def help_axioms(): print(AXIOMS) return AXIOMS def help_geom(): print(GEOM_HELP) return GEOM_HELP def help_gpt(): print(GPT_HELP) return GPT_HELP def help_academy(): print(ACADEMY_HELP) return ACADEMY_HELP def help_pyth(): print(PYTH_HELP) return PYTH_HELP def help_macros(): print(MACROS_HELP) return MACROS_HELP def help_api(): print(API_HELP) return API_HELP def help_opt_geom(): print(OPT_GEOM_HELP) return OPT_GEOM_HELP def help_doctor(): print(DOCTOR_HELP) return DOCTOR_HELP def slash(cmd: str): c = str(cmd).strip() if c == '/help': return help() if c == '/axioms': return help_axioms() if c == '/geom': return help_geom() if c == '/gpt': return help_gpt() if c == '/academy': return help_academy() if c == '/pyth': return help_pyth() if c == '/macros': return help_macros() if c == '/api': return help_api() if c == "/opt_geom": return help_opt_geom() if c == "/doctor": return help_doctor() raise ValueError('unknown cmd. try: /help /axioms /geom /gpt /academy /pyth /macros /api') if __name__ == "__main__": print("helpdoc.py loaded. use slash('/help')") """ Логика построения e8 print("=== E8_248 LESSON: VERIFIED INVARIANTS ===") print("Integer-only. Every claim checked. No assumptions.\n") # ═══ 1. CONSTRUCTION ═══ roots = [] for i in range(8): for j in range(i+1, 8): for s1 in (2, -2): for s2 in (2, -2): v = [0]*8; v[i] = s1; v[j] = s2 roots.append(tuple(v)) n_d8 = len(roots) for signs in itertools.product((1, -1), repeat=8): if signs.count(-1) % 2 == 0: roots.append(signs) n_spinor = len(roots) - n_d8 root_set = frozenset(roots) root_idx = {r: i for i, r in enumerate(roots)} print(f"1. CONSTRUCTION: D8={n_d8} + Spinor={n_spinor} = {len(roots)} roots") # ═══ 2. NORM ═══ norms = set(sum(x*x for x in r) for r in roots) print(f"2. NORM²: {norms}") # ═══ 3. TRIANGLES ═══ # r1+r2+r3=0 ↔ r3=-(r1+r2). Pair lookup O(n²), not triple scan O(n³). tri_count = 0 triangles = [] for i in range(len(roots)): for j in range(i+1, len(roots)): r3 = tuple(-roots[i][k]-roots[j][k] for k in range(8)) if root_idx.get(r3, -1) > j: tri_count += 1 if len(triangles) < 100: triangles.append((roots[i], roots[j], r3)) print(f"3. TRIANGLES: {tri_count} unordered, {tri_count*3} ordered (×3 cyclic)") # ═══ 4. TRIANGLE GEOMETRY ═══ dot_vals = set() side_vals = set() median_x4_vals = set() # Full scan: all 2240 triangles, all 3 edges each all_dot_ok = True for i in range(len(roots)): for j in range(i+1, len(roots)): r3 = tuple(-roots[i][k]-roots[j][k] for k in range(8)) if root_idx.get(r3, -1) > j: for a, b in [(roots[i],roots[j]),(roots[i],r3),(roots[j],r3)]: d = sum(a[k]*b[k] for k in range(8)) s = sum((a[k]-b[k])**2 for k in range(8)) dot_vals.add(d) side_vals.add(s) if d != -4: all_dot_ok = False # median from vertex r1 to midpoint of (r2,r3) # r1+r2+r3=0 → midpoint(r2,r3)=-r1/2 # integer: |2*r1 - r2 - r3|² = |3*r1|² = 9×norm² = 72 median_x4_vals.add(sum((2*roots[i][k]-roots[j][k]-r3[k])**2 for k in range(8))) print(f"4. TRIANGLE GEOMETRY (all {tri_count} verified):") print(f" dot(ri,rj): {dot_vals} all=-4: {all_dot_ok}") print(f" side²: {side_vals} → equilateral") print(f" median²: { {v//4 for v in median_x4_vals} } ratio: { {round(v/4/24,4) for v in median_x4_vals} }") # ═══ 5. DOT SPECTRUM ═══ ref_sp = None uniform = True for ref in roots: sp = {} for r in roots: if r != ref: d = sum(ref[k]*r[k] for k in range(8)) sp[d] = sp.get(d, 0) + 1 if ref_sp is None: ref_sp = sp elif sp != ref_sp: uniform = False break print(f"5. DOT SPECTRUM: {dict(sorted(ref_sp.items()))} sum={sum(ref_sp.values())}") print(f" Uniform across all 240: {uniform}") # ═══ 6. PARTNERS ═══ ref = roots[0] p_d8 = sum(1 for r in roots if r != ref and sum(ref[k]*r[k] for k in range(8)) == -4 and root_idx[r] < n_d8) p_sp = sum(1 for r in roots if r != ref and sum(ref[k]*r[k] for k in range(8)) == -4 and root_idx[r] >= n_d8) tri_per_root = tri_count * 3 // len(roots) print(f"6. PARTNERS: {ref_sp.get(-4,0)} per root = {p_d8} D8 + {p_sp} spinor") print(f" Triangles per root: {tri_per_root}") # ═══ 7. WEYL GRAPH ═══ d1_plus = sum(1 for r in roots if r != ref and sum(ref[k]*r[k] for k in range(8)) == 4) d1_anti = sum(1 for r in roots if r != ref and sum(ref[k]*r[k] for k in range(8)) == -8) d1 = d1_plus + d1_anti d2 = len(roots) - 1 - d1 print(f"7. WEYL: depth0=1 depth1={d1} ({d1_plus} aligned + {d1_anti} antipodal) depth2={d2}") print(f" Total: {1+d1+d2} Diameter: 2") # ═══ 8. DUALITY (V41) ═══ # ref + partner(dot=-4) must be root with dot(ref,σ)=+4 # Algebraic: dot(ref,ref+p) = |ref|²+dot(ref,p) = 8+(-4) = 4 # Norm: |ref+p|² = 8+2(-4)+8 = 8 → valid root dual_ok = True dual_n = 0 for r in roots: if r == ref: continue if sum(ref[k]*r[k] for k in range(8)) == -4: sigma = tuple(ref[k]+r[k] for k in range(8)) if sigma not in root_set or sum(ref[k]*sigma[k] for k in range(8)) != 4: dual_ok = False dual_n += 1 print(f"8. DUALITY: ref+partner→aligned checked={dual_n} all OK: {dual_ok}") print(f" 56 partners ↔ 56 aligned neighbors. 56+56=112=|D8|") # ═══ 9. CLOSURE EXAMPLE ═══ r1, r2, r3 = triangles[0] s = tuple(r1[k]+r2[k]+r3[k] for k in range(8)) print(f"\n9. CLOSURE EXAMPLE:") print(f" r1={r1}") print(f" r2={r2}") print(f" r3={r3}") print(f" r1+r2+r3={s}") print(f" Three roots, sum=zero vector. Algebraic closure in 8D.") # ═══ 10. TENSION SUMMARY ═══ checks = { "roots=240": len(roots)==240, "D8=112": n_d8==112, "spinor=128": n_spinor==128, "norm²={8}": norms=={8}, "triangles=2240": tri_count==2240, "ordered=6720": tri_count*3==6720, "all_dot=-4": all_dot_ok, "side²={24}": side_vals=={24}, "median²={18}": median_x4_vals=={72}, "ratio=3/4": all(v/4/24==0.75 for v in median_x4_vals), "spectrum_uniform": uniform, "spectrum={-8:1,-4:56,0:126,4:56}": ref_sp=={-8:1,-4:56,0:126,4:56}, "partners=56": ref_sp.get(-4,0)==56, "24D8+32spinor": p_d8==24 and p_sp==32, "weyl=57+182": d1==57 and d2==182, "duality": dual_ok, } tension = sum(1 for v in checks.values() if not v) print(f"\n10. TENSION SUMMARY:") for k, v in checks.items(): sym = chr(10003) if v else chr(10007) print(f" {sym} {k}") print(f"\n TENSION: {tension}")""" eccomontenegro@gmail.com