mirror of
https://github.com/allaunthefox/SilverSight.git
synced 2026-07-31 01:25:21 +00:00
Snapshot of previously-uncommitted local work so nothing is lost after the power outage. NOT reviewed for correctness — a WIP checkpoint, not a feature: - multi-language hachimoji encoders (c/cpp/fortran/julia/octave/r/scala/go/rust/coq) - formal Lean WIP (BraidTree, Eisenstein, HachimojiCapture, MathlibConnect, ModularFormBridge, ClusterManifold) + lakefile + E8Sidon edit - docs/, experiments/ (epyc oisc benches), deploy/, scripts, test scaffolding - .gitignore: exclude **/target/ and Coq build artifacts Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
822 lines
34 KiB
Python
822 lines
34 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
Autonomous Pipeline: unknown problem → solve → FAMM scar → RRC re-route → iterate
|
||
|
||
Markdown in → parse → classify → AngrySphinx solver → on fail: record scar
|
||
→ RRC reads scar, re-routes search → repeat until solved or exhausted → emit receipt
|
||
|
||
The FAMM scar is negative guidance: "the solution is NOT in this spectral region."
|
||
RRC reads all scars and routes the solver away from dead zones.
|
||
"""
|
||
import json, re, sys, math, hashlib, time, argparse, os
|
||
from pathlib import Path
|
||
from dataclasses import dataclass, field
|
||
from typing import List, Dict, Optional, Set, Tuple
|
||
|
||
# ── Database configuration ───────────────────────────────────────────────
|
||
NEON_PG = os.environ.get("NEON_PG", "postgres://postgres:postgres@100.92.88.64:5432/research_stack")
|
||
|
||
try:
|
||
import psycopg2
|
||
import psycopg2.extras
|
||
HAS_DB = True
|
||
except ImportError:
|
||
HAS_DB = False
|
||
|
||
def db_conn():
|
||
if not HAS_DB: return None
|
||
return psycopg2.connect(NEON_PG, connect_timeout=5)
|
||
|
||
def db_init():
|
||
"""Create ENE schema tables if they don't exist (idempotent)."""
|
||
if not HAS_DB: return
|
||
try:
|
||
conn = db_conn()
|
||
with conn.cursor() as cur:
|
||
cur.execute("CREATE SCHEMA IF NOT EXISTS ene")
|
||
cur.execute("""
|
||
CREATE TABLE IF NOT EXISTS ene.routes (
|
||
id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
|
||
start_package_id TEXT NOT NULL REFERENCES ene.packages(pkg) ON DELETE CASCADE,
|
||
end_package_id TEXT NOT NULL REFERENCES ene.packages(pkg) ON DELETE CASCADE,
|
||
route_type TEXT NOT NULL,
|
||
cost REAL DEFAULT 0,
|
||
residual REAL DEFAULT 0,
|
||
scar_pressure REAL DEFAULT 0,
|
||
receipt_hash TEXT,
|
||
path JSONB DEFAULT '[]'::jsonb,
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||
)
|
||
""")
|
||
cur.execute("""
|
||
CREATE TABLE IF NOT EXISTS ene.scars (
|
||
id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
|
||
package_id TEXT NOT NULL REFERENCES ene.packages(pkg) ON DELETE CASCADE,
|
||
scar_type TEXT NOT NULL,
|
||
scar_pressure REAL DEFAULT 0,
|
||
failure_mode TEXT,
|
||
residual JSONB DEFAULT '{}'::jsonb,
|
||
coarsening_agent JSONB DEFAULT '{}'::jsonb,
|
||
opened_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||
closed_at TIMESTAMPTZ,
|
||
status TEXT NOT NULL DEFAULT 'open'
|
||
)
|
||
""")
|
||
cur.execute("""
|
||
CREATE TABLE IF NOT EXISTS ene.rrc_classifications (
|
||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||
equation_id TEXT,
|
||
shape TEXT,
|
||
pist_label TEXT,
|
||
spectral_radius DOUBLE PRECISION,
|
||
weak_axes INT,
|
||
score DOUBLE PRECISION,
|
||
classified_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||
)
|
||
""")
|
||
cur.execute("CREATE INDEX IF NOT EXISTS idx_scar_pkg ON ene.scars(package_id)")
|
||
cur.execute("CREATE INDEX IF NOT EXISTS idx_scar_pressure ON ene.scars(scar_pressure DESC)")
|
||
cur.execute("CREATE INDEX IF NOT EXISTS idx_rrc_eq ON ene.rrc_classifications(equation_id)")
|
||
conn.commit()
|
||
conn.close()
|
||
except Exception as e:
|
||
print(f" [db] Schema init error: {e}", file=sys.stderr)
|
||
|
||
def db_load_guide_paths(equation_id: str) -> Dict:
|
||
"""Load guide paths from DB: existing scars + RRC classifications for this equation.
|
||
Returns dict of {scarred_regions: [...], classifications: [...], routes: [...]}."""
|
||
guide = {"scarred_regions": [], "classifications": [], "routes": []}
|
||
if not HAS_DB: return guide
|
||
try:
|
||
conn = db_conn()
|
||
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
|
||
cur.execute(
|
||
"SELECT DISTINCT scar_type, failure_mode, scar_pressure FROM ene.scars WHERE status='open' ORDER BY scar_pressure DESC",
|
||
()
|
||
)
|
||
for row in cur.fetchall():
|
||
guide["scarred_regions"].append(row)
|
||
cur.execute(
|
||
"SELECT shape, pist_label, spectral_radius, weak_axes, score FROM ene.rrc_classifications WHERE equation_id=%s ORDER BY score DESC",
|
||
(equation_id,)
|
||
)
|
||
for row in cur.fetchall():
|
||
guide["classifications"].append(row)
|
||
cur.execute(
|
||
"SELECT route_type, cost, residual, scar_pressure FROM ene.routes ORDER BY cost ASC",
|
||
()
|
||
)
|
||
for row in cur.fetchall():
|
||
guide["routes"].append(row)
|
||
conn.close()
|
||
except Exception as e:
|
||
print(f" [db] Load error: {e}", file=sys.stderr)
|
||
return guide
|
||
|
||
def db_write_scar(package_id: str, scar_type: str, pressure: float, failure_mode: str,
|
||
coarsening_agent: str = ""):
|
||
if not HAS_DB: return
|
||
try:
|
||
conn = db_conn()
|
||
with conn.cursor() as cur:
|
||
cur.execute(
|
||
"INSERT INTO ene.scars (package_id, scar_type, scar_pressure, failure_mode, coarsening_agent) "
|
||
"VALUES (%s, %s, %s, %s, %s::jsonb) ON CONFLICT DO NOTHING",
|
||
(package_id, scar_type, pressure, failure_mode,
|
||
json.dumps({"agent": coarsening_agent}))
|
||
)
|
||
conn.commit()
|
||
conn.close()
|
||
except Exception as e:
|
||
print(f" [db] Scar write error: {e}", file=sys.stderr)
|
||
|
||
def db_write_route(start_pkg: str, end_pkg: str, route_type: str, cost: float,
|
||
residual: float, scar_pressure: float, path: list):
|
||
if not HAS_DB: return
|
||
try:
|
||
conn = db_conn()
|
||
with conn.cursor() as cur:
|
||
cur.execute(
|
||
"INSERT INTO ene.routes (start_package_id, end_package_id, route_type, cost, residual, scar_pressure, path) "
|
||
"VALUES (%s, %s, %s, %s, %s, %s, %s::jsonb)",
|
||
(start_pkg, end_pkg, route_type, cost, residual, scar_pressure, json.dumps(path))
|
||
)
|
||
conn.commit()
|
||
conn.close()
|
||
except Exception as e:
|
||
print(f" [db] Route write error: {e}", file=sys.stderr)
|
||
|
||
def db_ensure_package(pkg_id: str, title: str = "", pkg_type: str = "lean_theorem"):
|
||
"""Upsert a package so foreign keys work."""
|
||
if not HAS_DB: return
|
||
try:
|
||
conn = db_conn()
|
||
with conn.cursor() as cur:
|
||
cur.execute(
|
||
"INSERT INTO ene.packages (pkg, package_type, title) VALUES (%s, %s, %s) ON CONFLICT (pkg) DO NOTHING",
|
||
(pkg_id, pkg_type, title)
|
||
)
|
||
conn.commit()
|
||
conn.close()
|
||
except Exception as e:
|
||
print(f" [db] Package error: {e}", file=sys.stderr)
|
||
|
||
sys.setrecursionlimit(10000)
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Core primitives
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
LETTERS = ["Φ","Λ","Ρ","Κ","Ω","Σ","Π","Ζ"]
|
||
|
||
def sigma3(n):
|
||
t = 0
|
||
for d in range(1, int(n**0.5)+1):
|
||
if n % d == 0:
|
||
t += d**3
|
||
if n//d != d: t += (n//d)**3
|
||
return t
|
||
|
||
def cartan_block(a, b):
|
||
if a == b: return 273
|
||
if a // 2 == b // 2: return 256
|
||
return 0
|
||
|
||
@dataclass
|
||
class FAMMScar:
|
||
"""A FAMM scar records a failure zone: where the solver hit a wall."""
|
||
region: str # which Cartan block pair collided
|
||
collision_sum: int # the sum value that collided
|
||
pressure: int # energy cost = 256*collisions
|
||
failure_mode: str # ROSSBY (retry) or SCARRED (quarantine)
|
||
coarsening_agent: str # fix route
|
||
timestamp: float = field(default_factory=time.time)
|
||
|
||
@dataclass
|
||
class RRCState:
|
||
"""RRC state: tracks which spectral regions are dead (scarred) and
|
||
which remain viable for search. The gate is a cumulative resource budget:
|
||
each collision charge consumes budget; when budget is exhausted the region
|
||
permanently scars (irreversible closure). Budget threshold decays over time,
|
||
so early search is forgiving and late search is strict."""
|
||
regions: List[str] = field(default_factory=lambda: [
|
||
"CANONICAL_pair0", "CANONICAL_pair1", "CANONICAL_pair2", "CANONICAL_pair3", "ROSSBY_all"
|
||
])
|
||
dead_regions: Set[str] = field(default_factory=set)
|
||
scars: List[FAMMScar] = field(default_factory=list)
|
||
_idx: int = 0
|
||
equation_id: str = ""
|
||
|
||
# Cumulative resource budget per region
|
||
region_budget: Dict[str, int] = field(default_factory=dict)
|
||
max_budget_initial: int = 20 # B₀
|
||
budget_decay: float = 0.85 # λ — threshold shrinks each iteration
|
||
_iteration: int = 0
|
||
|
||
def __post_init__(self):
|
||
"""On init, load guide paths from DB to skip known dead regions."""
|
||
if self.equation_id:
|
||
guide = db_load_guide_paths(self.equation_id)
|
||
for scar_row in guide.get("scarred_regions", []):
|
||
mode = scar_row.get("failure_mode", "ROSSBY")
|
||
sregion = scar_row.get("scar_type", "ROSSBY_all")
|
||
if mode == "SCARRED" or mode == "rosby_collapse":
|
||
self.dead_regions.add(sregion)
|
||
self.scars.append(FAMMScar(
|
||
region=sregion,
|
||
collision_sum=0,
|
||
pressure=int(scar_row.get("scar_pressure", 256)),
|
||
failure_mode="SCARRED",
|
||
coarsening_agent="persisted scar (loaded from DB)"
|
||
))
|
||
for cls_row in guide.get("classifications", []):
|
||
shape = cls_row.get("shape", "")
|
||
if shape and shape != "unknown":
|
||
pass
|
||
|
||
@property
|
||
def current_max_budget(self) -> int:
|
||
"""B(t): dynamic budget threshold. Decays with iterations, never below 3."""
|
||
return max(3, int(self.max_budget_initial * (self.budget_decay ** self._iteration)))
|
||
|
||
def charge_budget(self, region: str, cost: int) -> bool:
|
||
"""Charge cumulative collision cost to a region.
|
||
Returns True if budget is exhausted → region permanently scars."""
|
||
self.region_budget[region] = self.region_budget.get(region, 0) + cost
|
||
if self.region_budget[region] >= self.current_max_budget:
|
||
scar = FAMMScar(
|
||
region=region, collision_sum=cost,
|
||
pressure=self.region_budget[region],
|
||
failure_mode="SCARRED",
|
||
coarsening_agent=(
|
||
f"budget exhausted: cumulative {self.region_budget[region]} "
|
||
f"collisions ≥ B_max={self.current_max_budget}"
|
||
)
|
||
)
|
||
self.record_scar(scar)
|
||
return True
|
||
return False
|
||
|
||
def next_region(self) -> Optional[str]:
|
||
"""Return next viable region, cycling through all non-dead regions."""
|
||
tried = 0
|
||
while tried < len(self.regions):
|
||
r = self.regions[self._idx % len(self.regions)]
|
||
self._idx += 1
|
||
if r not in self.dead_regions:
|
||
return r
|
||
tried += 1
|
||
return None
|
||
|
||
def scar_blocked(self, region: str) -> bool:
|
||
"""Check if a given region (e.g. 'pair_0') is in the dead set."""
|
||
canonical_map = {"pair_0": "CANONICAL_pair0", "pair_1": "CANONICAL_pair1",
|
||
"pair_2": "CANONICAL_pair2", "pair_3": "CANONICAL_pair3"}
|
||
canonical = canonical_map.get(region, "ROSSBY_all")
|
||
return canonical in self.dead_regions
|
||
|
||
def record_scar(self, scar: FAMMScar):
|
||
self.scars.append(scar)
|
||
if scar.failure_mode == "SCARRED":
|
||
self.dead_regions.add(scar.region)
|
||
pkg_id = f"scar:{scar.region}"
|
||
db_ensure_package(pkg_id, title=f"FAMM scar @ {scar.region}", pkg_type="scar")
|
||
db_write_scar(
|
||
package_id=pkg_id,
|
||
scar_type=scar.region,
|
||
pressure=float(scar.pressure),
|
||
failure_mode=scar.failure_mode,
|
||
coarsening_agent=scar.coarsening_agent
|
||
)
|
||
|
||
def summary(self):
|
||
alive = [r for r in self.regions if r not in self.dead_regions]
|
||
dead = sorted(self.dead_regions)
|
||
return f"alive={alive} dead={dead} scars={len(self.scars)}"
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Solver: find Sidon set in [1,N] with scar recording
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
def solve_with_scars(N: int, rrc: RRCState, region: str = "", time_limit_s: float = 10.0):
|
||
"""
|
||
Find maximal Sidon subset in [1,N] using σ₃ pre-filtering.
|
||
On every collision, charge the region's cumulative budget.
|
||
RRC reads scars before search to avoid dead regions.
|
||
"""
|
||
# E8 σ₃ pre-filter: only search σ₃-bounded candidates
|
||
# This reduces search space from N to N^0.25 (~5-25 elements)
|
||
candidates = []
|
||
n = 1
|
||
while n**3 + 1 <= N:
|
||
if sigma3(n) <= N:
|
||
candidates.append(n)
|
||
n += 1
|
||
# If E8 pre-filter gives too few candidates, fall back to full range (capped)
|
||
if len(candidates) <= 1:
|
||
candidates = list(range(1, min(N + 1, 65))) # cap at 64 for brute-force
|
||
best = []
|
||
nodes = 0
|
||
t0 = time.time()
|
||
best_energy = 0
|
||
best_dna = ""
|
||
|
||
def collision_count(s):
|
||
sums = set()
|
||
coll = 0
|
||
coll_details = []
|
||
for i, a in enumerate(s):
|
||
for b in s[i:]:
|
||
p = a + b
|
||
if p in sums:
|
||
coll += 1
|
||
coll_details.append((a, b, p))
|
||
else:
|
||
sums.add(p)
|
||
return coll, coll_details
|
||
|
||
def new_collisions(current, x):
|
||
psums = {a + x for a in current} | {x + x}
|
||
existing = set()
|
||
for i, a in enumerate(current):
|
||
for b in current[i:]:
|
||
existing.add(a + b)
|
||
return len(psums & existing)
|
||
|
||
def search(current, idx, current_coll):
|
||
nonlocal best, nodes, t0, best_energy, best_dna
|
||
|
||
if time.time() - t0 > time_limit_s:
|
||
return
|
||
|
||
nodes += 1
|
||
|
||
# Upper bound prune
|
||
if len(current) + (len(candidates) - idx) <= len(best):
|
||
return
|
||
|
||
# AngrySphinx gate: at 2 collisions, record FAMM scar and return
|
||
if current_coll >= 2:
|
||
# Record scar for this failure
|
||
_, details = collision_count(current)
|
||
for a, b, p in details[-1:]: # last collision
|
||
# Determine which Cartan pair
|
||
li_a, li_b = sigma3(a) % 8, sigma3(b) % 8
|
||
pair = f"pair_{li_a//2}_{li_b//2}"
|
||
pressure = 256 * current_coll - 17 * current_coll
|
||
|
||
# Classify scar type
|
||
if any(li // 2 == (li_a // 2) and li // 2 == (li_b // 2) for li in [sigma3(x) % 8 for x in current]):
|
||
mode = "SCARRED" # same-pair collapse
|
||
coarsening = f"quarantine pair {li_a//2}, retry with single-element filter"
|
||
else:
|
||
mode = "ROSSBY" # cross-pair threading
|
||
coarsening = f"adjust Cartan block {li_a//2} energy ±256"
|
||
|
||
scar = FAMMScar(
|
||
region=pair,
|
||
collision_sum=p,
|
||
pressure=pressure,
|
||
failure_mode=mode,
|
||
coarsening=coarsening
|
||
)
|
||
rrc.record_scar(scar)
|
||
return
|
||
|
||
# Update best: compute Hachimoji encoding + Cartan energy
|
||
if len(current) > len(best):
|
||
best = sorted(current[:])
|
||
# Hachimoji DNA
|
||
dna = "".join(LETTERS[sigma3(n) % 8] for n in best)
|
||
# Cartan energy
|
||
indices = [sigma3(n) % 8 for n in best]
|
||
ce = sum(cartan_block(indices[i], indices[j])
|
||
for i in range(len(indices)) for j in range(i, len(indices)))
|
||
best_energy = ce
|
||
best_dna = dna
|
||
|
||
if idx >= len(candidates):
|
||
return
|
||
|
||
x = candidates[idx]
|
||
|
||
# RRC check: skip if this element falls in a dead region
|
||
li_x = sigma3(x) % 8
|
||
region = f"pair_{li_x//2}"
|
||
if rrc.scar_blocked(region):
|
||
# This Cartan block is dead — skip entire block
|
||
search(current, idx + 1, current_coll)
|
||
return
|
||
|
||
c = new_collisions(current, x)
|
||
|
||
if current_coll + c <= 1:
|
||
current.append(x)
|
||
search(current, idx + 1, current_coll + c)
|
||
current.pop()
|
||
|
||
search(current, idx + 1, current_coll)
|
||
|
||
search([], 0, 0)
|
||
elapsed = time.time() - t0
|
||
|
||
return {
|
||
"solution": best,
|
||
"size": len(best),
|
||
"dna": best_dna,
|
||
"cartan_energy": best_energy,
|
||
"nodes": nodes,
|
||
"time": round(elapsed, 4),
|
||
"timed_out": elapsed > time_limit_s
|
||
}
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Markdown Ingester (from existing ingest.py)
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
@dataclass
|
||
class ParsedEquation:
|
||
text: str
|
||
line: int
|
||
is_block: bool
|
||
classification: str = "unknown"
|
||
|
||
def parse_markdown(text: str) -> List[ParsedEquation]:
|
||
equations = []
|
||
lines = text.split('\n')
|
||
# Block equations: $$...$$
|
||
in_block = False
|
||
block_text = ""
|
||
for i, line in enumerate(lines):
|
||
if line.strip().startswith('$$') and not in_block:
|
||
in_block = True
|
||
block_text = line.strip()[2:]
|
||
if '$$' in block_text: # single-line block
|
||
eq = block_text.split('$$')[0].strip()
|
||
equations.append(ParsedEquation(text=eq, line=i+1, is_block=True))
|
||
in_block = False
|
||
continue
|
||
elif in_block:
|
||
if '$$' in line:
|
||
block_text += " " + line.split('$$')[0]
|
||
eq = block_text.strip()
|
||
if eq:
|
||
equations.append(ParsedEquation(text=eq, line=i+1, is_block=True))
|
||
in_block = False
|
||
block_text = ""
|
||
else:
|
||
block_text += " " + line
|
||
|
||
# Inline equations: $...$ (skip if already captured in blocks)
|
||
for i, line in enumerate(lines):
|
||
if '$$' in line:
|
||
continue
|
||
inlines = re.findall(r'\$([^$]+)\$', line)
|
||
for eq in inlines:
|
||
eq = eq.strip()
|
||
if eq and len(eq) >= 3: # meaningful equation, not empty/short
|
||
equations.append(ParsedEquation(text=eq, line=i+1, is_block=False))
|
||
return equations
|
||
|
||
SPECTRAL_KW = [r'spectral', r'eigenvalue', r'gap', r'Cartan', r'Sidon',
|
||
r'chiral', r'braid', r'sigma', r'tau', r'Delta', r'lambda']
|
||
BRAID_KW = [r'braid', r'strand', r'cross', r'Sidon', r'eigensolid']
|
||
CARTAN_KW = [r'Cartan', r'weight', r'diagonal', r'block', r'Gram']
|
||
|
||
def classify_equation(eq: ParsedEquation) -> ParsedEquation:
|
||
text = eq.text.lower()
|
||
scores = {"spectral": 0, "braid": 0, "cartan": 0}
|
||
for kw in SPECTRAL_KW:
|
||
if re.search(kw, text, re.IGNORECASE): scores["spectral"] += 1
|
||
for kw in BRAID_KW:
|
||
if re.search(kw, text, re.IGNORECASE): scores["braid"] += 1
|
||
for kw in CARTAN_KW:
|
||
if re.search(kw, text, re.IGNORECASE): scores["cartan"] += 1
|
||
best = max(scores, key=scores.get)
|
||
eq.classification = best if scores[best] > 0 else "unknown"
|
||
return eq
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# The Autonomous Loop
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
def autonomous_solve(equation: ParsedEquation, max_iterations: int = 10) -> Dict:
|
||
"""
|
||
Unknown equation → try multiple spectral regions → scar dead zones → re-route.
|
||
|
||
Each iteration tries a different RRC spectral region. If a region produces
|
||
a solution worse than the best so far, record a FAMM scar and move to
|
||
next region. This is the autonomous "solve → scar → re-route" cycle.
|
||
|
||
Guide paths are loaded from the ENE PostgreSQL database on startup and
|
||
new scars are persisted to guide future runs.
|
||
"""
|
||
# Determine N from equation
|
||
numbers = [int(x) for x in re.findall(r'\b(\d+)\b', equation.text) if 2 <= int(x) <= 10000]
|
||
N = min(max(max(numbers), 64) if numbers else 128, 10000)
|
||
|
||
# Create a deterministic equation_id for DB lookup
|
||
eq_hash = hashlib.sha256(equation.text.encode()).hexdigest()[:16]
|
||
equation_id = f"eq_{eq_hash}"
|
||
|
||
# RRC state loads guide paths from DB (scarred regions, classifications) on init
|
||
rrc = RRCState(equation_id=equation_id)
|
||
iteration_log = []
|
||
best_solution = []
|
||
best_dna = ""
|
||
|
||
# Ensure package exists in DB for this equation
|
||
db_ensure_package(equation_id, title=equation.text[:120], pkg_type="equation")
|
||
|
||
for iteration in range(max_iterations):
|
||
region = rrc.next_region()
|
||
if region is None:
|
||
iteration_log.append({"iteration": iteration, "status": "EXHAUSTED", "region": "—", "size": 0})
|
||
break
|
||
|
||
# Update dynamic budget threshold (decays with each iteration)
|
||
rrc._iteration = iteration
|
||
|
||
# Generate σ₃-bounded candidates for this region
|
||
candidates = []
|
||
n = 1
|
||
while n**3 + 1 <= N:
|
||
if sigma3(n) <= N:
|
||
candidates.append(n)
|
||
n += 1
|
||
|
||
# RRC filter: only process elements in viable region
|
||
region_blocks = {
|
||
"CANONICAL_pair0": (0,),
|
||
"CANONICAL_pair1": (1,),
|
||
"CANONICAL_pair2": (2,),
|
||
"CANONICAL_pair3": (3,),
|
||
"ROSSBY_all": (0, 1, 2, 3),
|
||
}
|
||
allowed_blocks = region_blocks.get(region, (0, 1, 2, 3))
|
||
|
||
# Filter candidates by region, but fall back to all if too few
|
||
filtered = [x for x in candidates if (sigma3(x) % 8) // 2 in allowed_blocks]
|
||
if len(filtered) <= 1:
|
||
filtered = candidates
|
||
|
||
result = solve_with_scars_prefiltered(filtered, N, rrc, region=region, time_limit_s=5.0)
|
||
|
||
budget_info = f"B={rrc.region_budget.get(region, 0)}/{rrc.current_max_budget}"
|
||
log_entry = {
|
||
"iteration": iteration,
|
||
"region": region,
|
||
"solution": result["solution"],
|
||
"size": result["size"],
|
||
"dna": result["dna"],
|
||
"cartan_energy": result["cartan_energy"],
|
||
"nodes": result["nodes"],
|
||
"time": result["time"],
|
||
"collisions": result.get("collisions", 0),
|
||
"budget": budget_info,
|
||
"budget_exhausted": result.get("budget_exhausted", False),
|
||
}
|
||
|
||
if result.get("budget_exhausted", False):
|
||
log_entry["status"] = "BUDGET_EXHAUSTED"
|
||
elif result["size"] == 0:
|
||
if not best_solution:
|
||
scar = FAMMScar(
|
||
region=region, collision_sum=0, pressure=256,
|
||
failure_mode="SCARRED" if "ROSSBY" not in region else "ROSSBY",
|
||
coarsening_agent=f"gate closed @ {region}"
|
||
)
|
||
rrc.record_scar(scar)
|
||
log_entry["status"] = "GATE_CLOSED"
|
||
elif result["size"] > len(best_solution):
|
||
best_solution = result["solution"]
|
||
best_dna = result["dna"]
|
||
log_entry["status"] = "IMPROVED"
|
||
# Write guide path to DB: this region was productive
|
||
db_ensure_package(equation_id, title=equation.text[:120], pkg_type="equation")
|
||
db_ensure_package(f"solution:size={result['size']}", title=f"Sidon set size {result['size']}", pkg_type="solution")
|
||
db_write_route(
|
||
start_pkg=equation_id,
|
||
end_pkg=f"solution:size={result['size']}",
|
||
route_type=f"rrc_region:{region}",
|
||
cost=float(result.get("time", 0)),
|
||
residual=0.0,
|
||
scar_pressure=0.0,
|
||
path=result["solution"]
|
||
)
|
||
elif result["size"] < len(best_solution) and best_solution:
|
||
# This region is worse → record a scar for future avoidance
|
||
scar = FAMMScar(
|
||
region=region,
|
||
collision_sum=0,
|
||
pressure=256,
|
||
failure_mode="SCARRED" if "ROSSBY" not in region else "ROSSBY",
|
||
coarsening_agent=f"region {region} is suboptimal (size {result['size']} < best {len(best_solution)})"
|
||
)
|
||
rrc.record_scar(scar)
|
||
log_entry["status"] = "SCARRED"
|
||
log_entry["collisions"] = 1 # mark as scarred
|
||
else:
|
||
log_entry["status"] = "SAME"
|
||
|
||
iteration_log.append(log_entry)
|
||
|
||
alpha = math.log(len(best_solution)) / math.log(N) if len(best_solution) > 0 and N > 1 else 0
|
||
epsilon = 1 - alpha
|
||
|
||
return {
|
||
"equation": equation.text,
|
||
"classification": equation.classification,
|
||
"N": N,
|
||
"iterations": len(iteration_log),
|
||
"log": iteration_log,
|
||
"final_size": len(best_solution),
|
||
"final_solution": best_solution,
|
||
"final_dna": best_dna,
|
||
"erdos_epsilon": round(epsilon, 4),
|
||
"rrc_summary": rrc.summary(),
|
||
"total_scars": len(rrc.scars),
|
||
"scars": [{"region": s.region, "mode": s.failure_mode,
|
||
"pressure": s.pressure, "agent": s.coarsening_agent}
|
||
for s in rrc.scars]
|
||
}
|
||
|
||
def solve_with_scars_prefiltered(candidates, N, rrc, region="", time_limit_s=5.0):
|
||
"""Solver with pre-filtered candidates. Charges cumulative resource budget.
|
||
|
||
Each collision event (≥2 collisions on a search path) charges the region's
|
||
cumulative budget. When budget > B_max(t), the region permanently scars.
|
||
This models the gate as a computational resource constraint, not a Sidon
|
||
feasibility check.
|
||
"""
|
||
best = []
|
||
nodes = 0
|
||
t0 = time.time()
|
||
best_energy = 0
|
||
best_dna = ""
|
||
collisions = 0
|
||
budget_exhausted = False
|
||
|
||
def collision_count(s):
|
||
sums = set()
|
||
coll = 0
|
||
for i, a in enumerate(s):
|
||
for b in s[i:]:
|
||
p = a + b
|
||
if p in sums: coll += 1
|
||
else: sums.add(p)
|
||
return coll, []
|
||
|
||
def new_collisions(current, x):
|
||
psums = {a + x for a in current} | {x + x}
|
||
existing = set()
|
||
for i, a in enumerate(current):
|
||
for b in current[i:]:
|
||
existing.add(a + b)
|
||
return len(psums & existing)
|
||
|
||
def search(current, idx, current_coll):
|
||
nonlocal best, nodes, t0, best_energy, best_dna, collisions, budget_exhausted
|
||
|
||
if budget_exhausted or time.time() - t0 > time_limit_s:
|
||
return
|
||
|
||
# Charge 1 effort unit per node explored to the region's cumulative budget
|
||
if region:
|
||
if rrc.charge_budget(region, 1):
|
||
budget_exhausted = True
|
||
return
|
||
|
||
nodes += 1
|
||
|
||
if len(current) + (len(candidates) - idx) <= len(best):
|
||
return
|
||
|
||
if current_coll >= 2:
|
||
collisions = max(collisions, current_coll)
|
||
# Charge additional collision cost when the path is pruned
|
||
if region:
|
||
if rrc.charge_budget(region, current_coll):
|
||
budget_exhausted = True
|
||
if current:
|
||
_, details = collision_count(current)
|
||
for a, b, p in details[-1:]:
|
||
li_a, li_b = sigma3(a) % 8, sigma3(b) % 8
|
||
rrc.scars.append(FAMMScar(
|
||
region=f"CANONICAL_pair{li_a // 2}",
|
||
collision_sum=p,
|
||
pressure=256 * current_coll,
|
||
failure_mode="ROSSBY",
|
||
coarsening_agent=f"collision @ depth {len(current)}"
|
||
))
|
||
return
|
||
|
||
if len(current) > len(best):
|
||
best = sorted(current[:])
|
||
dna = "".join(LETTERS[sigma3(n) % 8] for n in best)
|
||
indices = [sigma3(n) % 8 for n in best]
|
||
ce = sum(cartan_block(indices[i], indices[j])
|
||
for i in range(len(indices)) for j in range(i, len(indices)))
|
||
best_energy = ce
|
||
best_dna = dna
|
||
|
||
if idx >= len(candidates):
|
||
return
|
||
|
||
x = candidates[idx]
|
||
|
||
c = new_collisions(current, x)
|
||
if current_coll + c <= 1:
|
||
current.append(x)
|
||
search(current, idx + 1, current_coll + c)
|
||
current.pop()
|
||
|
||
search(current, idx + 1, current_coll)
|
||
|
||
search([], 0, 0)
|
||
elapsed = time.time() - t0
|
||
|
||
return {
|
||
"solution": best, "size": len(best),
|
||
"dna": best_dna, "cartan_energy": best_energy,
|
||
"nodes": nodes, "time": round(elapsed, 4),
|
||
"timed_out": elapsed > time_limit_s,
|
||
"collisions": collisions,
|
||
"budget_exhausted": budget_exhausted
|
||
}
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Main
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description="Autonomous pipeline: problem → solve → scar → re-route")
|
||
parser.add_argument("input", type=str, help="Markdown file with equations")
|
||
parser.add_argument("--max-iter", type=int, default=10, help="Max RRC re-route iterations")
|
||
parser.add_argument("--verbose", action="store_true")
|
||
|
||
args = parser.parse_args()
|
||
input_path = Path(args.input)
|
||
|
||
if not input_path.exists():
|
||
print(f"Error: {input_path} not found"); sys.exit(1)
|
||
|
||
text = input_path.read_text()
|
||
equations = parse_markdown(text)
|
||
equations = [classify_equation(e) for e in equations]
|
||
|
||
print(f"╔══════════════════════════════════════════════════════════╗")
|
||
print(f"║ AUTONOMOUS PIPELINE: {input_path.name}")
|
||
print(f"║ Equations parsed: {len(equations)}")
|
||
|
||
spectral = sum(1 for e in equations if e.classification == "spectral")
|
||
braid = sum(1 for e in equations if e.classification == "braid")
|
||
cartan = sum(1 for e in equations if e.classification == "cartan")
|
||
unknown = sum(1 for e in equations if e.classification == "unknown")
|
||
print(f"║ Spectral: {spectral} Braid: {braid} Cartan: {cartan} Unknown: {unknown}")
|
||
print(f"╚══════════════════════════════════════════════════════════╝")
|
||
|
||
all_results = []
|
||
for eq in equations:
|
||
if eq.classification == "unknown":
|
||
if args.verbose: print(f"\n[{eq.line}] UNKNOWN → skipped: `{eq.text[:80]}`")
|
||
all_results.append({"equation": eq.text, "line": eq.line, "result": "skipped"})
|
||
continue
|
||
|
||
print(f"\n── [{eq.line}] {eq.classification.upper()}: `{eq.text[:60]}...` ──")
|
||
result = autonomous_solve(eq)
|
||
all_results.append(result)
|
||
|
||
print(f" N={result['N']} Iterations: {result['iterations']}")
|
||
for i, entry in enumerate(result["log"]):
|
||
status_icon = {"IMPROVED": "✓", "SCARRED": "⚡", "SAME": "=", "EXHAUSTED": "✗",
|
||
"GATE_CLOSED": "💥", "BUDGET_EXHAUSTED": "💥"}.get(entry["status"], "?")
|
||
entry_region = entry.get("region", "—")
|
||
entry_size = entry.get("size", 0)
|
||
entry_dna = entry.get("dna", "") or ""
|
||
entry_budget = entry.get("budget", "")
|
||
budget_tag = f" [{entry_budget}]" if entry_budget else ""
|
||
print(f" [{i}] {status_icon} {entry_region}: size={entry_size} ({entry['status']}){budget_tag}")
|
||
|
||
print(f" Scars: {result['total_scars']}")
|
||
for s in result["scars"]:
|
||
print(f" ⚡ {s['mode']} @ {s['region']} → {s['agent']}")
|
||
|
||
print(f" Best: {result['final_solution']} ({result['final_size']} elts)")
|
||
print(f" DNA: {result['final_dna']}")
|
||
print(f" ε: {result['erdos_epsilon']:.4f}")
|
||
|
||
# Emit receipt
|
||
receipt = {
|
||
"schema": "autonomous_pipeline_v1",
|
||
"source": str(input_path),
|
||
"total_equations": len(equations),
|
||
"results": all_results
|
||
}
|
||
|
||
out_path = input_path.with_suffix(".autonomous.json")
|
||
out_path.write_text(json.dumps(receipt, indent=2))
|
||
print(f"\nReceipt: {out_path}")
|
||
|
||
if __name__ == "__main__":
|
||
main()
|