#!/usr/bin/env python3
# Generated by build.py; maintain frontend.py and the original converter engines.
# Deploy this single script: all three trusted engine sources are embedded below.
# No sibling scripts, downloads or third-party packages are required.
"""Convert supported Elegant, ASTRA or legacy OPAL inputs into OPALX candidates.

Python 3.9+, standard library only. Offline: no installation or tracking.
The deployable toOPALX.py embeds the three tested conversion engines.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import posixpath
import shutil
import sys
import tempfile
import textwrap
import types

VERSION = '1.4.2'
MODES = ('elegant', 'astra', 'opal')
_ENGINE_CACHE = {}
SCOPES = {
    'elegant': '''Elegant mode: one injected electron bunch, one pass, forward horizontal line.
Input: .ele with run_setup, run_control, sdds_beam, track; literal .lte lattice
and one counted SDDS1 ASCII particle page. Supply leading CHARGE or --charge-c.
Supports DRIF/DRIFT/EDRIFT, aligned hard-edge QUAD, MARK, pure zero-gap
SBEN/SBEND/CSBEND, and explicitly configured standing-wave RFCA longitudinal
kicks with known absolute RF time and no transverse focusing/reference retuning.
Unavailable element types (including RBEN) become equal-length drifts and are
listed in the report. Unsupported settings of available models remain errors.
No space charge: the target fieldsolver is always NONE. Binary/multipage SDDS,
RPN, includes, scans and optimization remain unsupported.
Arrival events must align within an existing leading drift (or have equal times).
Finite source matrices/kicks and target tracking can give different results.''',
    'astra': '''ASTRA mode: an injected equal-weight electron snapshot with a common clock.
Input: ASTRA namelist plus its particle distribution and any referenced maps.
Supports drift, supported axisymmetric RF/solenoid maps, quadrupoles, circular
apertures and planar dipole-only beamlines. Maps use existing OPALX models;
RF off-axis expansion and sampled magnetic maps require numerical review.
The target fieldsolver is always NONE, even when source space charge is enabled;
the original charge settings are recorded. Unsupported emission, namelists and
field models stop conversion when no valid drift geometry can be determined.
No cathode-emission equivalence or universal machine conversion.
--center-launch-frame is explicit and restricted to drift/RF/solenoid cases.
ASTRA H_max and Max_step remain the source of tracking timestep and step budget.''',
    'opal': '''OPAL mode: conservative structural migration of supported legacy OPAL-T files.
Input: entry .in and recursive literal CALL includes, particle files and maps
inside its case directory. Migrates supported syntax, particle counts and
beam/distribution/source attachments; records preserved field/track attributes.
Expressions are preserved, never evaluated. Recognized physics settings may
require review of units, reference rigidity, emission and placement conventions.
Unavailable lattice element types (including BEAMBEAM) become drifts retaining
length and placement; every replacement is listed. OPAL solver settings remain.
Obsolete SELECT and PARTICLEMATTERINTERACTION statements/attributes are removed
and reported; no particle-matter model is retained.
BINOMIAL distributions use a reported GAUSS approximation: widths/correlations
are retained without rescaling and binomial shape exponents are removed.
No arbitrary scripts, computed/absolute/escaping paths, include cycles or symlink
dependencies. Missing replacement lengths and unsupported commands remain errors.
Structural conversion is not a claim of equivalent physics or regression results.''',
}
ELEMENT_HELP = {
    'elegant': '''Elegant elements available for conversion:
  DRIF / DRIFT / EDRIFT -> DRIFT: nonnegative lengths.
  QUAD -> QUADRUPOLE: aligned hard-edge quadrupole, zero active fringes.
  SBEN / SBEND / CSBEND -> SBEND: pure sector bend, zero gap and edge angles;
      no multipole components, radiation or fringe fields.
  RFCA -> RFCAVITY: explicit standing wave, positive N_KICKS and known absolute
      T_REFERENCE; longitudinal kicks, no end focusing or reference retuning.
  MARK -> MARKER: no target tracking field; FITPOINT is metadata.
  CHARGE: one leading fixed TOTAL bunch charge; no target tracking field.
  LINE: earlier-defined nested/repeated lines are expanded in source order.
  Unavailable types (e.g. RBEN, CSRCSBEND, solenoids or higher multipoles) become
      DRIFT when an explicit finite nonnegative L is supplied; all are listed.
  Unsupported settings on the available types above remain errors.
  Space charge stays off (FIELDSOLVER TYPE=NONE). Forward horizontal lines only.''',
    'astra': '''ASTRA elements available for conversion:
  Drift: implicit field-free transport to Zstop; no source element declaration.
  &CAVITY -> RFCAVITY: standing-wave TM on-axis RF profiles; first-order or
      higher-order expansion. Absolute phase or independent target autophasing.
  &SOLENOID -> FIELDMAP: sampled on-axis magnetic profiles, higher-order model.
  &QUADRUPOLE -> FIELDMAP: normal/skew Q_grad/Q_length models or data-profile
      tables, with supported longitudinal roll and sampled physical fields.
  &APERTURE -> COLLIMATOR: circular RAD or supported constant/stepped pipe
      tables; hard particle removal, no scattering model.
  &DIPOLE -> FIELDMAP: restricted static horizontal or vertical D1-D4 geometry,
      physical D_strength and finite edge gaps; single-plane dipole-only lines.
  RF, solenoids, quadrupoles and circular apertures can share a straight line.
  Dipoles cannot be mixed with those active fields/apertures in this adapter.
  Not available: cathode emission, general 3D source maps, first-order solenoids,
      traveling-wave/TE/DC RF, wakefields or arbitrary multipoles.
  ASTRA namelists have no generic element length: unsupported models/groups
      without known drift geometry remain errors. Injected electrons only.
  FIELDSOLVER TYPE=NONE is enforced, independent of source charge settings.
  Independently solved RF crests require review.''',
    'opal': '''OPAL elements available for structural migration:
  DRIFT: drift length and placement.
  QUADRUPOLE: K1 quadrupole strength and placement.
  MULTIPOLE: normalized KN/KS multipoles; check reference rigidity.
  SOLENOID: KS strength and supported map attributes; check units/orientation.
  MULTIPOLET: physical field polynomial and fringe/aperture settings.
  SBEND: sector bend strengths and fringes; review legacy chord vs arc length.
      DESIGNENERGY and unproven/nonzero E1/E2 remain rejected by native SBEND.
  CYCLOTRONSECTOR: map, symmetry and radial settings; review map conventions.
  RFCAVITY: mapped RF and single-gap controls; review phase, voltage and units.
  TRAVELINGWAVE: mapped RF, cell count and mode; review normalization.
  CONSTANTEFIELDCAVITY: local EX/EY/EZ electric fields in MV/m.
  CONSTANTFOCUSING: self-field-scaled focusing; review space-charge assumptions.
  MONITOR: native spatial/temporal diagnostic and output; native length default.
  MARKER: native field-free marker, including dotted element names.
  LINE / RING: retained containers, with supported placement and membership.
  Auxiliary constructs include TRIMCOIL, COF, BEAM, DISTRIBUTION, emission
      sources, FIELDSOLVER, BINNING, TRACK/RUN and recursive literal CALL files.
  Only the recognized subset has verified migration/preservation rules;
      expressions are not evaluated and physics equivalence is not established.
  Types outside the verified converter scope (including BEAMBEAM) become DRIFT
      when a length is provided; unknown types must be LINE/RING members.
  Length and placement expressions are retained without evaluation; original
      field/model attributes are removed and every replacement is reported.
  Legacy SOURCE with only ELEMEDGE uses its documented 0.05 m upstream drift
      interval; particle interception/loss output is omitted and reported.
  Gas stripping (VACUUM) and UNDULATOR remain unsupported without replacement.
  Literal positional CALL is normalized to CALL, FILE=; native IF/ELSE wrappers
      and both branches are preserved without evaluating conditions. Ambiguous
      branch-dependent source attachment remains refused.
  SELECT and PARTICLEMATTERINTERACTION declarations/attributes are obsolete and
      removed before asset discovery and listed in the conversion report.
  DISTRIBUTION TYPE=BINOMIAL becomes GAUSS with an explicit approximation
      warning; binomial shape parameters are removed, other settings retained.
  Unknown commands remain errors; unverified attributes on retained elements
      are preserved and flagged for review. OPAL fieldsolver settings remain.''',
}
OUTPUT_HELP = '''Output: the exact --outfile name, <outfile>.assets/ for maps, particles and
includes, and <outfile>.report.json. All must be new. Run OPALX from the output
directory; keep the deck and its companion folder together when moving them.
A successful conversion returns 0 and can still require physics review.
Normal conversion prints concise output/report paths; the framed list is on stderr.
Use --json for the full terminal JSON. --inspect prints diagnostic JSON without writing.
The saved JSON report includes unavailable_elements.
Unsupported/invalid input returns 2. This tool never runs a simulator.'''


class ConversionFailure(ValueError):
    """A refused candidate, optionally carrying its original engine diagnostics."""

    def __init__(self, message, report=None):
        super().__init__(message)
        self.report = report


class _HelpFormatter(argparse.RawDescriptionHelpFormatter,
                     argparse.ArgumentDefaultsHelpFormatter):
    pass


def load_engine(mode):
    """Load only bundled, hash-checked trusted code in an isolated namespace."""
    if mode not in MODES:
        raise ValueError('Unknown conversion mode: ' + str(mode))
    if mode not in _ENGINE_CACHE:
        source = _ENGINE_SOURCES[mode]
        if hashlib.sha256(source.encode('utf-8')).hexdigest() != _ENGINE_HASHES[mode]:
            raise ValueError('Bundled engine fingerprint mismatch: ' + mode)
        name = '_toOPALX_' + mode + '_' + _ENGINE_HASHES[mode][:12]
        module = types.ModuleType(name)
        module.__file__ = str(Path(__file__).resolve())
        sys.modules[name] = module
        try:
            exec(compile(source, '<bundled ' + mode + ' converter>', 'exec'), module.__dict__)
        except Exception:
            sys.modules.pop(name, None)
            raise
        _ENGINE_CACHE[mode] = module
    return _ENGINE_CACHE[mode]


def build_parser(mode=None, *, more=False):
    """Expose the selected mode's contract and only its applicable controls."""
    if mode is not None and mode not in MODES:
        raise ValueError('Unknown conversion mode: ' + str(mode))
    description = __doc__.strip()
    scope = SCOPES[mode] if mode else '\n'.join(
        ('Modes: elegant, astra, opal.',
         'Use --help --mode elegant (or astra/opal) for expected inputs, supported',
         'physics, limitations and that mode\'s conversion controls.'))
    if more:
        scope += '\n\n' + '\n\n'.join(ELEMENT_HELP[item] for item in ((mode,) if mode else MODES))
    parser = argparse.ArgumentParser(prog='toOPALX.py', description=description,
        epilog=scope + '\n\n' + OUTPUT_HELP, formatter_class=_HelpFormatter)
    parser.add_argument('--version', action='version', version='toOPALX ' + VERSION)
    parser.add_argument('--more', action='store_true', help='With --help, list available elements and their restrictions')
    parser.add_argument('--mode', choices=MODES, required=True, help='Source input format')
    parser.add_argument('--infile', type=Path, required=True, help='Source entry input file')
    parser.add_argument('--outfile', type=Path, help='New OPALX entry file ending in .in')
    parser.add_argument('--inspect', action='store_true', help='Inspect supported source structure; write nothing')
    parser.add_argument('--json', action='store_true', dest='json_output',
                        help='Print the full conversion report as JSON instead of the concise terminal summary')
    if mode == 'elegant':
        parser.add_argument('--charge-c', type=float, dest='charge_C', help='Explicit positive bunch-charge magnitude [C]')
        parser.add_argument('--dt', type=float, default=1e-12, dest='dt_s', help='Target timestep [s]')
        parser.add_argument('--max-steps', type=int, default=100000, help='Target tracking step budget')
        parser.add_argument('--particle-dump-frequency', type=int, default=100000000, dest='dump_frequency', help='Particle-output step interval')
        parser.add_argument('--statistics-frequency', type=int, default=100, dest='stat_frequency', help='Statistics-output step interval')
        parser.add_argument('--source-rest-energy-ev', type=float, default=510999.06, dest='source_rest_energy_eV', help='Audited source electron rest energy [eV]')
    elif mode == 'astra':
        for flag, default, explanation in (
            ('rf-subdivisions', 4, 'RF longitudinal subdivisions'),
            ('map-radius', .05, 'First-order RF radial support [m]'),
            ('fourier-terms', 128, 'RF Fourier terms'),
            ('quad-dz', .00025, 'Maximum quadrupole z grid spacing [m]'),
            ('quad-radius', .05, 'Quadrupole transverse halfwidth [m]'),
            ('dipole-dz', .00025, 'Maximum dipole z grid spacing [m]'),
            ('dipole-dx', .0005, 'Maximum dipole bend-coordinate grid spacing [m]'),
            ('dipole-radius', .05, 'Dipole global x/y halfwidth [m]'),
            ('dipole-reference-ds', .00025, 'Dipole reference arc integration step [m]'),
            ('particle-dump-frequency', 100000000, 'Particle-output step interval')):
            parser.add_argument('--' + flag, type=int if isinstance(default, int) else float,
                                default=default, help=explanation)
        parser.add_argument('--center-launch-frame', action='store_true', help='Explicitly translate launch and RF/solenoid poses to the centroid frame')
    return parser


def inspect(mode, infile, **options):
    """Inspect without writing, preserving each backend's structural assessment."""
    source = Path(infile).expanduser().resolve()
    engine = load_engine(mode)
    if mode == 'elegant':
        backend = engine.inspect_source(source,
            source_rest_energy_eV=options.get('source_rest_energy_eV', engine.SOURCE_REST_EV),
            replace_unavailable=True)
    elif mode == 'astra':
        groups, policy = engine.conversion_groups(
            engine.parse_namelists(source.read_text(encoding='utf-8-sig')),
            force_no_space_charge=True)
        backend = engine.assess(groups)
        backend['fieldsolver_policy'] = policy
    else:
        backend = engine.process(source, replace_unavailable=True)
    return {'tool': 'toOPALX', 'version': VERSION, 'mode': mode,
            'backend_version': _ENGINE_VERSIONS[mode], 'infile': str(source),
            'status': backend['status'], 'physics_validated': False, 'backend_report': backend,
            **_policy_report(mode, backend)}


def _policy_report(mode, backend):
    """Expose removed elements and the mandatory solver policy in every report."""
    policy = backend.get('fieldsolver_policy')
    if policy is None:
        policy = ({'target_type': 'source-defined', 'forced_off': False,
                   'reason': 'OPAL fieldsolver settings are preserved'} if mode == 'opal'
                  else {'target_type': 'NONE', 'forced_off': True,
                        'reason': 'Non-OPAL conversions disable space charge'})
    return {'unavailable_elements': backend.get('unavailable_elements', []),
            'removed_constructs': backend.get('removed_constructs', []),
            'model_approximations': backend.get('model_approximations', []),
            'asset_migrations': backend.get('asset_migrations', []),
            'placement_warnings': [item['reason'] for file in backend.get('files', [])
                                   for item in file.get('changes', [])
                                   if item.get('rule') == 'legacy-cyclotron-sectors'],
            'fieldsolver_policy': policy}


def conversion_summary(report):
    """Frame every drift replacement in a visible, 80-column terminal box."""
    elements = report['unavailable_elements']
    lines = ['Unavailable elements replaced with DRIFT: ' + str(len(elements))]
    for element in elements:
        length = element.get('length_m', element.get('length'))
        source_file = report.get('backend_report', {}).get('lattice_file', report['infile'])
        location = element.get('file', source_file)
        if 'line' in element:
            location += ':' + str(element['line'])
        if 'occurrence' in element:
            location += ', occurrence ' + str(element['occurrence'])
        lines.append('  ' + element['name'] + ' (' + element['source_type']
                     + ') -> DRIFT, L=' + str(length) + ' m [' + location + ']')
        if element.get('length_origin'):
            lines.append('    '+element['reason'])
    if not elements:
        lines.append('  None.')
    removed = report.get('removed_constructs', [])
    if removed:
        lines.append('')
        lines.append('Obsolete constructs removed: '+str(len(removed)))
        for item in removed:
            label = item.get('kind', item.get('rule', 'obsolete construct'))
            if item.get('name'):
                label = item['name']+' ('+label+')'
            if item.get('attribute'):
                label += '.'+item['attribute']
            location = item.get('file', report['infile'])
            if item.get('line'):
                location += ':'+str(item['line'])
            lines.append('  '+label+' ['+location+']')
    approximations = report.get('model_approximations', [])
    if approximations:
        lines.append('')
        lines.append('Model approximations: '+str(len(approximations)))
        for item in approximations:
            location = item.get('file', report['infile'])
            if item.get('line'):
                location += ':'+str(item['line'])
            lines.append('  '+str(item.get('name') or item['kind'])+': '
                         +item['source_type']+' -> '+item['target_type']
                         +' (APPROXIMATION) ['+location+']')
            if item.get('discarded_attributes'):
                lines.append('    Dropped shape parameters: '+', '.join(sorted(item['discarded_attributes'])))
            lines.append('    '+item['reason'])
    if report['mode'] != 'opal':
        lines.append('Fieldsolver: NONE (space charge off).')
    asset_changes = report.get('asset_migrations', [])
    if asset_changes:
        lines.append('')
        lines.append('Particle-file migrations: '+str(len(asset_changes)))
        for item in asset_changes:
            lines.append('  '+item['file']+': inserted '+' '.join(item['columns'])+' header')
            lines.append('    '+item['reason'])
    for warning in report.get('placement_warnings', []):
        lines.extend(['', warning])
    framed = ['*' * 80]
    for line in lines:
        for row in textwrap.wrap(line, width=76, subsequent_indent='    ',
                                 break_on_hyphens=False) or ['']:
            framed.append('* ' + row.ljust(76) + ' *')
    framed.append('*' * 80)
    return '\n'.join(framed)


def relocate(text, asset_prefix, known_files):
    """Edit literal OPAL dependency value spans; all paths use the entry cwd."""
    if (not isinstance(asset_prefix, str) or not asset_prefix or asset_prefix in ('.', '..')
            or any(c in asset_prefix for c in '/\\\"\'\r\n\x00')):
        raise ValueError('Asset prefix must be one portable relative directory name')
    engine = load_engine('opal')
    edits, changes = [], []
    for tokens in engine.statements(text):
        statement = engine.describe(tokens, text)
        for key, attribute in statement['attrs'].items():
            if key not in ('FNAME', 'FMAPFN') and not (key == 'FILE' and statement['kind'] == 'CALL'):
                continue
            value = attribute['value']
            if engine.is_builtin_map(key, value):
                continue
            if len(value) < 2 or value[0] not in ('"', "'") or value[-1] != value[0]:
                raise ValueError('Computed dependency cannot be relocated: ' + value)
            name = value[1:-1]
            normalized = posixpath.normpath(name)
            if (not name or '\\' in name or any(c in name for c in '\r\n\x00')
                    or PurePosixPath(name).is_absolute() or normalized in ('.', '..')
                    or normalized.startswith('../') or normalized not in known_files):
                raise ValueError('Unsafe or missing dependency: ' + name)
            replacement = asset_prefix + '/' + normalized
            edits.append((attribute['value_start'], attribute['value_end'],
                          value[0] + replacement + value[0]))
            changes.append({'attribute': key, 'from': name, 'to': replacement})
    for start, end, value in sorted(edits, reverse=True):
        text = text[:start] + value + text[end:]
    return text, changes


def _workspace(source, output_parent):
    """Choose an owned temporary directory outside the source case tree."""
    candidates = (Path(tempfile.gettempdir()), Path(__file__).resolve().parent,
                  Path.cwd(), output_parent)
    for candidate in candidates:
        candidate = candidate.resolve()
        if candidate.is_relative_to(source.parent):
            continue
        try:
            return tempfile.TemporaryDirectory(prefix='.toOPALX-', dir=candidate)
        except OSError:
            continue
    raise ValueError('No writable staging directory outside the source case; use a dedicated input case directory')


def _fingerprint(path):
    """Hash generated assets without loading binary field maps into memory."""
    digest = hashlib.sha256()
    with path.open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            digest.update(block)
    return digest.hexdigest()


def convert(mode, infile, outfile, **options):
    """Stage unchanged engine output, relocate dependencies and publish new files.

    The exact entry filename is created last, exclusively. Rollback removes
    only paths created by this invocation, including failures during writes.
    No existing destination is overwritten and no source file is modified.
    """
    engine = load_engine(mode)
    source = Path(infile).expanduser().resolve()
    requested = Path(outfile).expanduser().absolute()
    if requested.suffix.lower() != '.in' or any(c in requested.name for c in '\\"\'\r\n\x00'):
        raise ValueError('--outfile must be a portable filename ending in .in')
    parent = requested.parent.resolve()
    if not parent.is_dir():
        raise ValueError('Output parent directory must already exist')
    destination = parent / requested.name
    assets = parent / (destination.name + '.assets')
    report_path = parent / (destination.name + '.report.json')
    for path in (destination, assets, report_path):
        if path.exists() or path.is_symlink():
            raise FileExistsError('Output already exists: ' + str(path))
    with _workspace(source, parent) as work:
        bundle = Path(work) / 'candidate'
        if mode == 'opal':
            if options:
                raise ValueError('OPAL mode has no additional conversion controls')
            backend = engine.process(source, bundle, replace_unavailable=True)
            entry = bundle / source.name
        else:
            if {'force_no_space_charge', 'replace_unavailable'} & options.keys():
                raise ValueError('Element replacement and inactive fieldsolver policies are fixed by --mode')
            if mode == 'astra':
                backend = engine.convert(source, bundle, force_no_space_charge=True, **options)
            else:
                backend = engine.convert(source, bundle, replace_unavailable=True, **options)
            entry = bundle / 'converted.in'
        if backend.get('status') == 'unsupported':
            raise ConversionFailure('Unsupported input; no output published. Use --inspect for diagnostics.', backend)
        files, problems = load_engine('opal').collect(entry)
        if problems:
            raise ConversionFailure('Generated dependency bundle cannot be relocated: ' + '; '.join(problems), backend)
        known = {path.relative_to(bundle).as_posix() for path in files}
        rewritten, relocations = {}, []
        for path, parsed in files.items():
            if parsed:
                text, changes = relocate(path.read_text(encoding='utf-8'), assets.name, known)
                rewritten[path] = text.encode('utf-8')
                relocations.extend({'file': path.relative_to(bundle).as_posix(), **change} for change in changes)
        report = {'tool': 'toOPALX', 'version': VERSION, 'mode': mode,
                  'backend_version': _ENGINE_VERSIONS[mode], 'backend_source_sha256': _ENGINE_HASHES[mode],
                  'infile': str(source), 'outfile': str(destination), 'assets_directory': str(assets),
                  'report_file': str(report_path), 'status': backend['status'],
                  'physics_validated': False, 'backend_report': backend,
                  'working_directory': str(parent), 'relocations': relocations,
                  'entry_mapping': {'backend': entry.relative_to(bundle).as_posix(), 'published': destination.name},
                  'output_sha256': {}, **_policy_report(mode, backend)}
        owned_assets = owned_report = owned_entry = False
        try:
            assets.mkdir()
            owned_assets = True
            for path in sorted(bundle.rglob('*')):
                if path.is_dir() or path == entry:
                    continue
                if path.is_symlink() or not path.is_file():
                    raise ValueError('Generated output must contain ordinary files')
                target = assets / path.relative_to(bundle)
                target.parent.mkdir(parents=True, exist_ok=True)
                if path in rewritten:
                    with target.open('xb') as stream:
                        stream.write(rewritten[path])
                else:
                    with path.open('rb') as src, target.open('xb') as dst:
                        shutil.copyfileobj(src, dst)
                report['output_sha256'][str(target)] = _fingerprint(target)
            entry_bytes = rewritten[entry]
            report['output_sha256'][str(destination)] = hashlib.sha256(entry_bytes).hexdigest()
            with report_path.open('x', encoding='utf-8') as stream:
                owned_report = True
                json.dump(report, stream, indent=2, allow_nan=False)
                stream.write('\n')
            with destination.open('xb') as stream:
                owned_entry = True
                stream.write(entry_bytes)
        except Exception:
            if owned_entry:
                destination.unlink()
            if owned_report:
                report_path.unlink()
            if owned_assets:
                shutil.rmtree(assets)
            raise
    return report


def failure_summary(report):
    """Keep blocking causes visible without dumping a structured report."""
    blockers = []
    for message in report.get('dependency_problems', []):
        blockers.append(('', str(message)))
    for issue in report.get('issues', []):
        if isinstance(issue, str):
            blockers.append(('', issue))
        elif isinstance(issue, dict) and issue.get('severity', 'unsupported') == 'unsupported':
            blockers.append(('', str(issue.get('message', issue.get('code', 'Unsupported input')))))
    for file in report.get('files', []):
        for issue in file.get('issues', []):
            default = 'unsupported' if file.get('status') == 'unsupported' else 'review'
            if issue.get('severity', default) != 'unsupported':
                continue
            location = str(file.get('file', ''))
            if issue.get('line'):
                location += ':'+str(issue['line'])
            blockers.append((location, str(issue.get('message', issue.get('code', 'Unsupported input')))))
    grouped = {}
    for location, message in blockers:
        if message in grouped:
            grouped[message][1] += 1
        else:
            grouped[message] = [location, 1]
    lines = []
    for message, (location, count) in grouped.items():
        text = '  '+(location+': ' if location else '')+message
        if count > 1:
            text += ' ('+str(count)+' occurrences; first location shown)'
        lines.append(text)
    return '\n'.join(lines)


def main(argv=None):
    """Parse mode before help, then inspect or convert without running a tracker."""
    arguments = list(sys.argv[1:] if argv is None else argv)
    preliminary = argparse.ArgumentParser(add_help=False)
    preliminary.add_argument('--mode', choices=MODES)
    preliminary.add_argument('--more', action='store_true')
    selected, _ = preliminary.parse_known_args(arguments)
    parser = build_parser(selected.mode, more=selected.more)
    args = parser.parse_args(arguments)
    if args.more:
        parser.error('--more is only available with --help')
    if not args.inspect and args.outfile is None:
        parser.error('--outfile is required for conversion')
    if args.inspect and args.outfile is not None:
        parser.error('--inspect writes nothing; omit --outfile')
    options = {key: value for key, value in vars(args).items()
               if key not in ('mode', 'infile', 'outfile', 'inspect', 'more', 'json_output')}
    try:
        report = (inspect(args.mode, args.infile, **options) if args.inspect else
                  convert(args.mode, args.infile, args.outfile, **options))
        if args.json_output or args.inspect:
            print(json.dumps(report, indent=2, allow_nan=False), flush=True)
        else:
            print('Converted ('+report['status']+'): '+report['outfile']+'\n'
                  +'Report: '+report['report_file'], flush=True)
        if not args.inspect:
            print(conversion_summary(report), file=sys.stderr)
        else:
            for warning in report.get('placement_warnings', []):
                print(warning, file=sys.stderr)
        return 2 if report['status'] == 'unsupported' else 0
    except (OSError, UnicodeError, ValueError) as exc:
        print('toOPALX: ' + str(exc), file=sys.stderr)
        if isinstance(exc, ConversionFailure) and exc.report is not None:
            if args.json_output:
                print(json.dumps(exc.report, indent=2, allow_nan=False), file=sys.stderr)
            else:
                summary = failure_summary(exc.report)
                if summary:
                    print(summary, file=sys.stderr)
        return 2


# Exact trusted sources; never substitute input-file contents here.
_ENGINE_SOURCES = {
    'opal': (
        '#!/usr/bin/env python3\n'
        '"""Standalone, conservative OPAL input migration. Python 3.9+, standard library only.\n'
        '\n'
        'Conversion success means supported structural translation, not physics validation.\n'
        'See USER_GUIDE.md for scope and limitations. No input expression is executed.\n'
        '"""\n'
        'import argparse\n'
        'from collections import Counter\n'
        'import difflib\n'
        'import hashlib\n'
        'import json\n'
        'import math\n'
        'from pathlib import Path\n'
        'import re\n'
        'import shutil\n'
        'import subprocess\n'
        'import sys\n'
        '\n'
        "VERSION = '0.11.1'\n"
        "RULESET = 'opal-t-conservative-13'\n"
        '# This is deliberately a small, explicit compatibility subset, not a target schema.\n'
        'SCHEMA = {\n'
        "    'DRIFT': 'L ELEMEDGE',\n"
        "    'QUADRUPOLE': 'L ELEMEDGE K1',\n"
        "    'BEAM': 'PARTICLE MASS CHARGE PC ENERGY GAMMA NALLOC BCHARGE SOURCES',\n"
        "    'DISTRIBUTION': 'TYPE FNAME NPARTDIST SIGMAX SIGMAY SIGMAZ SIGMAPX SIGMAPY SIGMAPZ',\n"
        "    'EMISSIONSOURCE': 'DISTRIBUTION',\n"
        "    'FIELDSOLVER': 'TYPE NX NY NZ PARFFTX PARFFTY PARFFTZ BCFFTX BCFFTY BCFFTZ BBOXINCR GREENSF',\n"
        "    'TRACK': 'LINE BEAM MAXSTEPS DT ZSTOP',\n"
        "    'RUN': 'METHOD BEAM FIELDSOLVER DISTRIBUTION',\n"
        "    'OPTION': 'VERSION PSDUMPFREQ STATDUMPFREQ BOUNDPDESTROY AUTOPHASE',\n"
        "    'TITLE': 'STRING', 'CALL': 'FILE',\n"
        '}\n'
        '# Attribute spellings checked against src/Elements/Opal*.cpp and BinningCmd.cpp.\n'
        '# Recognition preserves expressions and units; it does not establish equivalence.\n'
        "ELEMENT_KINDS = {'DRIFT', 'QUADRUPOLE', 'MULTIPOLE', 'SOLENOID', 'MULTIPOLET',\n"
        "                 'SBEND', 'CYCLOTRONSECTOR', 'RFCAVITY', 'TRAVELINGWAVE',\n"
        "                 'CONSTANTEFIELDCAVITY', 'CONSTANTFOCUSING', 'MONITOR', 'MARKER'}\n"
        "PLACEMENT = 'APERTURE X Y Z THETA PHI PSI'\n"
        'SCHEMA.update({\n'
        "    'MULTIPOLE': 'KN DKN KS DKS',\n"
        "    'SOLENOID': 'KS DKS FMAPFN FAST ZREVERSE',\n"
        "    'MULTIPOLET': 'TP LFRINGE RFRINGE HAPERT VAPERT MAXFORDER ROTATION EANGLE BBLENGTH ANGLE MAXXORDER VARRADIUS ENTRYOFFSET SCALING_MODEL',\n"
        "    'SBEND': 'ANGLE K0 K0S K1 K1S K2 K2S K3 K3S E1 E2 HGAP GAP FINT HAPERT DESIGNENERGY GREATERTHANPI',\n"
        "    'CYCLOTRONSECTOR': 'FMAPFN SYM RMIN RMAX VMIN VMAX BSCALE TRIMCOIL',\n"
        "    'RFCAVITY': 'VOLT DVOLT FREQ LAG DLAG FMAPFN FAST APVETO TYPE',\n"
        "    'BINNING': 'MAXBINS DESIREDWIDTH BINNINGALPHA BINNINGBETA PARAMETER ADAPTIVEBINNING DUMPBINSFILE DUMPBINSFREQ TABLEPRINTFREQ',\n"
        "    'LINE': 'TYPE ORIGIN ORIENTATION X Y Z THETA PHI PSI',\n"
        "    'RING': 'TYPE ORIGIN ORIENTATION X Y Z THETA PHI PSI',\n"
        "    'TRAVELINGWAVE': 'VOLT DVOLT FREQ LAG DLAG FMAPFN FAST APVETO NUMCELLS DESIGNENERGY MODE',\n"
        "    'TRIMCOIL': 'TYPE RMIN RMAX BMAX SLPTC',\n"
        "    'CONSTANTEFIELDCAVITY': 'EX EY EZ',\n"
        "    'CONSTANTFOCUSING': 'STRENGTH RADIUS',\n"
        "    'MONITOR': 'TYPE OUTFN',\n"
        "    'MARKER': '',\n"
        "    'COF': 'LINE BEAM DT MAXSTEPS T0 TIMEINTEGRATOR MAXPATH SECTION GEOMTOL ANGLETOL METHOD DIMENSION X PX Y PY MAXIT XTOL PTOL FDSTEP SCALES DAMPING JACOBIAN OUTPUT',\n"
        '})\n'
        'for _kind in ELEMENT_KINDS:\n'
        "    SCHEMA[_kind] += ' L ELEMEDGE ' + PLACEMENT\n"
        "SCHEMA['FIELDSOLVER'] += ' BINS'\n"
        "SCHEMA['OPTION'] += ' STEPINFOFQ'\n"
        "SCHEMA['EMISSIONSOURCE'] += ' R0X R0Y R0Z P0X P0Y P0Z T0'\n"
        "SCHEMA['TRACK'] += ' INITIALORBIT'\n"
        "DIST_EMISSION = {'EMITTED', 'EMISSIONSTEPS', 'SIGMAT', 'TRISE', 'TFALL',\n"
        "                 'TPULSEFWHM', 'FTOSCAMPLITUDE', 'FTOSCPERIODS'}\n"
        "DIST_SHAPE = {'CUTOFFX', 'CUTOFFY', 'CUTOFFLONG', 'CUTOFFPX', 'CUTOFFPY',\n"
        "              'CUTOFFPZ', 'CORR', 'CORRX', 'CORRY', 'CORRZ', 'CORRT'}\n"
        "SOURCE_THERMAL = {'EMISSIONMODEL', 'EKIN'}\n"
        "SOURCE_BOUNDARY = {'ZEROFACE_R0Z', 'SHIFTED_GREENS_FUNCTION',\n"
        "                   'ZEROFACE_MAXSTEPS', 'ZEROFACEPLANEDUMP'}\n"
        "RF_SINGLEGAP = {'RMIN', 'RMAX', 'GAPWIDTH', 'PHI0', 'ANGLE', 'PDIS'}\n"
        "RF_MODELS = {'PHASE_MODEL', 'AMPLITUDE_MODEL', 'FREQUENCY_MODEL'}\n"
        "SCHEMA['DISTRIBUTION'] += ' ' + ' '.join(sorted(DIST_EMISSION | DIST_SHAPE))\n"
        "SCHEMA['EMISSIONSOURCE'] += ' ' + ' '.join(sorted(SOURCE_THERMAL | SOURCE_BOUNDARY))\n"
        "SCHEMA['RFCAVITY'] += ' ' + ' '.join(sorted(RF_SINGLEGAP | RF_MODELS))\n"
        "SCHEMA['TRACK'] += ' BEAMS SOURCES ZSTART T0'\n"
        "SCHEMA['OPTION'] += ' REPARTFREQ ENABLELINEARTRANSFERMAPS ASCIIDUMP EBDUMP ECHO INFO SEED'\n"
        "SCHEMA['RUN'] += ' TURNS SCFIELDUPDATE'\n"
        "SCHEMA['FIELDSOLVER'] += ' RCUT'\n"
        "SCHEMA['BEAM'] += ' POLARIZATION'\n"
        "SCHEMA['TRACK'] += ' EKINSTOP'\n"
        'PRESERVE_RULES = {\n'
        "    'MULTIPOLE': ('multipole-preserve', 'Check KN/KS normalized strengths and reference rigidity; no rescaling applied'),\n"
        "    'SOLENOID': ('solenoid-preserve', 'Check normalized KS, field-map units/orientation and FAST behavior'),\n"
        "    'MULTIPOLET': ('multipolet-preserve', 'TP is a physical field polynomial [T/m^k], not normalized KN; check fringe/aperture conventions'),\n"
        "    'SBEND': ('sbend-preserve', 'OPALX L is arc length; legacy OPAL may use chord length. Check length, angle, strengths and fringe model'),\n"
        "    'CYCLOTRONSECTOR': ('cyclotronsector-preserve', 'Check PSI map units, symmetry, radial limits, placement and trim coils; legacy RING expansion is a separate guarded rule'),\n"
        "    'RFCAVITY': ('rfcavity-preserve', 'Check VOLT [MV], FREQ [MHz], LAG [rad], map units and autophasing'),\n"
        "    'BINNING': ('binning-preserve', 'Check bin parameter, adaptive settings and self-field frame; no binning algorithm conversion'),\n"
        "    'RING': ('ring-preserve', 'Check ordered ring placement and launch conventions; members are not flattened'),\n"
        "    'TRAVELINGWAVE': ('travelingwave-preserve', 'Check VOLT/DVOLT [MV/m], FREQ [MHz], LAG [rad], cell count, MODE and map normalization'),\n"
        "    'TRIMCOIL': ('trimcoil-preserve', 'Check PSI-BFIELD-MIRRORED model, radii [m], BMAX [T], SLPTC [1/m] and field-map pairing'),\n"
        "    'COF': ('cof-preserve', 'Check static magnetic RING, explicit reference energy, solver tolerances and orbit-local TRACK handover; no orbit solve performed'),\n"
        "    'CONSTANTEFIELDCAVITY': ('constantfield-preserve', 'EX/EY/EZ are local electric fields [MV/m]; check sign, frame and energy gain'),\n"
        "    'CONSTANTFOCUSING': ('constantfocusing-preserve', 'Check dimensionless STRENGTH scaled by initial mean self field, RADIUS [m] and active space-charge assumptions'),\n"
        "    'MONITOR': ('monitor-preserve', 'Native MONITOR retained, including diagnostic output and native minimum length of 0.01 m; verify collection type and output naming'),\n"
        "    'MARKER': ('marker-preserve', 'Native field-free MARKER retained; no drift length or diagnostic is substituted'),\n"
        '}\n'
        "UNAVAILABLE = {'BEAMBEAM': 'BEAMBEAM is outside the verified converter scope; no interaction model is substituted'}\n"
        'REFUSED = {\n'
        "    'VACUUM': 'Gas stripping via VACUUM is unsupported in OPALX; no drift replacement is permitted',\n"
        "    'UNDULATOR': 'UNDULATOR is unsupported in OPALX; no drift replacement is permitted',\n"
        '}\n'
        'TOKEN = re.compile(r\'\\s+|//[^\\n]*|/\\*[\\s\\S]*?\\*/|"(?:\\\\.|[^"\\\\])*"|\'\n'
        '                   r"\'(?:\\\\.|[^\'\\\\])*\'|[A-Za-z_][A-Za-z_0-9.]*|"\n'
        "                   r'(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eEdD][+-]?\\d+)?|:=|.', re.DOTALL)\n"
        "IDENT = re.compile(r'[A-Za-z_][A-Za-z_0-9.]*\\Z')\n"
        '\n'
        '\n'
        'class InputError(ValueError):\n'
        '    """An input cannot be safely interpreted by this converter."""\n'
        '\n'
        '\n'
        'def tokenize(text):\n'
        '    """Return (spelling, start, end) tokens without losing source locations."""\n'
        '    result = []\n'
        '    for m in TOKEN.finditer(text):\n'
        '        value = m.group()\n'
        "        if value.isspace() or value.startswith('//') or value.startswith('/*'):\n"
        '            continue\n'
        '        if value in (\'"\', "\'") or text[m.start():].startswith(\'/*\'):\n'
        "            raise InputError('Unterminated string or block comment')\n"
        '        result.append((value, m.start(), m.end()))\n'
        '    return result\n'
        '\n'
        '\n'
        'def scan_statements(tokens, error_type=ValueError):\n'
        '    """Return ``(leaves, controls)`` from ``(spelling, start, end)`` tokens.\n'
        '\n'
        '    ``leaves`` has the same shape as a flat simple-statement scanner. Each IF\n'
        '    record in ``controls`` contains original character spans and half-open leaf\n'
        '    ranges for its then/else branches; its integer ``id`` indexes that list.\n'
        '    ``parents`` lists the enclosing ``(control_id, branch)`` pairs. An absent\n'
        '    else branch has ``else_leaf_range=None``. These ranges include nested leaves\n'
        '    and can be used to guard branch-sensitive symbol resolution. No source text\n'
        '    or token is modified. A malformed control or an unsupported loop/macro fails\n'
        '    closed through ``error_type``.\n'
        '    """\n'
        '    tokens = list(tokens)\n'
        '    leaves, controls = [], []\n'
        '    cursor = 0\n'
        "    pairs = {')': '(', '}': '{', ']': '['}\n"
        '\n'
        '    def fail(message):\n'
        '        raise error_type(message)\n'
        '\n'
        '    def word(index):\n'
        '        return tokens[index][0].upper() if index < len(tokens) else None\n'
        '\n'
        '    def condition():\n'
        '        nonlocal cursor\n'
        "        if word(cursor) != '(':\n"
        "            fail('IF requires a parenthesized condition')\n"
        '        opening = tokens[cursor]\n'
        '        cursor += 1\n'
        '        start = cursor\n'
        "        stack = ['(']\n"
        '        while cursor < len(tokens):\n'
        '            token = tokens[cursor]\n'
        '            value = token[0]\n'
        "            if value == ';':\n"
        "                fail('Semicolon in IF condition')\n"
        "            if value in ('(', '{', '['):\n"
        '                stack.append(value)\n'
        '            elif value in pairs:\n'
        '                if not stack or stack.pop() != pairs[value]:\n'
        "                    fail('Unbalanced delimiters in IF condition')\n"
        '                if not stack:\n'
        '                    if cursor == start:\n'
        "                        fail('Empty IF condition')\n"
        '                    cursor += 1\n'
        '                    return opening[2], token[1]\n'
        '            cursor += 1\n'
        "        fail('Unterminated IF condition')\n"
        '\n'
        '    def body(parents):\n'
        '        if cursor >= len(tokens):\n'
        "            fail('IF/ELSE requires a statement or braced body')\n"
        "        if word(cursor) in (';', '}', 'ELSE'):\n"
        "            fail('IF/ELSE requires a statement or braced body')\n"
        '        return statement(parents)\n'
        '\n'
        '    def statement(parents):\n'
        '        nonlocal cursor\n'
        '        if cursor >= len(tokens):\n'
        "            fail('Unterminated statement')\n"
        '        start = tokens[cursor][1]\n'
        '        kind = word(cursor)\n'
        "        if kind == 'IF':\n"
        '            cursor += 1\n'
        '            condition_start, condition_end = condition()\n'
        '            control_id = len(controls)\n'
        "            record = {'kind': 'IF', 'id': control_id, 'start': start,\n"
        "                      'condition_start': condition_start, 'condition_end': condition_end,\n"
        "                      'parents': list(parents), 'else_start': None, 'else_end': None,\n"
        "                      'else_leaf_range': None}\n"
        '            controls.append(record)\n'
        '            first = len(leaves)\n'
        "            record['then_start'], record['then_end'] = body(parents + ((control_id, 'then'),))\n"
        "            record['then_leaf_range'] = [first, len(leaves)]\n"
        "            if word(cursor) == 'ELSE':\n"
        "                record['else_keyword_start'] = tokens[cursor][1]\n"
        '                cursor += 1\n'
        '                first = len(leaves)\n'
        "                record['else_start'], record['else_end'] = body(parents + ((control_id, 'else'),))\n"
        "                record['else_leaf_range'] = [first, len(leaves)]\n"
        "            record['end'] = record['else_end'] if record['else_end'] is not None else record['then_end']\n"
        "            return start, record['end']\n"
        "        if kind == '{':\n"
        '            cursor += 1\n'
        '            sequence(parents, compound=True)\n'
        '            end = tokens[cursor][2]\n'
        '            cursor += 1\n'
        '            return start, end\n'
        "        if kind == 'ELSE':\n"
        "            fail('Dangling ELSE without IF')\n"
        "        if kind in ('WHILE', 'FOR', 'DO'):\n"
        "            fail('Unsupported control syntax: ' + kind)\n"
        "        if kind in ('}', ')', ']'):\n"
        "            fail('Unexpected closing delimiter')\n"
        "        if cursor + 1 < len(tokens) and tokens[cursor + 1][0] == '(':\n"
        "            fail('Unsupported macro/control syntax: ' + tokens[cursor][0])\n"
        '\n'
        '        first = cursor\n'
        '        stack = []\n'
        '        while cursor < len(tokens):\n'
        '            token = tokens[cursor]\n'
        '            value = token[0]\n'
        "            if value.upper() == 'ELSE' and not stack:\n"
        "                fail('ELSE encountered before statement terminator')\n"
        "            if value == ':' and not stack and cursor != first + 1:\n"
        "                fail('Unexpected declaration before statement terminator')\n"
        "            if value in ('(', '{', '['):\n"
        '                stack.append(value)\n'
        '            elif value in pairs:\n'
        '                if not stack or stack.pop() != pairs[value]:\n'
        "                    fail('Unbalanced delimiters')\n"
        '            cursor += 1\n'
        "            if value == ';' and not stack:\n"
        '                leaves.append(tokens[first:cursor])\n'
        '                return start, token[2]\n'
        "        fail('Unterminated statement or unsupported compound syntax')\n"
        '\n'
        '    def sequence(parents, compound=False):\n'
        '        nonlocal cursor\n'
        '        while cursor < len(tokens):\n'
        '            kind = word(cursor)\n'
        "            if kind == '}':\n"
        '                if compound:\n'
        '                    return\n'
        "                fail('Unexpected closing delimiter')\n"
        "            if kind == ';':\n"
        '                cursor += 1\n'
        '                continue\n'
        '            statement(parents)\n'
        '        if compound:\n'
        "            fail('Unterminated braced body')\n"
        '\n'
        '    try:\n'
        '        sequence(())\n'
        '    except RecursionError:\n'
        "        fail('Control nesting is too deep')\n"
        '    return leaves, controls\n'
        '\n'
        '\n'
        'def branch_paths(leaf_count, controls):\n'
        '    """Return each leaf\'s enclosing IF branches, outermost first.\n'
        '\n'
        '    Opposite branches of the same IF are mutually exclusive. This says nothing\n'
        '    about the values of conditions, later redefinitions, or missing symbols.\n'
        '    """\n'
        '    result = [[] for _ in range(leaf_count)]\n'
        '    for control in controls:\n'
        "        for branch in ('then', 'else'):\n"
        "            bounds = control[branch + '_leaf_range']\n"
        '            if bounds is not None:\n'
        '                for index in range(*bounds):\n'
        "                    result[index].append((control['id'], branch))\n"
        '    return result\n'
        '\n'
        '\n'
        'def statements(text):\n'
        '    """Expose simple leaves of native IF/ELSE without evaluating conditions."""\n'
        '    return scan_statements(tokenize(text), InputError)[0]\n'
        '\n'
        '\n'
        '\n'
        'def normalize_legacy_syntax(text, split_statements=None):\n'
        '    """Make the FILE keyword explicit in an exact positional CALL statement.\n'
        '\n'
        '    Only ``CALL, "literal";`` and the equivalent single-quoted form qualify.\n'
        '    Ambiguous, extended, named or expression forms are left for the normal\n'
        '    parser to diagnose. The original literal and all existing source bytes are\n'
        '    retained. Record offsets refer to ``text``; inserted text contains no\n'
        '    newline, so source line numbers are unchanged.\n'
        '    """\n'
        '    split_statements = split_statements or statements\n'
        '    insertions, records = [], []\n'
        '    for tokens in split_statements(text):\n'
        '        if len(tokens) != 4:\n'
        '            continue\n'
        '        command, comma, literal, terminator = tokens\n'
        '        value = literal[0]\n'
        "        if (command[0].upper() != 'CALL' or comma[0] != ','\n"
        "                or terminator[0] != ';' or len(value) < 2\n"
        '                or value[0] not in (\'"\', "\'") or value[-1] != value[0]\n'
        "                or '\\r' in value or '\\n' in value):\n"
        '            continue\n'
        '        insertions.append(literal[1])\n'
        '        records.append({\n'
        "            'rule': 'legacy-call-file-keyword', 'kind': 'CALL', 'name': None,\n"
        "            'line': text.count('\\n', 0, command[1])+1,\n"
        "            'value': value, 'start': literal[1], 'end': literal[2],\n"
        "            'reason': 'Made FILE explicit in the legacy positional CALL command; the file literal is unchanged',\n"
        '        })\n'
        '    candidate = text\n'
        '    for offset in sorted(insertions, reverse=True):\n'
        "        candidate = candidate[:offset]+'FILE='+candidate[offset:]\n"
        '    return candidate, records\n'
        '\n'
        '\n'
        'def describe(ts, text):\n'
        '    """Extract a command and top-level attributes; retain spans for local edits."""\n'
        "    named = len(ts) > 2 and ts[1][0] == ':'\n"
        '    i = 2 if named else 0\n'
        '    kind = ts[i][0].upper()\n'
        '    name = ts[0][0] if named else None\n'
        "    if len(ts) > 1 and ts[1][0] in ('=', ':='):\n"
        "        return {'kind': 'SCALAR_ASSIGNMENT', 'name': None, 'attrs': {}, 'tokens': ts}\n"
        "    if kind == 'VALUE':\n"
        "        return {'kind': kind, 'name': name, 'attrs': {}, 'tokens': ts}\n"
        '    attrs, depth, start = {}, 0, None\n'
        '    for j in range(i + 1, len(ts)):\n'
        '        v = ts[j][0]\n'
        "        if v in ('(', '{', '['):\n"
        '            depth += 1\n'
        "        elif v in (')', '}', ']'):\n"
        '            depth -= 1\n'
        "        if v == ',' and depth == 0:\n"
        '            if start is not None:\n'
        '                add_attr(attrs, ts, start, j, text)\n'
        '            start = j\n'
        "        elif v == ';' and depth == 0 and start is not None:\n"
        '            add_attr(attrs, ts, start, j, text)\n'
        "    return {'kind': kind, 'name': name, 'attrs': attrs, 'tokens': ts}\n"
        '\n'
        '\n'
        'def add_attr(attrs, ts, start, end, text):\n'
        '    """Record an attribute and its preceding comma for safe removal."""\n'
        '    part = ts[start + 1:end]\n'
        "    if len(part) < 3 or part[1][0] != '=' or not IDENT.fullmatch(part[0][0]):\n"
        "        raise InputError('Unsupported attribute syntax')\n"
        '    key = part[0][0].upper()\n'
        '    if key in attrs:\n'
        "        raise InputError('Duplicate attribute: ' + key)\n"
        "    attrs[key] = {'value': text[part[2][1]:part[-1][2]],\n"
        "                  'start': ts[start][1], 'end': ts[end][1],\n"
        "                  'value_start': part[2][1], 'value_end': part[-1][2],\n"
        "                  'key_start': part[0][1], 'key_end': part[0][2]}\n"
        '\n'
        '\n'
        'def remove_obsolete(text):\n'
        '    """Remove retired SELECT and particle-matter syntax with token-span edits.\n'
        '\n'
        '    Tokens are replaced by spaces, preserving comments, newlines and all source\n'
        '    offsets. Obsolete declarations do not need valid migration attributes, but\n'
        '    their statement delimiters must still be balanced. Particle-matter\n'
        '    attachments are removed along with their declarations, never evaluated.\n'
        '    """\n'
        '    edits, removed, empty_bodies = [], [], []\n'
        '    leaves, controls = scan_statements(tokenize(text), InputError)\n'
        "    direct_bodies = {(c[branch+'_start'], c[branch+'_end']) for c in controls\n"
        "                     for branch in ('then', 'else') if c[branch+'_start'] is not None}\n"
        '    for tokens in leaves:\n'
        "        named = len(tokens) > 2 and tokens[1][0] == ':'\n"
        "        if not named and len(tokens) > 1 and tokens[1][0] in ('=', ':='):\n"
        '            # Reserved-looking scalar identifiers are assignments, not retired\n'
        '            # commands. Keep expressions and delayed-assignment diagnostics.\n'
        '            continue\n'
        '        kind = tokens[2 if named else 0][0].upper()\n'
        '        name = tokens[0][0] if named else None\n'
        "        if kind in ('SELECT', 'PARTICLEMATTERINTERACTION'):\n"
        "            rule = ('obsolete-select-remove' if kind == 'SELECT'\n"
        "                    else 'obsolete-particlematter-remove')\n"
        "            reason = ('Removed obsolete SELECT command; explicit TRACK.LINE is retained'\n"
        "                      if kind == 'SELECT' else\n"
        "                      'Removed retired particle-matter declaration; its interaction physics is omitted')\n"
        "            removed.append({'rule': rule, 'kind': kind, 'name': name,\n"
        "                            'line': text.count('\\n', 0, tokens[0][1])+1, 'reason': reason})\n"
        '            edits.extend((start, end) for _, start, end in tokens)\n'
        '            span = (tokens[0][1], tokens[-1][2])\n'
        '            if span in direct_bodies:\n'
        '                empty_bodies.append(span)\n'
        '            continue\n'
        '        declaration = describe(tokens, text)\n'
        "        attribute = declaration['attrs'].get('PARTICLEMATTERINTERACTION')\n"
        '        if attribute is not None:\n'
        "            removed.append({'rule': 'obsolete-particlematter-attachment-remove',\n"
        "                            'kind': kind, 'name': name, 'attribute': 'PARTICLEMATTERINTERACTION',\n"
        "                            'value': attribute['value'],\n"
        "                            'line': text.count('\\n', 0, attribute['key_start'])+1,\n"
        "                            'reason': 'Removed retired particle-matter attachment; no interaction is substituted'})\n"
        '            edits.extend((start, end) for _, start, end in tokens\n'
        "                         if start >= attribute['start'] and end <= attribute['end'])\n"
        '    candidate = text\n'
        '    for start, end in sorted(edits, reverse=True):\n'
        "        blank = ''.join(char if char in '\\r\\n' else ' ' for char in candidate[start:end])\n"
        '        candidate = candidate[:start] + blank + candidate[end:]\n'
        '    for start, end in empty_bodies:\n'
        '        # Keep a single-statement branch from capturing the following command\n'
        '        # or leaving a dangling ELSE after its obsolete body is removed.\n'
        "        candidate = candidate[:start]+'{'+candidate[start+1:end-1]+'}'+candidate[end:]\n"
        '    return candidate, removed\n'
        '\n'
        '\n'
        'def approximate_binomial(text):\n'
        '    """Replace a literal BINOMIAL distribution with the authorized GAUSS model.\n'
        '\n'
        '    The legacy shape exponents MX/MY/MT do not belong to GAUSS and are removed.\n'
        '    Widths, correlations, counts, emission controls and other expressions are\n'
        '    left unchanged without evaluation or moment matching. Space padding keeps\n'
        '    source offsets and embedded newlines intact for later migration diagnostics.\n'
        '    """\n'
        '    edits, approximations = [], []\n'
        '    for tokens in statements(text):\n'
        '        statement = describe(tokens, text)\n'
        "        attrs = statement['attrs']\n"
        "        typ = attrs.get('TYPE')\n"
        "        if statement['kind'] != 'DISTRIBUTION' or typ is None:\n"
        '            continue\n'
        "        if reference_name(typ['value']) != 'BINOMIAL':\n"
        '            continue\n'
        '        quote = typ[\'value\'][0] if typ[\'value\'][0] in (\'"\', "\'") else \'\'\n'
        "        target = quote+'GAUSS'+quote\n"
        "        edits.append((typ['value_start'], typ['value_end'], target.ljust(len(typ['value']))))\n"
        '        discarded = {}\n'
        "        for key in ('MX', 'MY', 'MT'):\n"
        '            attribute = attrs.get(key)\n'
        '            if attribute is None:\n'
        '                continue\n'
        "            discarded[key] = attribute['value']\n"
        '            for _, start, end in tokens:\n'
        "                if start >= attribute['start'] and end <= attribute['end']:\n"
        "                    blank = ''.join(char if char in '\\r\\n' else ' ' for char in text[start:end])\n"
        '                    edits.append((start, end, blank))\n'
        '        approximations.append({\n'
        "            'rule': 'binomial-to-gauss', 'kind': 'DISTRIBUTION', 'name': statement['name'],\n"
        "            'line': text.count('\\n', 0, tokens[0][1])+1,\n"
        "            'source_type': 'BINOMIAL', 'target_type': 'GAUSS',\n"
        "            'discarded_attributes': discarded,\n"
        "            'reason': 'Approximation: BINOMIAL replaced with GAUSS; distribution shape, tails and higher moments are not preserved. Width/correlation expressions are retained without rescaling',\n"
        '        })\n'
        '    candidate = text\n'
        '    for start, end, replacement in sorted(edits, reverse=True):\n'
        '        candidate = candidate[:start]+replacement+candidate[end:]\n'
        '    return candidate, approximations\n'
        '\n'
        '\n'
        'def list_members(ts, allow_modifiers=True):\n'
        '    """Parse OPAL LINE list syntax without expanding repetitions or reversals."""\n'
        '    values = [t[0] for t in ts]\n'
        "    if len(values) < 7 or values[1] != ':' or values[3:5] != ['=', '(']:\n"
        "        raise InputError('Expected a named parenthesized list')\n"
        '    names, modified = [], False\n'
        '\n'
        '    def group(i):\n'
        '        nonlocal modified\n'
        '        while True:\n'
        '            if i >= len(values):\n'
        "                raise InputError('Incomplete list')\n"
        "            if values[i] == '-':\n"
        '                if not allow_modifiers:\n'
        "                    raise InputError('Modifiers are not allowed in this list')\n"
        '                modified = True\n'
        '                i += 1\n'
        "            if i < len(values) and re.fullmatch(r'\\d+', values[i]):\n"
        "                if not allow_modifiers or i + 1 >= len(values) or values[i + 1] != '*':\n"
        "                    raise InputError('Invalid list repetition')\n"
        '                modified = True\n'
        '                i += 2\n'
        "            if i < len(values) and values[i] == '(':\n"
        '                if not allow_modifiers:\n'
        "                    raise InputError('Nested groups are only supported in LINE')\n"
        '                modified = True\n'
        '                i = group(i + 1)\n'
        '            elif i < len(values) and IDENT.fullmatch(values[i]):\n'
        '                names.append(values[i])\n'
        '                i += 1\n'
        '            else:\n'
        "                raise InputError('Expected a list member')\n"
        "            if i >= len(values) or values[i] not in (',', ')'):\n"
        "                raise InputError('Expected comma or closing parenthesis')\n"
        "            if values[i] == ')':\n"
        '                return i + 1\n'
        '            i += 1\n'
        '\n'
        '    end = group(5)\n'
        "    if end >= len(values) or values[end] not in (',', ';'):\n"
        "        raise InputError('Unexpected tokens after list')\n"
        '    return names, modified\n'
        '\n'
        '\n'
        'def reference_name(value):\n'
        '    """Accept one bare/quoted local identifier, without evaluating strings."""\n'
        '    if len(value) >= 2 and value[0] in (\'"\', "\'") and value[-1] == value[0]:\n'
        '        value = value[1:-1]\n'
        '    return value.upper() if IDENT.fullmatch(value) else None\n'
        '\n'
        '\n'
        'def reference_array(value):\n'
        '    """Read a literal brace-delimited list of reference names, not expressions."""\n'
        '    ts = tokenize(value)\n'
        "    if len(ts) < 3 or ts[0][0] != '{' or ts[-1][0] != '}':\n"
        "        raise InputError('Expected a nonempty literal reference array')\n"
        '    names = []\n'
        '    for i, t in enumerate(ts[1:-1]):\n'
        '        if i % 2:\n'
        "            if t[0] != ',':\n"
        "                raise InputError('Expected reference array comma')\n"
        '        else:\n'
        '            name = reference_name(t[0])\n'
        '            if not name:\n'
        "                raise InputError('Expected a literal reference name')\n"
        '            names.append(name)\n'
        '    if (len(ts) - 2) % 2 == 0:\n'
        "        raise InputError('Trailing comma in reference array')\n"
        '    return names\n'
        '\n'
        '\n'
        'def literal_zero(value):\n'
        '    """Classify a decimal numeric literal as zero/nonzero, or unknown expression."""\n'
        "    if not re.fullmatch(r'[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eEdD][+-]?\\d+)?', value):\n"
        '        return None\n'
        "    mantissa = re.split('[eEdD]', value)[0]\n"
        "    return all(c in '+-.0' for c in mantissa)\n"
        '\n'
        '\n'
        '_ZERO_FACE_LEXER = re.compile(\n'
        "    r'\\s+|//[^\\n]*|/\\*[\\s\\S]*?\\*/|'\n"
        "    r'(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eEdD][+-]?\\d+)?|'\n"
        "    r'[A-Za-z_][A-Za-z_0-9.]*|.', re.DOTALL)\n"
        '_ZERO_FACE_NUMBER = re.compile(\n'
        "    r'(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eEdD][+-]?\\d+)?\\Z')\n"
        "_ZERO_FACE_NAME = re.compile(r'[A-Za-z_][A-Za-z_0-9.]*\\Z')\n"
        '\n'
        '\n'
        'def _zero_face_tokens(value):\n'
        '    if not isinstance(value, str):\n'
        '        return None\n'
        '    result = []\n'
        '    for match in _ZERO_FACE_LEXER.finditer(value):\n'
        '        token = match.group()\n'
        "        if token.isspace() or token.startswith('//') or token.startswith('/*'):\n"
        '            continue\n'
        "        if token not in ('(', ')', '+', '-', '*', '/') and not (\n"
        '                _ZERO_FACE_NUMBER.fullmatch(token) or _ZERO_FACE_NAME.fullmatch(token)):\n'
        '            return None\n'
        '        result.append(token)\n'
        '    return result\n'
        '\n'
        '\n'
        'def _zero_face_number(token):\n'
        '    """Return Z for a lexical zero, A for a finite nonzero atom, else U."""\n'
        '    if not _ZERO_FACE_NUMBER.fullmatch(token):\n'
        "        return 'U'\n"
        '    try:\n'
        "        number = float(token.replace('d', 'e').replace('D', 'E'))\n"
        '    except (ValueError, OverflowError):\n'
        "        return 'U'\n"
        '    if not math.isfinite(number):\n'
        "        return 'U'\n"
        "    significand = re.split(r'[eEdD]', token, maxsplit=1)[0]\n"
        "    lexical_zero = all(char in '0.' for char in significand)\n"
        '    if lexical_zero:\n'
        "        return 'Z'\n"
        '    # A nonzero literal that rounded to zero is not a provable zero and cannot\n'
        '    # be used as a nonzero divisor or safe finite multiplier.\n'
        "    return 'A' if number != 0.0 else 'U'\n"
        '\n'
        '\n'
        'def _zero_face_literal(tokens):\n'
        '    """Accept only a signed, parenthesized numeric zero, not an expression."""\n'
        '    cursor = 0\n'
        '\n'
        '    def atom(depth):\n'
        '        nonlocal cursor\n'
        '        if depth > 100 or cursor >= len(tokens):\n'
        '            return False\n'
        "        while cursor < len(tokens) and tokens[cursor] in ('+', '-'):\n"
        '            cursor += 1\n'
        '        if cursor >= len(tokens):\n'
        '            return False\n'
        '        token = tokens[cursor]\n'
        '        cursor += 1\n'
        "        if token == '(':\n"
        '            zero = atom(depth+1)\n'
        "            if cursor >= len(tokens) or tokens[cursor] != ')':\n"
        '                return False\n'
        '            cursor += 1\n'
        '            return zero\n'
        "        return _zero_face_number(token) == 'Z'\n"
        '\n'
        '    return bool(tokens) and atom(0) and cursor == len(tokens)\n'
        '\n'
        '\n'
        'def proven_zero_face(value, stmt, stmts):\n'
        '    """Return supporting zero-scalar evidence, or None when zero is unproved.\n'
        '\n'
        "    ``stmt`` and ``stmts`` are the engine's declarations with original token\n"
        '    spans and explicit ``branch_path`` metadata. Evidence is an empty list for\n'
        '    a literal-only proof; truthiness must not be used to distinguish failure.\n'
        '\n'
        '    Allowed expression forms are signed atoms, parentheses, multiplication and\n'
        '    division. An atom can be a finite numeric literal, native PI, or a uniquely\n'
        '    declared unconditional REAL literal-zero scalar preceding this statement.\n'
        '    Scalars with any assignment/redeclaration, conditional or late declaration,\n'
        '    conflicting name, or any CALL in the file are not used as proof. No aliases,\n'
        '    functions, addition, cancellation or general arithmetic are interpreted.\n'
        '    """\n'
        '    tokens = _zero_face_tokens(value)\n'
        '    if not tokens or not isinstance(stmt, dict) or not isinstance(stmts, (list, tuple)):\n'
        '        return None\n'
        '    try:\n'
        "        offset = stmt['tokens'][0][1]\n"
        '    except (KeyError, IndexError, TypeError):\n'
        '        return None\n'
        '    if not isinstance(offset, int):\n'
        '        return None\n'
        "    has_call = any(isinstance(item, dict) and item.get('kind') == 'CALL' for item in stmts)\n"
        '\n'
        '    def binding(item):\n'
        '        if not isinstance(item, dict):\n'
        '            return None\n'
        "        name = item.get('name')\n"
        '        if isinstance(name, str):\n'
        '            return name.upper()\n'
        "        ts = item.get('tokens', [])\n"
        "        if item.get('kind') in ('REAL', 'BOOL', 'STRING') and len(ts) > 1:\n"
        '            return ts[1][0].upper()\n'
        '        return None\n'
        '\n'
        '    def starts_with(item, name):\n'
        "        ts = item.get('tokens', []) if isinstance(item, dict) else []\n"
        '        return bool(ts) and ts[0][0].upper() == name\n'
        '\n'
        '    def identifier(name):\n'
        '        upper = name.upper()\n'
        '        # A CALL may introduce/reassign a global scalar or shadow a name. Even\n'
        '        # includes after the bend are not opened or interpreted by this proof.\n'
        '        if has_call:\n'
        "            return 'U', []\n"
        '        declarations = [item for item in stmts if binding(item) == upper]\n'
        '        writes = [item for item in stmts if starts_with(item, upper)]\n'
        "        if upper == 'PI':\n"
        "            return ('A', []) if not declarations and not writes else ('U', [])\n"
        '        if len(declarations) != 1 or writes:\n'
        "            return 'U', []\n"
        '        declaration = declarations[0]\n'
        "        ts = declaration.get('tokens', [])\n"
        "        if (declaration.get('kind') != 'REAL' or 'branch_path' not in declaration\n"
        "                or declaration['branch_path'] or len(ts) < 5 or ts[2][0] != '='\n"
        "                or ts[-1][0] != ';' or ts[0][1] >= offset):\n"
        "            return 'U', []\n"
        '        initial_tokens = [token[0] for token in ts[3:-1]]\n'
        '        if not _zero_face_literal(initial_tokens):\n'
        "            return 'U', []\n"
        "        evidence = {'kind': 'REAL', 'name': ts[1][0],\n"
        "                    'declaration_offset': ts[0][1],\n"
        "                    'literal': ''.join(initial_tokens)}\n"
        "        return 'Z', [evidence]\n"
        '\n'
        '    cursor = 0\n'
        '\n'
        '    def atom(depth):\n'
        '        nonlocal cursor\n'
        '        if depth > 100 or cursor >= len(tokens):\n'
        "            return 'U', []\n"
        "        while cursor < len(tokens) and tokens[cursor] in ('+', '-'):\n"
        '            cursor += 1\n'
        '        if cursor >= len(tokens):\n'
        "            return 'U', []\n"
        '        token = tokens[cursor]\n'
        '        cursor += 1\n'
        "        if token == '(':\n"
        '            result = product(depth+1)\n'
        "            if cursor >= len(tokens) or tokens[cursor] != ')':\n"
        "                return 'U', []\n"
        '            cursor += 1\n'
        '            return result\n'
        '        if _ZERO_FACE_NUMBER.fullmatch(token):\n'
        '            return _zero_face_number(token), []\n'
        '        if _ZERO_FACE_NAME.fullmatch(token):\n'
        '            return identifier(token)\n'
        "        return 'U', []\n"
        '\n'
        '    def product(depth):\n'
        '        nonlocal cursor\n'
        '        state, evidence = atom(depth)\n'
        "        while cursor < len(tokens) and tokens[cursor] in ('*', '/'):\n"
        '            operator = tokens[cursor]\n'
        '            cursor += 1\n'
        '            other, more = atom(depth)\n'
        '            evidence += more\n'
        "            if operator == '*':\n"
        "                state = 'Z' if (state in ('Z', 'A') and other in ('Z', 'A')\n"
        "                                and 'Z' in (state, other)) else 'U'\n"
        '            else:\n'
        "                state = 'Z' if state == 'Z' and other == 'A' else 'U'\n"
        '        return state, evidence\n'
        '\n'
        '    try:\n'
        '        state, evidence = product(0)\n'
        '    except (RecursionError, IndexError, TypeError):\n'
        '        return None\n'
        "    if state != 'Z' or cursor != len(tokens):\n"
        '        return None\n'
        '    unique = []\n'
        '    for item in evidence:\n'
        '        if item not in unique:\n'
        '            unique.append(item)\n'
        '    return unique\n'
        '\n'
        '\n'
        'def track_beam_names(attrs):\n'
        '    """Resolve literal beam selection in order, including empty-array fallback."""\n'
        "    if 'BEAMS' in attrs:\n"
        "        value = attrs['BEAMS']['value']\n"
        "        if [t[0] for t in tokenize(value)] != ['{', '}']:\n"
        '            return reference_array(value)\n'
        "    name = reference_name(attrs.get('BEAM', {}).get('value', ''))\n"
        '    if not name:\n'
        "        raise InputError('Expected BEAM or a nonempty literal BEAMS array')\n"
        '    return [name]\n'
        '\n'
        '\n'
        'def array_arity(value):\n'
        '    """Count components of a well-formed literal array; never evaluate components."""\n'
        '    ts = [t[0] for t in tokenize(value)]\n'
        "    if len(ts) < 2 or ts[0] != '{' or ts[-1] != '}':\n"
        '        return None\n'
        '    if len(ts) == 2:\n'
        '        return 0\n'
        '    stack, count, has_value = [], 1, False\n'
        "    pairs = {')': '(', '}': '{', ']': '['}\n"
        '    for v in ts[1:-1]:\n'
        "        if v in ('(', '{', '['):\n"
        '            stack.append(v)\n'
        '        elif v in pairs:\n'
        '            if not stack or stack.pop() != pairs[v]:\n'
        '                return None\n'
        "        if v == ',' and not stack:\n"
        '            if not has_value:\n'
        '                return None\n'
        '            count += 1\n'
        '            has_value = False\n'
        '        else:\n'
        '            has_value = True\n'
        '    return count if not stack and has_value else None\n'
        '\n'
        '\n'
        'def conditional_attachment_problem(stmts, track, run, symbols):\n'
        '    """Guard source generation after one conditional distribution declaration.\n'
        '\n'
        '    The declaration and its condition stay where they are. New source/list\n'
        '    statements are emitted only at an unconditional BEAM after the complete\n'
        '    conditional. No condition is evaluated or distribution hoisted. If the\n'
        '    original condition leaves its selected distribution undefined, the target\n'
        '    still has an unresolved source rather than an invented alternative.\n'
        '    """\n'
        "    conditional = [s for s in stmts if s['branch_path'] and s['kind'] in\n"
        "                   ('BEAM', 'DISTRIBUTION', 'TRACK', 'RUN', 'EMISSIONSOURCE', 'EMISSIONSOURCELIST')]\n"
        '    if not conditional:\n'
        '        return None\n'
        "    if any(s['kind'] != 'DISTRIBUTION' for s in conditional):\n"
        "        return 'Branch-dependent beam/source/tracking declarations need explicit source attachment review; no source expansion performed'\n"
        "    if 'DISTRIBUTION' not in run['attrs']:\n"
        '        # Already migrated decks can retain conditional distributions. No\n'
        '        # attachment expansion or count inference is needed when the target\n'
        "        # beam owns its source list. TRACK.SOURCES is then only the target's\n"
        '        # accepted-but-ignored setting and must not create another source.\n'
        "        if 'SOURCES' in track['attrs']:\n"
        "            selected = symbols.get(reference_name(track['attrs'].get('BEAM', {}).get('value', '')))\n"
        "            if ('BEAMS' in track['attrs'] or not selected or selected['kind'] != 'BEAM'\n"
        "                    or 'SOURCES' not in selected['attrs']):\n"
        "                return 'Legacy TRACK.SOURCES expansion with conditional distributions needs explicit source attachment review'\n"
        '        return None\n'
        '    if len(conditional) != 1:\n'
        "        return 'Conditional source attachment requires one uniquely declared selected distribution'\n"
        '    dist = conditional[0]\n'
        "    name = reference_name(run['attrs'].get('DISTRIBUTION', {}).get('value', ''))\n"
        "    if (not dist['name'] or name != dist['name'].upper() or symbols.get(name) is not dist\n"
        "            or sum(bool(s['name']) and s['name'].upper() == name for s in stmts) != 1):\n"
        "        return 'Conditional source attachment requires one uniquely declared selected distribution'\n"
        "    beam_name = reference_name(track['attrs'].get('BEAM', {}).get('value', ''))\n"
        '    beam = symbols.get(beam_name)\n'
        "    if ('BEAMS' in track['attrs'] or not beam or beam['kind'] != 'BEAM'\n"
        "            or beam['branch_path'] or track['branch_path'] or run['branch_path']):\n"
        "        return 'Conditional distribution attachment requires unconditional single-beam BEAM, TRACK and RUN statements'\n"
        "    if 'SOURCES' in beam['attrs'] or 'SOURCES' in track['attrs']:\n"
        "        return 'Existing BEAM.SOURCES or TRACK.SOURCES conflicts with conditional RUN.DISTRIBUTION migration'\n"
        "    dist_end = dist['tokens'][-1][2]\n"
        "    beam_start = beam['tokens'][0][1]\n"
        "    if not dist_end < beam_start < track['tokens'][0][1] < run['tokens'][0][1]:\n"
        "        return 'Conditional selected distribution must precede the unconditional BEAM, TRACK and RUN'\n"
        "    if 'NPARTDIST' in dist['attrs']:\n"
        '        return None\n'
        "    count = beam['attrs'].get('NALLOC', beam['attrs'].get('NPART'))\n"
        '    if count is None:\n'
        "        return 'Conditional distribution needs an explicit count or a safely available beam allocation count'\n"
        "    tokens = tokenize(count['value'])\n"
        '    names = set()\n'
        '    for index, (token, _, _) in enumerate(tokens):\n'
        '        if IDENT.fullmatch(token):\n'
        "            if index+1 < len(tokens) and tokens[index+1][0] == '(':\n"
        "                return 'Conditional distribution count cannot infer function calls or computed references'\n"
        '            names.add(token.upper())\n'
        "        elif (token not in ('+', '-', '*', '/', '^', '(', ')')\n"
        "              and not re.fullmatch(r'(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eEdD][+-]?\\d+)?', token)):\n"
        "            return 'Conditional distribution count must use a literal or earlier unchanged scalar identifiers'\n"
        '    if not tokens:\n'
        "        return 'Conditional distribution count must be a nonempty scalar expression'\n"
        '    for name in names:\n'
        "        declarations = [s for s in stmts if s['kind'] == 'REAL' and len(s['tokens']) >= 5\n"
        "                        and s['tokens'][1][0].upper() == name and s['tokens'][2][0] == '='\n"
        "                        and not s['branch_path'] and s['tokens'][-1][2] < dist['tokens'][0][1]]\n"
        '        if not declarations:\n'
        "            return 'Conditional distribution count identifier must be declared before the distribution: '+name\n"
        '    for s in stmts:\n'
        "        if not dist_end < s['tokens'][0][1] < beam_start:\n"
        '            continue\n'
        "        if s['kind'] == 'CALL' and names:\n"
        "            return 'An include between conditional distribution and BEAM can change the inferred count'\n"
        "        if s['kind'] == 'SCALAR_ASSIGNMENT':\n"
        "            assigned = s['tokens'][0][0].upper()\n"
        "        elif s['kind'] in ('REAL', 'BOOL', 'STRING') and len(s['tokens']) > 1:\n"
        "            assigned = s['tokens'][1][0].upper()\n"
        '        else:\n'
        '            continue\n'
        '        if assigned in names:\n'
        "            return 'Conditional distribution count identifier changes before BEAM: '+assigned\n"
        '    return None\n'
        '\n'
        '\n'
        'def check_run_controls(track, run, symbols, issue):\n'
        '    """Check locally provable turn/energy-stop constraints for one TRACK/RUN pair."""\n'
        "    ta, ra = track['attrs'], run['attrs']\n"
        "    line = symbols.get(reference_name(ta.get('LINE', {}).get('value', '')))\n"
        "    ring = line is not None and line['kind'] == 'RING'\n"
        "    turns = 'TURNS' in ra\n"
        "    ordinary = ra.get('SPECTRALTUNES', {}).get('value', 'FALSE').upper() == 'FALSE'\n"
        "    kinetic = 'EKINSTOP' in ta\n"
        '    if not turns and not kinetic:\n'
        '        return\n'
        '    if turns and (not ring or not ordinary):\n'
        "        issue('run-turns-context', 'Directed TURNS is a RING limit; verify LINE topology and tracking mode', run)\n"
        '    if kinetic and line and not ring:\n'
        "        issue('ekinstop-ring-required', 'EKINSTOP requires a RING with the single-container cyclotron-gap path', track, 'unsupported')\n"
        '    if kinetic and turns:\n'
        "        issue('ekinstop-turns-conflict', 'EKINSTOP cannot be combined with explicit RUN.TURNS', run, 'unsupported')\n"
        '    if (ring and turns and ordinary) or kinetic:\n'
        "        for key in ('DT', 'MAXSTEPS', 'ZSTOP'):\n"
        "            if key in ta and (array_arity(ta[key]['value']) or 0) > 1:\n"
        "                issue('stop-schedule-unsupported', 'Explicit ring TURNS/EKINSTOP requires one ' + key + ' segment', track, 'unsupported')\n"
        '        try:\n'
        '            names = track_beam_names(ta)\n'
        '        except InputError:\n'
        "            issue('stop-beam-review', 'Resolve beam selection before validating turn/energy stopping', track)\n"
        '        else:\n'
        '            if len(names) != 1:\n'
        "                issue('stop-multibeam-unsupported', 'Directed ring TURNS/EKINSTOP requires one selected beam', track, 'unsupported')\n"
        '\n'
        '\n'
        'def check_attribute_rules(s, symbols, issue, recognized):\n'
        '    """Recognize emission/beam/RF controls without evaluating OPAL expressions."""\n'
        "    k, a = s['kind'], s['attrs']\n"
        '    def note(rule, message):\n'
        "        recognized.append({'rule': rule, 'name': s['name']})\n"
        '        issue(rule, message, s)\n'
        "    if k == 'OPTION':\n"
        "        if 'REPARTFREQ' in a:\n"
        "            note('option-repartition-preserve', 'Repartition frequency retained; review load balance and changes to layout/reduction order and floating-point reproducibility')\n"
        "        if 'ENABLELINEARTRANSFERMAPS' in a:\n"
        "            note('option-transfermaps-preserve', 'First-order external-field maps during design-orbit threading retained; no tracking integrator or map-accuracy conversion')\n"
        "        if set(a) & {'ASCIIDUMP', 'EBDUMP', 'ECHO', 'INFO'}:\n"
        "            note('option-output-preserve', 'ASCII/field dumps and message controls retained; verify output availability and downstream analysis expectations')\n"
        "        if 'SEED' in a:\n"
        "            note('option-seed-preserve', 'Random seed expression retained; -1 requests a time-based seed, and fixed seeds alone do not ensure backend/MPI reproducibility')\n"
        "    if k == 'RUN':\n"
        "        if 'TURNS' in a:\n"
        "            note('run-turns-preserve', 'Directed RING turn limit retained; check positive integer count, single schedule/beam, fresh run and return-plane eligibility')\n"
        "        if 'SCFIELDUPDATE' in a:\n"
        "            note('run-self-field-preserve', 'MIDPOINT/PRESTEP self-field timing retained; PRESTEP is the historical OPAL ordering, no default or timing change inferred')\n"
        '            if a[\'SCFIELDUPDATE\'][\'value\'].strip(\'"\\\'\').upper() not in {\'MIDPOINT\', \'PRESTEP\'}:\n'
        "                issue('self-field-mode-unsupported', 'SCFIELDUPDATE must be MIDPOINT or PRESTEP in this target', s, 'unsupported')\n"
        "    if k == 'FIELDSOLVER' and 'RCUT' in a:\n"
        "        note('fieldsolver-cutoff-preserve', 'P3M RCUT [m] retained; target derives ALPHA=2/RCUT, review cutoff positivity, mesh/particle resolution and force accuracy')\n"
        '        if a.get(\'TYPE\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper() != \'P3M\':\n'
        "            issue('fieldsolver-cutoff-context', 'RCUT belongs to P3M; verify selected solver before using this setting', s)\n"
        "    if k == 'BEAM' and 'POLARIZATION' in a:\n"
        "        note('beam-polarization-preserve', 'Rest-frame polarization vector in lab axes retained; even zero enables muon spin tracking, review magnitude and decay behavior')\n"
        "        arity = array_arity(a['POLARIZATION']['value'])\n"
        '        if arity not in (None, 0, 3):\n'
        "            issue('polarization-shape-unsupported', 'POLARIZATION must have three components (empty means unset)', s, 'unsupported')\n"
        "        if arity and reference_name(a.get('PARTICLE', {}).get('value', '')) != 'MUON':\n"
        "            issue('polarization-species-unsupported', 'Nonempty POLARIZATION requires explicit PARTICLE=MUON', s, 'unsupported')\n"
        "    if k == 'TRACK' and 'EKINSTOP' in a:\n"
        "        note('track-energy-stop-preserve', 'Kinetic energy stop [GeV] retained; requires positive threshold above launch energy, fresh single-container cyclotron RING, complete RF kick and no explicit TURNS')\n"
        "    if k == 'DISTRIBUTION':\n"
        '        if a.get(\'TYPE\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper() == \'GAUSS\':\n'
        "            degenerate = [key for key in ('SIGMAX', 'SIGMAY', 'SIGMAZ')\n"
        "                          if key not in a or literal_zero(a[key]['value']) is True]\n"
        '            if degenerate:\n'
        "                issue('gauss-zero-width-target', 'Zero/default spatial widths retained: '\n"
        "                      + ', '.join(degenerate) + '; requires target Gaussian point-mass fix (older builds can produce NaN); no finite width is invented', s)\n"
        '        if set(a) & DIST_EMISSION:\n'
        "            note('distribution-emission-preserve', 'Emission flag, time profile and step controls preserved; review cathode versus injection, time units and type-specific scheduling')\n"
        '        if set(a) & DIST_SHAPE:\n'
        "            note('distribution-shape-preserve', 'Cutoffs/correlations preserved; check sigma normalization, longitudinal time/space convention and correlation ordering')\n"
        "    if k == 'EMISSIONSOURCE':\n"
        '        if set(a) & SOURCE_THERMAL:\n'
        "            note('source-thermal-preserve', 'EMISSIONMODEL and EKIN [eV] preserved; check thermal momentum versus source P0 and distribution eligibility')\n"
        '            model = a.get(\'EMISSIONMODEL\', {}).get(\'value\', \'NONE\').strip(\'"\\\'\').upper()\n'
        "            if model not in {'NONE', 'ASTRA'}:\n"
        "                issue('emission-model-unsupported', 'Only NONE and ASTRA are target emission models', s, 'unsupported')\n"
        "            dist = symbols.get(reference_name(a.get('DISTRIBUTION', {}).get('value', '')))\n"
        '            dist_type = dist[\'attrs\'].get(\'TYPE\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper() if dist else \'\'\n'
        "            if model == 'ASTRA' and dist_type in {'GAUSS', 'UNIFORM', 'MULTIVARIATEGAUSS', 'FROMFILE', 'EMITTEDFROMFILE'}:\n"
        "                code = 'emittedfile-thermal-unsupported' if dist_type == 'EMITTEDFROMFILE' else 'thermal-distribution-unsupported'\n"
        "                issue(code, dist_type + ' requires EMISSIONMODEL=NONE; no thermal model is substituted', s, 'unsupported')\n"
        '        if set(a) & SOURCE_BOUNDARY:\n'
        "            note('source-boundary-preserve', 'Image/shifted-Green plane controls preserved; review OPEN solver eligibility, selected sources, single-plane constraints and dump/step counts')\n"
        "            zero = a.get('ZEROFACE_R0Z', {}).get('value', 'FALSE').upper()\n"
        "            shifted = a.get('SHIFTED_GREENS_FUNCTION', {}).get('value', 'FALSE').upper()\n"
        "            if zero == shifted == 'TRUE':\n"
        "                issue('source-boundary-conflict', 'ZEROFACE_R0Z and SHIFTED_GREENS_FUNCTION cannot both be true', s, 'unsupported')\n"
        "    if k == 'TRACK':\n"
        "        if 'SOURCES' in a:\n"
        "            note('track-sources-ignored', 'Target ignores TRACK.SOURCES; actual source lists must be attached to selected BEAM definitions')\n"
        "        if 'BEAMS' in a:\n"
        "            note('track-beams-preserve', 'BEAMS selection and order preserved; review primary reference beam, per-beam charge/sources and shared field evolution')\n"
        '            try:\n'
        '                names = track_beam_names(a)\n'
        '            except InputError as exc:\n'
        "                issue('track-beams-selection', str(exc), s, 'unsupported')\n"
        '            else:\n'
        '                for name in names:\n'
        "                    if name not in symbols or symbols[name]['kind'] != 'BEAM':\n"
        "                        issue('track-beams-reference', 'BEAMS member does not resolve to a local BEAM: ' + name, s)\n"
        '                if len(names) != len(set(names)):\n'
        "                    issue('track-beams-duplicate', 'Repeated beam names retained; verify repeated-container intent', s)\n"
        "                if 'BEAM' in a:\n"
        "                    issue('track-beams-precedence', 'Nonempty BEAMS overrides BEAM; an empty literal array falls back to BEAM', s)\n"
        "                if len(names) > 1 and 'INITIALORBIT' in a:\n"
        "                    issue('multibeam-initialorbit-unsupported', 'INITIALORBIT requires exactly one selected beam', s, 'unsupported')\n"
        '    if k == \'RFCAVITY\' and (set(a) & (RF_SINGLEGAP | RF_MODELS) or a.get(\'TYPE\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper() == \'SINGLEGAP\'):\n'
        "        note('rf-singlegap-preserve', 'Single-gap controls preserved: RMIN/RMAX/GAPWIDTH [m], PHI0 [deg]; legacy nonzero literal ANGLE/PDIS with complete geometry are converted separately; remaining legacy controls require review')\n"
        '        typ = a.get(\'TYPE\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper()\n'
        "        fmap = a.get('FMAPFN', {}).get('value', '')\n"
        '        if typ != \'SINGLEGAP\' or not fmap or fmap in (\'""\', "\'\'"):\n'
        "            issue('rf-singlegap-context', 'Native single-gap map controls require TYPE=SINGLEGAP and a nonempty FMAPFN; verify actual cavity mode', s)\n"
        '        else:\n'
        "            for key in ('ANGLE', 'PDIS', 'DVOLT', 'LAG', 'DLAG'):\n"
        "                if key in a and literal_zero(a[key]['value']) is not True:\n"
        "                    severity = 'unsupported' if literal_zero(a[key]['value']) is False else 'review'\n"
        "                    issue('rf-singlegap-static-conflict', key + ' must be zero for native map SINGLEGAP; symbolic values require review, no phase/pose rewrite inferred', s, severity)\n"
        '            for key in sorted(RF_MODELS & a.keys()):\n'
        '                if a[key][\'value\'] not in (\'""\', "\'\'"):\n'
        "                    issue('rf-singlegap-model-conflict', 'Native map SINGLEGAP requires empty ' + key + '; retained', s, 'unsupported')\n"
        '\n'
        '\n'
        'def convert_legacy_gap_poses(text):\n'
        '    """Convert explicit legacy SINGLEGAP geometry in the cyclotron-centred lab.\n'
        '\n'
        '    OPAL e01a0804714008cf287a078af9e829a4e5000c8b:\n'
        '    ParallelCyclotronTracker::checkGapCross uses D=x*sin(a)-y*cos(a)-d,\n'
        '    Dold>0 -> Dnew<=0. OpalCavity::update converts mm and degrees to SI.\n'
        '    With (x,y,z)_old -> (x,-z,y)_new, Ry(-a) has radial local x and\n'
        '    local z=-D. Origin is (d*sin(a),0,-d*cos(a)). No sector-frame shift\n'
        '    is included: magnetic sectors must share this cyclotron-centred lab.\n'
        '    Nonzero ANGLE/PDIS distinguish legacy geometry from native SI gaps.\n'
        '    Expressions are retained algebraically, never evaluated.\n'
        '    """\n'
        '    edits, records = [], []\n'
        '    for ts in statements(text):\n'
        '        stmt = describe(ts, text)\n'
        "        a = stmt['attrs']\n"
        "        if (stmt['kind'] != 'RFCAVITY'\n"
        '                or a.get(\'TYPE\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper() != \'SINGLEGAP\'\n'
        '                or a.get(\'FMAPFN\', {}).get(\'value\', \'\') in (\'\', \'""\', "\'\'")\n'
        "                or not {'ANGLE', 'PDIS', 'RMIN', 'RMAX', 'GAPWIDTH'} <= a.keys()\n"
        "                or any(k in a for k in ('X', 'Y', 'Z', 'THETA', 'PHI', 'PSI', 'ELEMEDGE'))):\n"
        '            continue\n'
        "        raw = [a[k]['value'] for k in ('ANGLE', 'PDIS')]\n"
        '        if any(literal_zero(v) is None for v in raw) or all(literal_zero(v) for v in raw):\n'
        '            continue\n'
        "        angle, distance = [float(v.replace('D', 'e').replace('d', 'e')) for v in raw]\n"
        '        if not all(math.isfinite(v) for v in (angle, distance)):\n'
        '            continue\n'
        '        theta, d = -math.radians(angle), distance * 0.001\n'
        '        x, z = d * math.sin(-theta), -d * math.cos(-theta)\n'
        '        pose = dict(X=x, Y=0.0, Z=z, THETA=theta, PHI=0.0, PSI=0.0)\n'
        "        for key in ('ANGLE', 'PDIS'):\n"
        '            attr = a[key]\n'
        '            # Blank tokens only, preserving source comments and line numbers.\n'
        "            for token, start, end in tokenize(text[attr['start']:attr['end']]):\n"
        "                edits.append((attr['start']+start, attr['start']+end, ' '*(end-start)))\n"
        "        for key in ('RMIN', 'RMAX', 'GAPWIDTH'):\n"
        '            attr = a[key]\n'
        "            value = attr['value']\n"
        '            if literal_zero(value) is not None:\n'
        "                number = float(value.replace('D', 'e').replace('d', 'e')) * 0.001\n"
        "                replacement = format(number, '.17g') if math.isfinite(number) else '0.001*('+value+')'\n"
        '            else:\n'
        "                replacement = '0.001*('+value+')'\n"
        "            edits.append((attr['value_start'], attr['value_end'], replacement))\n"
        '        end = ts[-1][1]\n'
        "        edits.append((end, end, ', '+', '.join(k+'='+format(v, '.17g') for k, v in pose.items())))\n"
        "        records.append(dict(rule='legacy-singlegap-pose', name=stmt['name'], kind='RFCAVITY',\n"
        "                            line=text.count('\\n', 0, ts[0][1])+1, pose=pose,\n"
        "                            reason='Converted legacy ANGLE/PDIS to cyclotron-centred SI pose and gap dimensions mm to m; verify sector placement and positive radial branch'))\n"
        '    for start, end, replacement in sorted(edits, reverse=True):\n'
        '        text = text[:start]+replacement+text[end:]\n'
        '    return text, records\n'
        '\n'
        '\n'
        'def convert_legacy_cyclotrons(text, map_headers=None, reserved_names=()):\n'
        '    """Expand PSI RING maps about the cyclotron-centred lab origin.\n'
        '\n'
        '    The map determines Rm, not RINIT. At azimuth a the entrance is\n'
        '    (Rm*cos(a),0,Rm*sin(a)), Ry(-a). Hence local (-Rm,0,0) is\n'
        '    the common ring centre and local angular support tiles [a,a+2*pi/SYM).\n'
        '    Old OPAL folds theta modulo 360/SYMMETRY with zero map origin.\n'
        '    """\n'
        '    map_headers = map_headers or {}\n'
        '    declarations = [describe(ts, text) for ts in statements(text)]\n'
        '    used = {str(n).upper() for n in reserved_names}\n'
        "    used.update(d['name'].upper() for d in declarations if d['name'])\n"
        "    used.update(d['tokens'][1][0].upper() for d in declarations\n"
        "                if d['kind'] in ('REAL', 'BOOL', 'STRING') and len(d['tokens'])>1)\n"
        '    edits, records = [], []\n'
        "    allowed = {'TYPE', 'FMAPFN', 'SYMMETRY', 'BSCALE', 'CYHARMON', 'RFFREQ',\n"
        "               'RINIT', 'PHIINIT', 'PRINIT', 'ZINIT', 'PZINIT'}\n"
        '    for stmt in declarations:\n'
        "        if stmt['kind'] != 'CYCLOTRON':\n"
        '            continue\n'
        "        a, name = stmt['attrs'], stmt['name']\n"
        '        def fail(message):\n'
        "            raise InputError('CYCLOTRON '+str(name)+': '+message)\n"
        '        if not name or a.get(\'TYPE\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper() != \'RING\':\n'
        "            fail('only named TYPE=RING PSI maps can be converted')\n"
        '        if set(a)-allowed:\n'
        "            fail('unconverted settings: '+', '.join(sorted(set(a)-allowed)))\n"
        "        symmetry = a.get('SYMMETRY', {}).get('value', '')\n"
        '        if literal_zero(symmetry) is None:\n'
        "            fail('SYMMETRY must be an explicit integer literal')\n"
        "        sym = float(symmetry.replace('D','e').replace('d','e'))\n"
        '        if not math.isfinite(sym) or not 2 <= sym <= 128 or sym != int(sym):\n'
        "            fail('SYMMETRY must be an integer between 2 and 128')\n"
        '        sym = int(sym)\n'
        "        fmap = a.get('FMAPFN', {}).get('value', '')\n"
        '        if len(fmap)<2 or fmap[0] not in (\'"\', "\'") or fmap[-1] != fmap[0]:\n'
        "            fail('FMAPFN must be a literal PSI map filename')\n"
        '        header = map_headers.get(fmap[1:-1])\n'
        '        if header is None:\n'
        "            fail('PSI map header is required to derive the sector reference radius')\n"
        '        try:\n'
        '            tokens = header.split()\n'
        '            rmin, dr, amin, da = map(float, tokens[:4])\n'
        '            nr, nt = int(tokens[17]), int(tokens[18])\n'
        '            if dr < 0: dr = -1/dr\n'
        '            if da < 0: da = -1/da\n'
        '            rmin, dr = rmin*0.001, dr*0.001\n'
        '            if (not all(math.isfinite(v) for v in (rmin,dr,amin,da))\n'
        '                    or not (rmin>0 and dr>0 and da>0 and 5<=nr<=100000 and 5<=nt<=100000)\n'
        '                    or nr*nt>100000000 or abs(math.radians(amin))>1e-12\n'
        '                    or abs(math.radians(nt*da)-2*math.pi/sym)>1e-8):\n'
        "                raise ValueError('incompatible grid')\n"
        '            radius = rmin+0.5*(nr-1)*dr\n'
        "            if not math.isfinite(radius): raise ValueError('invalid radius')\n"
        '        except (ValueError, IndexError, TypeError, OverflowError):\n'
        "            fail('invalid PSI map header or angular coverage does not match SYMMETRY')\n"
        "        names = [name+'_sector'+str(k) for k in range(sym)]\n"
        '        if any(n.upper() in used for n in names):\n'
        "            fail('generated sector name conflicts with an existing declaration')\n"
        '        used.update(n.upper() for n in names)\n'
        "        warning = ('WARNING: Generated CYCLOTRON sector placements need to be checked. '\n"
        "                   'Verify the cyclotron centre, map orientation, sector seams and RF placements; '\n"
        "                   'legacy initial conditions and RF timing require separate migration.')\n"
        "        poses, lines = [], ['// '+warning]\n"
        '        for k, sector in enumerate(names):\n'
        '            angle = 2*math.pi*k/sym\n'
        '            pose = dict(X=radius*math.cos(angle), Y=0.0, Z=radius*math.sin(angle),\n'
        '                        THETA=-angle, PHI=0.0, PSI=0.0)\n'
        '            poses.append(dict(name=sector, **pose))\n'
        "            attrs = ['FMAPFN='+fmap, 'SYM='+str(sym)]\n"
        "            if 'BSCALE' in a: attrs.append('BSCALE='+a['BSCALE']['value'])\n"
        "            attrs += [key+'='+format(value,'.17g') for key,value in pose.items()]\n"
        "            lines.append(sector+': CYCLOTRONSECTOR, '+', '.join(attrs)+';')\n"
        "        lines.append(name+': LINE=('+','.join(names)+');')\n"
        "        start,end = stmt['tokens'][0][1], stmt['tokens'][-1][2]\n"
        '        original = text[start:end]\n'
        "        lines += ['// Legacy declaration retained for review:']+['// '+line for line in original.splitlines()]\n"
        "        edits.append((start,end,'\\n'.join(lines)+'\\n'))\n"
        "        records.append(dict(rule='legacy-cyclotron-sectors', name=name, kind='CYCLOTRON',\n"
        "                            line=text.count('\\n',0,start)+1, reason=warning, sectors=poses,\n"
        '                            reference_radius_m=radius, map_header_checked=True,\n'
        "                            legacy_attributes={key: value['value'] for key,value in a.items()}))\n"
        '    for start,end,replacement in sorted(edits, reverse=True):\n'
        '        text = text[:start]+replacement+text[end:]\n'
        '    return text, records\n'
        '\n'
        '\n'
        'def migrate(text, *, map_headers=None, reserved_names=(), allow_zero_face_references=True):\n'
        '    """Apply guarded source/count rules and return candidate plus diagnostics."""\n'
        '    issues, changes, edits, recognized = [], [], [], []\n'
        "    def issue(code, message, stmt=None, severity='review'):\n"
        "        offset = stmt['tokens'][0][1] if stmt else 0\n"
        "        issues.append({'code': code, 'severity': severity,\n"
        "                       'line': text.count('\\n', 0, offset) + 1, 'message': message})\n"
        '    try:\n'
        '        text, syntax_changes = normalize_legacy_syntax(text)\n'
        '        text, removed = remove_obsolete(text)\n'
        '        text, approximations = approximate_binomial(text)\n'
        '        text, gap_poses = convert_legacy_gap_poses(text)\n'
        '        text, cyclotrons = convert_legacy_cyclotrons(text, map_headers, reserved_names)\n'
        '        leaves, controls = scan_statements(tokenize(text), InputError)\n'
        '        paths = branch_paths(len(leaves), controls)\n'
        "        stmts = [{**describe(t, text), 'branch_path': path} for t, path in zip(leaves, paths)]\n"
        '    except InputError as exc:\n'
        "        issue('parse', str(exc), severity='unsupported')\n"
        "        return text, {'status': 'unsupported', 'issues': issues, 'changes': [],\n"
        "                      'recognized_rules': [], 'constructs': {}, 'removed_constructs': [],\n"
        "                      'model_approximations': []}\n"
        '    for item in syntax_changes + gap_poses + cyclotrons:\n'
        '        changes.append(dict(item))\n'
        "        issues.append({'code': item['rule'], 'severity': 'review',\n"
        "                       'line': item['line'], 'message': item['reason']})\n"
        "        recognized.append({'rule': item['rule'], 'name': item.get('name')})\n"
        '    for item in removed:\n'
        '        changes.append(dict(item))\n'
        "        issues.append({'code': item['rule'], 'severity': 'review',\n"
        "                       'line': item['line'], 'message': item['reason']})\n"
        "        recognized.append({'rule': item['rule'], 'name': item['name']})\n"
        '    for item in approximations:\n'
        '        changes.append(dict(item))\n'
        "        issues.append({'code': item['rule'], 'severity': 'review',\n"
        "                       'line': item['line'], 'message': item['reason']})\n"
        "        recognized.append({'rule': item['rule'], 'name': item['name']})\n"
        '    for control in controls:\n'
        "        issues.append({'code': 'conditional-preserve', 'severity': 'review',\n"
        "                       'line': text.count('\\n', 0, control['start'])+1,\n"
        "                       'message': 'Native IF/ELSE and all branches retained; condition is not evaluated and may depend on target OPALVERSION'})\n"
        "        recognized.append({'rule': 'conditional-preserve', 'name': None})\n"
        '    symbols = {}\n'
        '    for s in stmts:\n'
        "        if s['name']:\n"
        "            key = s['name'].upper()\n"
        '            if key in symbols:\n'
        "                code = 'conditional-definition-ambiguous' if s['branch_path'] or symbols[key]['branch_path'] else 'duplicate-name'\n"
        "                issue(code, 'Repeated or branch-dependent definition requires explicit migration review: ' + key, s, 'unsupported')\n"
        '            symbols[key] = s\n'
        '    scalar_names = {}\n'
        '    for s in stmts:\n'
        "        k, a = s['kind'], s['attrs']\n"
        '        check_attribute_rules(s, symbols, issue, recognized)\n'
        "        if k == 'SCALAR_ASSIGNMENT':\n"
        "            ts = s['tokens']\n"
        '            target = ts[0][0].upper()\n'
        '            if (target not in scalar_names or target in symbols or len(ts) < 4\n'
        "                    or not any(set(path).issubset(s['branch_path']) for path in scalar_names[target])):\n"
        "                issue('scalar-assignment-target', 'Reassignment needs a preceding immediate REAL declaration and a nonempty expression: ' + target, s, 'unsupported')\n"
        "            elif ts[1][0] != '=':\n"
        "                issue('scalar-assignment-delayed', 'Delayed reassignment is outside this ruleset; retained', s, 'unsupported')\n"
        '            else:\n'
        "                recognized.append({'rule': 'scalar-assignment-preserve', 'name': ts[0][0]})\n"
        "                issue('scalar-assignment-preserve', 'Immediate REAL reassignment retained in order; expression and downstream values are not evaluated', s)\n"
        "        if k == 'REAL' and len(s['tokens']) >= 5 and s['tokens'][2][0] == '=':\n"
        "            scalar_names.setdefault(s['tokens'][1][0].upper(), []).append(s['branch_path'])\n"
        '        if k in UNAVAILABLE:\n'
        "            recognized.append({'rule': 'target-feature-unavailable', 'name': s['name']})\n"
        "            issue('target-feature-unavailable', UNAVAILABLE[k], s, 'unsupported')\n"
        '        if k in REFUSED:\n'
        "            recognized.append({'rule': 'unsupported-model', 'name': s['name']})\n"
        "            issue('unsupported-model', REFUSED[k], s, 'unsupported')\n"
        '        if k in PRESERVE_RULES:\n'
        '            rule, message = PRESERVE_RULES[k]\n'
        "            recognized.append({'rule': rule, 'name': s['name']})\n"
        '            issue(rule, message, s)\n'
        '        if k == \'TRIMCOIL\' and \'TYPE\' in a and a[\'TYPE\'][\'value\'].strip(\'"\\\'\') != \'PSI-BFIELD-MIRRORED\':\n'
        "            issue('trimcoil-model-unsupported', 'Only PSI-BFIELD-MIRRORED is implemented in this target; type retained', s, 'unsupported')\n"
        "        if k == 'CYCLOTRONSECTOR' and 'TRIMCOIL' in a:\n"
        '            try:\n'
        "                coil_names = reference_array(a['TRIMCOIL']['value'])\n"
        '            except InputError as exc:\n'
        "                issue('trimcoil-reference', str(exc), s)\n"
        '            else:\n'
        '                for name in coil_names:\n'
        "                    if name not in symbols or symbols[name]['kind'] != 'TRIMCOIL':\n"
        "                        issue('trimcoil-reference', 'Unresolved TRIMCOIL definition: ' + name, s)\n"
        "        if k == 'COF':\n"
        "            for key in sorted({'LINE', 'BEAM', 'MAXPATH'} - a.keys()):\n"
        "                issue('cof-required-setting', 'COF requires ' + key, s, 'unsupported')\n"
        "            for key, allowed in {'METHOD': {'NEWTON'}, 'DIMENSION': {'4'}, 'JACOBIAN': {'CENTRAL'},\n"
        "                                 'TIMEINTEGRATOR': {'BORIS', 'LF2', 'RK4', 'DOP853'}}.items():\n"
        '                if key in a and a[key][\'value\'].strip(\'"\\\'\').upper() not in allowed:\n'
        "                    issue('cof-setting-unsupported', 'Unverified COF.' + key + '=' + a[key]['value'], s, 'unsupported')\n"
        "            line = symbols.get(reference_name(a.get('LINE', {}).get('value', '')))\n"
        "            beam = symbols.get(reference_name(a.get('BEAM', {}).get('value', '')))\n"
        "            if line and line['kind'] != 'RING':\n"
        "                issue('cof-ring-required', 'COF.LINE must reference a RING', s, 'unsupported')\n"
        "            if beam and beam['kind'] == 'BEAM' and not ({'PC', 'ENERGY', 'GAMMA'} & beam['attrs'].keys()):\n"
        "                issue('cof-energy-required', 'COF.BEAM needs explicit PC, ENERGY or GAMMA', s, 'unsupported')\n"
        "        if k == 'BINNING' and 'PARAMETER' in a:\n"
        '            parameter = a[\'PARAMETER\'][\'value\'].strip(\'"\\\'\').upper()\n'
        "            if parameter not in {'VELOCITYZ', 'POSITIONZ', 'PZ', 'GAMMAZ'}:\n"
        "                issue('binning-parameter-unsupported', 'Unverified BINNING.PARAMETER=' + parameter, s, 'unsupported')\n"
        '        if k in ELEMENT_KINDS and set(a) & set(PLACEMENT.split()):\n'
        "            recognized.append({'rule': 'placement-preserve', 'name': s['name']})\n"
        "            issue('placement-physics', 'Placement/aperture expressions preserved; check coordinate frame, rotations and full-width aperture convention', s)\n"
        "        if k == 'EMISSIONSOURCE' and set(a) & {'R0X', 'R0Y', 'R0Z', 'P0X', 'P0Y', 'P0Z', 'T0'}:\n"
        "            issue('source-offset-physics', 'Source offsets preserved: R0 [m], P0 [beta*gamma], T0 [s]; verify launch frame and momentum', s)\n"
        "        if k == 'SBEND':\n"
        "            for key in ('E1', 'E2'):\n"
        '                if key not in a:\n'
        '                    continue\n'
        '                p = a[key]\n'
        '                # Restricted exact-zero proof, never an OPAL expression evaluator.\n'
        "                proof_context = stmts if allow_zero_face_references else stmts + [{'kind': 'CALL'}]\n"
        "                evidence = proven_zero_face(p['value'], s, proof_context)\n"
        '                if evidence is not None:\n'
        "                    edits.append((p['start'], p['end'], ''))\n"
        "                    changes.append({'rule': 'sbend-zero-face', 'element': s['name'],\n"
        "                                    'attribute': key, 'value': p['value'],\n"
        "                                    'zero_scalars': evidence})\n"
        '                    if evidence:\n'
        "                        issue('sbend-zero-face-proof', key + ' omitted: a unique preceding immutable REAL literal zero proves this restricted product/division expression is exactly zero; no general expression evaluation performed', s)\n"
        '                else:\n'
        "                    issue('sbend-face-unsupported', key + ' is not supported by OPALX SBEND; value retained', s, 'unsupported')\n"
        "            if 'GAP' in a:\n"
        "                if 'HGAP' in a:\n"
        "                    issue('sbend-gap-conflict', 'GAP and HGAP both set; neither changed', s)\n"
        '                else:\n'
        "                    p = a['GAP']\n"
        "                    edits.extend([(p['key_start'], p['key_end'], 'HGAP'),\n"
        "                                  (p['value_start'], p['value_end'], '(' + p['value'] + ')/2')])\n"
        "                    changes.append({'rule': 'sbend-half-gap', 'element': s['name'], 'from': 'GAP', 'to': 'HGAP'})\n"
        "                    issue('sbend-gap-semantics', 'Converted full GAP [m] to HGAP=GAP/2 [m]; confirm legacy full-gap convention', s)\n"
        "            for key in ('DESIGNENERGY', 'GREATERTHANPI'):\n"
        '                if key in a:\n'
        "                    issue('sbend-setting-unsupported', key + ' is rejected by native OPALX SBEND; legacy value retained. RBEND support does not establish SBEND support', s, 'unsupported')\n"
        "        if k == 'CALL':\n"
        "            issue('include-scope', 'Include copied recursively; cross-file symbol/order semantics require review', s)\n"
        '        if k in SCHEMA:\n'
        "            allowed = set(SCHEMA[k].split()) | ({'NPART', 'BCURRENT', 'BFREQ'} if k == 'BEAM' else set())\n"
        '            for key in sorted(a.keys() - allowed):\n'
        "                issue('unknown-attribute', k + '.' + key + ' has no verified rule', s)\n"
        "        elif k not in ('REAL', 'BOOL', 'STRING', 'LINE', 'EMISSIONSOURCELIST',\n"
        "                       'VALUE', 'ENDTRACK', 'QUIT', 'STOP', 'SCALAR_ASSIGNMENT') and k not in UNAVAILABLE and k not in REFUSED:\n"
        "            issue('unknown-construct', k + ' has no verified rule', s, 'unsupported')\n"
        '        # The simple statement parser is not a macro/control-flow interpreter.\n'
        "        if k in ('REAL', 'BOOL', 'STRING') and (len(s['tokens']) < 4 or s['tokens'][2][0] != '='):\n"
        "            issue('declaration', 'Only immediate scalar declarations are supported', s, 'unsupported')\n"
        "        if k == 'DISTRIBUTION':\n"
        '            typ = a.get(\'TYPE\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper()\n'
        "            if typ != 'FROMFILE':\n"
        "                issue('distribution-physics', 'Only FROMFILE is in the initial compatibility subset; review generation/emission semantics', s)\n"
        '        if k == \'FIELDSOLVER\' and a.get(\'TYPE\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper() != \'NONE\':\n'
        "            issue('solver-physics', 'Active space charge requires solver and boundary-condition review', s)\n"
        '        if k == \'RUN\' and a.get(\'METHOD\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper() != \'PARALLEL\':\n'
        '            issue(\'tracking-method\', \'Only METHOD="PARALLEL" is in the initial subset\', s)\n'
        "        if k in ('LINE', 'RING', 'EMISSIONSOURCELIST'):\n"
        '            try:\n'
        "                members, modified = list_members(s['tokens'], k == 'LINE')\n"
        '            except InputError as exc:\n'
        "                issue('list-syntax', str(exc), s, 'unsupported')\n"
        '            else:\n'
        '                if modified:\n'
        "                    recognized.append({'rule': 'line-modifiers-preserve', 'name': s['name']})\n"
        "                    issue('line-modifiers', 'Repetition/reversal/grouping preserved; verify ordering and reflected-element behavior', s)\n"
        "                expected = {'EMISSIONSOURCE'} if k == 'EMISSIONSOURCELIST' else ELEMENT_KINDS | {'LINE', 'RING'}\n"
        '                for member in members:\n'
        '                    target = symbols.get(member.upper())\n'
        "                    if not target or target['kind'] not in expected:\n"
        "                        issue('list-member', 'Unverified list member: ' + member, s)\n"
        "        if k == 'DISTRIBUTION' and 'NPARTDIST' not in a:\n"
        "            issue('distribution-count-review', 'Missing NPARTDIST; inspect any generated count and allocation semantics', s)\n"
        "        if k in ('TRACK', 'RUN'):\n"
        "            required = {'LINE', 'DT', 'MAXSTEPS'} if k == 'TRACK' else {'METHOD', 'FIELDSOLVER'}\n"
        "            if k == 'TRACK' and 'BEAMS' not in a:\n"
        "                required.add('BEAM')\n"
        '            for key in sorted(required - a.keys()):\n'
        "                issue('missing-attribute', k + '.' + key + ' is missing', s)\n"
        "        if k == 'BEAM':\n"
        "            if 'NPART' in a:\n"
        "                if 'NALLOC' in a:\n"
        "                    issue('count-conflict', 'NPART and NALLOC both set; neither changed', s)\n"
        '                else:\n'
        "                    p = a['NPART']\n"
        "                    edits.append((p['key_start'], p['key_end'], 'NALLOC'))\n"
        "                    changes.append({'rule': 'count-name', 'beam': s['name'], 'from': 'NPART', 'to': 'NALLOC'})\n"
        "                    issue('count-semantics', 'Confirm legacy NPART denotes allocated macroparticles', s)\n"
        "            if 'BCURRENT' in a or 'BFREQ' in a:\n"
        "                issue('bunch-charge', 'Set BCHARGE [C] after checking current/frequency units and bunch convention; legacy values retained', s)\n"
        "            if 'BCHARGE' not in a:\n"
        "                issue('missing-charge', 'BCHARGE [C] is required; no charge inferred', s)\n"
        "            if not ({'NALLOC', 'NPART'} & a.keys()):\n"
        "                issue('missing-count', 'NALLOC is required', s)\n"
        '    # Only one TRACK/RUN context is supported for attachment migration.\n'
        "    tracks = [s for s in stmts if s['kind'] == 'TRACK']\n"
        "    runs = [s for s in stmts if s['kind'] == 'RUN']\n"
        '    attachment_problem = (conditional_attachment_problem(stmts, tracks[0], runs[0], symbols)\n'
        '                          if len(tracks) == len(runs) == 1 else None)\n'
        '    if len(tracks) != 1 or len(runs) != 1:\n'
        "        issue('track-context', 'Expected exactly one TRACK and RUN; attachments left unchanged')\n"
        '    elif attachment_problem is not None:\n'
        "        issue('conditional-source-context', attachment_problem, severity='unsupported')\n"
        '    else:\n'
        '        tr, run = tracks[0], runs[0]\n'
        '        check_run_controls(tr, run, symbols, issue)\n'
        "        ra = run['attrs']\n"
        "        selected = symbols.get(reference_name(tr['attrs'].get('BEAM', {}).get('value', '')))\n"
        "        if 'BEAM' in ra:\n"
        "            run_name = reference_name(ra['BEAM']['value'])\n"
        "            if ('BEAMS' not in tr['attrs'] and selected and selected['kind'] == 'BEAM'\n"
        "                    and run_name == selected['name'].upper()):\n"
        "                p = ra['BEAM']\n"
        "                edits.append((p['start'], p['end'], ''))\n"
        "                changes.append({'rule': 'run-beam-remove', 'beam': selected['name']})\n"
        '            else:\n'
        "                issue('run-beam-conflict', 'Target RUN has no BEAM attribute; legacy selector cannot be removed without resolving selection intent', run, 'unsupported')\n"
        "        if 'SOURCES' in tr['attrs'] and 'DISTRIBUTION' not in ra:\n"
        "            source_name = reference_name(tr['attrs']['SOURCES']['value'])\n"
        '            source_list = symbols.get(source_name)\n'
        "            if ('BEAMS' not in tr['attrs'] and selected and selected['kind'] == 'BEAM'\n"
        "                    and 'SOURCES' not in selected['attrs'] and source_list\n"
        "                    and source_list['kind'] == 'EMISSIONSOURCELIST'\n"
        "                    and source_list['tokens'][0][1] < tr['tokens'][0][1]\n"
        '                    and selected[\'attrs\'].get(\'PARTICLE\', {}).get(\'value\', \'\').strip(\'"\\\'\').upper() != \'PHOTON\'):\n'
        "                pos = selected['tokens'][-1][1]\n"
        '                # The list may be declared after BEAM. A bare identifier would\n'
        '                # need to resolve during BEAM parsing; a canonical string does not.\n'
        '                edits.append((pos, pos, \', SOURCES="\' + source_name + \'"\'))\n'
        "                p = tr['attrs']['SOURCES']\n"
        "                edits.append((p['start'], p['end'], ''))\n"
        "                changes.append({'rule': 'track-source-attachment', 'beam': selected['name'], 'sources': source_list['name']})\n"
        "                issue('track-source-migration-review', 'Moved ignored TRACK.SOURCES onto the single BEAM; verify intended emission and source frame', tr)\n"
        "            elif not selected or 'SOURCES' not in selected['attrs']:\n"
        "                issue('track-source-attachment-conflict', 'Cannot migrate TRACK.SOURCES without one resolved beam and a preceding source-list definition', tr)\n"
        "        if 'DISTRIBUTION' in ra:\n"
        "            bname = reference_name(ra.get('BEAM', tr['attrs'].get('BEAM', {})).get('value', ''))\n"
        '            beam = symbols.get(bname)\n'
        "            distname = reference_name(ra['DISTRIBUTION']['value'])\n"
        '            dist = symbols.get(distname)\n'
        "            tb = reference_name(tr['attrs'].get('BEAM', {}).get('value', ''))\n"
        "            if 'BEAMS' in tr['attrs']:\n"
        "                issue('attachment-beams-ambiguous', 'Legacy RUN.DISTRIBUTION is not assigned across TRACK.BEAMS; attach sources per beam explicitly', run)\n"
        "            elif not beam or beam['kind'] != 'BEAM' or not dist or dist['kind'] != 'DISTRIBUTION' or tb != bname:\n"
        "                issue('attachment-reference', 'Cannot resolve one matching TRACK/RUN beam and distribution', run)\n"
        "            elif 'SOURCES' in beam['attrs'] or 'SOURCES' in tr['attrs']:\n"
        "                issue('attachment-conflict', 'Existing SOURCES and legacy RUN.DISTRIBUTION coexist', run)\n"
        '            else:\n'
        "                if dist['branch_path']:\n"
        "                    record = {'rule': 'conditional-distribution-source-attachment',\n"
        "                              'beam': beam['name'], 'distribution': dist['name'],\n"
        "                              'conditions': [{'condition': text[controls[index]['condition_start']:controls[index]['condition_end']],\n"
        "                                              'branch': branch} for index, branch in dist['branch_path']]}\n"
        '                    changes.append(record)\n'
        "                    recognized.append({'rule': record['rule'], 'name': dist['name']})\n"
        "                    issue(record['rule'], 'Conditional distribution retained without evaluating its condition; source declarations follow the branch at the unconditional BEAM. An undefined distribution remains a runtime error when the original branch is not taken', dist)\n"
        "                stem, n = 'OPAL2OPALX', 1\n"
        "                while f'{stem}_SOURCE'.upper() in symbols or f'{stem}_SOURCES'.upper() in symbols:\n"
        "                    stem = f'OPAL2OPALX_{n}'\n"
        '                    n += 1\n'
        "                pos = beam['tokens'][0][1]\n"
        '                generated = (f\'{stem}_SOURCE: EMISSIONSOURCE, DISTRIBUTION={dist["name"]};\\n\'\n'
        "                             f'{stem}_SOURCES: EMISSIONSOURCELIST=({stem}_SOURCE);\\n')\n"
        '                edits.append((pos, pos, generated))\n'
        "                pos = beam['tokens'][-1][1]\n"
        "                edits.append((pos, pos, f', SOURCES={stem}_SOURCES'))\n"
        "                p = ra['DISTRIBUTION']\n"
        "                edits.append((p['start'], p['end'], ''))\n"
        "                count = beam['attrs'].get('NALLOC', beam['attrs'].get('NPART'))\n"
        "                if 'NPARTDIST' not in dist['attrs'] and count:\n"
        "                    pos = dist['tokens'][-1][1]\n"
        "                    edits.append((pos, pos, ', NPARTDIST=' + count['value']))\n"
        "                    changes.append({'rule': 'distribution-count', 'distribution': dist['name']})\n"
        '                elif not count:\n'
        "                    issue('distribution-count', 'Cannot infer NPARTDIST without allocation count', dist)\n"
        "                issue('source-semantics', 'Verify absolute particle coordinates/momenta and source defaults against legacy tracking; structural attachment only', run)\n"
        "                changes.append({'rule': 'source-attachment', 'beam': beam['name'], 'distribution': dist['name']})\n"
        '    for s in stmts:\n'
        "        if s['kind'] == 'BEAM' and 'SOURCES' not in s['attrs']:\n"
        "            if not any(c['rule'] in ('source-attachment', 'track-source-attachment') and c['beam'] == s['name'] for c in changes):\n"
        "                issue('missing-sources', 'Beam needs a resolvable emission source list', s)\n"
        "        for key, expected in {'BEAM': {'BEAM'}, 'LINE': {'LINE', 'RING'},\n"
        "                              'FIELDSOLVER': {'FIELDSOLVER'}, 'DISTRIBUTION': {'DISTRIBUTION'},\n"
        "                              'SOURCES': {'EMISSIONSOURCELIST'}, 'BINS': {'BINNING'},\n"
        "                              'INITIALORBIT': {'COF'}}.items():\n"
        "            if key in s['attrs']:\n"
        "                val = s['attrs'][key]['value']\n"
        '                if key == \'BINS\' and val.strip(\'"\\\'\').upper() == \'NONE\':\n'
        '                    continue\n'
        '                target = symbols.get(reference_name(val))\n'
        "                if not target or target['kind'] not in expected:\n"
        "                    issue('unresolved-reference', key + '=' + val + ' is not locally resolved', s)\n"
        "                elif key == 'INITIALORBIT':\n"
        "                    issue('initialorbit-handover', 'Verify orbit-local generated distribution, energy/time consistency and fresh single-beam launch', s)\n"
        "                    if target['tokens'][0][1] >= s['tokens'][0][1]:\n"
        "                        issue('initialorbit-order', 'COF must execute before TRACK.INITIALORBIT', s, 'unsupported')\n"
        '    candidate = text\n'
        '    for start, end, replacement in sorted(edits, reverse=True):\n'
        '        candidate = candidate[:start] + replacement + candidate[end:]\n'
        "    status = 'unsupported' if any(i['severity'] == 'unsupported' for i in issues) else ('review-required' if issues else 'converted')\n"
        "    return candidate, {'status': status, 'issues': issues, 'changes': changes,\n"
        "                       'recognized_rules': recognized,\n"
        "                       'removed_constructs': removed,\n"
        "                       'model_approximations': approximations,\n"
        "                       'constructs': dict(sorted(Counter(s['kind'] for s in stmts).items()))}\n"
        '\n'
        '\n'
        'def dependencies(text):\n'
        '    """Find literal include/asset references without interpreting expressions."""\n'
        '    refs = []\n'
        '    for ts in statements(text):\n'
        '        s = describe(ts, text)\n'
        "        for key, a in s['attrs'].items():\n"
        "            if key in ('FNAME', 'FMAPFN') or (s['kind'] == 'CALL' and key == 'FILE'):\n"
        "                v = a['value']\n"
        '                if is_builtin_map(key, v):\n'
        '                    continue\n'
        '                literal = len(v) >= 2 and v[0] in (\'"\', "\'") and v[-1] == v[0]\n'
        "                refs.append((v[1:-1] if literal else v, s['kind'] == 'CALL', literal))\n"
        '    return refs\n'
        '\n'
        '\n'
        'def is_builtin_map(attribute, value):\n'
        '    """The exact native profile sentinel bypasses Fieldmap\'s filesystem access."""\n'
        '    return attribute == \'FMAPFN\' and value in (\'"1DPROFILE1-DEFAULT"\', "\'1DPROFILE1-DEFAULT\'")\n'
        '\n'
        '\n'
        'def collect(entry, *, texts=None, includes_only=False):\n'
        '    """Collect safe dependencies, optionally using rewritten input texts.\n'
        '\n'
        '    An include-only pass discovers lattice declarations before unavailable\n'
        '    elements are replaced; their discarded maps need not exist. The regular\n'
        '    pass then checks every dependency that the candidate still references.\n'
        '    """\n'
        '    entry = entry.resolve()\n'
        '    root = entry.parent\n'
        '    files, problems, active = {}, [], set()\n'
        '    def visit(path, parse):\n'
        '        if path.absolute() != path.resolve():\n'
        "            problems.append('Symlink dependency requires manual copying: ' + str(path))\n"
        '            return\n'
        '        path = path.resolve()\n'
        '        try:\n'
        '            path.relative_to(root)\n'
        '        except ValueError:\n'
        "            problems.append('Dependency escapes case directory: ' + str(path))\n"
        '            return\n'
        '        if path in active:\n'
        "            problems.append('Include cycle: ' + str(path))\n"
        '            return\n'
        '        if path in files and (files[path] or not parse):\n'
        '            return\n'
        '        if not path.is_file():\n'
        "            problems.append('Missing dependency: ' + str(path))\n"
        '            return\n'
        '        files[path] = parse\n'
        '        if parse:\n'
        '            active.add(path)\n'
        '            try:\n'
        "                text = texts[path] if texts is not None and path in texts else path.read_text(encoding='utf-8')\n"
        '                text, _ = normalize_legacy_syntax(text)\n'
        '                text, _ = remove_obsolete(text)\n'
        '                for name, include, literal in dependencies(text):\n'
        '                    if includes_only and not include:\n'
        '                        continue\n'
        "                    if not literal or '\\\\' in name or Path(name).is_absolute():\n"
        "                        problems.append('Nonportable or computed dependency: ' + name)\n"
        '                    else:\n'
        '                        # OPAL resolves CALL and asset paths from its working directory.\n'
        '                        visit(root / name, include)\n'
        '            except (InputError, UnicodeError) as exc:\n'
        "                problems.append(str(path) + ': ' + str(exc))\n"
        '            active.remove(path)\n'
        '    visit(entry, True)\n'
        '    return files, problems\n'
        '\n'
        '\n'
        'def drift_replacements(entry):\n'
        '    """Replace identifiable unavailable lattice declarations without evaluation.\n'
        '\n'
        '    Membership is discovered across literal includes, but source files and\n'
        '    their scalar expressions remain untouched. Only named unknown element\n'
        '    types used by LINE/RING, or explicitly excluded element types, qualify;\n'
        '    arbitrary commands and known non-element constructs remain strict errors.\n'
        '    """\n'
        '    entry = Path(entry).resolve()\n'
        '    files, problems = collect(entry, includes_only=True)\n'
        '    texts, parsed, members = {}, {}, set()\n'
        '    for path in files:\n'
        '        try:\n'
        "            text, _ = normalize_legacy_syntax(path.read_text(encoding='utf-8'))\n"
        '            text, _ = remove_obsolete(text)\n'
        '            declarations = [describe(tokens, text) for tokens in statements(text)]\n'
        '            for declaration in declarations:\n'
        "                if declaration['kind'] in ('LINE', 'RING'):\n"
        "                    names, _ = list_members(declaration['tokens'], declaration['kind'] == 'LINE')\n"
        '                    members.update(name.upper() for name in names)\n'
        '            texts[path], parsed[path] = text, declarations\n'
        '        except (InputError, UnicodeError) as exc:\n'
        "            problems.append(str(path) + ': ' + str(exc))\n"
        '    replacements, declared_names, duplicate_names = [], set(), set()\n'
        '    for declarations in parsed.values():\n'
        '        for declaration in declarations:\n'
        "            if declaration['name']:\n"
        "                name = declaration['name'].upper()\n"
        '                if name in declared_names:\n'
        '                    duplicate_names.add(name)\n'
        '                declared_names.add(name)\n'
        '    if duplicate_names:\n'
        "        problems.append('Duplicate source declaration names: ' + ', '.join(sorted(duplicate_names)))\n"
        '        return texts, replacements, problems\n'
        "    non_elements = set(SCHEMA) | {'REAL', 'BOOL', 'STRING', 'LINE', 'RING',\n"
        "        'EMISSIONSOURCELIST', 'VALUE', 'ENDTRACK', 'QUIT', 'STOP', 'SCALAR_ASSIGNMENT'}\n"
        "    keep = {'L', 'ELEMEDGE'} | set(PLACEMENT.split())\n"
        '    for path, declarations in parsed.items():\n'
        '        text, edits = texts[path], []\n'
        '        for declaration in declarations:\n'
        "            kind, name, attrs = declaration['kind'], declaration['name'], declaration['attrs']\n"
        "            if not name or kind in non_elements or kind == 'CYCLOTRON':\n"
        '                continue\n'
        '            if kind in REFUSED:\n'
        "                problems.append(name+': '+REFUSED[kind])\n"
        '                continue\n'
        '            # A source type can name an earlier element declaration. Resolving\n'
        '            # inheritance requires separate geometry/model rules; never label\n'
        '            # such an instance unavailable just because its base is not a type\n'
        '            # keyword. The normal migration diagnostics keep it unsupported.\n'
        '            if kind in declared_names:\n'
        '                continue\n'
        '            if kind not in UNAVAILABLE and name.upper() not in members:\n'
        '                continue\n'
        "            source_default = kind == 'SOURCE'\n"
        "            if source_default and set(attrs) != {'ELEMEDGE'}:\n"
        "                extras = ', '.join(sorted(set(attrs) - {'ELEMEDGE'})) or 'missing ELEMEDGE'\n"
        "                raise InputError(f'{name}: legacy SOURCE drift rule requires only ELEMEDGE; {extras} needs review')\n"
        "            if 'L' not in attrs and not source_default:\n"
        "                raise InputError(f'{name}: unavailable {kind} requires explicit L for drift replacement')\n"
        '            # The retired SOURCE used a fixed 5 cm field-free interval upstream\n'
        '            # of ELEMEDGE, unlike an ordinary downstream-placed element. This\n'
        '            # documented legacy default is not a general missing-length guess.\n'
        "            length = '0.05' if source_default else attrs['L']['value']\n"
        "            compact = re.sub(r'\\s+', '', length)\n"
        "            literal = re.fullmatch(r'\\(*([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eEdD][+-]?\\d+)?)\\)*', compact)\n"
        '            if literal:\n'
        "                number = float(literal.group(1).replace('d', 'e').replace('D', 'E'))\n"
        '                if not math.isfinite(number) or number < 0:\n'
        "                    raise InputError(f'{name}: drift replacement L must be finite and nonnegative')\n"
        "            elif (compact.upper().strip('()+-') in {'NAN', 'INF', 'INFINITY', 'TRUE', 'FALSE'}\n"
        '                  or any(token[0] in (\'{\', \'}\', \'[\', \']\') or token[0].startswith((\'"\', "\'"))\n'
        '                         for token in tokenize(length))):\n'
        "                raise InputError(f'{name}: drift replacement L must be a scalar length expression')\n"
        "            retained_values = {key: value['value'] for key, value in attrs.items() if key in keep}\n"
        '            if source_default:\n'
        "                retained_values = {'L': length, 'ELEMEDGE': '('+attrs['ELEMEDGE']['value']+')-0.05'}\n"
        "            retained = [key + '=' + value for key, value in retained_values.items()]\n"
        "            replacement = name + ': DRIFT, ' + ', '.join(retained) + ';'\n"
        "            start, end = declaration['tokens'][0][1], declaration['tokens'][-1][2]\n"
        '            edits.append((start, end, replacement))\n'
        "            record = {'name': name, 'source_type': kind, 'replacement_type': 'DRIFT',\n"
        "                'length': length, 'length_requires_review': literal is None,\n"
        "                'file': str(path.relative_to(entry.parent)), 'line': text.count('\\n', 0, start) + 1,\n"
        "                'reason': UNAVAILABLE.get(kind, kind + ' has no verified element conversion rule'),\n"
        "                'retained_attributes': retained_values}\n"
        '            if source_default:\n'
        "                record.update(length_origin='legacy-source-fixed-upstream-interval',\n"
        "                    reason='Legacy SOURCE fixed 0.05 m upstream interval preserved as DRIFT; backward-particle interception and loss output are omitted')\n"
        '            replacements.append(record)\n'
        '        for start, end, replacement in sorted(edits, reverse=True):\n'
        '            text = text[:start] + replacement + text[end:]\n'
        '        texts[path] = text\n'
        '    return texts, replacements, problems\n'
        '\n'
        '\n'
        "_NUMBER = re.compile(rb'[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?\\Z')\n"
        "_FORTRAN_NUMBER = re.compile(rb'[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)[dD][+-]?\\d+\\Z')\n"
        "_INTEGER = re.compile(rb'[+-]?\\d+\\Z')\n"
        "_NONFINITE = {b'nan', b'+nan', b'-nan', b'inf', b'+inf', b'-inf',\n"
        "              b'infinity', b'+infinity', b'-infinity'}\n"
        "_HEADER = b'x px y py z pz'\n"
        "_COLUMNS = ('x', 'px', 'y', 'py', 'z', 'pz')\n"
        '\n'
        '\n'
        'def _numeric_like(token):\n'
        '    return bool(_NUMBER.fullmatch(token) or _FORTRAN_NUMBER.fullmatch(token)\n'
        '                or token.lower() in _NONFINITE)\n'
        '\n'
        '\n'
        'def _literal(value):\n'
        '    """Recognize a bare or quoted keyword; never evaluate an input expression."""\n'
        '    if isinstance(value, dict):\n'
        "        value = value.get('value')\n"
        '    if not isinstance(value, str):\n'
        '        return None\n'
        '    value = value.strip()\n'
        '    if len(value) >= 2 and value[0] in (\'"\', "\'") and value[-1] == value[0]:\n'
        '        value = value[1:-1]\n'
        '    return value.upper()\n'
        '\n'
        '\n'
        'def normalize_legacy_particles(raw, contexts):\n'
        '    """Return ``(candidate_bytes, migration_record_or_None, problem_or_None)``.\n'
        '\n'
        '    ``contexts`` contains all references to this asset. Each reference is either\n'
        "    an engine-shaped declaration ``{'attrs': {'TYPE': {'value': 'FROMFILE'},\n"
        "    ...}, ...}`` or a simple mapping ``{'TYPE': 'FROMFILE', ...}``. Attributes\n"
        '    must use their uppercase keys. The only safe context is literal FROMFILE\n'
        '    with INPUTMOUNITS absent/NONE and EMITTED absent/FALSE. No expression or\n'
        '    unknown context is resolved by this helper.\n'
        '\n'
        '    Recognized native headers and opaque/unrecognized assets pass through\n'
        '    without validation claims. Once an integer/numeric count plus numeric data\n'
        '    identifies a headerless candidate, malformed counts, rows, values or unsafe\n'
        '    contexts return a blocking problem and unchanged bytes. Bare count-only\n'
        '    files remain opaque. Complete six-column finite data is required; no rows,\n'
        '    units, values, comments or existing line endings are rewritten.\n'
        '    """\n'
        '    if not isinstance(raw, bytes):\n'
        "        raise TypeError('Particle asset must be bytes')\n"
        '    lines = raw.splitlines(keepends=True)\n'
        '    content = [(index, line.strip()) for index, line in enumerate(lines)\n'
        "               if line.strip() and not line.lstrip().startswith(b'#')]\n"
        '    if len(content) < 2:\n'
        '        return raw, None, None\n'
        '    count_index, count_line = content[0]\n'
        "    data_tokens = content[1][1].split(b'#', 1)[0].split()\n"
        '    header_names = {token.lower() for token in data_tokens}\n'
        '    # Native headers may contain additional columns or use a different order.\n'
        "    if set(_COLUMNS).issubset({name.decode('ascii', errors='replace') for name in header_names}):\n"
        '        return raw, None, None\n'
        '    looks_numeric = bool(data_tokens) and (\n'
        '        _numeric_like(data_tokens[0])\n'
        '        or (len(data_tokens) == 6 and sum(_numeric_like(token) for token in data_tokens) >= 5))\n'
        '    if not looks_numeric:\n'
        '        return raw, None, None\n'
        '    # A text/map asset beginning with a word is not a legacy particle file.\n'
        '    if not (_INTEGER.fullmatch(count_line) or _numeric_like(count_line)\n'
        "            or _INTEGER.fullmatch(count_line.split(b'#', 1)[0].strip())):\n"
        '        return raw, None, None\n'
        '\n'
        '    def refuse(message):\n'
        "        return raw, None, 'Legacy FROMFILE particle data: '+message\n"
        '\n'
        '    if not _INTEGER.fullmatch(count_line):\n'
        "        return refuse('the count line must be one positive integer without an inline comment')\n"
        '    try:\n'
        '        count = int(count_line)\n'
        '    except ValueError:\n'
        "        return refuse('the count is too large to interpret safely')\n"
        '    if count <= 0:\n'
        "        return refuse('the particle count must be positive')\n"
        '    records = content[1:]\n'
        '    if len(records) != count:\n'
        "        return refuse('declared count '+str(count)+' does not match '+str(len(records))+' data rows')\n"
        '    for line_index, line in records:\n'
        "        tokens = line.split(b'#', 1)[0].split()\n"
        '        if len(tokens) != 6:\n'
        "            return refuse('line '+str(line_index+1)+' must contain exactly six numeric columns')\n"
        '        for token in tokens:\n'
        '            if not _NUMBER.fullmatch(token):\n'
        "                return refuse('line '+str(line_index+1)+' contains a non-finite or unsupported numeric token')\n"
        '            try:\n'
        '                finite = math.isfinite(float(token))\n'
        '            except (ValueError, OverflowError):\n'
        '                finite = False\n'
        '            if not finite:\n'
        "                return refuse('line '+str(line_index+1)+' contains a non-finite numeric value')\n"
        '    if not isinstance(contexts, (list, tuple)) or not contexts:\n'
        "        return refuse('no verified FROMFILE reference context was supplied')\n"
        '    for context in contexts:\n'
        '        if not isinstance(context, dict):\n'
        "            return refuse('an asset reference context is not a declaration')\n"
        "        attrs = context.get('attrs', context)\n"
        "        if not isinstance(attrs, dict) or _literal(attrs.get('TYPE')) != 'FROMFILE':\n"
        "            return refuse('every asset reference must be literal TYPE=FROMFILE')\n"
        "        if 'INPUTMOUNITS' in attrs and _literal(attrs['INPUTMOUNITS']) != 'NONE':\n"
        "            return refuse('INPUTMOUNITS must be absent or literal NONE; no momentum rescaling is inferred')\n"
        "        if 'EMITTED' in attrs and _literal(attrs['EMITTED']) != 'FALSE':\n"
        "            return refuse('EMITTED must be absent or literal FALSE; emission-time data needs a separate rule')\n"
        '    count_raw = lines[count_index]\n'
        "    if count_raw.endswith(b'\\r\\n'):\n"
        "        newline = b'\\r\\n'\n"
        "    elif count_raw.endswith(b'\\n'):\n"
        "        newline = b'\\n'\n"
        '    else:\n'
        "        return refuse('count and data must use LF or CRLF line boundaries')\n"
        '    insertion = sum(len(line) for line in lines[:count_index+1])\n'
        '    candidate = raw[:insertion]+_HEADER+newline+raw[insertion:]\n'
        '    record = {\n'
        "        'rule': 'legacy-particle-header',\n"
        "        'source_sha256': hashlib.sha256(raw).hexdigest(),\n"
        "        'output_sha256': hashlib.sha256(candidate).hexdigest(),\n"
        "        'particle_count': count,\n"
        "        'columns': list(_COLUMNS),\n"
        "        'header_line': count_index+2,\n"
        "        'momentum_rescaled': False,\n"
        "        'reason': 'Inserted native FROMFILE column names in legacy x px y py z pz order; particle records, values and units are unchanged, with no rescaling',\n"
        '    }\n'
        '    return candidate, record, None\n'
        '\n'
        '\n'
        'def migrate_particle_assets(entry, payload, reports):\n'
        '    """Normalize verified legacy particle assets, preserving original sources.\n'
        '\n'
        '    Only literal distribution references qualify. Every use of a shared asset\n'
        '    is checked so a map, include, or different source model is never silently\n'
        '    interpreted as the legacy six-column nonemitted FROMFILE format.\n'
        '    """\n'
        '    uses, migrations, problems = {}, [], []\n'
        "    parsed_files = {report['file'] for report in reports}\n"
        '    for report in reports:\n'
        '        try:\n'
        "            text = payload[report['file']].decode('utf-8')\n"
        '            for tokens in statements(text):\n'
        '                statement = describe(tokens, text)\n'
        "                for key, attr in statement['attrs'].items():\n"
        "                    if key not in ('FNAME', 'FMAPFN') and not (key == 'FILE' and statement['kind'] == 'CALL'):\n"
        '                        continue\n'
        "                    value = attr['value']\n"
        '                    if is_builtin_map(key, value):\n'
        '                        continue\n'
        '                    if len(value) < 2 or value[0] not in (\'"\', "\'") or value[-1] != value[0]:\n'
        '                        continue\n'
        '                    target = (entry.parent/value[1:-1]).resolve()\n'
        '                    if not target.is_relative_to(entry.parent):\n'
        '                        continue\n'
        '                    rel = str(target.relative_to(entry.parent))\n'
        '                    uses.setdefault(rel, []).append({\n'
        "                        'kind': statement['kind'], 'attribute': key,\n"
        "                        'attrs': statement['attrs'], 'name': statement['name'],\n"
        "                        'file': report['file'], 'line': text.count('\\n', 0, tokens[0][1])+1})\n"
        '        except (UnicodeError, InputError):\n'
        '            # Existing file diagnostics retain the parse/encoding failure.\n'
        '            continue\n'
        "    by_name = {report['file']: report for report in reports}\n"
        '    for rel, contexts in sorted(uses.items()):\n'
        '        if rel not in payload or rel in parsed_files:\n'
        '            continue\n'
        "        if not any(context['kind'] == 'DISTRIBUTION' and context['attribute'] == 'FNAME'\n"
        "                   and reference_name(context['attrs'].get('TYPE', {}).get('value', ''))\n"
        "                   in ('FROMFILE', 'EMITTEDFROMFILE') for context in contexts):\n"
        '            continue\n'
        "        if any(context['kind'] != 'DISTRIBUTION' or context['attribute'] != 'FNAME'\n"
        '               for context in contexts):\n'
        "            problems.append(rel+': shared particle asset is also used by a map, include or non-distribution construct; no header rewrite performed')\n"
        '            continue\n'
        '        normalized, record, problem = normalize_legacy_particles(payload[rel], contexts)\n'
        '        if problem:\n'
        "            problems.append(rel+': '+problem)\n"
        '        if record is not None:\n'
        '            payload[rel] = normalized\n'
        "            record = {**record, 'file': rel}\n"
        '            migrations.append(record)\n'
        '            for context in contexts:\n'
        "                result = by_name[context['file']]\n"
        "                result['changes'].append(dict(record))\n"
        "                result['recognized_rules'].append({'rule': record['rule'], 'name': context['name']})\n"
        "                result['issues'].append({'code': record['rule'], 'severity': 'review',\n"
        "                                         'line': context['line'], 'message': rel+': '+record['reason']})\n"
        "                if result['status'] == 'converted':\n"
        "                    result['status'] = 'review-required'\n"
        '    return migrations, problems\n'
        '\n'
        '\n'
        'def process(entry, output=None, *, replace_unavailable=False):\n'
        '    """Inspect one dependency bundle, optionally writing into a fresh directory."""\n'
        '    entry = entry.resolve()\n'
        '    if not isinstance(replace_unavailable, bool):\n'
        "        raise InputError('Drift replacement flag must be logical')\n"
        '    if not entry.is_file():\n'
        "        raise InputError('Input does not exist: ' + str(entry))\n"
        '    if output is not None and (output.exists() or output.resolve().is_relative_to(entry.parent)):\n'
        "        raise InputError('Output must be new and outside the source case directory')\n"
        '    try:\n'
        '        texts, replacements, prior_problems = drift_replacements(entry) if replace_unavailable else ({}, [], [])\n'
        '    except InputError as exc:\n'
        '        texts, replacements, prior_problems = {}, [], [str(exc)]\n'
        '    files, problems = collect(entry, texts=texts)\n'
        '    problems = list(dict.fromkeys(prior_problems + problems))\n'
        '    # Use only dependencies already checked by collect; never open arbitrary map paths.\n'
        '    map_headers, reserved_names = {}, set()\n'
        '    for asset, parsed in files.items():\n'
        '        if not parsed:\n'
        "            with asset.open('rb') as stream:\n"
        "                map_headers[str(asset.relative_to(entry.parent))] = stream.read(65536).decode('ascii', errors='replace')\n"
        '        else:\n'
        '            try:\n'
        "                source_text = texts[asset] if asset in texts else asset.read_text(encoding='utf-8')\n"
        '                for ts in statements(source_text):\n'
        '                    declaration = describe(ts, source_text)\n'
        "                    if declaration['name']: reserved_names.add(declaration['name'].upper())\n"
        "                    elif declaration['kind'] in ('REAL', 'BOOL', 'STRING') and len(ts)>1:\n"
        '                        reserved_names.add(ts[1][0].upper())\n'
        '            except (InputError, UnicodeError):\n'
        '                pass  # Normal migration reports the parse error.\n'
        '    reports, payload, removed_constructs, model_approximations = [], {}, [], []\n'
        '    for path, parse in sorted(files.items()):\n'
        '        rel = str(path.relative_to(entry.parent))\n'
        '        raw = path.read_bytes()\n'
        '        if parse:\n'
        '            try:\n'
        "                original = raw.decode('utf-8')\n"
        '                try:\n'
        '                    filtered, syntax_changes = normalize_legacy_syntax(original)\n'
        '                    filtered, removed = remove_obsolete(filtered)\n'
        '                except InputError:\n'
        '                    filtered, removed, syntax_changes = original, [], []\n'
        '                candidate, result = migrate(texts.get(path, filtered), map_headers=map_headers,\n'
        '                    reserved_names=reserved_names, allow_zero_face_references=sum(files.values()) == 1)\n'
        "                result['model_approximations'] = [{**item, 'file': rel}\n"
        "                                                 for item in result['model_approximations']]\n"
        "                model_approximations.extend(result['model_approximations'])\n"
        "                result['removed_constructs'] = [{**item, 'file': rel} for item in removed]\n"
        "                removed_constructs.extend(result['removed_constructs'])\n"
        '                for item in syntax_changes + removed:\n'
        "                    result['changes'].append(dict(item))\n"
        "                    result['issues'].append({'code': item['rule'], 'severity': 'review',\n"
        "                                            'line': item['line'], 'message': item['reason']})\n"
        "                    result['recognized_rules'].append({'rule': item['rule'], 'name': item['name']})\n"
        "                    if result['status'] == 'converted':\n"
        "                        result['status'] = 'review-required'\n"
        '                for replacement in replacements:\n'
        "                    if replacement['file'] == rel:\n"
        "                        result['changes'].append({'rule': 'unavailable-element-drift', **replacement})\n"
        "                        result['issues'].append({'code': 'unavailable-element-drift', 'severity': 'review',\n"
        "                            'line': replacement['line'], 'message': replacement['name'] + ': ' +\n"
        "                            replacement['source_type'] + ' replaced with DRIFT; ' + replacement['reason']})\n"
        "                        if result['status'] == 'converted':\n"
        "                            result['status'] = 'review-required'\n"
        "                payload[rel] = candidate.encode('utf-8')\n"
        "                result['diff'] = ''.join(difflib.unified_diff(original.splitlines(True), candidate.splitlines(True), fromfile=rel, tofile=rel + ' (OPALX candidate)'))\n"
        '            except UnicodeError:\n'
        "                result = {'status': 'unsupported', 'issues': [{'code': 'encoding', 'message': 'UTF-8 input required'}], 'changes': [], 'constructs': {}, 'removed_constructs': [], 'model_approximations': []}\n"
        '                payload[rel] = raw\n'
        '            result.update(file=rel, sha256=hashlib.sha256(raw).hexdigest())\n'
        '            reports.append(result)\n'
        '        else:\n'
        '            payload[rel] = raw\n'
        '    asset_migrations, asset_problems = migrate_particle_assets(entry, payload, reports)\n'
        '    problems.extend(asset_problems)\n'
        '    # Cross-file symbols are intentionally not flattened into local scope.\n'
        "    status = 'unsupported' if problems or any(r['status'] == 'unsupported' for r in reports) else ('review-required' if any(r['status'] == 'review-required' for r in reports) else 'converted')\n"
        "    report = {'tool_version': VERSION, 'ruleset': RULESET, 'input': str(entry),\n"
        "              'status': status, 'physics_validated': False, 'dependency_problems': problems,\n"
        "              'unavailable_elements': replacements,\n"
        "              'removed_constructs': removed_constructs,\n"
        "              'model_approximations': model_approximations,\n"
        "              'asset_migrations': asset_migrations,\n"
        "              'files': reports, 'assets': sorted(set(payload) - {r['file'] for r in reports})}\n"
        '    if output is not None:\n'
        '        # Own metadata namespace avoids collisions with source assets.\n'
        "        if any(Path(p).parts[0] == '_opal2opalx' for p in payload):\n"
        "            raise InputError('Input uses reserved metadata directory _opal2opalx')\n"
        '        output.mkdir(parents=True, exist_ok=False)\n'
        '        for rel, raw in payload.items():\n'
        '            target = output / rel\n'
        '            target.parent.mkdir(parents=True, exist_ok=True)\n'
        '            target.write_bytes(raw)\n'
        "        meta = output / '_opal2opalx'\n"
        '        meta.mkdir()\n'
        "        (meta / 'report.json').write_text(json.dumps(report, indent=2) + '\\n', encoding='utf-8')\n"
        "        (meta / 'changes.diff').write_text(''.join(r.get('diff', '') for r in reports), encoding='utf-8')\n"
        '    return report\n'
        '\n'
        '\n'
        'def validate(entry, executable, output, timeout=60.0, allow_review=False):\n'
        '    """Run one copied case directly (one rank); execution is not physics validation."""\n'
        '    executable = executable.resolve()\n'
        '    if not executable.is_file():\n'
        "        raise InputError('OPALX executable not found; supply an existing installation with --opalx')\n"
        '    if not math.isfinite(timeout) or timeout <= 0:\n'
        "        raise InputError('Timeout must be positive')\n"
        '    inspection = process(entry)\n'
        "    prior = entry.resolve().parent / '_opal2opalx' / 'report.json'\n"
        '    if prior.is_file():\n'
        '        try:\n'
        "            prior_status = json.loads(prior.read_text(encoding='utf-8'))['status']\n"
        '        except (ValueError, KeyError) as exc:\n'
        "            raise InputError('Invalid prior conversion report') from exc\n"
        "        if prior_status != 'converted':\n"
        "            inspection['status'] = prior_status\n"
        "    if inspection['status'] != 'converted' and not allow_review:\n"
        "        raise InputError('Case requires review; inspect it first, or explicitly use --allow-review')\n"
        '    root = entry.resolve().parent\n'
        '    if output.exists() or output.resolve().is_relative_to(root):\n'
        "        raise InputError('Validation output must be new and outside the case directory')\n"
        "    if any(p.is_symlink() for p in root.rglob('*')):\n"
        "        raise InputError('Validation copy must not contain symlinks')\n"
        "    work = output / 'work'\n"
        '    shutil.copytree(root, work)\n'
        '    command = [str(executable), entry.name]\n'
        '    timed_out = False\n'
        "    with (output / 'stdout.log').open('wb') as stdout, (output / 'stderr.log').open('wb') as stderr:\n"
        '        try:\n'
        '            completed = subprocess.run(command, cwd=work, stdout=stdout, stderr=stderr,\n'
        '                                       timeout=timeout, check=False)\n'
        '            code = completed.returncode\n'
        '        except subprocess.TimeoutExpired:\n'
        '            timed_out, code = True, None\n'
        "    result = {'tool_version': VERSION, 'command': command, 'returncode': code,\n"
        "              'timed_out': timed_out, 'execution_passed': code == 0,\n"
        "              'physics_validated': False, 'inspection_status': inspection['status'],\n"
        "              'mode': 'direct single-rank execution; no numerical metric comparison'}\n"
        "    (output / 'validation.json').write_text(json.dumps(result, indent=2) + '\\n', encoding='utf-8')\n"
        '    return result\n'
        '\n'
        '\n'
        'def main(argv=None):\n'
        '    """CLI: exit 0 supported, 1 review/unsupported, 2 setup/I/O error."""\n'
        '    parser = argparse.ArgumentParser(description=__doc__)\n'
        "    parser.add_argument('--version', action='version', version=VERSION)\n"
        "    sub = parser.add_subparsers(dest='command', required=True)\n"
        "    for command in ('inspect', 'inventory', 'convert', 'batch'):\n"
        '        p = sub.add_parser(command)\n'
        "        p.add_argument('input', type=Path)\n"
        "        if command in ('convert', 'batch'):\n"
        "            p.add_argument('--output', type=Path, required=True)\n"
        "        p.add_argument('--report', type=Path, help='New JSON report path (never overwrite)')\n"
        "    p = sub.add_parser('validate', help='Optional isolated single-rank execution check')\n"
        "    p.add_argument('input', type=Path, help='Converted entry .in file')\n"
        "    p.add_argument('--opalx', type=Path, required=True)\n"
        "    p.add_argument('--output', type=Path, required=True)\n"
        "    p.add_argument('--timeout', type=float, default=60.0)\n"
        "    p.add_argument('--allow-review', action='store_true')\n"
        '    args = parser.parse_args(argv)\n'
        '    try:\n'
        "        if args.command == 'validate':\n"
        '            result = validate(args.input, args.opalx, args.output, args.timeout, args.allow_review)\n'
        '            print(json.dumps(result, indent=2))\n'
        "            return int(not result['execution_passed'])\n"
        '        if args.report and args.report.exists():\n'
        "            raise InputError('Report already exists')\n"
        "        if args.command in ('batch', 'inventory'):\n"
        '            root = args.input.resolve()\n'
        '            if not root.is_dir():\n'
        "                raise InputError('Batch input must be a directory')\n"
        "            if args.command == 'batch' and (args.output.exists() or args.output.resolve().is_relative_to(root)):\n"
        "                raise InputError('Batch output must be new and outside input tree')\n"
        "            entries = sorted(root.rglob('*.in'))\n"
        '            if not entries:\n'
        "                raise InputError('No .in files found')\n"
        "            reports = [process(p, args.output / p.relative_to(root).with_suffix('.in.opalx') if args.command == 'batch' else None) for p in entries]\n"
        '        else:\n'
        "            reports = [process(args.input, args.output if args.command == 'convert' else None)]\n"
        "        result = {'tool_version': VERSION, 'ruleset': RULESET,\n"
        "                  'summary': dict(sorted(Counter(r['status'] for r in reports).items())), 'cases': reports}\n"
        "        rendered = json.dumps(result, indent=2) + '\\n'\n"
        '        if args.report:\n'
        "            with args.report.open('x', encoding='utf-8') as f:\n"
        '                f.write(rendered)\n'
        "        print(rendered, end='')\n"
        '        for report in reports:\n'
        "            for file in report.get('files', []):\n"
        "                for change in file.get('changes', []):\n"
        "                    if change.get('rule') == 'legacy-cyclotron-sectors':\n"
        "                        print(change['reason'], file=sys.stderr)\n"
        "        return int(any(r['status'] != 'converted' for r in reports))\n"
        '    except (OSError, InputError) as exc:\n'
        "        print('opal2opalx: ' + str(exc), file=sys.stderr)\n"
        '        return 2\n'
        '\n'
        '\n'
        "if __name__ == '__main__':\n"
        '    sys.exit(main())\n'
    ),
    'astra': (
        '#!/usr/bin/env python3\n'
        '"""Standalone, standard-library-only ASTRA-to-OPALX converter (Python 3.9+).\n'
        '\n'
        'The namelist parser deliberately accepts a scalar subset of Fortran namelists.\n'
        'Unsupported syntax or physics is refused instead of guessing its meaning.\n'
        'Use inspect to classify a deck; convert supports injected electrons, on-axis RF\n'
        'solenoid/quadrupole fields, circular apertures, and planar dipole-only lines,\n'
        'with optional open, average-rest-frame 3D space charge.\n'
        'Lattice conversion candidates require review.\n'
        '"""\n'
        '\n'
        'from __future__ import annotations\n'
        '\n'
        'import math\n'
        'import bisect\n'
        'import hashlib\n'
        'from pathlib import Path\n'
        'import re\n'
        'from typing import Dict, Tuple, Union\n'
        '\n'
        '\n'
        'Scalar = Union[str, int, float, bool, Tuple[float, float]]\n'
        'Namelists = Dict[str, Dict[str, Scalar]]\n'
        '\n'
        '_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]*")\n'
        '_KEY = re.compile(\n'
        '    r"([A-Za-z][A-Za-z0-9_]*)(?:\\s*\\(\\s*([0-9]+)"\n'
        '    r"(?:\\s*,\\s*([0-9]+))?\\s*\\))?\\s*="\n'
        ')\n'
        '_INTEGER = re.compile(r"[+-]?[0-9]+\\Z")\n'
        '_REAL = re.compile(\n'
        '    r"[+-]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eEdD][+-]?[0-9]+)?\\Z"\n'
        ')\n'
        '_PAIR_NUMBER = re.compile(\n'
        '    r"[+-]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eEdD][+-]?[0-9]+)?"\n'
        ')\n'
        '\n'
        '\n'
        'class ConversionError(ValueError):\n'
        '    """An input cannot be interpreted safely within the supported subset."""\n'
        '\n'
        '\n'
        'def _skip_layout(text: str, position: int, *, commas: bool = False) -> int:\n'
        '    """Skip whitespace and outside-string comments, optionally also commas."""\n'
        '    while position < len(text):\n'
        '        if text[position].isspace() or (commas and text[position] == ","):\n'
        '            position += 1\n'
        '        elif text[position] == "!":\n'
        '            end = text.find("\\n", position)\n'
        '            position = len(text) if end < 0 else end + 1\n'
        '        else:\n'
        '            break\n'
        '    return position\n'
        '\n'
        '\n'
        'def _read_value(text: str, position: int) -> Tuple[Scalar, int]:\n'
        '    """Read one quoted string, Boolean, integer, or finite real literal."""\n'
        '    if position >= len(text) or text[position] in ",/!&":\n'
        '        raise ConversionError("Missing scalar value")\n'
        '    if text[position] in "\\"\'":\n'
        '        quote = text[position]\n'
        '        position += 1\n'
        '        characters = []\n'
        '        while position < len(text):\n'
        '            character = text[position]\n'
        '            position += 1\n'
        '            if character == quote:\n'
        '                if position < len(text) and text[position] == quote:\n'
        '                    characters.append(quote)\n'
        '                    position += 1\n'
        '                else:\n'
        '                    return "".join(characters), position\n'
        '            elif character in "\\r\\n":\n'
        '                raise ConversionError("Multiline character literals are unsupported")\n'
        '            else:\n'
        '                characters.append(character)\n'
        '        raise ConversionError("Unterminated quoted string")\n'
        '\n'
        '    end = position\n'
        '    while end < len(text) and not text[end].isspace() and text[end] not in ",/!":\n'
        '        end += 1\n'
        '    token = text[position:end]\n'
        '    lowered = token.lower()\n'
        '    if lowered in {".true.", "t"}:\n'
        '        return True, end\n'
        '    if lowered in {".false.", "f"}:\n'
        '        return False, end\n'
        '    if _INTEGER.fullmatch(token):\n'
        '        return int(token), end\n'
        '    if _REAL.fullmatch(token):\n'
        '        value = float(token.replace("D", "e").replace("d", "e"))\n'
        '        if math.isfinite(value):\n'
        '            return value, end\n'
        '        raise ConversionError("Nonfinite real literal: " + token)\n'
        '    raise ConversionError("Unsupported scalar value: " + repr(token))\n'
        '\n'
        '\n'
        'def _read_coordinate_pair(text: str, position: int) -> Tuple[Tuple[float, float], int]:\n'
        '    """Read ASTRA\'s finite numeric ``(transverse, z)`` dipole coordinate."""\n'
        '    if position >= len(text) or text[position] != "(":\n'
        '        raise ConversionError("Expected a dipole coordinate pair")\n'
        '    position += 1\n'
        '    coordinates = []\n'
        '    for separator in (",", ")"):\n'
        '        position = _skip_layout(text, position)\n'
        '        match = _PAIR_NUMBER.match(text, position)\n'
        '        if not match:\n'
        '            raise ConversionError("Dipole coordinates require two numeric literals")\n'
        '        value = float(match.group().replace("D", "e").replace("d", "e"))\n'
        '        if not math.isfinite(value):\n'
        '            raise ConversionError("Dipole coordinates must be finite")\n'
        '        coordinates.append(value)\n'
        '        position = _skip_layout(text, match.end())\n'
        '        if position >= len(text) or text[position] != separator:\n'
        '            raise ConversionError("Dipole coordinates require \'(transverse, z)\'")\n'
        '        position += 1\n'
        '    return (coordinates[0], coordinates[1]), position\n'
        '\n'
        '\n'
        'def parse_namelists(text: str) -> Namelists:\n'
        '    """Parse ASTRA\'s scalar namelist subset without evaluating expressions.\n'
        '\n'
        '    Group and attribute names are case insensitive and returned in lowercase.\n'
        '    Nonnegative array indices are retained in canonical form, for example\n'
        '    ``Q_Grad( 01 )`` becomes ``q_grad(1)``. Only ``D_Gap`` in ``&DIPOLE`` may\n'
        '    have two indices. Only indexed ``D1`` through ``D4`` in ``&DIPOLE`` may use\n'
        '    finite numeric coordinate pairs, returned as two-float tuples. Assignments\n'
        '    must be separated by a comma or a newline; groups end with an unquoted slash.\n'
        '    Duplicate groups/keys, slices, lists, repetition, other complex values and\n'
        '    executable expressions are rejected. Scalar types are retained.\n'
        '    """\n'
        '    groups: Namelists = {}\n'
        '    position = _skip_layout(text, 0)\n'
        '    while position < len(text):\n'
        '        if text[position] != "&":\n'
        '            raise ConversionError("Expected \'&namelist\' at character " + str(position))\n'
        '        match = _NAME.match(text, position + 1)\n'
        '        if not match:\n'
        '            raise ConversionError("Missing namelist name at character " + str(position))\n'
        '        group_name = match.group().lower()\n'
        '        if group_name in groups:\n'
        '            raise ConversionError("Duplicate namelist: " + group_name)\n'
        '        values: Dict[str, Scalar] = {}\n'
        '        position = match.end()\n'
        '\n'
        '        while True:\n'
        '            position = _skip_layout(text, position, commas=True)\n'
        '            if position >= len(text):\n'
        '                raise ConversionError("Unterminated namelist: " + group_name)\n'
        '            if text[position] == "/":\n'
        '                position += 1\n'
        '                break\n'
        '            match = _KEY.match(text, position)\n'
        '            if not match:\n'
        '                raise ConversionError(\n'
        '                    "Expected scalar assignment in &" + group_name\n'
        '                    + " at character " + str(position)\n'
        '                )\n'
        '            key = match.group(1).lower()\n'
        '            if match.group(2) is not None:\n'
        '                indices = str(int(match.group(2)))\n'
        '                if match.group(3) is not None:\n'
        '                    if group_name != "dipole" or key != "d_gap":\n'
        '                        raise ConversionError("Two indices are supported only for &DIPOLE D_Gap")\n'
        '                    indices += "," + str(int(match.group(3)))\n'
        '                key += "(" + indices + ")"\n'
        '            if key in values:\n'
        '                raise ConversionError("Duplicate attribute in &" + group_name + ": " + key)\n'
        '            position = _skip_layout(text, match.end())\n'
        '            if (group_name == "dipole" and match.group(1).lower() in {"d1", "d2", "d3", "d4"}\n'
        '                    and match.group(2) is not None and position < len(text)\n'
        '                    and text[position] == "("):\n'
        '                value, position = _read_coordinate_pair(text, position)\n'
        '            else:\n'
        '                value, position = _read_value(text, position)\n'
        '            values[key] = value\n'
        '\n'
        '            # Horizontal whitespace is allowed here, but another value or key\n'
        '            # on the same line still needs a comma. Keep the newline significant.\n'
        '            while position < len(text) and text[position] in " \\t\\v\\f":\n'
        '                position += 1\n'
        '            if position < len(text) and text[position] not in ",\\r\\n/!":\n'
        '                raise ConversionError(\n'
        '                    "Expected a comma, newline, or \'/\' after " + group_name + "." + key\n'
        '                )\n'
        '\n'
        '        groups[group_name] = values\n'
        '        position = _skip_layout(text, position)\n'
        '    return groups\n'
        '\n'
        '# On-axis map adapters. ASTRA preprocessing was verified against native\n'
        '# RF/solenoid controls; interpolation onto OPALX maps is reported separately.\n'
        'MU_0 = 1.25663706212e-6\n'
        'C_LIGHT = 299792458.0\n'
        '\n'
        'def read_axis_map(text: str) -> list:\n'
        '    """Read a finite ASCII z[m],field table without silently discarding rows.\n'
        '\n'
        '    Blank lines and Fortran ``!`` comments are allowed. Commas and whitespace\n'
        '    delimit the two numeric values; Fortran D exponents are accepted. A strict\n'
        "    gap above 1e-10 m avoids OPALX's native point-skipping rule. Three points are\n"
        '    required by its cubic-spline interpolation. No scaling or sign changes are\n'
        '    made here. All-zero maps are refused before the native normalization stage.\n'
        '    """\n'
        '    try:\n'
        "        text.encode('ascii')\n"
        '    except UnicodeError as exc:\n'
        "        raise ConversionError('Field map must be ASCII') from exc\n"
        '    rows = []\n'
        '    for line_number, line in enumerate(text.splitlines(), 1):\n'
        "        line = line.split('!', 1)[0].strip()\n"
        '        if not line:\n'
        '            continue\n'
        "        tokens = line.replace(',', ' ').split()\n"
        '        if len(tokens) != 2:\n'
        "            raise ConversionError(f'Field map line {line_number}: need exactly two columns')\n"
        '        try:\n'
        "            z, field = (float(v.replace('D', 'e').replace('d', 'e')) for v in tokens)\n"
        '        except ValueError as exc:\n'
        "            raise ConversionError(f'Field map line {line_number}: invalid numeric value') from exc\n"
        '        if not math.isfinite(z) or not math.isfinite(field):\n'
        "            raise ConversionError(f'Field map line {line_number}: need finite values')\n"
        '        if rows and z - rows[-1][0] <= 1e-10:\n'
        "            raise ConversionError(f'Field map line {line_number}: z spacing must exceed 1e-10 m')\n"
        '        rows.append((z, field))\n'
        '    if len(rows) < 3:\n'
        "        raise ConversionError('Field map requires at least three points for native interpolation')\n"
        '    if not any(field != 0 for _, field in rows):\n'
        "        raise ConversionError('Field map has zero peak amplitude')\n"
        '    return rows\n'
        '\n'
        '\n'
        'def smooth_axis_map(rows: list, iterations: int, *, order: str) -> list:\n'
        '    """Apply the manual Appendix-I weighted-neighbor recurrence, explicitly.\n'
        '\n'
        '    For each interior point, F_i becomes the value interpolated linearly between\n'
        "    F_(i-1) and F_(i+1). Endpoints stay fixed. ``order='simultaneous'`` reads the\n"
        "    previous iteration; ``order='forward'`` reads each newly updated left point.\n"
        '    The ASTRA manual states the recurrence but does not specify update ordering\n'
        '    or endpoint handling. Isolated RF/solenoid controls against ASTRA 4.0 match\n'
        '    simultaneous updates and fixed endpoints; this helper keeps order explicit.\n'
        '    Returned input/output coordinates and field units are unchanged. The caller\n'
        '    owns the choice of peak normalization before or after this operation.\n'
        '    """\n'
        '    if isinstance(iterations, bool) or not isinstance(iterations, int) or iterations < 0:\n'
        "        raise ConversionError('Map smoothing iterations must be a nonnegative integer')\n"
        "    if order not in ('simultaneous', 'forward'):\n"
        "        raise ConversionError('Map smoothing order must be simultaneous or forward')\n"
        '    result = list(rows)\n'
        '    for _ in range(iterations):\n'
        "        previous = result[:] if order == 'simultaneous' else result\n"
        '        for i in range(1, len(result) - 1):\n'
        '            z = result[i][0]\n'
        '            zl, fl = previous[i - 1]\n'
        '            zr, fr = previous[i + 1]\n'
        '            value = fl + (fr - fl) * ((z - zl) / (zr - zl))\n'
        '            if not math.isfinite(value):\n'
        "                raise ConversionError('Map smoothing produced a nonfinite field')\n"
        '            result[i] = (z, value)\n'
        '    return result\n'
        '\n'
        '\n'
        'def scale_axis_map(rows: list, amplitude: float) -> list:\n'
        '    """Scale a smoothed profile by ASTRA\'s signed absolute-peak sample.\n'
        '\n'
        '    ASTRA chooses the first sample with largest absolute value, then scales that\n'
        '    signed sample to MaxE [MV/m] or MaxB [T]. The sign of the profile can therefore\n'
        '    flip when its largest-magnitude peak is negative. Apply smoothing first.\n'
        '    The unit/sign/order contract was verified with isolated RF and solenoid\n'
        '    trajectory controls, including tied opposite-sign peaks. ``noscale`` callers\n'
        '    bypass this function so the physical field values/sign remain untouched.\n'
        '    """\n'
        '    if (isinstance(amplitude, bool) or not isinstance(amplitude, (int, float))\n'
        '            or not math.isfinite(amplitude) or amplitude == 0):\n'
        "        raise ConversionError('Map amplitude must be finite and nonzero')\n"
        '    if not rows:\n'
        "        raise ConversionError('Cannot normalize an empty map')\n"
        '    peak = max(rows, key=lambda row: abs(row[1]))[1]\n'
        '    if peak == 0:\n'
        "        raise ConversionError('Cannot normalize a zero-peak map after smoothing')\n"
        '    scaled = [(z, field * (amplitude / peak)) for z, field in rows]\n'
        '    if not all(math.isfinite(field) for _, field in scaled):\n'
        "        raise ConversionError('Map amplitude scaling produced a nonfinite field')\n"
        '    return scaled\n'
        '\n'
        '\n'
        'def render_axis_map(rows: list, kind: str, *, accuracy: int,\n'
        '                    normalize: bool, frequency_MHz=None) -> str:\n'
        '    """Wrap samples for OPALX\'s native Fourier on-axis field-map readers.\n'
        '\n'
        '    This preserves every sample, its coordinate, sign and magnitude. The caller\n'
        "    must review the native Fourier and cubic off-axis model against ASTRA's\n"
        '    requested interpolation/expansion. ``normalize=True`` selects native peak\n'
        '    absolute-value normalization; ``False`` treats RF values as MV/m, or\n'
        "    solenoid values as T. RF frequency is explicitly in MHz, not ASTRA's GHz.\n"
        '    """\n'
        "    if kind not in ('rf', 'solenoid'):\n"
        "        raise ConversionError('Native map kind must be rf or solenoid')\n"
        '    if isinstance(accuracy, bool) or not isinstance(accuracy, int) or not 2 <= accuracy <= len(rows):\n'
        "        raise ConversionError('Native Fourier accuracy must be between 2 and map point count')\n"
        '    if not isinstance(normalize, bool):\n'
        "        raise ConversionError('Native normalization flag must be logical')\n"
        "    if kind == 'rf':\n"
        '        if (isinstance(frequency_MHz, bool) or not isinstance(frequency_MHz, (int, float))\n'
        '                or not math.isfinite(frequency_MHz) or frequency_MHz <= 0):\n'
        "            raise ConversionError('RF map frequency must be positive finite MHz')\n"
        "        header = f'AstraDynamic {accuracy} {str(normalize).upper()}\\n{frequency_MHz:.17g}\\n'\n"
        '    else:\n'
        '        if frequency_MHz is not None:\n'
        "            raise ConversionError('A solenoid map must not specify RF frequency')\n"
        "        header = f'AstraMagnetoStatic {accuracy} {str(normalize).upper()}\\n'\n"
        "    return header + ''.join(f'{z:.17g} {field:.17g}\\n' for z, field in rows)\n"
        '\n'
        '\n'
        'def _validate_rf_rows(rows: list) -> list:\n'
        '    """Copy at least three finite, strictly increasing z[m],field samples."""\n'
        '    result = []\n'
        '    for row in rows:\n'
        '        if len(row) != 2:\n'
        "            raise ConversionError('RF axis map rows need two columns')\n"
        '        z, field = row\n'
        '        if (isinstance(z, bool) or isinstance(field, bool)\n'
        '                or not isinstance(z, (int, float)) or not isinstance(field, (int, float))\n'
        '                or not math.isfinite(z) or not math.isfinite(field)):\n'
        "            raise ConversionError('RF axis map needs finite numeric samples')\n"
        '        if result and z - result[-1][0] <= 1e-10:\n'
        "            raise ConversionError('RF axis map z spacing must exceed 1e-10 m')\n"
        '        result.append((float(z), float(field)))\n'
        '    if len(result) < 3:\n'
        "        raise ConversionError('RF axis map needs at least three points')\n"
        '    if not any(field != 0 for _, field in result):\n'
        "        raise ConversionError('RF axis map has zero peak amplitude')\n"
        '    return result\n'
        '\n'
        '\n'
        'def rf_axis_derivatives(rows: list) -> list:\n'
        '    """Reproduce ASTRA\'s first-order RF gradient table on a uniform grid.\n'
        '\n'
        '    Interior slopes average the two adjacent secants. Five-point boundary\n'
        '    stencils were established with ASTRA-only basis-profile/tiny-kick controls.\n'
        '    Nonuniform grids are refused until their boundary operator is established;\n'
        '    guessing a quadratic endpoint derivative changes the transverse force.\n'
        '    """\n'
        '    rows = _validate_rf_rows(rows)\n'
        '    if len(rows) < 5:\n'
        "        raise ConversionError('ASTRA field tables need at least five samples')\n"
        '    h = (rows[-1][0] - rows[0][0]) / (len(rows) - 1)\n'
        '    if any(not math.isclose(right[0]-left[0], h, rel_tol=1e-8, abs_tol=1e-12)\n'
        '           for left, right in zip(rows, rows[1:])):\n'
        "        raise ConversionError('First-order RF currently requires a uniform source grid')\n"
        '    secants = [(right[1]-left[1])/(right[0]-left[0])\n'
        '               for left, right in zip(rows, rows[1:])]\n'
        '    f = [field for _, field in rows]\n'
        '    first = (-13*f[0]+16*f[1]+2*f[2]-8*f[3]+3*f[4])/(8*h)\n'
        '    last = (13*f[-1]-16*f[-2]-2*f[-3]+8*f[-4]-3*f[-5])/(8*h)\n'
        '    slopes = [first] + [(left+right)/2 for left,right in zip(secants,secants[1:])] + [last]\n'
        '    if not all(math.isfinite(slope) for slope in slopes):\n'
        "        raise ConversionError('RF axis derivative overflow')\n"
        '    return slopes\n'
        '\n'
        '\n'
        'def _evaluate_rf_linear_prepared(rows: list, slopes: list, coordinates: list,\n'
        '                                 z: float) -> tuple:\n'
        '    """Interpolate validated samples using a prepared z lookup.\n'
        '\n'
        '    Callers validate matching finite slopes and increasing rows once. Reusing\n'
        '    coordinates avoids scanning the entire source table for every map sample.\n'
        '    """\n'
        '    if isinstance(z, bool) or not math.isfinite(z) or z < rows[0][0] or z > rows[-1][0]:\n'
        "        raise ConversionError('RF interpolation requires a finite in-range coordinate')\n"
        '    index = max(0,min(len(rows)-2,bisect.bisect_right(coordinates,z)-1))\n'
        '    z0,f0 = rows[index];z1,f1 = rows[index+1]\n'
        '    w = (z-z0)/(z1-z0)\n'
        '    return f0+(f1-f0)*w, slopes[index]+(slopes[index+1]-slopes[index])*w\n'
        '\n'
        '\n'
        'def evaluate_rf_linear(rows: list, slopes: list, z: float) -> tuple:\n'
        '    """Interpolate E0 and its independently tabulated derivative linearly.\n'
        '\n'
        '    ASTRA-only densification controls establish piecewise-linear on-axis fields.\n'
        '    Extrapolation is refused. Derivatives are separately interpolated, matching\n'
        "    the first-order expansion's tabulated-gradient interpretation.\n"
        '    """\n'
        '    if len(slopes) != len(rows) or not all(math.isfinite(v) for v in slopes):\n'
        "        raise ConversionError('RF slopes must match the finite axis samples')\n"
        '    if isinstance(z, bool) or not math.isfinite(z) or z < rows[0][0] or z > rows[-1][0]:\n'
        "        raise ConversionError('RF interpolation requires a finite in-range coordinate')\n"
        '    return _evaluate_rf_linear_prepared(rows, slopes, [r[0] for r in rows], z)\n'
        '\n'
        '\n'
        'def render_first_order_rf_map(rows: list, frequency_MHz: float, *,\n'
        '                              radius_m: float = 0.01, z_subdivisions: int = 4) -> dict:\n'
        '    """Emit a normalized OPALX 2DDynamic XZ map and its interpolation metadata.\n'
        '\n'
        'The file header uses centimetres and MHz. Each row contains Ez[MV/m], Er[MV/m],\n'
        'unused zero, Htheta[A/m]. In the first-order ASTRA TM model,\n'
        '\n'
        "    Ez = E0(z), Er = -r E0'(z)/2, Btheta = r omega E0(z)/(2 c**2).\n"
        '\n'
        'E0 is normalized by the maximum absolute value on the emitted longitudinal\n'
        'grid, without introducing smooth-interpolant overshoot. The two radial samples are at 0 and\n'
        'radius_m; bilinear interpolation is exact in r for this model. z_subdivisions\n'
        'sets the number of uniform target intervals per input interval on average.\n'
        "The target reader's default normalization leaves the unit peak unchanged.\n"
        '\n'
        'The caller first applies ASTRA smoothing and physical signed-peak scaling.\n'
        "Use VOLT=metadata['interpolated_peak'] to recover that physical MV/m profile,\n"
        'including target-grid sampling; do not renormalize it a second time.\n'
        'Coordinates remain in the input map frame; C_pos belongs to the element pose.\n'
        '"""\n'
        '    rows = _validate_rf_rows(rows)\n'
        "    for name, value in [('RF frequency', frequency_MHz), ('RF radius', radius_m)]:\n"
        '        if (isinstance(value, bool) or not isinstance(value, (int, float))\n'
        '                or not math.isfinite(value) or value <= 0):\n'
        "            raise ConversionError(name + ' must be positive and finite')\n"
        '    if (isinstance(z_subdivisions, bool) or not isinstance(z_subdivisions, int)\n'
        '            or z_subdivisions < 1):\n'
        "        raise ConversionError('RF subdivisions must be a positive integer')\n"
        '    intervals = (len(rows) - 1) * z_subdivisions\n'
        '    slopes = rf_axis_derivatives(rows)\n'
        '    coordinates = [row[0] for row in rows]\n'
        '    z0, z1 = rows[0][0], rows[-1][0]\n'
        '    profile = []\n'
        '    for i in range(intervals + 1):\n'
        '        z = z1 if i == intervals else z0 + (z1 - z0) * i / intervals\n'
        '        value, derivative = _evaluate_rf_linear_prepared(rows, slopes, coordinates, z)\n'
        '        profile.append((value, derivative))\n'
        '    peak = max(abs(value) for value, _ in profile)\n'
        '    if peak == 0 or not math.isfinite(peak):\n'
        "        raise ConversionError('Resampled RF map has invalid peak amplitude')\n"
        '    omega = 2 * math.pi * frequency_MHz * 1e6\n'
        '    magnetic_factor = omega * 1e6 / (2 * C_LIGHT * C_LIGHT * MU_0)\n'
        "    lines = ['2DDynamic XZ', f'{100*z0:.17g} {100*z1:.17g} {intervals}',\n"
        "             f'{frequency_MHz:.17g}', f'0 {100*radius_m:.17g} 1']\n"
        '    for radius in (0.0, radius_m):\n'
        '        for value, derivative in profile:\n'
        '            ez = value / peak\n'
        '            er = -radius * (derivative / peak) / 2\n'
        '            htheta = radius * magnetic_factor * ez\n'
        '            if not all(math.isfinite(v) for v in (ez, er, htheta)):\n'
        "                raise ConversionError('RF map field conversion overflow')\n"
        "            lines.append(f'{ez:.17g} {er:.17g} 0 {htheta:.17g}')\n"
        "    return {'text': '\\n'.join(lines) + '\\n', 'metadata': {\n"
        "        'interpolation': 'piecewise-linear field and independently interpolated nodal derivative',\n"
        "        'target_interpolation': 'bilinear; exact radial dependence for first-order RF',\n"
        "        'expansion_order': 1, 'input_points': len(rows),\n"
        "        'target_z_points': intervals + 1, 'target_radial_points': 2,\n"
        "        'z_subdivisions': z_subdivisions, 'radius_m': radius_m,\n"
        "        'input_peak': max(abs(field) for _, field in rows),\n"
        "        'interpolated_peak': peak, 'native_peak_normalized': True,\n"
        "        'field_columns': ['Ez_MV_per_m', 'Er_MV_per_m', 'unused_zero', 'Htheta_A_per_m'],\n"
        '    }}\n'
        '\n'
        '\n'
        'def astra_absolute_rf_lag(phase_deg: float, frequency_MHz: float,\n'
        '                          clock_origin_s: float = 0.0) -> float:\n'
        '    """Translate ASTRA absolute sine phase to OPALX cosine phase in radians.\n'
        '\n'
        'OPALX starts at t=0; the ASTRA absolute time is t+clock_origin_s. This helper\n'
        'does not perform autophasing or interpret input phases relative to the crest.\n'
        'Returned phases are reduced to [-pi,pi], modulo the physically periodic cycle.\n'
        '"""\n'
        '    for value in (phase_deg, frequency_MHz, clock_origin_s):\n'
        '        if (isinstance(value, bool) or not isinstance(value, (int, float))\n'
        '                or not math.isfinite(value)):\n'
        "            raise ConversionError('RF phase, frequency and clock must be finite numbers')\n"
        '    if frequency_MHz <= 0:\n'
        "        raise ConversionError('RF phase conversion frequency must be positive')\n"
        '    phase = math.radians(phase_deg) - math.pi / 2 + 2 * math.pi * frequency_MHz * 1e6 * clock_origin_s\n'
        '    if not math.isfinite(phase):\n'
        "        raise ConversionError('RF phase conversion overflow')\n"
        '    return math.remainder(phase, 2 * math.pi)\n'
        '\n'
        '\n'
        '# The target mass is explicit so the eV/c -> p/(mc) conversion is reproducible.\n'
        'ELECTRON_REST_EV = 510998.95000  # OPALX Physics::m_e [GeV] * 1e9\n'
        'C_LIGHT = 299792458.0\n'
        "VERSION = '0.7.0'\n"
        '\n'
        '\n'
        'def read_particles(text: str) -> dict:\n'
        '    """Decode an equal-weight electron snapshot, including ASTRA\'s first row.\n'
        '\n'
        '    x,y,z are metres; px,py,pz are eV/c; clocks are ns; charges are nC.\n'
        '    Only z,pz,clock on subsequent rows are relative to row zero. Status 3\n'
        '    (active trajectory probe) and 5 (active standard particle) carry charge\n'
        '    and enter the statistics. Lost/passive/cathode and mixed species are refused.\n'
        '    """\n'
        '    rows = []\n'
        '    for line_number, line in enumerate(text.splitlines(), 1):\n'
        "        line = line.split('!', 1)[0].strip()\n"
        '        if not line:\n'
        '            continue\n'
        '        try:\n'
        "            row = [float(v.replace('D', 'e').replace('d', 'e')) for v in line.split()]\n"
        '        except ValueError as exc:\n'
        "            raise ConversionError(f'Particle line {line_number}: expected numeric ASCII columns') from exc\n"
        '        if len(row) != 10 or not all(math.isfinite(v) for v in row):\n'
        "            raise ConversionError(f'Particle line {line_number}: need ten finite columns')\n"
        '        if row[8] != 1 or row[9] not in (3, 5):\n'
        "            raise ConversionError(f'Particle line {line_number}: only active electron status 3/5 supported')\n"
        '        if row[7] == 0:\n'
        "            raise ConversionError('Zero-charge particles are not supported in this pilot')\n"
        '        rows.append(row)\n'
        '    if not rows:\n'
        "        raise ConversionError('Empty particle distribution')\n"
        '    q = abs(rows[0][7])\n'
        '    if any(not math.isclose(abs(r[7]), q, rel_tol=1e-12, abs_tol=0) for r in rows):\n'
        "        raise ConversionError('Unequal macroparticle charges require weighted-particle support')\n"
        '    ref = rows[0]\n'
        '    particles = []\n'
        '    for i, row in enumerate(rows):\n'
        '        z = row[2] + (ref[2] if i else 0)\n'
        '        pz = row[5] + (ref[5] if i else 0)\n'
        '        clock = row[6] + (ref[6] if i else 0)\n'
        '        if not math.isclose(clock, ref[6], rel_tol=0, abs_tol=1e-9):  # ns; 1e-18 s\n'
        "            raise ConversionError('Unequal snapshot clocks/cathode emission require timed injection support')\n"
        '        if pz <= 0:\n'
        "            raise ConversionError('Only forward-going injected particles are supported')\n"
        '        if not math.isfinite(z) or not math.isfinite(pz):\n'
        "            raise ConversionError('Reference-relative coordinates overflow')\n"
        '        particles.append([row[0], row[1], z, row[3]/ELECTRON_REST_EV,\n'
        '                          row[4]/ELECTRON_REST_EV, pz/ELECTRON_REST_EV])\n'
        '    charge = -math.fsum(abs(r[7])*1e-9 for r in rows)\n'
        '    if not math.isfinite(charge):\n'
        "        raise ConversionError('Total charge is not finite')\n"
        "    return {'particles': particles, 'count': len(rows),\n"
        "            'charge_C': charge,\n"
        "            'clock_origin_s': ref[6]*1e-9,\n"
        "            'reference_row_included': True, 'reference_z_m': ref[2],\n"
        "            'status_counts': {str(s): sum(r[9] == s for r in rows) for s in (3, 5)}}\n"
        '\n'
        '\n'
        'def center_launch_sample(sample: dict) -> tuple:\n'
        '    """Translate an injected snapshot to its centroid without changing momenta.\n'
        '\n'
        '    Return an independent particle table and the source-frame origin [m].\n'
        '    Source positions equal target positions plus this origin. Charge, clock,\n'
        '    population and status metadata are preserved; no particle is propagated.\n'
        '    """\n'
        "    rows = sample.get('particles', [])\n"
        "    count = sample.get('count')\n"
        '    if (isinstance(count, bool) or not isinstance(count, int) or count < 1\n'
        '            or len(rows) != count):\n'
        "        raise ConversionError('Launch centering requires a nonempty consistent particle table')\n"
        '    if any(len(row) != 6 or any(isinstance(v, bool) or not isinstance(v, (int, float))\n'
        '                              or not math.isfinite(v) for v in row) for row in rows):\n'
        "        raise ConversionError('Launch centering requires six finite particle coordinates')\n"
        '    origin = [math.fsum(row[d]/count for row in rows) for d in range(3)]\n'
        '    translated = [[row[d]-origin[d] for d in range(3)]+list(row[3:]) for row in rows]\n'
        '    if any(not math.isfinite(v) for row in translated for v in row):\n'
        "        raise ConversionError('Centered launch coordinates overflow')\n"
        '    result = dict(sample, particles=translated)\n'
        "    result['reference_z_m'] = sample['reference_z_m']-origin[2]\n"
        '    return result, origin\n'
        '\n'
        '\n'
        'def _field_real(value, name: str) -> float:\n'
        '    """Require a finite numeric field parameter without accepting logicals."""\n'
        '    if (isinstance(value, bool) or not isinstance(value, (int, float))\n'
        '            or not math.isfinite(value)):\n'
        "        raise ConversionError(name + ' must be a finite number')\n"
        '    return float(value)\n'
        '\n'
        '\n'
        'def _field_logical(value, name: str) -> bool:\n'
        '    """Require an ASTRA logical field parameter without truth-value coercion."""\n'
        '    if not isinstance(value, bool):\n'
        "        raise ConversionError(name + ' must be logical')\n"
        '    return value\n'
        '\n'
        '\n'
        'def field_specs(groups: dict) -> list:\n'
        '    """Validate indexed RF/solenoid settings and return normalized map specs.\n'
        '\n'
        '    Maps must form contiguous 1..N arrays. Only Phi(0), a global RF phase in\n'
        '    degrees, may use index zero. Active maps support straight, on-axis placement;\n'
        '    nonzero offsets/rotations, special RF file modes, and first-order solenoids\n'
        '    are refused. Inactive groups do not load files. Space-charge and other\n'
        '    namelists are assessed by the enclosing converter, not by this helper.\n'
        '    """\n'
        '    specs = []\n'
        "    nr = groups.get('newrun', {})\n"
        "    auto_phase = _field_logical(nr.get('auto_phase', True), 'NEWRUN.Auto_phase')\n"
        "    configurations = [('cavity', 'rf', 'lefield', 'c', 'file_efield', 'maxe'),\n"
        "                      ('solenoid', 'solenoid', 'lbfield', 's', 'file_bfield', 'maxb')]\n"
        '    for group, kind, switch, prefix, file_key, amplitude_key in configurations:\n'
        '        values = groups.get(group, {})\n'
        "        active = _field_logical(values.get(switch, False), group + '.' + switch)\n"
        '        if not active:\n'
        '            continue\n'
        "        _field_logical(values.get('loop', False), group + '.LOOP')\n"
        "        if values.get('loop', False):\n"
        "            raise ConversionError(group + '.LOOP is unsupported')\n"
        "        allowed = {file_key, amplitude_key, prefix+'_pos', prefix+'_noscale',\n"
        "                   prefix+'_smooth', prefix+'_higher_order', prefix+'_xoff',\n"
        "                   prefix+'_yoff', prefix+'_xrot', prefix+'_yrot'}\n"
        "        if kind == 'rf':\n"
        "            allowed.update(('nue', 'phi'))\n"
        '        indices = set()\n'
        '        for key in values:\n'
        "            if key in (switch, 'loop'):\n"
        '                continue\n'
        "            match = re.fullmatch(r'([a-z][a-z0-9_]*)\\(([0-9]+)\\)', key)\n"
        '            if not match or match.group(1) not in allowed:\n'
        "                raise ConversionError(f'Unsupported active {group}.{key}')\n"
        '            base, index = match.group(1), int(match.group(2))\n'
        '            if index == 0:\n'
        "                if kind == 'rf' and base == 'phi':\n"
        '                    continue\n'
        "                raise ConversionError(f'Index zero is unsupported for {group}.{base}')\n"
        '            indices.add(index)\n'
        '        if not indices or sorted(indices) != list(range(1, len(indices)+1)):\n'
        "            raise ConversionError(group + ' map indices must be contiguous 1..N')\n"
        "        global_phase = (_field_real(values.get('phi(0)', 0.), 'cavity.Phi(0)')\n"
        "                        if kind == 'rf' else 0.)\n"
        '        for index in sorted(indices):\n'
        '            def parameter(key, default=None):\n'
        "                return values.get(f'{key}({index})', default)\n"
        '\n'
        '            filename = parameter(file_key)\n'
        '            if (not isinstance(filename, str) or not filename.strip()\n'
        "                    or any(c in filename for c in '\\0\\r\\n')):\n"
        "                raise ConversionError(f'{group}.{file_key}({index}) requires a nonempty filename')\n"
        '            mode = Path(filename).name.lower()\n'
        "            if kind == 'rf' and (mode.startswith(('tws', 'te_', 'dc')) or mode == 'plasma'):\n"
        "                raise ConversionError('Only ordinary standing-wave TM RF map files are supported')\n"
        "            position = _field_real(parameter(prefix+'_pos', 0.), f'{group} position({index})')\n"
        "            for suffix in ('xoff', 'yoff', 'xrot', 'yrot'):\n"
        "                value = _field_real(parameter(prefix+'_'+suffix, 0.), f'{group} {suffix}({index})')\n"
        '                if value != 0:\n'
        "                    raise ConversionError(f'Nonzero {group}.{prefix}_{suffix}({index}) is unsupported')\n"
        "            noscale = _field_logical(parameter(prefix+'_noscale', False), f'{group} noscale({index})')\n"
        "            higher_order = _field_logical(parameter(prefix+'_higher_order', kind == 'solenoid'),\n"
        "                                           f'{group} higher_order({index})')\n"
        "            if kind == 'solenoid' and not higher_order:\n"
        "                raise ConversionError('First-order solenoid expansion is unsupported')\n"
        "            smooth = parameter(prefix+'_smooth', 0)\n"
        '            if isinstance(smooth, bool) or not isinstance(smooth, int) or smooth < 0:\n'
        "                raise ConversionError(f'{group} smoothing({index}) must be a nonnegative integer')\n"
        "            amplitude = _field_real(parameter(amplitude_key, 0.), f'{group} amplitude({index})')\n"
        '            if not noscale and amplitude == 0:\n'
        "                raise ConversionError(f'{group} amplitude({index}) must be nonzero unless noscale is true')\n"
        '            frequency = None\n'
        '            phase = 0.\n'
        "            if kind == 'rf':\n"
        "                frequency = 1000*_field_real(parameter('nue'), f'cavity.Nue({index})')\n"
        '                if (not math.isfinite(frequency) or frequency <= 0\n'
        '                        or not math.isfinite(2*math.pi*frequency*1e6)):\n'
        "                    raise ConversionError('RF frequency must be positive finite GHz')\n"
        "                phase = global_phase + _field_real(parameter('phi', 0.), f'cavity.Phi({index})')\n"
        '                if not math.isfinite(phase):\n'
        "                    raise ConversionError('Total RF phase overflow')\n"
        "            specs.append({'kind': kind, 'index': index, 'filename': filename,\n"
        "                          'position': position, 'frequencyMHz': frequency,\n"
        "                          'phase_deg': phase, 'auto_phase': auto_phase,\n"
        "                          'higher_order': higher_order, 'noscale': noscale,\n"
        "                          'smooth': smooth, 'amplitude': amplitude})\n"
        '    return specs\n'
        '\n'
        '\n'
        'def prepare_fields(groups: dict, source_dir, clock_origin_s: float, *,\n'
        '                   rf_subdivisions: int = 4, rf_radius_m: float = .05,\n'
        '                   fourier_terms: int = 128, coordinate_origin_m=(0., 0., 0.)) -> dict:\n'
        '    """Read/prepare mapped fields and render OPALX elements in the target frame.\n'
        '\n'
        "    Smoothing uses simultaneous passes with fixed endpoints, then ASTRA's signed\n"
        '    peak scaling. These conventions were verified against ASTRA-only controls.\n'
        '    RF first-order expansion uses an explicit piecewise-linear 2D model; higher-order RF\n'
        "    and solenoids use OPALX's native Fourier model. Metadata records these model\n"
        '    differences and every source/output hash. No external process is launched.\n'
        '    """\n'
        "    clock_origin_s = _field_real(clock_origin_s, 'Snapshot clock origin')\n"
        '    if not isinstance(coordinate_origin_m, (list, tuple)) or len(coordinate_origin_m) != 3:\n'
        "        raise ConversionError('Field coordinate origin needs three finite metres')\n"
        "    origin = [_field_real(value, 'Field coordinate origin') for value in coordinate_origin_m]\n"
        '    if (isinstance(rf_subdivisions, bool) or not isinstance(rf_subdivisions, int)\n'
        '            or rf_subdivisions < 1):\n'
        "        raise ConversionError('RF subdivisions must be a positive integer')\n"
        "    rf_radius_m = _field_real(rf_radius_m, 'RF support radius')\n"
        '    if rf_radius_m <= 0:\n'
        "        raise ConversionError('RF support radius must be positive')\n"
        '    if (isinstance(fourier_terms, bool) or not isinstance(fourier_terms, int)\n'
        '            or fourier_terms < 2):\n'
        "        raise ConversionError('Fourier terms must be an integer of at least two')\n"
        "    result = {'elements': [], 'files': {}, 'maps': []}\n"
        '    for spec in field_specs(groups):\n'
        "        source = (Path(source_dir)/spec['filename']).resolve()\n"
        '        raw = source.read_bytes()\n'
        '        try:\n'
        "            rows = read_axis_map(raw.decode('ascii'))\n"
        '        except UnicodeError as exc:\n'
        "            raise ConversionError(f'Map {source} must be ASCII') from exc\n"
        '        if len(rows) < 5:\n'
        "            raise ConversionError('ASTRA field tables need at least five samples')\n"
        '        signed_input_peak = max(rows, key=lambda row: abs(row[1]))[1]\n'
        "        smoothed = smooth_axis_map(rows, spec['smooth'], order='simultaneous')\n"
        '        signed_smoothed_peak = max(smoothed, key=lambda row: abs(row[1]))[1]\n'
        "        physical = smoothed if spec['noscale'] else scale_axis_map(smoothed, spec['amplitude'])\n"
        '        physical_peak = max(abs(field) for _, field in physical)\n'
        '        if physical_peak == 0:\n'
        "            raise ConversionError('Smoothed physical field has zero amplitude')\n"
        "        global_bounds = [spec['position']+rows[0][0], spec['position']+rows[-1][0]]\n"
        '        if not all(math.isfinite(value) for value in global_bounds):\n'
        "            raise ConversionError('Global field-map bounds overflow')\n"
        '        extent = rows[-1][0]-rows[0][0]\n'
        '        if not math.isfinite(extent):\n'
        "            raise ConversionError('Field-map extent overflow')\n"
        '        name = f\'ASTRA_{"RF" if spec["kind"] == "rf" else "SOL"}_{spec["index"]}\'\n'
        '        filename = f\'{spec["kind"]}_{spec["index"]:03d}.map\'\n'
        '        metadata = dict(spec)\n'
        '        target_pose = [0. if value == 0 else -value for value in origin[:2]]\n'
        "        target_pose.append(spec['position']-origin[2])\n"
        '        target_bounds = [value-origin[2] for value in global_bounds]\n'
        '        if not all(math.isfinite(value) for value in target_pose+target_bounds):\n'
        "            raise ConversionError('Translated field-map pose overflows')\n"
        '        metadata.update(source=str(source), source_sha256=hashlib.sha256(raw).hexdigest(),\n'
        "                        source_config=dict(groups['cavity' if spec['kind']=='rf' else 'solenoid']),\n"
        '                        output_filename=filename, input_points=len(rows),\n'
        '                        input_signed_absolute_peak=signed_input_peak,\n'
        '                        smoothed_signed_absolute_peak=signed_smoothed_peak,\n'
        '                        physical_peak=physical_peak, local_bounds_m=[rows[0][0], rows[-1][0]],\n'
        '                        global_bounds_m=global_bounds,\n'
        '                        target_pose_m=target_pose, target_global_bounds_m=target_bounds,\n'
        "                        preprocessing={'smoothing': 'simultaneous weighted-neighbor passes; fixed endpoints',\n"
        "                                       'iterations': spec['smooth'],\n"
        "                                       'normalization': ('disabled; physical table values retained' if spec['noscale']\n"
        "                                                         else 'signed first absolute peak after smoothing'),\n"
        "                                       'physical_field_unit': 'MV/m' if spec['kind']=='rf' else 'T'})\n"
        "        if spec['kind'] == 'rf':\n"
        "            if not spec['higher_order']:\n"
        '                try:\n'
        "                    rendered = render_first_order_rf_map(physical, spec['frequencyMHz'],\n"
        '                                                        radius_m=rf_radius_m,\n'
        '                                                        z_subdivisions=rf_subdivisions)\n'
        '                except ValueError as exc:\n'
        '                    raise ConversionError(str(exc)) from exc\n'
        "                text = rendered['text']\n"
        "                metadata['interpolation_model'] = rendered['metadata']\n"
        "                voltage = rendered['metadata']['interpolated_peak']\n"
        '            else:\n'
        '                accuracy = min(fourier_terms, len(rows))\n'
        "                text = render_axis_map(physical, 'rf', accuracy=accuracy, normalize=True,\n"
        "                                       frequency_MHz=spec['frequencyMHz'])\n"
        "                # AstraDynamic's getOnaxisEz auto-phase reader requires two\n"
        '                # header tokens. Its omitted normalization flag defaults TRUE.\n'
        "                text = text.replace(f'AstraDynamic {accuracy} TRUE\\n',\n"
        "                                    f'AstraDynamic {accuracy}\\n', 1)\n"
        '                voltage = physical_peak\n'
        "                metadata['interpolation_model'] = {'model': 'native Fourier on-axis map; cubic transverse expansion',\n"
        "                                                   'fourier_terms': accuracy,\n"
        "                                                   'native_peak_normalized': True}\n"
        "            if spec['auto_phase']:\n"
        "                lag = math.radians(spec['phase_deg'])\n"
        '                if not math.isfinite(lag):\n'
        "                    raise ConversionError('Relative RF phase overflow')\n"
        '                lag = math.remainder(lag, 2*math.pi)\n'
        '            else:\n'
        '                try:\n'
        "                    lag = astra_absolute_rf_lag(spec['phase_deg'], spec['frequencyMHz'], clock_origin_s)\n"
        '                except ValueError as exc:\n'
        '                    raise ConversionError(str(exc)) from exc\n'
        "            veto = not spec['auto_phase']\n"
        '            metadata.update(element=name, target_voltage_MV_per_m=voltage,\n'
        '                            target_lag_rad=lag, target_autophase_veto=veto,\n'
        '                            clock_origin_s=clock_origin_s,\n'
        "                            phase_convention=('relative to independently solved crest' if spec['auto_phase']\n"
        "                                              else 'absolute ASTRA sine to OPALX cosine; snapshot clock retained'))\n"
        "            element = (f'{name}: RFCAVITY, L={extent:.17g}, VOLT={voltage:.17g}, '\n"
        '                       f\'FREQ={spec["frequencyMHz"]:.17g}, LAG={lag:.17g}, \'\n'
        '                       f\'APVETO={str(veto).upper()}, FMAPFN="{filename}", \'\n'
        "                       f'X={target_pose[0]:.17g}, Y={target_pose[1]:.17g}, Z={target_pose[2]:.17g};')\n"
        '        else:\n'
        '            accuracy = min(fourier_terms, len(rows))\n'
        "            text = render_axis_map(physical, 'solenoid', accuracy=accuracy, normalize=True)\n"
        '            metadata.update(element=name, target_bscale_T=physical_peak,\n'
        "                            interpolation_model={'model': 'native Fourier on-axis map; cubic transverse expansion',\n"
        "                                                 'fourier_terms': accuracy, 'native_peak_normalized': True})\n"
        '            element = (f\'{name}: FIELDMAP, FMAPFN="{filename}", BSCALE={physical_peak:.17g}, \'\n'
        "                       f'X={target_pose[0]:.17g}, Y={target_pose[1]:.17g}, Z={target_pose[2]:.17g};')\n"
        "        metadata['output_sha256'] = hashlib.sha256(text.encode('ascii')).hexdigest()\n"
        "        result['elements'].append(element)\n"
        "        result['files'][filename] = text\n"
        "        result['maps'].append(metadata)\n"
        '    return result\n'
        '\n'
        '\n'
        'def quadrupole_specs(groups: dict) -> list:\n'
        '    """Validate ASTRA straight analytic/profile quadrupoles, without tracking.\n'
        '\n'
        '    Normal and skew magnets use signed physical Q_grad [T/m], an effective\n'
        '    Q_length [m], Q_pos at the centre, and Q_bore=0.035 m by default. The two\n'
        '    finite analytic fringes may not overlap (L >= 3*bore). Profile filenames\n'
        "    must contain ASTRA's `data` keyword. Q_K, compound magnets, multipole\n"
        '    errors, nonzero transverse shifts/tilts and loops remain unsupported.\n'
        '    A longitudinal roll is represented by rotating the entire normal map.\n'
        '    """\n'
        "    values = groups.get('quadrupole', {})\n"
        "    if not _field_logical(values.get('lquad', False), 'quadrupole.Lquad'):\n"
        '        return []\n'
        "    if _field_logical(values.get('loop', False), 'quadrupole.LOOP'):\n"
        "        raise ConversionError('quadrupole.LOOP is unsupported')\n"
        "    allowed = {'q_type', 'q_grad', 'q_length', 'q_bore', 'q_pos', 'q_noscale',\n"
        "               'q_smooth', 'q_xoff', 'q_yoff', 'q_xrot', 'q_yrot', 'q_zrot'}\n"
        '    indices = set()\n'
        '    for key in values:\n'
        "        if key in ('lquad', 'loop'):\n"
        '            continue\n'
        "        match = re.fullmatch(r'([a-z][a-z0-9_]*)\\(([0-9]+)\\)', key)\n"
        '        if not match or match.group(1) not in allowed:\n'
        "            raise ConversionError('Unsupported active quadrupole.' + key)\n"
        '        index = int(match.group(2))\n'
        '        if index == 0:\n'
        "            raise ConversionError('Quadrupole indices must start at one')\n"
        '        indices.add(index)\n'
        '    if not indices or sorted(indices) != list(range(1, len(indices)+1)):\n'
        "        raise ConversionError('Quadrupole indices must be contiguous 1..N')\n"
        '    specs = []\n'
        '    for index in sorted(indices):\n'
        '        def parameter(name, default=None):\n'
        "            return values.get(f'{name}({index})', default)\n"
        '\n'
        "        kind = parameter('q_type', '')\n"
        "        if not isinstance(kind, str) or any(c in kind for c in '\\0\\r\\n'):\n"
        "            raise ConversionError('Quadrupole Q_type must be a safe character value')\n"
        "        is_profile = 'data' in kind.lower()\n"
        "        if not is_profile and kind.strip().lower() not in ('', 'skew'):\n"
        "            raise ConversionError('Only standard, skew and data-profile quadrupoles are supported')\n"
        "        position = _field_real(parameter('q_pos', 0.), 'quadrupole position')\n"
        "        for name in ('q_xoff', 'q_yoff', 'q_xrot', 'q_yrot'):\n"
        "            if _field_real(parameter(name, 0.), 'quadrupole.' + name) != 0:\n"
        "                raise ConversionError('Nonzero quadrupole.' + name + ' is unsupported')\n"
        "        rotation = _field_real(parameter('q_zrot', 0.), 'quadrupole.Q_zrot')\n"
        "        if kind.strip().lower() == 'skew':\n"
        '            rotation -= math.pi / 4\n'
        '        rotation = math.remainder(rotation, 2*math.pi)\n'
        "        noscale = _field_logical(parameter('q_noscale', False), 'quadrupole.Q_noscale')\n"
        "        smooth = parameter('q_smooth', 0)\n"
        '        if isinstance(smooth, bool) or not isinstance(smooth, int) or smooth < 0:\n'
        "            raise ConversionError('Quadrupole smoothing must be a nonnegative integer')\n"
        "        amplitude = _field_real(parameter('q_grad', 0.), 'quadrupole.Q_grad')\n"
        "        length = _field_real(parameter('q_length', 0.), 'quadrupole.Q_length')\n"
        "        bore = _field_real(parameter('q_bore', .035), 'quadrupole.Q_bore')\n"
        '        if not is_profile:\n'
        '            if length <= 0 or bore <= 0:\n'
        "                raise ConversionError('Analytic quadrupole length and bore must be positive')\n"
        '            if length < 3*bore and not math.isclose(length, 3*bore, rel_tol=1e-14):\n'
        "                raise ConversionError('Overlapping analytic quadrupole fringes (L < 3*bore) are unsupported')\n"
        '            if smooth or noscale:\n'
        "                raise ConversionError('Quadrupole smoothing/noscale apply only to data profiles')\n"
        '        if amplitude == 0 and not (is_profile and noscale):\n'
        "            raise ConversionError('Quadrupole Q_grad must be nonzero unless a profile uses noscale')\n"
        "        specs.append({'kind': 'quadrupole', 'index': index,\n"
        "                      'type': 'profile' if is_profile else ('skew' if kind.strip() else 'normal'),\n"
        "                      'filename': kind if is_profile else None, 'position': position,\n"
        "                      'rotation_rad': rotation, 'amplitude_T_per_m': amplitude,\n"
        "                      'length_m': length, 'bore_m': bore,\n"
        "                      'noscale': noscale, 'smooth': smooth})\n"
        '    return specs\n'
        '\n'
        '\n'
        'def quadrupole_axis_derivatives(rows: list) -> list:\n'
        '    """ASTRA quadrupole dG/dz [T/m²] from physical G [T/m] samples.\n'
        '\n'
        '    Interior nodes average adjacent interval slopes even on nonuniform grids.\n'
        '    Endpoints use 1.5 times the edge secant minus .5 times the next secant.\n'
        "    This differs from ASTRA's RF five-point endpoint rule. Native tiny kicks on\n"
        '    uniform and nonuniform synthetic profiles establish this operator.\n'
        '    """\n'
        '    if len(rows) < 3:\n'
        "        raise ConversionError('Quadrupole derivative needs at least three samples')\n"
        '    for i, row in enumerate(rows):\n'
        '        if len(row) != 2:\n'
        "            raise ConversionError('Quadrupole rows need z and gradient')\n"
        "        z = _field_real(row[0], 'Quadrupole profile z')\n"
        "        _field_real(row[1], 'Quadrupole profile gradient')\n"
        '        if i and z - rows[i-1][0] <= 1e-10:\n'
        "            raise ConversionError('Quadrupole profile z spacing must exceed 1e-10 m')\n"
        '    secants = [(right[1]-left[1])/(right[0]-left[0])\n'
        '               for left, right in zip(rows, rows[1:])]\n'
        '    result = ([1.5*secants[0]-.5*secants[1]]\n'
        '              + [(left+right)/2 for left,right in zip(secants,secants[1:])]\n'
        '              + [1.5*secants[-1]-.5*secants[-2]])\n'
        '    if not all(math.isfinite(value) for value in result):\n'
        "        raise ConversionError('Quadrupole derivative overflow')\n"
        '    return result\n'
        '\n'
        '\n'
        'def analytic_quadrupole_axis(z: float, length_m: float, bore_m: float,\n'
        '                             gradient_T_per_m: float) -> tuple:\n'
        '    """Return ASTRA\'s normal analytic G(z), G\'(z), in T/m and T/m².\n'
        '\n'
        '    Each logistic edge 1/(1+exp(4*distance/bore)) extends 1.5*bore to\n'
        '    either side of the effective edge. Beyond the inner cutoff the field is\n'
        '    exactly its plateau; beyond the outer cutoff it is exactly zero. The\n'
        '    discontinuities at cutoffs are retained. Overlapping fringes are refused.\n'
        '    """\n'
        "    z = _field_real(z, 'Quadrupole evaluation z')\n"
        "    length_m = _field_real(length_m, 'Quadrupole length')\n"
        "    bore_m = _field_real(bore_m, 'Quadrupole bore')\n"
        "    gradient_T_per_m = _field_real(gradient_T_per_m, 'Quadrupole gradient')\n"
        '    if length_m <= 0 or bore_m <= 0 or length_m < 3*bore_m-1e-14*length_m:\n'
        "        raise ConversionError('Analytic quadrupole requires positive bore and L >= 3*bore')\n"
        '    distance = abs(z)-length_m/2\n'
        '    if distance > 1.5*bore_m:\n'
        '        return 0., 0.\n'
        '    if distance < -1.5*bore_m or gradient_T_per_m == 0:\n'
        '        return gradient_T_per_m, 0.\n'
        '    fraction = 1/(1+math.exp(4*distance/bore_m))\n'
        '    gradient = gradient_T_per_m*fraction\n'
        '    derivative = (-math.copysign(1.,z)*4/bore_m*gradient_T_per_m\n'
        '                  * fraction*(1-fraction))\n'
        '    return gradient, derivative\n'
        '\n'
        '\n'
        'def render_quadrupole_map(spec: dict, rows=None, *, dz_m: float = .00025,\n'
        '                          radius_m: float = .05) -> dict:\n'
        '    """Render a static physical-Tesla G4beamline grid for a normal quadrupole.\n'
        '\n'
        "    Bx=-G*y, By=-G*x and Bz=-G'*x*y reproduce ASTRA's leading quadrupole\n"
        '    model, including its longitudinal fringe field. Two vertices per transverse\n'
        '    axis represent this model exactly by trilinear interpolation. A skew/rolled\n'
        '    quadrupole rotates the complete element pose, preserving this property.\n'
        '    The longitudinal grid samples the analytic profile or independently linearly\n'
        '    interpolated profile/gradient tables. Its spacing must be converged by the\n'
        "    caller; map boundaries retain ASTRA's finite field support.\n"
        '    """\n'
        "    dz_m = _field_real(dz_m, 'Quadrupole map dz')\n"
        "    radius_m = _field_real(radius_m, 'Quadrupole map support radius')\n"
        '    if dz_m <= 0 or radius_m <= 0:\n'
        "        raise ConversionError('Quadrupole dz and support radius must be positive')\n"
        '    if rows is None:\n'
        "        bounds = [-(spec['length_m']+3*spec['bore_m'])/2,\n"
        "                   (spec['length_m']+3*spec['bore_m'])/2]\n"
        "        step = min(dz_m, spec['bore_m']/100)\n"
        '        def evaluate(z):\n'
        "            return analytic_quadrupole_axis(z, spec['length_m'], spec['bore_m'],\n"
        "                                           spec['amplitude_T_per_m'])\n"
        "        description = 'ASTRA finite logistic edges and exact flat plateau; sampled longitudinally'\n"
        '    else:\n'
        '        slopes = quadrupole_axis_derivatives(rows)\n'
        '        bounds = [rows[0][0], rows[-1][0]]\n'
        '        step = dz_m\n'
        '        def evaluate(z):\n'
        '            return evaluate_rf_linear(rows, slopes, z)\n'
        "        description = 'piecewise-linear gradient and independently linearly interpolated nodal dG/dz'\n"
        '    if not all(math.isfinite(v) for v in bounds) or not bounds[1] > bounds[0]:\n'
        "        raise ConversionError('Quadrupole map bounds must be finite and increasing')\n"
        '    span = bounds[1]-bounds[0]\n'
        '    if not math.isfinite(span) or step <= 0 or not math.isfinite(span/step):\n'
        "        raise ConversionError('Quadrupole grid extent or interval count overflow')\n"
        '    intervals = math.ceil(span/step)\n'
        '    # Avoid accidental multi-gigabyte maps from a mistyped CLI spacing.\n'
        '    if intervals > 1000000:\n'
        "        raise ConversionError('Quadrupole map would exceed one million longitudinal intervals')\n"
        '    intervals = max(1, intervals)\n'
        '    spacing = (bounds[1]-bounds[0])/intervals\n'
        "    header = (f'param current=1 normB=1\\n'\n"
        "              f'grid X0={-1000*radius_m:.17g} Y0={-1000*radius_m:.17g} '\n"
        "              f'Z0={1000*bounds[0]:.17g} nX=2 nY=2 nZ={intervals+1} '\n"
        "              f'dX={2000*radius_m:.17g} dY={2000*radius_m:.17g} dZ={1000*spacing:.17g}\\n'\n"
        "              f'data\\n')\n"
        '    profile = [evaluate(bounds[0]+i*spacing if i < intervals else bounds[1])\n'
        '               for i in range(intervals+1)]\n'
        '    records = [header]\n'
        '    for x in (-radius_m, radius_m):\n'
        '        for y in (-radius_m, radius_m):\n'
        '            for i, (gradient, derivative) in enumerate(profile):\n'
        '                z = bounds[0]+i*spacing if i < intervals else bounds[1]\n'
        '                values = (1000*x, 1000*y, 1000*z,\n'
        '                          -gradient*y, -gradient*x, -derivative*x*y)\n'
        '                if not all(math.isfinite(v) for v in values):\n'
        "                    raise ConversionError('Quadrupole grid field overflow')\n"
        "                records.append(' '.join(f'{v:.17g}' for v in values)+'\\n')\n"
        "    return {'text': ''.join(records), 'metadata': {\n"
        "        'model': description, 'local_bounds_m': bounds,\n"
        "        'grid_intervals': [1,1,intervals], 'dz_m': spacing,\n"
        "        'transverse_support_halfwidth_m': radius_m,\n"
        "        'transverse_interpolation': 'exact bilinear xy for this leading model; roll in element pose',\n"
        "        'field_units': 'Tesla', 'coordinate_units': 'mm',\n"
        "        'normal_field_convention': 'Bx=-G*y; By=-G*x; Bz=-dG/dz*x*y'}}\n"
        '\n'
        '\n'
        'def prepare_quadrupoles(groups: dict, source_dir, sample: dict, *,\n'
        '                         dz_m: float = .00025, radius_m: float = .05) -> dict:\n'
        '    """Prepare static quadrupole maps and absolute-pose FIELDMAP elements.\n'
        '\n'
        '    ASTRA scales profile quadrupoles differently from RF/solenoid maps: after\n'
        '    smoothing, each individual sample is made positive and normalized to its\n'
        '    absolute peak before multiplication by signed Q_grad. Q_noscale retains\n'
        '    signed physical table values. Source and generated hashes are recorded.\n'
        '    The sample argument is reserved for future momentum-dependent Q_K support;\n'
        '    Q_K is currently refused by quadrupole_specs.\n'
        '    """\n'
        "    result = {'elements': [], 'files': {}, 'quadrupoles': []}\n"
        '    for spec in quadrupole_specs(groups):\n'
        '        metadata = dict(spec)\n'
        "        metadata['source_config'] = dict(groups['quadrupole'])\n"
        '        rows = None\n'
        "        if spec['filename'] is not None:\n"
        "            source = (Path(source_dir)/spec['filename']).resolve()\n"
        '            raw = source.read_bytes()\n'
        '            try:\n'
        "                original = read_axis_map(raw.decode('ascii'))\n"
        '            except UnicodeError as exc:\n'
        "                raise ConversionError('Quadrupole map must be ASCII') from exc\n"
        '            if len(original) < 5:\n'
        "                raise ConversionError('ASTRA quadrupole profiles need at least five samples')\n"
        "            smoothed = smooth_axis_map(original, spec['smooth'], order='simultaneous')\n"
        '            peak = max(abs(f) for _,f in smoothed)\n'
        '            if not peak:\n'
        "                raise ConversionError('Smoothed quadrupole profile has zero amplitude')\n"
        "            rows = smoothed if spec['noscale'] else [\n"
        "                (z, spec['amplitude_T_per_m']*abs(f)/peak) for z,f in smoothed]\n"
        '            metadata.update(source=str(source), source_sha256=hashlib.sha256(raw).hexdigest(),\n'
        '                            input_points=len(rows), smoothed_absolute_peak=peak,\n'
        "                            normalization=('disabled; signed physical table retained' if spec['noscale']\n"
        "                                           else 'absolute value of each smoothed sample; abs peak; signed Q_grad'),\n"
        "                            ignored_profile_geometry='Q_length/Q_bore do not resize the source profile')\n"
        '        rendered = render_quadrupole_map(spec, rows, dz_m=dz_m, radius_m=radius_m)\n'
        "        text = rendered['text']\n"
        '        name = f\'ASTRA_QUAD_{spec["index"]}\'\n'
        '        filename = f\'quadrupole_{spec["index"]:03d}.map\'\n'
        "        local_bounds = rendered['metadata']['local_bounds_m']\n"
        "        bounds = [spec['position']+v for v in local_bounds]\n"
        '        if not all(math.isfinite(v) for v in bounds):\n'
        "            raise ConversionError('Global quadrupole map bounds overflow')\n"
        '        metadata.update(element=name, output_filename=filename,\n'
        "                        output_sha256=hashlib.sha256(text.encode('ascii')).hexdigest(),\n"
        '                        global_bounds_m=bounds,\n'
        "                        interpolation_model=rendered['metadata'],\n"
        "                        target_psi_rad=spec['rotation_rad'])\n"
        '        element = (f\'{name}: FIELDMAP, FMAPFN="{filename}", BSCALE=1, \'\n'
        '                   f\'X=0, Y=0, Z={spec["position"]:.17g}, PSI={spec["rotation_rad"]:.17g};\')\n'
        "        result['elements'].append(element)\n"
        "        result['files'][filename] = text\n"
        "        result['quadrupoles'].append(metadata)\n"
        '    return result\n'
        '\n'
        '\n'
        'def _dipole_intersection(first: tuple, second: tuple) -> tuple:\n'
        '    """Intersect n_u*u+n_z*z=c lines in physical metres."""\n'
        '    a,b,c=first\n'
        '    d,e,f=second\n'
        '    determinant=a*e-b*d\n'
        '    if not math.isfinite(determinant) or abs(determinant) < 1e-12:\n'
        "        raise ConversionError('Dipole edges must intersect at finite, well-conditioned corners')\n"
        '    point=((c*e-b*f)/determinant,(a*f-c*d)/determinant)\n'
        '    if not all(math.isfinite(v) for v in point):\n'
        "        raise ConversionError('Dipole corner intersection overflow')\n"
        '    return point\n'
        '\n'
        '\n'
        'def _dipole_geometry(corners: list, gaps: list) -> dict:\n'
        '    """Check clockwise D1,D2,D4,D3 convex geometry and nonoverlapping fringes.\n'
        '\n'
        '    The first and last faces must be graphs over the bending coordinate u, so\n'
        '    forward z tracking is unambiguous. Side lines D1-D3/D2-D4 are extrapolated\n'
        '    through both fringe regions, exactly as in ASTRA. Positive outward signed\n'
        '    distances determine the finite logistic face taper.\n'
        '    """\n'
        '    polygon=[corners[i] for i in (0,1,3,2)]\n'
        '    if not corners[0][0] > corners[1][0] or not corners[2][0] > corners[3][0]:\n'
        "        raise ConversionError('Dipole requires D1/D3 to the right of D2/D4 in the bending plane')\n"
        '    edges=[]\n'
        '    for i,one in enumerate(polygon):\n'
        '        two=polygon[(i+1)%4]\n'
        '        du,dz=two[0]-one[0],two[1]-one[1]\n'
        '        norm=math.hypot(du,dz)\n'
        '        if not math.isfinite(norm) or norm <= 1e-10:\n'
        "            raise ConversionError('Dipole faces and sides need distinct finite corner points')\n"
        '        nu,nz=-dz/norm,du/norm\n'
        '        constant=nu*one[0]+nz*one[1]\n'
        '        if not math.isfinite(constant):\n'
        "            raise ConversionError('Dipole edge coordinate overflow')\n"
        '        edges.append((nu,nz,constant))\n'
        '        three=polygon[(i+2)%4]\n'
        '        cross=du*(three[1]-two[1])-dz*(three[0]-two[0])\n'
        '        if not math.isfinite(cross) or cross >= -1e-14*norm:\n'
        "            raise ConversionError('Dipole D1,D2,D4,D3 must form a strictly convex clockwise polygon')\n"
        '    entrance,left,exit_face,right=edges\n'
        '    if entrance[1] >= -1e-10 or exit_face[1] <= 1e-10:\n'
        "        raise ConversionError('Dipole entrance/exit must allow forward longitudinal tracking')\n"
        '    face_edges=[entrance,exit_face]\n'
        '    inner=[]\n'
        '    outer=[]\n'
        '    for face,gap in zip(face_edges,gaps):\n'
        '        inner.append((face[0],face[1],face[2]-1.5*gap))\n'
        '        outer.append((face[0],face[1],face[2]+1.5*gap))\n'
        '    inner_corners=[_dipole_intersection(inner[0],side) for side in (right,left)]\n'
        '    inner_corners += [_dipole_intersection(inner[1],side) for side in (right,left)]\n'
        '    # Both inner faces must retain their order along each extrapolated side.\n'
        '    # Their signed opposite-face distances make this also sufficient throughout\n'
        '    # the convex interpolation between the two side lines.\n'
        '    for point in inner_corners[:2]:\n'
        '        if exit_face[0]*point[0]+exit_face[1]*point[1]-exit_face[2] > -1.5*gaps[1]+1e-12:\n'
        "            raise ConversionError('Dipole entrance and exit fringe regions overlap')\n"
        '    for point in inner_corners[2:]:\n'
        '        if entrance[0]*point[0]+entrance[1]*point[1]-entrance[2] > -1.5*gaps[0]+1e-12:\n'
        "            raise ConversionError('Dipole entrance and exit fringe regions overlap')\n"
        '    outer_corners=[_dipole_intersection(outer[0],side) for side in (right,left)]\n'
        '    outer_corners += [_dipole_intersection(outer[1],side) for side in (right,left)]\n'
        "    return {'faces':face_edges,'sides':[left,right],\n"
        "            'outer_corners_m':outer_corners,\n"
        "            'z_bounds_m':[min(p[1] for p in outer_corners),max(p[1] for p in outer_corners)]}\n"
        '\n'
        '\n'
        'def dipole_specs(groups: dict) -> list:\n'
        '    """Validate the external physical-strength planar ASTRA dipole field model.\n'
        '\n'
        '    D1..D4 are (bending coordinate,z) metres. D_Gap(edge,magnet) is in metres\n'
        '    and defaults to .05. Horizontal D_strength gives By in Tesla; vertical\n'
        '    gives -Bx. Translations are supported; rotations and reference-momentum\n'
        '    D_radius remain explicit refusals. Source infinite off-plane support is\n'
        '    replaced only at rendering by a declared finite Cartesian map extent.\n'
        '    """\n'
        "    values=groups.get('dipole',{})\n"
        "    if not _field_logical(values.get('ldipole',False),'DIPOLE.LDipole'):\n"
        '        return []\n'
        "    if _field_logical(values.get('loop',False),'DIPOLE.LOOP'):\n"
        "        raise ConversionError('DIPOLE.LOOP is unsupported')\n"
        "    allowed={'d_type','d1','d2','d3','d4','d_strength','d_radius',\n"
        "             'd_xoff','d_yoff','d_zoff','d_xrot','d_yrot','d_zrot'}\n"
        '    indices=set()\n'
        '    for key in values:\n'
        "        if key in ('ldipole','loop'):\n"
        '            continue\n'
        "        match=re.fullmatch(r'([a-z][a-z0-9_]*)\\(([0-9]+)(?:,([0-9]+))?\\)',key)\n"
        '        if not match:\n'
        "            raise ConversionError('Unsupported active dipole.'+key)\n"
        '        base,first,second=match.group(1),int(match.group(2)),match.group(3)\n'
        "        if base == 'd_gap':\n"
        '            if second is None or first not in (1,2):\n'
        "                raise ConversionError('DIPOLE.D_gap needs edge 1/2 and a magnet index')\n"
        '            index=int(second)\n'
        '        elif base in allowed and second is None:\n'
        '            index=first\n'
        '        else:\n'
        "            raise ConversionError('Unsupported active dipole.'+key)\n"
        '        if index == 0:\n'
        "            raise ConversionError('Dipole indices must start at one')\n"
        '        indices.add(index)\n'
        '    if not indices or sorted(indices) != list(range(1,len(indices)+1)):\n'
        "        raise ConversionError('Dipole indices must be contiguous 1..N')\n"
        '    specs=[]\n'
        '    for index in sorted(indices):\n'
        '        def parameter(name,default=None):\n'
        "            return values.get(f'{name}({index})',default)\n"
        "        raw_kind=parameter('d_type','')\n"
        '        if (not isinstance(raw_kind,str) or not raw_kind.isascii()\n'
        "                or raw_kind.strip(' ').lower() not in ('horizontal','vertical')):\n"
        "            raise ConversionError('Dipole D_type must explicitly be horizontal or vertical; blank source types produce no field')\n"
        "        kind=raw_kind.strip(' ').lower()\n"
        '        # ASTRA stores only ten characters. A long leading blank prefix can\n'
        '        # erase a type or even turn a truncated vertical type into horizontal.\n'
        '        # Refuse source truncation rather than guess its abbreviation rules.\n'
        "        if raw_kind[:10].strip(' ').lower() != kind:\n"
        "            raise ConversionError('Dipole D_type must fit ASTRA ten-character storage without truncation')\n"
        "        radius=_field_real(parameter('d_radius',0.),'DIPOLE.D_radius')\n"
        '        if radius != 0:\n'
        "            raise ConversionError('Momentum-dependent DIPOLE.D_radius is unsupported; use verified physical D_strength')\n"
        "        strength=_field_real(parameter('d_strength',0.),'DIPOLE.D_strength')\n"
        '        if strength == 0:\n'
        "            raise ConversionError('Dipole D_strength must be nonzero')\n"
        "        for suffix in ('xrot','yrot','zrot'):\n"
        "            if _field_real(parameter('d_'+suffix,0.),'DIPOLE.D_'+suffix) != 0:\n"
        "                raise ConversionError('Nonzero DIPOLE.D_'+suffix+' is unsupported')\n"
        "        offsets=[_field_real(parameter('d_'+suffix,0.),'DIPOLE.D_'+suffix)\n"
        "                 for suffix in ('xoff','yoff','zoff')]\n"
        '        corners=[]\n'
        '        for number in range(1,5):\n'
        "            pair=parameter('d'+str(number))\n"
        '            if not isinstance(pair,(tuple,list)) or len(pair) != 2:\n'
        "                raise ConversionError(f'DIPOLE.D{number}({index}) requires a (transverse,z) coordinate pair')\n"
        "            u,z=(_field_real(v,f'DIPOLE.D{number} coordinate') for v in pair)\n"
        "            u += offsets[0 if kind=='horizontal' else 1]\n"
        '            z += offsets[2]\n'
        '            if not math.isfinite(u) or not math.isfinite(z):\n'
        "                raise ConversionError('Translated dipole corner overflow')\n"
        '            corners.append((u,z))\n'
        "        gaps=[_field_real(values.get(f'd_gap({edge},{index})',.05),'DIPOLE.D_gap')\n"
        '              for edge in (1,2)]\n'
        '        if any(g <= 0 or not math.isfinite(1.5*g) or not math.isfinite(4/g) for g in gaps):\n'
        "            raise ConversionError('Dipole edge gaps must be finite positive taper lengths')\n"
        '        if corners[0][0] != corners[2][0] or corners[1][0] != corners[3][0]:\n'
        "            raise ConversionError('Nonvertical dipole connecting sidewalls are not yet verified')\n"
        '        geometry=_dipole_geometry(corners,gaps)\n'
        "        specs.append({'kind':'dipole','index':index,'type':kind,\n"
        "                      'amplitude_T':strength,'corners_m':corners,'gaps_m':gaps,\n"
        "                      'offsets_m':offsets,'geometry':geometry})\n"
        '    # ASTRA prohibits simultaneous horizontal/vertical dipole fields. A z-range\n'
        '    # test is deliberately conservative, because native finite grids alone are\n'
        '    # not evidence that the infinite off-plane source fields do not overlap.\n'
        '    for i,first in enumerate(specs):\n'
        '        for second in specs[i+1:]:\n'
        "            if first['type'] != second['type']:\n"
        "                a,b=first['geometry']['z_bounds_m'],second['geometry']['z_bounds_m']\n"
        '                if max(a[0],b[0]) < min(a[1],b[1]):\n'
        "                    raise ConversionError('Overlapping horizontal and vertical dipole supports are unsupported')\n"
        '    return specs\n'
        '\n'
        '\n'
        'def analytic_dipole_field(spec: dict, x: float, y: float, z: float) -> tuple:\n'
        '    """Return ASTRA\'s leading planar (Bx,By,Bz), in physical Tesla.\n'
        '\n'
        '    Horizontal B=(v*dB0/du, B0, v*dB0/dz), where u=x and v=y-yoff.\n'
        '    A positive vertical magnet is its +pi/2 rotation around z:\n'
        '    B=(-B0, -v*dB0/du, -v*dB0/dz), u=y and v=x-xoff.\n'
        '    B0 has finite logistic tapers and an exact plateau. Source tiny-kick\n'
        '    controls establish no quadratic off-plane correction to B0 in ASTRA 4.\n'
        '    """\n'
        "    x,y,z=(_field_real(v,'Dipole evaluation coordinate') for v in (x,y,z))\n"
        "    u=x if spec['type']=='horizontal' else y\n"
        "    v=y-spec['offsets_m'][1] if spec['type']=='horizontal' else x-spec['offsets_m'][0]\n"
        "    geom=spec['geometry']\n"
        "    for number,(nu,nz,constant) in enumerate(geom['sides']):\n"
        '        signed=nu*u+nz*z-constant\n'
        '        if signed > 0 or (number == 1 and signed == 0):\n'
        '            return 0.,0.,0.\n'
        '    values=[]\n'
        "    for face,gap in zip(geom['faces'],spec['gaps_m']):\n"
        '        nu,nz,constant=face\n'
        '        distance=nu*u+nz*z-constant\n'
        '        if distance > 1.5*gap:\n'
        '            return 0.,0.,0.\n'
        '        if distance >= -1.5*gap:\n'
        '            fraction=1/(1+math.exp(4*distance/gap))\n'
        '            slope=-4/gap*fraction*(1-fraction)\n'
        '            values.append((fraction,slope*nu,slope*nz))\n'
        '    if len(values)>1:\n'
        '        # Geometry validation prevents finite-volume overlap; roundoff on the\n'
        '        # common inner cutoff is harmless and either edge has its source jump.\n'
        '        fraction,du,dz=min(values,key=lambda item:item[0])\n'
        '    elif values:\n'
        '        fraction,du,dz=values[0]\n'
        '    else:\n'
        '        fraction,du,dz=1.,0.,0.\n'
        "    strength=spec['amplitude_T']\n"
        "    result=(strength*v*du,strength*fraction,strength*v*dz) if spec['type']=='horizontal' else (\n"
        '        -strength*fraction,-strength*v*du,-strength*v*dz)\n'
        '    if not all(math.isfinite(value) for value in result):\n'
        "        raise ConversionError('Dipole field overflow')\n"
        '    return result\n'
        '\n'
        '\n'
        'def render_dipole_map(spec: dict, *, dz_m: float=.00025, dx_m: float=.0005,\n'
        '                      radius_m: float=.05) -> dict:\n'
        '    """Render finite Cartesian G4BL3DGrid sampling of the ASTRA planar field.\n'
        '\n'
        '    Both bending-coordinate and z variation are sampled; two vertices represent\n'
        '    the linear off-plane dependence exactly. Coordinates are mm, fields Tesla,\n'
        '    and native BSCALE=1 preserves physical strength. The source field has no\n'
        '    off-plane boundary; the finite support halfwidth must contain every tracked\n'
        '    particle and be expanded/converged for strongly bent trajectories.\n'
        '    """\n'
        "    dz_m=_field_real(dz_m,'Dipole map longitudinal spacing')\n"
        "    dx_m=_field_real(dx_m,'Dipole map bending-plane spacing')\n"
        "    radius_m=_field_real(radius_m,'Dipole map support halfwidth')\n"
        '    if min(dz_m,dx_m,radius_m) <= 0 or not math.isfinite(2*radius_m):\n'
        "        raise ConversionError('Dipole map spacings and halfwidth must be finite positive values')\n"
        "    z0,z1=spec['geometry']['z_bounds_m']\n"
        '    span=z1-z0\n'
        '    if not span>0 or not math.isfinite(span) or not math.isfinite(span/dz_m) or not math.isfinite(2*radius_m/dx_m):\n'
        "        raise ConversionError('Dipole map grid interval count overflow')\n"
        '    # Resolve the logistic taper with at least 100 samples per gap in each\n'
        '    # varying axis even if a coarse CLI spacing is requested.\n'
        "    stepz=min(dz_m,min(spec['gaps_m'])/100)\n"
        "    gradient_u=max(abs(face[0])/gap for face,gap in zip(spec['geometry']['faces'],spec['gaps_m']))\n"
        '    stepu=min(dx_m,(1/gradient_u)/100) if gradient_u else dx_m\n'
        '    if min(stepz,stepu) <= 0 or not math.isfinite(span/stepz) or not math.isfinite(2*radius_m/stepu):\n'
        "        raise ConversionError('Dipole map grid interval count overflow')\n"
        '    nz=max(1,math.ceil(span/stepz))\n'
        '    nu=max(1,math.ceil(2*radius_m/stepu))\n'
        '    # A rectangular source cropped strictly within its vertical sidewalls has\n'
        '    # no bending-coordinate field variation. Two samples then represent it\n'
        '    # exactly; never interpolate across a sidewall jump with only two points.\n'
        "    if gradient_u == 0 and all(nz_side == 0 for _,nz_side,_ in spec['geometry']['sides']):\n"
        "        sides=spec['geometry']['sides']\n"
        '        lower=sides[0][2]/sides[0][0]\n'
        '        upper=sides[1][2]/sides[1][0]\n'
        '        if -radius_m >= lower and radius_m <= upper:\n'
        '            nu=1\n'
        '    if 2*(nu+1)*(nz+1)>2000000:\n'
        "        raise ConversionError('Dipole map would exceed two million grid vertices; reduce support or use coarser verified controls')\n"
        "    sides=spec['geometry']['sides']\n"
        '    upper_side=sides[1]\n'
        '    one_sided_upper=(upper_side[1] == 0 and radius_m == upper_side[2]/upper_side[0])\n'
        '    du=2*radius_m/nu\n'
        '    dz=span/nz\n'
        "    nx,ny=(nu+1,2) if spec['type']=='horizontal' else (2,nu+1)\n"
        "    hx,hy=(du,2*radius_m) if spec['type']=='horizontal' else (2*radius_m,du)\n"
        "    records=[f'param current=1 normB=1\\n'\n"
        "             f'grid X0={-1000*radius_m:.17g} Y0={-1000*radius_m:.17g} Z0={1000*z0:.17g} '\n"
        "             f'nX={nx} nY={ny} nZ={nz+1} dX={1000*hx:.17g} dY={1000*hy:.17g} dZ={1000*dz:.17g}\\n'\n"
        "             f'data\\n']\n"
        '    for ix in range(nx):\n'
        '        x=-radius_m+ix*hx if ix<nx-1 else radius_m\n'
        '        for iy in range(ny):\n'
        '            y=-radius_m+iy*hy if iy<ny-1 else radius_m\n'
        '            for iz in range(nz+1):\n'
        '                z=z0+iz*dz if iz<nz else z1\n'
        "                # G4BL's upper grid plane is excluded. When that plane is\n"
        "                # exactly the source's excluded sidewall, store its interior\n"
        '                # limit so interpolation inside the last cell retains the\n'
        '                # correct field. Evaluating the excluded plane still yields 0.\n'
        '                evalx,evaly=x,y\n'
        '                if one_sided_upper:\n'
        "                    if spec['type']=='horizontal' and ix==nx-1:\n"
        '                        evalx=math.nextafter(x,-math.inf)\n'
        "                    elif spec['type']=='vertical' and iy==ny-1:\n"
        '                        evaly=math.nextafter(y,-math.inf)\n'
        '                values=(1000*x,1000*y,1000*z,*analytic_dipole_field(spec,evalx,evaly,z))\n'
        "                records.append(' '.join(f'{value:.17g}' for value in values)+'\\n')\n"
        "    return {'text':''.join(records),'metadata':{\n"
        "        'model':'ASTRA leading planar dipole: finite logistic edges, exact plateau, linear off-plane Maxwell components',\n"
        "        'coordinate_units':'mm','field_units':'Tesla','local_bounds_m':[[-radius_m,radius_m],[-radius_m,radius_m],[z0,z1]],\n"
        "        'grid_intervals':[nx-1,ny-1,nz], 'bending_spacing_m':du,'longitudinal_spacing_m':dz,\n"
        "        'transverse_support_halfwidth_m':radius_m,\n"
        "        'excluded_upper_sidewall_node':'one-sided interior limit' if one_sided_upper else 'ordinary physical field',\n"
        "        'interpolation':'trilinear; exact linear off-plane, sampled bending coordinate and z',\n"
        "        'field_convention':('Bx=(y-yoff)*dB0/dx; By=B0; Bz=(y-yoff)*dB0/dz' if spec['type']=='horizontal' else\n"
        "                            'Bx=-B0; By=-(x-xoff)*dB0/dy; Bz=-(x-xoff)*dB0/dz')}}\n"
        '\n'
        '\n'
        'def prepare_dipoles(groups: dict, source_dir, sample: dict, *, dz_m: float=.00025,\n'
        '                    dx_m: float=.0005, radius_m: float=.05) -> dict:\n'
        '    """Prepare physical-strength dipole maps and absolute FIELDMAP elements.\n'
        '\n'
        '    source_dir/sample are reserved for future independently validated external\n'
        '    profile/rigidity features; no momentum rescaling is performed.\n'
        '    """\n'
        "    result={'elements':[],'files':{},'dipoles':[]}\n"
        '    for spec in dipole_specs(groups):\n'
        '        rendered=render_dipole_map(spec,dz_m=dz_m,dx_m=dx_m,radius_m=radius_m)\n'
        "        text=rendered['text']\n"
        '        name=f\'ASTRA_DIPOLE_{spec["index"]}\'\n'
        '        filename=f\'dipole_{spec["index"]:03d}.map\'\n'
        '        metadata=dict(spec)\n'
        '        metadata.update(element=name,output_filename=filename,\n'
        "                        output_sha256=hashlib.sha256(text.encode('ascii')).hexdigest(),\n"
        "                        source_config=dict(groups['dipole']),\n"
        "                        global_bounds_m=spec['geometry']['z_bounds_m'],\n"
        "                        interpolation_model=rendered['metadata'])\n"
        '        result[\'elements\'].append(f\'{name}: FIELDMAP, FMAPFN="{filename}", BSCALE=1, X=0, Y=0, Z=0;\')\n'
        "        result['files'][filename]=text\n"
        "        result['dipoles'].append(metadata)\n"
        '    return result\n'
        '\n'
        '\n'
        'def evaluate_dipole_field(spec: dict, position: tuple) -> tuple:\n'
        '    """Evaluate a physical ASTRA source field at a laboratory (x,y,z) [m]."""\n'
        '    if len(position) != 3:\n'
        "        raise ConversionError('Dipole evaluation needs three laboratory coordinates')\n"
        '    return analytic_dipole_field(spec,*position)\n'
        '\n'
        '\n'
        'def _dipole_reference_field(field_at, position):\n'
        '    """Check one physical three-component magnetic field in Tesla."""\n'
        '    field = field_at(tuple(position))\n'
        '    if not isinstance(field, (tuple, list)) or len(field) != 3:\n'
        "        raise ConversionError('Dipole reference field must contain three Tesla components')\n"
        "    return tuple(_field_real(value, 'Dipole reference field [T]') for value in field)\n"
        '\n'
        '\n'
        'def _dipole_reference_step(state, step_m, curvature_scale, field_at):\n'
        '    """Take an RK4 arc-length step with constant magnetic momentum magnitude.\n'
        '\n'
        '    For an electron, dR/ds=n and dn/ds=(c/p[eV/c]) (B[T] cross n).\n'
        '    Full-step direction normalization removes only integration norm drift.\n'
        '    All RK stages must point forward in laboratory z; a turn is refused.\n'
        '    """\n'
        '    increments = []\n'
        '    for stage, fraction in ((None, 0.0), (0, 0.5), (1, 0.5), (2, 1.0)):\n'
        '        point = state if stage is None else tuple(\n'
        '            value + fraction * step_m * increment\n'
        '            for value, increment in zip(state, increments[stage])\n'
        '        )\n'
        '        if not all(math.isfinite(value) for value in point) or point[5] <= 0:\n'
        "            raise ConversionError('Dipole reference turns backward or has nonfinite state before ZSTOP')\n"
        '        bx, by, bz = _dipole_reference_field(field_at, point[:3])\n'
        '        nx, ny, nz = point[3:]\n'
        '        change = (\n'
        '            nx, ny, nz,\n'
        '            curvature_scale * (by * nz - bz * ny),\n'
        '            curvature_scale * (bz * nx - bx * nz),\n'
        '            curvature_scale * (bx * ny - by * nx),\n'
        '        )\n'
        '        if not all(math.isfinite(value) for value in change):\n'
        "            raise ConversionError('Dipole reference curvature overflows')\n"
        '        increments.append(change)\n'
        '    result = tuple(state[d] + step_m / 6 * (\n'
        '        increments[0][d] + 2 * increments[1][d]\n'
        '        + 2 * increments[2][d] + increments[3][d]\n'
        '    ) for d in range(6))\n'
        '    norm = math.hypot(*result[3:])\n'
        '    if (not all(math.isfinite(value) for value in result)\n'
        '            or not math.isfinite(norm) or norm == 0 or result[5] <= 0):\n'
        "        raise ConversionError('Dipole reference turns backward or has nonfinite state before ZSTOP')\n"
        '    return result[:3] + tuple(value / norm for value in result[3:])\n'
        '\n'
        '\n'
        'def estimate_dipole_reference_path(sample, zstop, field_at, *, ds_m=0.00025, max_steps=200000):\n'
        '    """Estimate static-field reference arc length to a forward lab-z plane.\n'
        '\n'
        '    The launch reference uses the physical particle centroid and direction of\n'
        '    mean normalized momentum, as OPALX does. RK4 advances in fixed arc-length\n'
        '    increments, with a bracketed final partial step. Momentum magnitude remains\n'
        '    constant: only a static magnetic field and no electric/space-charge force\n'
        '    are allowed. ``field_at((x,y,z))`` returns physical Tesla components.\n'
        '\n'
        '    The result is a reference-orbit approximation, not an exact ensemble mean-z\n'
        '    stopping rule. Endpoint sampling, map interpolation and reference/bunch\n'
        '    differences must still be checked in the actual tracking comparison.\n'
        '    """\n'
        "    zstop = _field_real(zstop, 'Dipole reference ZSTOP [m]')\n"
        "    ds_m = _field_real(ds_m, 'Dipole reference integration step [m]')\n"
        '    if ds_m <= 0:\n'
        "        raise ConversionError('Dipole reference integration step must be positive')\n"
        '    if (isinstance(max_steps, bool) or not isinstance(max_steps, int)\n'
        '            or not 1 <= max_steps <= 10000000):\n'
        "        raise ConversionError('Dipole reference max_steps must be an integer from 1 to 10000000')\n"
        '    if not callable(field_at):\n'
        "        raise ConversionError('Dipole reference requires a magnetic-field callable')\n"
        "    rows = sample.get('particles') if isinstance(sample, dict) else None\n"
        '    if not isinstance(rows, (tuple, list)) or not rows:\n'
        "        raise ConversionError('Dipole reference requires nonempty physical particle rows')\n"
        "    count = sample.get('count', len(rows))\n"
        '    if isinstance(count, bool) or not isinstance(count, int) or count != len(rows):\n'
        "        raise ConversionError('Dipole reference particle count does not match rows')\n"
        '    checked = []\n'
        '    for row in rows:\n'
        '        if not isinstance(row, (tuple, list)) or len(row) != 6:\n'
        "            raise ConversionError('Dipole reference rows require x,y,z,px,py,pz')\n"
        "        checked.append(tuple(_field_real(value, 'Dipole reference particle coordinate') for value in row))\n"
        '    try:\n'
        '        mean = tuple(math.fsum(row[d] / len(rows) for row in checked) for d in range(6))\n'
        '    except OverflowError as exc:\n'
        "        raise ConversionError('Dipole reference mean coordinate overflows') from exc\n"
        '    magnitude = math.hypot(*mean[3:])\n'
        '    momentum_eVc = magnitude * ELECTRON_REST_EV\n'
        '    if not math.isfinite(momentum_eVc) or momentum_eVc <= 0 or mean[5] <= 0:\n'
        "        raise ConversionError('Dipole reference requires finite positive forward mean momentum')\n"
        '    if not all(math.isfinite(value) for value in mean) or zstop <= mean[2]:\n'
        "        raise ConversionError('Dipole reference ZSTOP must be downstream of the initial centroid')\n"
        '    curvature_scale = C_LIGHT / momentum_eVc\n'
        '    if not math.isfinite(curvature_scale):\n'
        "        raise ConversionError('Dipole reference curvature scale overflows')\n"
        '    state = mean[:3] + tuple(value / magnitude for value in mean[3:])\n'
        '    path = 0.0\n'
        '    root_tolerance_m = max(1e-13, 8 * math.ulp(zstop))\n'
        '    for step in range(1, max_steps + 1):\n'
        '        # No forward unit tangent can reach the plane in less than its z gap.\n'
        '        # Taking a shorter last trial step also avoids unnecessary overshoot.\n'
        '        distance_to_plane = zstop - state[2]\n'
        '        step_m = min(ds_m, max(distance_to_plane, ds_m * 1e-3))\n'
        '        candidate = _dipole_reference_step(state, step_m, curvature_scale, field_at)\n'
        '        if candidate[2] <= state[2] or not math.isfinite(path + step_m):\n'
        "            raise ConversionError('Dipole reference makes no representable forward progress')\n"
        '        if candidate[2] >= zstop:\n'
        '            lower, upper = 0.0, step_m\n'
        '            endpoint = candidate\n'
        '            for _ in range(64):\n'
        '                middle = (lower + upper) / 2\n'
        '                trial = _dipole_reference_step(state, middle, curvature_scale, field_at)\n'
        '                if abs(trial[2] - zstop) <= root_tolerance_m:\n'
        '                    endpoint, upper = trial, middle\n'
        '                    break\n'
        '                if trial[2] < zstop:\n'
        '                    lower = middle\n'
        '                else:\n'
        '                    upper, endpoint = middle, trial\n'
        '            path += upper\n'
        '            return {\n'
        "                'path_length_m': path,\n"
        "                'reference_position_m': list(endpoint[:3]),\n"
        "                'direction': list(endpoint[3:]),\n"
        "                'steps': step,\n"
        "                'ds_m': ds_m,\n"
        "                'momentum_eV_c': momentum_eVc,\n"
        "                'target_lab_z_m': zstop,\n"
        "                'endpoint_z_residual_m': endpoint[2] - zstop,\n"
        "                'model': 'Static magnetic centroid reference, normalized RK4 in arc length, bracketed final step',\n"
        "                'limitations': [\n"
        "                    'Reference-orbit approximation; ASTRA stops on ensemble mean laboratory z',\n"
        "                    'Reference equation includes only static external magnetic fields; no collective force acts on the native reference',\n"
        "                    'Forward monotone laboratory z required at every integration stage',\n"
        "                    'Actual endpoint sampling and map interpolation require tracking comparison',\n"
        '                ],\n'
        '            }\n'
        '        path += step_m\n'
        '        state = candidate\n'
        "    raise ConversionError('Dipole reference exceeds the integration step ceiling before ZSTOP')\n"
        '\n'
        '\n'
        'def read_aperture_table(text: str) -> list:\n'
        '    """Read ASTRA z[m], radius[mm] rows, preserving vertical steps.\n'
        '\n'
        "    Nondecreasing positions match ASTRA's manual: duplicate positions describe\n"
        '    vertical walls. Finite strictly positive radii are needed by native OPALX\n'
        '    circular holes. Plugs, closed ends and tapered intervals are handled by\n'
        '    explicit refusals, not replaced by approximate cylinders.\n'
        '    """\n'
        '    try:\n'
        "        text.encode('ascii')\n"
        '    except UnicodeError as exc:\n'
        "        raise ConversionError('Aperture table must be ASCII') from exc\n"
        '    rows = []\n'
        '    for line_number, line in enumerate(text.splitlines(), 1):\n'
        "        line = line.split('!', 1)[0].strip()\n"
        '        if not line:\n'
        '            continue\n'
        "        tokens = line.replace(',', ' ').split()\n"
        '        if len(tokens) != 2:\n'
        "            raise ConversionError(f'Aperture table line {line_number}: need exactly two columns')\n"
        '        try:\n'
        "            z, radius_mm = (float(value.replace('D', 'e').replace('d', 'e')) for value in tokens)\n"
        '        except ValueError as exc:\n'
        "            raise ConversionError(f'Aperture table line {line_number}: invalid numeric value') from exc\n"
        '        if not math.isfinite(z) or not math.isfinite(radius_mm) or radius_mm <= 0:\n'
        "            raise ConversionError(f'Aperture table line {line_number}: need finite z and positive radius')\n"
        '        if rows and z < rows[-1][0]:\n'
        "            raise ConversionError(f'Aperture table line {line_number}: z must not decrease')\n"
        '        radius_m = radius_mm * .001\n'
        '        if radius_m == 0 or not math.isfinite(2*radius_m):\n'
        "            raise ConversionError('Aperture radius cannot be represented as a positive finite diameter')\n"
        '        rows.append((z, radius_m))\n'
        '    if len(rows) < 2 or rows[-1][0] <= rows[0][0]:\n'
        "        raise ConversionError('Aperture table needs at least two positions spanning a positive length')\n"
        '    return rows\n'
        '\n'
        '\n'
        'def aperture_specs(groups: dict) -> list:\n'
        '    """Validate finite, straight circular holes in an active ASTRA APERTURE.\n'
        '\n'
        '    Positive RAD and tabulated piecewise-constant positive circular holes are\n'
        '    supported. Arrays must be contiguous 1..N. Secondary emission, rotations,\n'
        '    plugs, grids and planar geometries remain explicit refusals. Transverse\n'
        '    translations [m] are supported while the straight design axis remains\n'
        '    strictly inside every section, so native orbit threading registers it.\n'
        '    A_pos shifts keyword and file positions in metres; Ap_R is millimetres.\n'
        '    Source lost-particle stack cleanup is retained only as report metadata:\n'
        '    native OPALX always deletes absorbed particles at its end-of-step flush.\n'
        '    """\n'
        "    values = groups.get('aperture', {})\n"
        "    active = _field_logical(values.get('lapert', False), 'APERTURE.LApert')\n"
        '    if not active:\n'
        '        return []\n'
        "    if _field_logical(values.get('loop', False), 'APERTURE.LOOP'):\n"
        "        raise ConversionError('APERTURE.LOOP is unsupported')\n"
        "    check_ref = _field_logical(groups.get('newrun', {}).get('check_ref_part', True),\n"
        "                               'NEWRUN.Check_ref_part')\n"
        '    if check_ref:\n'
        "        raise ConversionError('Active apertures require NEWRUN.Check_ref_part=FALSE; OPALX cannot mirror ASTRA probe-abort semantics')\n"
        "    clean_stack = _field_logical(values.get('lclean_stack', False), 'APERTURE.LClean_Stack')\n"
        "    capacity = values.get('max_secondary', 500000)\n"
        '    if isinstance(capacity, bool) or not isinstance(capacity, int) or capacity <= 0:\n'
        "        raise ConversionError('APERTURE.Max_Secondary must be a positive integer')\n"
        "    scalar_allowed = {'lapert', 'loop', 'lclean_stack', 'max_secondary'}\n"
        "    indexed_allowed = {'file_aperture', 'ap_z1', 'ap_z2', 'ap_r', 'a_pos',\n"
        "                       'a_xoff', 'a_yoff', 'a_xrot', 'a_yrot', 'a_zrot',\n"
        "                       'se_d0', 'se_epm', 'se_fs', 'se_tau', 'se_esc', 'se_ff1', 'se_ff2'}\n"
        '    indices = set()\n'
        '    for key in values:\n'
        '        if key in scalar_allowed:\n'
        '            continue\n'
        "        match = re.fullmatch(r'([a-z][a-z0-9_]*)\\(([0-9]+)\\)', key)\n"
        '        if not match or match.group(1) not in indexed_allowed:\n'
        "            raise ConversionError('Unsupported active aperture.'+key)\n"
        '        index = int(match.group(2))\n'
        '        if index == 0:\n'
        "            raise ConversionError('APERTURE arrays start at index one')\n"
        '        indices.add(index)\n'
        '    if not indices or sorted(indices) != list(range(1, len(indices)+1)):\n'
        "        raise ConversionError('APERTURE indices must be contiguous 1..N')\n"
        "    hmax_ns = _field_real(groups.get('newrun', {}).get('h_max', .001), 'NEWRUN.H_max')\n"
        '    if hmax_ns <= 0:\n'
        "        raise ConversionError('NEWRUN.H_max must be positive for aperture thickness checks')\n"
        '    maximum_step_m = C_LIGHT * (hmax_ns*1e-9)\n'
        '    if not math.isfinite(maximum_step_m) or maximum_step_m <= 0:\n'
        "        raise ConversionError('Aperture maximum particle step overflow')\n"
        '    specs = []\n'
        '    for index in sorted(indices):\n'
        '        def parameter(base, default=None):\n'
        "            return values.get(f'{base}({index})', default)\n"
        '\n'
        "        filename = parameter('file_aperture')\n"
        '        if (not isinstance(filename, str) or not filename.strip()\n'
        "                or any(c in filename for c in '\\0\\r\\n')):\n"
        "            raise ConversionError(f'APERTURE.File_Aperture({index}) requires a nonempty filename or RAD')\n"
        '        mode = filename.strip().lower()\n'
        "        if mode != 'rad' and mode.startswith(('rad', 'cir', 'scr_x', 'scr_y', 'col_x', 'col_y')):\n"
        "            raise ConversionError('Only exact RAD keyword is supported; reserved ASTRA aperture keyword prefixes cannot name tables')\n"
        "        position = _field_real(parameter('a_pos', 0.), f'APERTURE.A_pos({index})')\n"
        "        offsets = [_field_real(parameter('a_'+suffix, 0.), f'APERTURE.A_{suffix}({index})')\n"
        "                   for suffix in ('xoff', 'yoff')]\n"
        "        for suffix in ('xrot', 'yrot', 'zrot'):\n"
        "            value = _field_real(parameter('a_'+suffix, 0.), f'APERTURE.A_{suffix}({index})')\n"
        '            if value != 0:\n'
        "                raise ConversionError(f'Nonzero APERTURE.A_{suffix}({index}) is unsupported')\n"
        "        for base, default in [('se_d0', 0.), ('se_epm', 10.), ('se_fs', 0.), ('se_tau', 0.),\n"
        "                              ('se_esc', 0.), ('se_ff1', 0.), ('se_ff2', 0.)]:\n"
        "            value = _field_real(parameter(base, default), f'APERTURE.{base}({index})')\n"
        '            if value != default:\n'
        "                raise ConversionError(f'Secondary-emission setting APERTURE.{base}({index}) is unsupported')\n"
        "        spec = {'kind': 'aperture', 'index': index, 'filename': filename, 'position': position,\n"
        "                'mode': 'rad' if mode == 'rad' else 'table',\n"
        "                'maximum_step_m': maximum_step_m, 'source_clean_stack': clean_stack,\n"
        "                'offset_x_m': offsets[0], 'offset_y_m': offsets[1]}\n"
        "        if mode == 'rad':\n"
        "            z1 = _field_real(parameter('ap_z1'), f'APERTURE.Ap_Z1({index})')\n"
        "            z2 = _field_real(parameter('ap_z2'), f'APERTURE.Ap_Z2({index})')\n"
        "            radius_mm = _field_real(parameter('ap_r'), f'APERTURE.Ap_R({index})')\n"
        '            radius_m = radius_mm*.001\n'
        '            if radius_m <= 0 or not math.isfinite(2*radius_m):\n'
        "                raise ConversionError('RAD requires a positive finite hole radius; plugs/closed holes are unsupported')\n"
        '            if math.hypot(*offsets) >= radius_m:\n'
        "                raise ConversionError('Translated aperture must strictly contain the design axis for native orbit threading')\n"
        '            if not math.isfinite(z2-z1) or z2-z1 <= maximum_step_m:\n'
        "                raise ConversionError('RAD aperture thickness must exceed c*H_max to prevent skipped walls')\n"
        "            spec['segments'] = [(z1, z2, radius_m)]\n"
        "        elif any(f'{base}({index})' in values for base in ('ap_z1', 'ap_z2', 'ap_r')):\n"
        "            raise ConversionError('Ap_Z1/Ap_Z2/Ap_R are keyword-only and cannot accompany a table')\n"
        '        specs.append(spec)\n'
        '    return specs\n'
        '\n'
        '\n'
        'def aperture_segments(rows: list, maximum_step_m: float) -> list:\n'
        '    """Reduce exact constant-radius table intervals, refusing smooth tapers.\n'
        '\n'
        '    Duplicate-z transitions encode a step. Every emitted interval is required\n'
        '    to exceed the light-speed maximum particle step so neither tracker can\n'
        '    jump a whole restrictive section. Adjacent equal-radius intervals merge\n'
        '    before this test, so harmless dense sampling does not trigger a refusal.\n'
        '    """\n'
        "    maximum_step_m = _field_real(maximum_step_m, 'Maximum particle step')\n"
        '    if maximum_step_m <= 0:\n'
        "        raise ConversionError('Maximum particle step must be positive')\n"
        '    # Keep this callable safe independently of the table reader.\n'
        '    if not isinstance(rows, list) or len(rows) < 2:\n'
        "        raise ConversionError('Aperture segments require at least two table rows')\n"
        '    previous_z = None\n'
        '    for row in rows:\n'
        '        if not isinstance(row, (tuple, list)) or len(row) != 2:\n'
        "            raise ConversionError('Aperture row must contain z and radius')\n"
        "        z = _field_real(row[0], 'Aperture z')\n"
        "        radius = _field_real(row[1], 'Aperture radius')\n"
        '        if radius <= 0 or not math.isfinite(2*radius):\n'
        "            raise ConversionError('Aperture radius must be positive finite')\n"
        '        if previous_z is not None and z < previous_z:\n'
        "            raise ConversionError('Aperture z must not decrease')\n"
        '        previous_z = z\n'
        '    segments = []\n'
        '    for i, ((left, radius), (right, next_radius)) in enumerate(zip(rows, rows[1:])):\n'
        '        if right == left:\n'
        '            if radius != next_radius:\n'
        '                if (i == 0 or i+1 == len(rows)-1\n'
        '                        or rows[i-1][0] == left or rows[i+2][0] == right):\n'
        "                    raise ConversionError('Aperture vertical transitions need positive-length sections on both sides')\n"
        '            continue\n'
        '        if radius != next_radius:\n'
        "            raise ConversionError('Tapered aperture intervals are unsupported; no cylindrical approximation is made')\n"
        '        if segments and segments[-1][1] == left and segments[-1][2] == radius:\n'
        '            segments[-1] = (segments[-1][0], right, radius)\n'
        '        else:\n'
        '            segments.append((left, right, radius))\n'
        '    if not segments:\n'
        "        raise ConversionError('Aperture table has no positive-length intervals')\n"
        '    if any(not math.isfinite(right-left) or right-left <= maximum_step_m\n'
        '           for left, right, _ in segments):\n'
        "        raise ConversionError('Every aperture section thickness must exceed c*H_max to prevent skipped walls')\n"
        '    return segments\n'
        '\n'
        '\n'
        'def prepare_apertures(groups: dict, source_dir) -> dict:\n'
        '    """Render straight circular holes as native positive-length COLLIMATORs.\n'
        '\n'
        '    ASTRA radius[mm] becomes OPALX CIRCLE diameter[m]. Both codes count the\n'
        '    radial boundary as lost (verified in native controls); body-exit sampling\n'
        '    and loss timing differ by up to a tracking step. No map file is needed.\n'
        '    """\n'
        "    result = {'elements': [], 'files': {}, 'apertures': []}\n"
        '    for spec in aperture_specs(groups):\n'
        '        metadata = dict(spec)\n'
        "        if spec['mode'] == 'table':\n"
        "            source = (Path(source_dir)/spec['filename']).resolve()\n"
        '            raw = source.read_bytes()\n'
        '            try:\n'
        "                rows = read_aperture_table(raw.decode('ascii'))\n"
        '            except UnicodeError as exc:\n'
        "                raise ConversionError(f'Aperture table {source} must be ASCII') from exc\n"
        "            segments = aperture_segments(rows, spec['maximum_step_m'])\n"
        '            metadata.update(source=str(source), source_sha256=hashlib.sha256(raw).hexdigest(),\n'
        '                            input_points=len(rows))\n'
        '        else:\n'
        "            segments = spec['segments']\n"
        "        offset_radius = math.hypot(spec['offset_x_m'], spec['offset_y_m'])\n"
        '        if any(offset_radius >= radius for _, _, radius in segments):\n'
        "            raise ConversionError('Translated aperture must strictly contain the design axis for native orbit threading')\n"
        '        target_names = []\n'
        '        target_segments = []\n'
        '        for segment_index, (left, right, radius) in enumerate(segments, 1):\n'
        "            start = left+spec['position']\n"
        "            end = right+spec['position']\n"
        '            if not all(math.isfinite(value) for value in (start, end)) or end <= start:\n'
        "                raise ConversionError('Global aperture bounds overflow or lose their positive span')\n"
        '            name = f\'ASTRA_AP_{spec["index"]}_{segment_index}\'\n'
        "            text = (f'{name}: COLLIMATOR, L={right-left:.17g}, '\n"
        '                    f\'APERTURE="CIRCLE({2*radius:.17g})", \'\n'
        '                    f\'DELETEONTRANSVERSEEXIT=TRUE, X={spec["offset_x_m"]:.17g}, \'\n'
        '                    f\'Y={spec["offset_y_m"]:.17g}, Z={start:.17g};\')\n'
        "            result['elements'].append(text)\n"
        '            target_names.append(name)\n'
        "            target_segments.append({'element': name, 'global_bounds_m': [start, end],\n"
        "                                    'radius_m': radius, 'target_diameter_m': 2*radius,\n"
        "                                    'center_xy_m': [spec['offset_x_m'], spec['offset_y_m']],\n"
        "                                    'design_axis_clearance_m': radius-offset_radius})\n"
        '        metadata.update(elements=target_names, segments=target_segments,\n'
        "                        source_config=dict(groups['aperture']),\n"
        "                        geometry_model='constant circular holes; exact stepped geometry with no taper approximation',\n"
        "                        radial_boundary='r >= radius is lost in both native codes',\n"
        "                        target_body_interval='[z_start,z_end)',\n"
        "                        loss_model='sampled absorption; OPALX deletes lost particles after each step',\n"
        "                        caveat='Loss timing and endpoint sampling differ by up to a step; native reference must remain inside every section; compare survivor IDs/counts')\n"
        "        result['apertures'].append(metadata)\n"
        '    return result\n'
        '\n'
        '\n'
        'def validate_aperture_reference(groups: dict, sample: dict, apertures_metadata: list) -> dict:\n'
        '    """Refuse aperture geometries native OPALX reference threading can miss.\n'
        '\n'
        "    OPALX registers COLLIMATOR through the reference trajectory's strict inside\n"
        '    predicate. In a field-free line the reference follows the initial centroid\n'
        '    and normalized mean momentum, so checking both ends of every circular body\n'
        '    proves containment throughout that convex section. Every body must extend\n'
        '    downstream of launch. With on-axis RF, solenoid or quadrupole fields, only\n'
        '    a centered axial reference is certified; transverse centroid/momentum means\n'
        '    within 1e-14 are treated as roundoff around the invariant design axis.\n'
        '    This roundoff guard is a conversion scope condition, not a metric tolerance.\n'
        '    """\n'
        '    if not apertures_metadata:\n'
        "        return {'required': False, 'policy': 'No active aperture reference registration required',\n"
        "                'checked_segments': []}\n"
        '    if dipole_specs(groups):\n'
        "        raise ConversionError('Apertures with dipoles need a separately verified curved reference registration')\n"
        "    rows = sample.get('particles')\n"
        '    if not isinstance(rows, list) or not rows:\n'
        "        raise ConversionError('Aperture reference preflight requires nonempty physical particle rows')\n"
        '    n = len(rows)\n'
        '    validated_rows = []\n'
        '    for row in rows:\n'
        '        if not isinstance(row, (list, tuple)) or len(row) != 6:\n'
        "            raise ConversionError('Aperture reference particle rows must contain x,y,z,px,py,pz')\n"
        "        validated_rows.append([_field_real(value, 'Aperture reference particle coordinate') for value in row])\n"
        '    centroid = [math.fsum(row[d]/n for row in validated_rows) for d in range(3)]\n'
        '    momentum = [math.fsum(row[d]/n for row in validated_rows) for d in range(3, 6)]\n'
        '    if not all(math.isfinite(value) for value in centroid+momentum) or momentum[2] <= 0:\n'
        "        raise ConversionError('Aperture reference requires finite centroid and positive mean longitudinal momentum')\n"
        '    active_fields = []\n'
        "    for name, switch in [('cavity', 'lefield'), ('solenoid', 'lbfield'), ('quadrupole', 'lquad')]:\n"
        "        if _field_logical(groups.get(name, {}).get(switch, False), name+'.'+switch):\n"
        '            active_fields.append(name)\n'
        '    roundoff = 1e-14\n'
        '    if active_fields:\n'
        '        if any(abs(value) > roundoff for value in centroid[:2]+momentum[:2]):\n'
        "            raise ConversionError('Apertures with RF/solenoid/quadrupole fields require a centered axial centroid reference')\n"
        '        origin_xy, slopes = [0., 0.], [0., 0.]\n'
        "        policy = 'Invariant on-axis field reference; transverse centroid and mean momentum treated as zero within roundoff'\n"
        '    else:\n'
        '        origin_xy = centroid[:2]\n'
        '        slopes = [momentum[d]/momentum[2] for d in range(2)]\n'
        '        if not all(math.isfinite(value) for value in slopes):\n'
        "            raise ConversionError('Aperture drift reference slope overflow')\n"
        "        policy = 'Exact field-free reference line from initial centroid and normalized mean momentum'\n"
        '    checked = []\n'
        '    for aperture in apertures_metadata:\n'
        "        if not isinstance(aperture, dict) or not aperture.get('segments'):\n"
        "            raise ConversionError('Aperture reference metadata requires nonempty circular segments')\n"
        "        for segment in aperture['segments']:\n"
        '            if not isinstance(segment, dict):\n'
        "                raise ConversionError('Aperture reference segment metadata must be a mapping')\n"
        "            bounds, center = segment.get('global_bounds_m'), segment.get('center_xy_m')\n"
        '            if (not isinstance(bounds, (list, tuple)) or len(bounds) != 2\n'
        '                    or not isinstance(center, (list, tuple)) or len(center) != 2):\n'
        "                raise ConversionError('Aperture reference segment needs two bounds and a transverse center')\n"
        "            left, right = [_field_real(value, 'Aperture reference body bound') for value in bounds]\n"
        "            center = [_field_real(value, 'Aperture reference center') for value in center]\n"
        "            radius = _field_real(segment.get('radius_m'), 'Aperture reference radius')\n"
        '            if radius <= 0 or right <= left:\n'
        "                raise ConversionError('Aperture reference body length and circular radius must be positive')\n"
        '            if right <= centroid[2]:\n'
        "                raise ConversionError('Aperture body must extend downstream of the initial centroid reference')\n"
        '            entry = max(left, centroid[2])\n'
        '            endpoints, clearances = [], []\n'
        '            for z in (entry, right):\n'
        '                xy = [origin_xy[d]+(z-centroid[2])*slopes[d] for d in range(2)]\n'
        '                distance = math.hypot(xy[0]-center[0], xy[1]-center[1])\n'
        '                if not all(math.isfinite(value) for value in xy) or distance >= radius:\n'
        "                    raise ConversionError('Centroid reference misses or crosses an aperture body; native registration is not certified')\n"
        '                endpoints.append(xy)\n'
        '                clearances.append(radius-distance)\n'
        "            checked.append({'element': segment.get('element'), 'checked_z_m': [entry, right],\n"
        "                            'reference_xy_m': endpoints, 'center_xy_m': center,\n"
        "                            'radius_m': radius, 'minimum_reference_clearance_m': min(clearances)})\n"
        "    return {'required': True, 'policy': policy, 'active_fields': active_fields,\n"
        "            'initial_centroid_m': centroid, 'initial_mean_normalized_momentum': momentum,\n"
        "            'reference_line_xy_at_launch_m': origin_xy, 'reference_slope_dx_dz_dy_dz': slopes,\n"
        "            'centered_field_roundoff_absolute': roundoff if active_fields else None,\n"
        "            'checked_segments': checked,\n"
        "            'condition': 'Strict circular containment at both ends proves containment of each straight reference segment'}\n"
        '\n'
        '\n'
        'def dipole_beamline_specs(groups: dict) -> list:\n'
        '    """Restrict first dipole migration to static, single-plane dipole-only lines.\n'
        '\n'
        '    Coupled RF/solenoid/quadrupole fields and aperture reference threading need\n'
        '    separate curved-orbit validation. Centered, axial reference controls in a\n'
        '    fixed bend plane permit laboratory reconstruction from reference momentum;\n'
        '    off-plane offsets or launch momenta can break that analysis assumption.\n'
        '    """\n'
        '    specs = dipole_specs(groups)\n'
        '    if specs:\n'
        "        for group, switch in [('cavity','lefield'), ('solenoid','lbfield'),\n"
        "                              ('quadrupole','lquad'), ('aperture','lapert')]:\n"
        "            if _field_logical(groups.get(group,{}).get(switch,False), group+'.'+switch):\n"
        "                raise ConversionError('Dipoles combined with active '+group+' are not yet verified')\n"
        "        if len({one['type'] for one in specs}) != 1:\n"
        "            raise ConversionError('Compound horizontal/vertical dipole beamlines are not yet verified')\n"
        '    return specs\n'
        '\n'
        '\n'
        'def prepare_dipole_reference(groups: dict, sample: dict, metadata: list, *, ds_m=.00025):\n'
        '    """Estimate the source centroid reference arc and certify map containment.\n'
        '\n'
        '    The analytic source field is used; actual trilinear grid error is checked\n'
        '    independently in tracking. Only the reference is certified here. Every\n'
        '    particle must remain inside the declared finite x/y map support during\n'
        '    tracking; expanding support and grid refinement remain user review items.\n'
        '    """\n'
        '    specs = dipole_beamline_specs(groups)\n'
        '    if not specs:\n'
        '        return None\n'
        '    if len(metadata) != len(specs):\n'
        "        raise ConversionError('Dipole reference requires matching prepared map metadata')\n"
        '    def field_at(position):\n'
        '        components = [0.,0.,0.]\n'
        '        for spec, prepared in zip(specs, metadata):\n'
        '            field = evaluate_dipole_field(spec, position)\n'
        "            bounds = prepared['interpolation_model']['local_bounds_m']\n"
        '            if any(field) and any(not bounds[d][0] <= position[d] < bounds[d][1] for d in (0,1)):\n'
        "                raise ConversionError('Dipole centroid reference leaves finite map support; enlarge --dipole-radius')\n"
        '            for d in range(3):\n'
        '                components[d] += field[d]\n'
        '        return tuple(components)\n'
        "    requested_ds = _field_real(ds_m, 'Dipole reference integration step [m]')\n"
        '    if requested_ds <= 0:\n'
        "        raise ConversionError('Dipole reference integration step must be positive')\n"
        '    # RK stages could otherwise jump entirely over a short magnet, even though\n'
        '    # its emitted map is well resolved. Bound motion in every face normal by\n'
        '    # the smallest source gap/100, since |dR/ds|=1.\n'
        "    effective_ds = min(requested_ds, min(gap for spec in specs for gap in spec['gaps_m'])/100)\n"
        "    result = estimate_dipole_reference_path(sample, groups['output']['zstop'], field_at, ds_m=effective_ds)\n"
        "    result['requested_ds_m'] = requested_ds\n"
        "    result['step_policy'] = 'At most requested step and smallest source fringe gap/100; prevents skipped short magnets'\n"
        "    result['field_model'] = 'Analytic ASTRA source; emitted map interpolation is separately reviewable'\n"
        "    result['reference_transverse_map_containment'] = 'Checked at all RK4 stages with nonzero source field'\n"
        "    result['limitations'].append('All-particle transverse support needs tracking checks; reference containment alone is insufficient')\n"
        '    return result\n'
        '\n'
        '\n'
        'def space_charge_spec(groups):\n'
        '    """Describe an approximate open, single-rest-frame 3D PIC migration.\n'
        '\n'
        "    ASTRA's N*f are grid lines; N*0 are empty intervals at each side. OPALX\n"
        '    uses N points with spacing span/(N-1), and one common fractional margin.\n'
        '    Matching this geometric relationship does not make the PIC discretizations\n'
        '    identical: ASTRA describes cell-constant charge and smoothed potentials;\n'
        '    OPALX deposits/gathers CIC and differentiates an integrated Green function.\n'
        '    """\n'
        "    values = groups.get('charge', {})\n"
        "    for key in ('lspch', 'lspch3d', 'l2d_3d', 'lspch3dmg', 'l2d_3dmg',\n"
        "                'lmirror', 'l_curved_cathode', 'l_qscale', 'loop'):\n"
        '        if key in values and not isinstance(values[key], bool):\n'
        "            raise ConversionError(f'Expected logical CHARGE.{key}')\n"
        "    if not values.get('lspch', False):\n"
        '        return None\n'
        "    if values.get('lspch3d') is not True:\n"
        "        raise ConversionError('Active space charge requires CHARGE.LSPCH3D=True; cylindrical source solver is unsupported')\n"
        "    for key in ('loop', 'l2d_3d', 'lspch3dmg', 'l2d_3dmg', 'l_curved_cathode'):\n"
        '        if values.get(key, False):\n'
        "            raise ConversionError(f'Active CHARGE.{key} is unsupported with injected 3DFFT space charge')\n"
        "    allowed = {'lspch', 'lspch3d', 'l2d_3d', 'lspch3dmg', 'l2d_3dmg', 'lmirror',\n"
        "               'l_curved_cathode', 'loop', 'nxf', 'nyf', 'nzf',\n"
        "               'nx0', 'ny0', 'nz0', 'smooth_x', 'smooth_y', 'smooth_z',\n"
        "               'max_scale', 'max_count', 'exp_control', 'melange',\n"
        "               'nrad', 'cell_var', 'nlong_in', 'n_min', 'min_grid'}\n"
        '    unknown = sorted(set(values) - allowed)\n'
        '    if unknown:\n'
        "        raise ConversionError(f'Unsupported active space-charge attribute CHARGE.{unknown[0]}')\n"
        "    if values.get('melange', 0) != 0 or isinstance(values.get('melange', 0), bool):\n"
        "        raise ConversionError('ASTRA velocity-binned space charge MELANGE is unsupported')\n"
        "    mesh = [values.get(f'n{axis}f', 8) for axis in 'xyz']\n"
        "    padding = [values.get(f'n{axis}0', 2) for axis in 'xyz']\n"
        "    for axis, n, pad in zip('xyz', mesh, padding):\n"
        '        if isinstance(n, bool) or not isinstance(n, int) or n < 4 or n > 512 or n & (n-1):\n'
        "            raise ConversionError(f'CHARGE.N{axis}f must be a power-of-two integer in 4..512; source auto-rounding is not migrated')\n"
        '        if isinstance(pad, bool) or not isinstance(pad, int) or pad < 1 or n-1-2*pad <= 0:\n'
        "            raise ConversionError(f'CHARGE.N{axis}0 must leave positive bunch intervals and at least one empty interval on each side')\n"
        '    if math.prod(mesh) > 2097152:\n'
        "        raise ConversionError('Space-charge mesh exceeds the converter resource ceiling of 2097152 points')\n"
        '    occupied = [n-1-2*p for n,p in zip(mesh,padding)]\n'
        '    if any(p*occupied[0] != padding[0]*n for p,n in zip(padding,occupied)):\n'
        "        raise ConversionError('Per-axis ASTRA padding fractions differ; OPALX has one BBOXINCR so this geometry cannot be preserved')\n"
        "    for axis in 'xyz':\n"
        "        smooth = values.get(f'smooth_{axis}', 0)\n"
        '        if isinstance(smooth, bool) or not isinstance(smooth, int) or smooth != 0:\n'
        "            raise ConversionError(f'Nonzero/invalid CHARGE.Smooth_{axis} potential smoothing is unsupported')\n"
        "    max_count = values.get('max_count', 40)\n"
        '    if isinstance(max_count, bool) or not isinstance(max_count, int) or max_count != 1:\n'
        "        raise ConversionError('Active 3DFFT migration requires explicit CHARGE.Max_count=1; source field caching/scaling is not migrated')\n"
        "    for key, default in (('max_scale', .05), ('exp_control', .1)):\n"
        '        value = values.get(key, default)\n'
        '        if isinstance(value, bool) or not isinstance(value, (int,float)) or not math.isfinite(value) or value <= 0:\n'
        "            raise ConversionError(f'CHARGE.{key} must be finite and positive')\n"
        "    ignored = {k:values[k] for k in ('nrad','cell_var','nlong_in','n_min','min_grid') if k in values}\n"
        '    return {\n'
        "        'model': 'ASTRA 3DFFT average-rest-frame electrostatics to OPALX open Cartesian PIC, one fixed gamma bin',\n"
        "        'mesh': mesh, 'source_padding_intervals': padding,\n"
        "        'source_occupied_intervals': occupied,\n"
        "        'bbox_increase_percent': 100.0*padding[0]/occupied[0],\n"
        "        'target_solver': 'OPEN', 'target_green_function': 'INTEGRATED',\n"
        "        'target_bins': 1, 'target_binning_parameter': 'GAMMAZ', 'target_adaptive_binning': False,\n"
        "        'target_field_update': 'MIDPOINT', 'target_boundary': 'OPEN',\n"
        "        'target_image_charges': False, 'source_mirror_setting_ignored_in_3d': values.get('lmirror', True),\n"
        "        'source_update_controls': {'max_scale':values.get('max_scale',.05), 'max_count':max_count,\n"
        "                                   'exp_control':values.get('exp_control',.1)},\n"
        "        'inactive_2d_settings': ignored,\n"
        "        'limitations': [\n"
        "            'Both are quasi-static average-rest-frame models; broad energy spread is not represented by multiple bins',\n"
        "            'Matching mesh counts and fractional margins preserves nominal support and spacing, not deposition/interpolation identity',\n"
        "            'ASTRA potential smoothing must be zero; OPALX uses CIC deposition/gather and its integrated Green function',\n"
        "            'ASTRA adaptively rescales/recomputes fields and may reduce timesteps; OPALX recomputes every fixed-H_max midpoint step',\n"
        "            'ASTRA4 observed to bypass 3DFFT forces at five or fewer particles; such snapshots need separate handling',\n"
        "            'Sparse and collapsing bunches require explicit population, mesh and timestep validation',\n"
        '        ]}\n'
        '\n'
        '\n'
        'def validate_space_charge_sample(sample: dict, spec):\n'
        '    """Require a finite-volume interacting source population for 3D PIC.\n'
        '\n'
        '    ASTRA4 source controls bypass collective forces for five or fewer active\n'
        '    particles. A zero spatial extent makes its 3D grid singular. Neither case\n'
        '    is silently replaced by a different target collective model.\n'
        '    """\n'
        '    if spec is None:\n'
        '        return None\n'
        "    rows = sample.get('particles', [])\n"
        '    if len(rows) <= 5:\n'
        "        raise ConversionError('3D space charge needs at least six particles; ASTRA4 bypasses forces for five or fewer')\n"
        '    spans = [max(row[d] for row in rows)-min(row[d] for row in rows) for d in range(3)]\n'
        '    if any(not math.isfinite(span) or span <= 0 for span in spans):\n'
        "        raise ConversionError('3D space charge requires finite nonzero x/y/z extents; zero-thickness snapshots need an explicit finite-volume variant')\n"
        "    return {'particles': len(rows), 'initial_lab_spans_m': spans,\n"
        "            'classification': 'Sparse-particle code-path test' if len(rows)<10000 else 'Finite-particle PIC comparison',\n"
        "            'notes': ['Population/mesh/time convergence is required before quantitative space-charge validation',\n"
        "                      'Native mesh minimum-span handling and deposition are not identical across codes']}\n"
        '\n'
        '\n'
        'def conversion_groups(groups: Namelists, force_no_space_charge: bool = False) -> tuple:\n'
        '    """Copy parsed namelists and optionally disable the source charge solver.\n'
        '\n'
        '    The unified converter deliberately uses external fields only for ASTRA.\n'
        '    When requested, replace the complete CHARGE namelist before assessing any\n'
        '    solver settings or particles. Preserve its original contents in the returned\n'
        '    policy so the omission is visible without interpreting inactive parameters.\n'
        "    The standalone engine's default retains its existing space-charge rules.\n"
        '    """\n'
        '    if not isinstance(force_no_space_charge, bool):\n'
        "        raise ConversionError('Force-no-space-charge flag must be logical')\n"
        '    prepared = {name: dict(values) for name, values in groups.items()}\n'
        '    if not force_no_space_charge:\n'
        '        return prepared, None\n'
        "    original_charge = dict(groups.get('charge', {}))\n"
        "    prepared['charge'] = {'lspch': False}\n"
        '    policy = {\n'
        "        'target_type': 'NONE',\n"
        "        'forced_off': True,\n"
        "        'source_charge': original_charge,\n"
        "        'reason': 'ASTRA conversion uses external fields only; source space charge is disabled',\n"
        '    }\n'
        '    return prepared, policy\n'
        '\n'
        '\n'
        'def assess(groups: Namelists) -> dict:\n'
        '    """Classify supported injected tracking, refusing unsupported physics.\n'
        '\n'
        '    Inactive field/charge groups are retained in the report but have no effect.\n'
        '    Output sampling differs between codes and is explicitly reported.\n'
        '    """\n'
        '    issues = []\n'
        "    known = {'newrun', 'output', 'charge', 'cavity', 'solenoid', 'quadrupole',\n"
        "             'dipole', 'aperture', 'wake', 'laser', 'scan', 'error', 'modules', 'fem'}\n"
        '    for group in sorted(set(groups)-known):\n'
        "        issues.append(f'Unsupported namelist &{group}')\n"
        "    for group, switch in [('wake','lwake'),\n"
        "                          ('laser','llaser'), ('scan','lscan'), ('error','lerror')]:\n"
        '        values = groups.get(group, {})\n'
        '        if switch in values and not isinstance(values[switch], bool):\n'
        "            issues.append(f'Expected logical {group}.{switch}')\n"
        '        elif values.get(switch, False):\n'
        "            issues.append(f'Active {group}.{switch} is unsupported')\n"
        '    # These groups contain placements/replication and cannot be discarded safely.\n'
        "    for group in ('modules',):\n"
        '        if groups.get(group):\n'
        "            issues.append(f'&{group} is unsupported')\n"
        '    # Real machine templates include an empty FEM placeholder. No FEM setting\n'
        '    # or model is migrated; a populated group remains outside this converter.\n'
        "    if groups.get('fem'):\n"
        "        issues.append('Nonempty &FEM is unsupported')\n"
        '    # Unknown content in inactive groups is safe only when inactivity is explicit.\n'
        "    switches = {'charge':'lspch', 'cavity':'lefield', 'solenoid':'lbfield',\n"
        "                'quadrupole':'lquad', 'dipole':'ldipole', 'aperture':'lapert',\n"
        "                'wake':'lwake', 'laser':'llaser', 'scan':'lscan', 'error':'lerror'}\n"
        '    for group, switch in switches.items():\n'
        '        if groups.get(group) and switch not in groups[group]:\n'
        "            issues.append(f'Nonempty &{group} requires an explicit {switch} logical switch')\n"
        "        if groups.get(group, {}).get('loop', False):\n"
        "            issues.append(f'{group}.loop is unsupported')\n"
        "    nr = groups.get('newrun', {})\n"
        "    out = groups.get('output', {})\n"
        '    if not nr:\n'
        "        issues.append('Missing &NEWRUN')\n"
        "    if not isinstance(nr.get('distribution'), str) or not nr.get('distribution'):\n"
        "        issues.append('NEWRUN.Distribution must name an ASCII particle snapshot')\n"
        "    allowed_nr = {'head','run','version','distribution','h_max','h_min','max_step','track_all',\n"
        "                  'auto_phase','phase_scan','check_ref_part','high_res','qbunch',\n"
        "                  'xoff','yoff','zoff','toff','xp','yp','n_red','loop','track_on_axis',\n"
        "                  'nloop','lmonitor'}\n"
        "    allowed_out = {'zstart','zstop','zemit','zphase','refs','emits','phases','high_res',\n"
        "                   'local_emit','lproject_emit','lmagnetized','lsub_rot','lsub_larmor',\n"
        "                   'lsub_coup','lsub_cor','tchecks','tracks','cathodes','t_phases','step_width','step_max'}\n"
        "    for group, values, allowed in [('newrun',nr,allowed_nr),('output',out,allowed_out)]:\n"
        "        diagnostic_screens = {key for key in values if group == 'output'\n"
        "                              and re.fullmatch(r'screen\\([1-9][0-9]*\\)', key)}\n"
        '        for key in sorted(set(values)-allowed-diagnostic_screens):\n'
        "            issues.append(f'Unsupported attribute {group}.{key}')\n"
        '        for key in diagnostic_screens:\n'
        '            value = values[key]\n'
        '            if (isinstance(value, bool) or not isinstance(value, (int, float))\n'
        '                    or not math.isfinite(value)):\n'
        "                issues.append(f'Finite numeric OUTPUT.{key} required')\n"
        "    if 'lmonitor' in nr and not isinstance(nr['lmonitor'], bool):\n"
        "        issues.append('Expected logical NEWRUN.Lmonitor')\n"
        "    if 'nloop' in nr:\n"
        "        value = nr['nloop']\n"
        '        if isinstance(value, bool) or not isinstance(value, int) or value < 1:\n'
        "            issues.append('NEWRUN.Nloop must be a positive integer')\n"
        "        if nr.get('loop', False) is not False:\n"
        "            issues.append('NEWRUN.Nloop is recognized only when LOOP is false')\n"
        "    for key in ('xoff','yoff','zoff','toff','xp','yp'):\n"
        '        if nr.get(key, 0) != 0:\n'
        "            issues.append(f'Nonzero NEWRUN.{key} is unsupported')\n"
        "    if nr.get('n_red', 1) != 1 or nr.get('track_all', True) is not True:\n"
        "        issues.append('Particle reduction/single-reference tracking is unsupported')\n"
        "    if nr.get('phase_scan', False) or nr.get('loop', False) or nr.get('track_on_axis', False):\n"
        "        issues.append('Scanning/loop/on-axis-reference modes are unsupported')\n"
        "    for key in ('local_emit','lproject_emit','lsub_rot','lsub_larmor','lsub_coup','lsub_cor'):\n"
        '        if out.get(key, False):\n'
        "            issues.append(f'OUTPUT.{key} changes observable definitions and is unsupported')\n"
        '    # Validate values used in generated code without accepting bool as a number.\n'
        "    for name, value in [('h_max',nr.get('h_max', 0.001)), ('zstop',out.get('zstop'))]:\n"
        '        if isinstance(value, bool) or not isinstance(value, (int,float)) or value <= 0:\n'
        "            issues.append(f'Positive numeric {name} required')\n"
        "    zstart = out.get('zstart', 0)\n"
        '    if (isinstance(zstart, bool) or not isinstance(zstart, (int, float))\n'
        '            or not math.isfinite(zstart)):\n'
        "        issues.append('Finite numeric OUTPUT.ZSTART required')\n"
        "    elif isinstance(out.get('zstop'), (int, float)) and zstart >= out['zstop']:\n"
        "        issues.append('OUTPUT.ZSTART must precede ZSTOP')\n"
        "    qbunch = nr.get('qbunch', 0)\n"
        '    if isinstance(qbunch, bool) or not isinstance(qbunch, (int,float)):\n'
        "        issues.append('Numeric NEWRUN.Qbunch required')\n"
        "    max_steps = nr.get('max_step', 100000)\n"
        '    if isinstance(max_steps, bool) or not isinstance(max_steps, int) or not 1 <= max_steps <= 10000000:\n'
        "        issues.append('NEWRUN.Max_step must be an integer in 1..10000000')\n"
        '    try:\n'
        '        collective = space_charge_spec(groups)\n'
        '        specs = field_specs(groups) + quadrupole_specs(groups) + aperture_specs(groups) + dipole_beamline_specs(groups)\n'
        '    except ConversionError as exc:\n'
        '        specs, collective = [], None\n'
        '        issues.append(str(exc))\n'
        "    status = 'unsupported' if issues else ('review-required' if specs or collective else 'convertible-pilot')\n"
        "    return {'status':status, 'issues':issues,\n"
        "            'scope':'Injected equal-weight electrons; supported external elements with optional open, one-rest-frame 3DFFT space-charge migration',\n"
        "            'namelists':groups,\n"
        "            'notes':['No expressions or generator distributions are evaluated',\n"
        "                     'H_max [ns] maps to OPALX DT [s]; integrators/output grids differ',\n"
        "                     'Snapshot time origin is recorded; absolute RF phase includes its advance',\n"
        "                     'ZSTART and Screen positions select source diagnostics; target launch and map poses stay global',\n"
        "                     'OPALX uses a centroid reference frame; ASTRA uses its first row',\n"
        "                     'ASTRA Zemit emittance uses z/energy and is not OPALX emit_s']\n"
        "                    + (collective['limitations'] if collective else [])\n"
        "                    + (['Mapped tracking needs review of interpolation, radial support and output frames',\n"
        "                        'ASTRA default transverse emittances are canonical in solenoids; OPALX statistics are mechanical',\n"
        "                        'Automatic phasing uses each code reference; no numerical phase is copied from rounded logs',\n"
        "                        'Mapped MAXSTEPS uses ASTRA Max_step (default 100000) as a safety ceiling; check completion',\n"
        "                        'Dipoles use an estimated static centroid reference arc to laboratory ZSTOP; other fields use straight distance; verify the actual endpoint'] if specs else [])}\n"
        '\n'
        '\n'
        '\n'
        "def render_deck(groups: Namelists, sample: dict, stem: str = 'converted', fields=None, *, particle_dump_frequency=100000000) -> str:\n"
        '    """Render an injected target; preserve particles and field-map poses.\n'
        '\n'
        '    OPALX ZSTOP is a path length relative to launch; ASTRA stops at the mean\n'
        '    global z. With straight drift the centroid speed is the mean particle velocity,\n'
        '    while the reference speed comes from mean momentum; both are used below.\n'
        '    Terminal positions can differ by a timestep in either direction. No claim\n'
        '    of identical output grids or stopping times is made.\n'
        '    """\n'
        '    report = assess(groups)\n'
        "    if report['issues']:\n"
        "        raise ConversionError('; '.join(report['issues']))\n"
        "    if not re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]*', stem):\n"
        "        raise ConversionError('Unsafe output stem')\n"
        '    specs = field_specs(groups) + quadrupole_specs(groups) + aperture_specs(groups) + dipole_beamline_specs(groups)\n'
        '    if specs and fields is None:\n'
        "        raise ConversionError('Active elements require prepared field/aperture adapters')\n"
        '    collective = space_charge_spec(groups)\n'
        '    validate_space_charge_sample(sample, collective)\n'
        '    if (isinstance(particle_dump_frequency, bool) or not isinstance(particle_dump_frequency, int)\n'
        '            or not 1 <= particle_dump_frequency <= 1000000000):\n'
        "        raise ConversionError('Particle dump frequency must be an integer in 1..1000000000')\n"
        "    rows = sample['particles']\n"
        "    n = sample['count']\n"
        '    mean_z = math.fsum(r[2]/n for r in rows)\n'
        '    momentum = [math.fsum(r[d]/n for r in rows) for d in (3,4,5)]\n'
        '    mean_beta_z = math.fsum(r[5]/math.hypot(1.0,*r[3:]) for r in rows)/n\n'
        '    reference_beta = math.hypot(*momentum)/math.hypot(1.0,*momentum)\n'
        '    if mean_beta_z <= 0 or not math.isfinite(reference_beta):\n'
        "        raise ConversionError('Nonfinite/zero derived drift velocity')\n"
        "    distance = (groups['output']['zstop']-mean_z)\n"
        '    if dipole_beamline_specs(groups):\n'
        "        if not fields.get('dipole_reference'):\n"
        "            raise ConversionError('Dipoles require a prepared curved reference-path estimate')\n"
        "        distance = _field_real(fields['dipole_reference']['path_length_m'], 'Dipole reference path length')\n"
        '    elif not specs:\n'
        '        distance *= reference_beta/mean_beta_z\n'
        '    if not math.isfinite(distance) or distance <= 0:\n'
        "        raise ConversionError('ZSTOP must be downstream of the initial bunch centroid')\n"
        "    dt = groups['newrun'].get('h_max',0.001)*1e-9\n"
        '    if not math.isfinite(dt) or dt <= 0:\n'
        "        raise ConversionError('Derived timestep must be finite and nonzero')\n"
        '    # Initial velocities cannot bound a mapped flight: an RF cavity may slow\n'
        "    # the beam down. Preserve ASTRA's explicit/default safety step ceiling.\n"
        '    # In a drift, the initial velocities can additionally give a tighter bound.\n'
        "    steps = groups['newrun'].get('max_step', 100000)\n"
        '    if not specs and collective is None:\n'
        '        beta_min = min(r[5]/math.hypot(1.0,*r[3:]) for r in rows)\n'
        '        estimated_steps = 2*(distance/C_LIGHT)/beta_min/dt + 100\n'
        '        if not math.isfinite(estimated_steps) or estimated_steps > 10000000:\n'
        "            raise ConversionError('Inferred run exceeds ten million steps; reduce scope explicitly')\n"
        '        steps = min(steps, math.ceil(estimated_steps))\n'
        "    charge = -abs(groups['newrun'].get('qbunch',0))*1e-9 or sample['charge_C']\n"
        "    length = max(groups['output']['zstop']+1, max(r[2] for r in rows)+1)\n"
        '    if specs:\n'
        "        geometry = '\\n'.join(fields['elements'])\n"
        "        names = ','.join(line.split(':',1)[0] for line in fields['elements'])\n"
        "        autophase = 4 if groups['newrun'].get('auto_phase',True) and any(x['kind']=='rf' for x in specs) else 0\n"
        '    else:\n'
        "        geometry = f'D: DRIFT, L={length:.17g}, ELEMEDGE=0;'\n"
        "        names, autophase = 'D', 0\n"
        "    collective_comment = 'open 3D space charge' if collective else 'no space charge'\n"
        "    collective_options = ', MINBINEMITTED=5' if collective else ''\n"
        "    solver = 'F: FIELDSOLVER, TYPE=NONE, NX=8, NY=8, NZ=8,\\n   PARFFTX=TRUE, PARFFTY=TRUE, PARFFTZ=TRUE,\\n   BCFFTX=OPEN, BCFFTY=OPEN, BCFFTZ=OPEN;'\n"
        "    update = ''\n"
        '    if collective:\n'
        "        nx,ny,nz = collective['mesh']\n"
        '        solver = (\'ASTRA_SC_BIN: BINNING, MAXBINS=1, PARAMETER=GAMMAZ, ADAPTIVEBINNING=FALSE, TABLEPRINTFREQ=0, DUMPBINSFILE=\\"NONE\\";\\n\'\n'
        "                  f'F: FIELDSOLVER, TYPE=OPEN, BINS=ASTRA_SC_BIN, NX={nx}, NY={ny}, NZ={nz},\\n'\n"
        "                  '   PARFFTX=TRUE, PARFFTY=TRUE, PARFFTZ=TRUE,\\n'\n"
        "                  '   BCFFTX=OPEN, BCFFTY=OPEN, BCFFTZ=OPEN,\\n'\n"
        '                  f\'   GREENSF=INTEGRATED, BBOXINCR={collective["bbox_increase_percent"]:.17g};\')\n'
        '        update = \', SCFIELDUPDATE="MIDPOINT"\'\n'
        "    return f'''// ASTRA conversion candidate: {collective_comment}; inspect report.json.\n"
        'OPTION, VERSION=10900, AUTOPHASE={autophase}, STATDUMPFREQ=1, PSDUMPFREQ={particle_dump_frequency}, BOUNDPDESTROY=1000{collective_options};\n'
        '{geometry}\n'
        'L: LINE=({names});\n'
        '{solver}\n'
        'P: DISTRIBUTION, TYPE=FROMFILE, FNAME="particles.opalx", NPARTDIST={n};\n'
        'S: EMISSIONSOURCE, DISTRIBUTION=P;\n'
        'SL: EMISSIONSOURCELIST=(S);\n'
        'B: BEAM, PARTICLE=ELECTRON, CHARGE=-1, NALLOC={n}, BCHARGE={abs(charge):.17g}, SOURCES=SL;\n'
        'TRACK, LINE=L, BEAM=B, DT={{{dt:.17g}}}, MAXSTEPS={steps}, ZSTOP={distance:.17g};\n'
        'RUN, METHOD=PARALLEL, FIELDSOLVER=F{update};\n'
        'ENDTRACK;\n'
        'QUIT;\n'
        "'''\n"
        '\n'
        '\n'
        'def convert(source, output, *, rf_subdivisions=4, map_radius=0.05, fourier_terms=128,\n'
        '            quad_dz=0.00025, quad_radius=0.05, dipole_dz=0.00025,\n'
        '            dipole_dx=0.0005, dipole_radius=0.05, dipole_reference_ds=0.00025,\n'
        '            particle_dump_frequency=100000000, center_launch_frame=False,\n'
        '            force_no_space_charge=False) -> dict:\n'
        '    """Write a fresh isolated candidate only after all conversions validate."""\n'
        '    import hashlib\n'
        '    import json\n'
        '    from pathlib import Path\n'
        '    source, output = Path(source).resolve(), Path(output).resolve()\n'
        '    if output.exists() or output.is_relative_to(source.parent):\n'
        "        raise ConversionError('Output must be new and outside the source case directory')\n"
        '    raw = source.read_bytes()\n'
        "    groups, solver_policy = conversion_groups(parse_namelists(raw.decode('utf-8-sig')),\n"
        '                                              force_no_space_charge)\n'
        '    report = assess(groups)\n'
        "    if report['issues']:\n"
        "        raise ConversionError('; '.join(report['issues']))\n"
        '    if solver_policy is not None:\n'
        "        report['fieldsolver_policy'] = solver_policy\n"
        "        report['notes'].append(solver_policy['reason'])\n"
        "    particle_path = (source.parent/groups['newrun']['distribution']).resolve()\n"
        '    raw_particles = particle_path.read_bytes()\n'
        "    sample = read_particles(raw_particles.decode('ascii'))\n"
        '    if not isinstance(center_launch_frame, bool):\n'
        "        raise ConversionError('Launch-frame centering flag must be logical')\n"
        '    coordinate_origin = [0., 0., 0.]\n'
        '    target_sample, target_groups = sample, groups\n'
        '    if center_launch_frame:\n'
        '        if quadrupole_specs(groups) or aperture_specs(groups) or dipole_beamline_specs(groups):\n'
        "            raise ConversionError('Launch-frame centering supports drift, RF and solenoid fields only; active quadrupoles, apertures and dipoles require complete pose adapters')\n"
        '        target_sample, coordinate_origin = center_launch_sample(sample)\n'
        '        target_groups = {name: dict(values) for name, values in groups.items()}\n'
        "        target_output = target_groups['output']\n"
        '        for key in list(target_output):\n'
        "            if key in ('zstart', 'zstop') or re.fullmatch(r'screen\\([1-9][0-9]*\\)', key):\n"
        '                target_output[key] -= coordinate_origin[2]\n'
        '    collective = space_charge_spec(groups)\n'
        '    collective_sample = validate_space_charge_sample(target_sample, collective)\n'
        "    fields = prepare_fields(groups, source.parent, sample['clock_origin_s'],\n"
        '                            rf_subdivisions=rf_subdivisions, rf_radius_m=map_radius,\n'
        '                            fourier_terms=fourier_terms, coordinate_origin_m=coordinate_origin)\n'
        '    quadrupoles = prepare_quadrupoles(groups, source.parent, sample,\n'
        '                                      dz_m=quad_dz, radius_m=quad_radius)\n'
        "    fields['elements'].extend(quadrupoles['elements'])\n"
        "    fields['files'].update(quadrupoles['files'])\n"
        '    apertures = prepare_apertures(groups, source.parent)\n'
        "    aperture_reference = validate_aperture_reference(groups, sample, apertures['apertures'])\n"
        "    fields['elements'].extend(apertures['elements'])\n"
        "    fields['files'].update(apertures['files'])\n"
        '    dipoles = prepare_dipoles(groups, source.parent, sample,\n'
        '                              dz_m=dipole_dz, dx_m=dipole_dx, radius_m=dipole_radius)\n'
        "    fields['elements'].extend(dipoles['elements'])\n"
        "    fields['files'].update(dipoles['files'])\n"
        "    fields['dipole_reference'] = prepare_dipole_reference(\n"
        "        groups, sample, dipoles['dipoles'], ds_m=dipole_reference_ds)\n"
        '    deck = render_deck(target_groups,target_sample,fields=fields,particle_dump_frequency=particle_dump_frequency)\n'
        '    output.mkdir(parents=True)\n'
        "    (output/'converted.in').write_text(deck)\n"
        "    for name, text in fields['files'].items():\n"
        '        (output/name).write_text(text)\n'
        "    with (output/'particles.opalx').open('w') as f:\n"
        "        f.write(str(sample['count'])+'\\nx y z px py pz\\n')\n"
        "        for row in target_sample['particles']:\n"
        "            f.write(' '.join(format(v,'.17g') for v in row)+'\\n')\n"
        "    target_centroid = [math.fsum(row[d]/sample['count'] for row in target_sample['particles'])\n"
        '                       for d in range(3)]\n'
        '    if center_launch_frame:\n'
        "        report['notes'] = [note.replace('target launch and map poses stay global',\n"
        "                                       'source diagnostic positions are retained in this report')\n"
        "                           for note in report['notes']]\n"
        "        report['notes'].append('Launch coordinates and every RF/solenoid pose were translated by the reported coordinate_origin_m; restore this origin when comparing machine positions')\n"
        '    elif any(value != 0 for value in target_centroid):\n'
        "        report['notes'].append('Nonzero launch centroid: native OPALX builds with absolute launch-frame path initialization (including 7c8a8ba) can misalign travelled-path field selection; use explicit --center-launch-frame for supported drift/RF/solenoid cases and verify the endpoint')\n"
        '    report.update(tool_version=VERSION, input=str(source),\n'
        '                  space_charge=collective, space_charge_sample=collective_sample,\n'
        "                  particle_dump_frequency=particle_dump_frequency, maps=fields['maps'],\n"
        "                  apertures=apertures['apertures'], quadrupoles=quadrupoles['quadrupoles'],\n"
        '                  aperture_reference=aperture_reference,\n'
        "                  dipoles=dipoles['dipoles'], dipole_reference=fields['dipole_reference'],\n"
        '                  input_sha256=hashlib.sha256(raw).hexdigest(),\n'
        '                  particle_sha256=hashlib.sha256(raw_particles).hexdigest(),\n'
        '                  electron_rest_energy_eV=ELECTRON_REST_EV,\n'
        "                  target_charge_C=-abs(groups['newrun'].get('qbunch',0))*1e-9 or sample['charge_C'],\n"
        "                  target_bunch_charge_magnitude_C=abs(-abs(groups['newrun'].get('qbunch',0))*1e-9 or sample['charge_C']),\n"
        '                  coordinate_origin_m=coordinate_origin,\n'
        "                  target_coordinate_frame='source_position_m = target_position_m + coordinate_origin_m; momenta and clock unchanged',\n"
        '                  center_launch_frame=center_launch_frame,\n'
        '                  target_launch_centroid_m=target_centroid,\n'
        "                  target_reference_row_position_m=target_sample['particles'][0][:3],\n"
        "                  sample={k:v for k,v in sample.items() if k != 'particles'},\n"
        '                  physics_validated=False)\n'
        "    (output/'report.json').write_text(json.dumps(report,indent=2)+'\\n')\n"
        '    return report\n'
        '\n'
        '\n'
        'def main(argv=None) -> int:\n'
        '    """Inspect or convert; never execute external binaries or install packages."""\n'
        '    import argparse\n'
        '    import json\n'
        '    import sys\n'
        '    from pathlib import Path\n'
        '    parser = argparse.ArgumentParser(description=__doc__)\n'
        "    parser.add_argument('--version',action='version',version=VERSION)\n"
        "    sub = parser.add_subparsers(dest='command',required=True)\n"
        "    p = sub.add_parser('inspect'); p.add_argument('input',type=Path)\n"
        "    p = sub.add_parser('particles'); p.add_argument('input',type=Path)\n"
        "    p = sub.add_parser('convert'); p.add_argument('input',type=Path); p.add_argument('--output',type=Path,required=True)\n"
        "    p.add_argument('--rf-subdivisions',type=int,default=4)\n"
        "    p.add_argument('--map-radius',type=float,default=0.05,help='First-order RF radial support [m]')\n"
        "    p.add_argument('--fourier-terms',type=int,default=128)\n"
        "    p.add_argument('--quad-dz',type=float,default=0.00025,help='Maximum quadrupole z grid spacing [m]')\n"
        "    p.add_argument('--quad-radius',type=float,default=0.05,help='Quadrupole transverse grid halfwidth [m]')\n"
        "    p.add_argument('--dipole-dz',type=float,default=0.00025,help='Maximum dipole z grid spacing [m]')\n"
        "    p.add_argument('--dipole-dx',type=float,default=0.0005,help='Maximum dipole bending-coordinate grid spacing [m]')\n"
        "    p.add_argument('--dipole-radius',type=float,default=0.05,help='Dipole global x/y grid halfwidth [m]')\n"
        "    p.add_argument('--dipole-reference-ds',type=float,default=0.00025,help='Static dipole reference arc integration step [m]')\n"
        "    p.add_argument('--particle-dump-frequency',type=int,default=100000000,help='Positive particle-output step interval; use periodic dumps for collective comparisons')\n"
        "    p.add_argument('--center-launch-frame',action='store_true',help='Translate launch centroid and RF/solenoid poses to zero; record the source-coordinate origin (drift/RF/solenoid only)')\n"
        '    args = parser.parse_args(argv)\n'
        '    try:\n'
        "        if args.command == 'convert':\n"
        '            report = convert(args.input,args.output,rf_subdivisions=args.rf_subdivisions,\n'
        '                             map_radius=args.map_radius,fourier_terms=args.fourier_terms,\n'
        '                             quad_dz=args.quad_dz,quad_radius=args.quad_radius,\n'
        '                             dipole_dz=args.dipole_dz,dipole_dx=args.dipole_dx,\n'
        '                             dipole_radius=args.dipole_radius,dipole_reference_ds=args.dipole_reference_ds,\n'
        '                             particle_dump_frequency=args.particle_dump_frequency,\n'
        '                             center_launch_frame=args.center_launch_frame)\n'
        "        elif args.command == 'particles':\n"
        "            report = read_particles(args.input.read_text(encoding='ascii'))\n"
        "            report.pop('particles')\n"
        '        else:\n'
        "            report = assess(parse_namelists(args.input.read_text(encoding='utf-8-sig')))\n"
        '        print(json.dumps(report,indent=2))\n'
        "        return int(report.get('status') in ('unsupported','review-required'))\n"
        '    except (OSError,UnicodeError,ConversionError) as exc:\n'
        "        print('astra2opalx: '+str(exc),file=sys.stderr)\n"
        '        return 2\n'
        '\n'
        '\n'
        "if __name__ == '__main__':\n"
        '    raise SystemExit(main())\n'
    ),
    'elegant': (
        '#!/usr/bin/env python3\n'
        '"""Standalone standard-library Elegant-to-OPALX converter (Python 3.9+).\n'
        '\n'
        'Initial static injected-electron subset. No installation, expression execution,\n'
        'or tracking. Unsupported inputs are refused; converted candidates require review.\n'
        '"""\n'
        'from __future__ import annotations\n'
        '\n'
        'import math\n'
        'import re\n'
        '\n'
        '\n'
        'class ConversionError(ValueError):\n'
        '    """An Elegant input is outside the explicitly supported safe subset."""\n'
        '\n'
        '\n'
        '_ELEGANT_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_.-]*")\n'
        '_ELEGANT_KEY = re.compile(r"[A-Za-z][A-Za-z0-9_]*")\n'
        '_ELEGANT_NUMBER = re.compile(\n'
        '    r"[+-]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?\\Z"\n'
        ')\n'
        '_ELEGANT_INTEGER = re.compile(r"[+-]?[0-9]+\\Z")\n'
        '_ELEGANT_MACRO = re.compile(r"<[^<>\\r\\n]+>|\\$[A-Za-z_][A-Za-z0-9_]*")\n'
        '_ELEGANT_MAX_DEPTH = 64\n'
        '\n'
        '\n'
        'def _read_elegant_string(text, position):\n'
        '    """Read a single-line double-quoted string without evaluating its contents."""\n'
        '    if position >= len(text) or text[position] != \'"\':\n'
        '        raise ConversionError("Expected a double-quoted string")\n'
        '    position += 1\n'
        '    characters = []\n'
        '    while position < len(text):\n'
        '        character = text[position]\n'
        '        position += 1\n'
        '        if character in "\\r\\n":\n'
        '            raise ConversionError("Multiline quoted strings are unsupported")\n'
        '        if character == \'"\':\n'
        '            return "".join(characters), position\n'
        '        if character == "\\\\" and position < len(text):\n'
        '            following = text[position]\n'
        '            if following in {\'"\', "\\\\"}:\n'
        '                characters.append(following)\n'
        '                position += 1\n'
        '                continue\n'
        '        characters.append(character)\n'
        '    raise ConversionError("Unterminated double-quoted string")\n'
        '\n'
        '\n'
        'def _strip_elegant_comment(text):\n'
        '    """Strip an unquoted exclamation comment while validating quoted layout."""\n'
        '    position = 0\n'
        '    while position < len(text):\n'
        '        if text[position] == \'"\':\n'
        '            _, position = _read_elegant_string(text, position)\n'
        '        elif text[position] == "!":\n'
        '            return text[:position]\n'
        '        else:\n'
        '            position += 1\n'
        '    return text\n'
        '\n'
        '\n'
        'def _parse_elegant_scalar(token):\n'
        '    """Return a finite literal or quoted string, with no RPN or shell evaluation."""\n'
        '    token = token.strip()\n'
        '    if not token:\n'
        '        raise ConversionError("Missing scalar value")\n'
        '    if _ELEGANT_MACRO.search(token):\n'
        '        raise ConversionError("Command-line macro substitution is unsupported")\n'
        '    if token.startswith(\'"\'):\n'
        '        value, end = _read_elegant_string(token, 0)\n'
        '        if end != len(token):\n'
        '            raise ConversionError("Unexpected text after quoted scalar")\n'
        '        return value\n'
        '    if not _ELEGANT_NUMBER.fullmatch(token):\n'
        '        raise ConversionError("Unsupported scalar literal: " + repr(token))\n'
        '    value = float(token)\n'
        '    if not math.isfinite(value):\n'
        '        raise ConversionError("Nonfinite numeric literal: " + repr(token))\n'
        '    if _ELEGANT_INTEGER.fullmatch(token):\n'
        "        digits = token.lstrip('+-').lstrip('0') or '0'\n"
        "        return int(('-' if token.startswith('-') else '') + digits)\n"
        '    return value\n'
        '\n'
        '\n'
        'def _parse_elegant_assignments(text):\n'
        '    """Parse unique scalar assignments separated by commas or newlines."""\n'
        '    values = {}\n'
        '    position = 0\n'
        '    while position < len(text) and text[position].isspace():\n'
        '        position += 1\n'
        '    while position < len(text):\n'
        '        match = _ELEGANT_KEY.match(text, position)\n'
        '        if not match:\n'
        '            raise ConversionError("Expected a scalar parameter assignment")\n'
        '        key = match.group().upper()\n'
        '        if key in values:\n'
        '            raise ConversionError("Duplicate parameter: " + key)\n'
        '        position = match.end()\n'
        '        while position < len(text) and text[position].isspace():\n'
        '            position += 1\n'
        '        if position >= len(text) or text[position] != "=":\n'
        '            raise ConversionError("Expected \'=\' after parameter " + key)\n'
        '        position += 1\n'
        '        while position < len(text) and text[position].isspace():\n'
        '            position += 1\n'
        '        start = position\n'
        '        if position < len(text) and text[position] == \'"\':\n'
        '            _, position = _read_elegant_string(text, position)\n'
        '        else:\n'
        '            while position < len(text) and text[position] not in ",\\r\\n":\n'
        '                position += 1\n'
        '        values[key] = _parse_elegant_scalar(text[start:position])\n'
        '        while position < len(text) and text[position] in " \\t\\v\\f":\n'
        '            position += 1\n'
        '        if position == len(text):\n'
        '            break\n'
        '        if text[position] not in ",\\r\\n":\n'
        '            raise ConversionError("Expected a comma or newline after parameter " + key)\n'
        '        if text[position] == ",":\n'
        '            position += 1\n'
        '        while position < len(text) and text[position].isspace():\n'
        '            position += 1\n'
        '        if position < len(text) and text[position] == ",":\n'
        '            raise ConversionError("Empty parameter assignment")\n'
        '    return values\n'
        '\n'
        '\n'
        'def parse_commands(text):\n'
        '    """Parse ordered Elegant scalar ``&name ... &end`` command records.\n'
        '\n'
        '    Command and parameter names become uppercase. Repeated command groups retain\n'
        '    their order, while duplicate keys in one group are refused. Quoted values\n'
        '    remain strings, including possible RPN or shell text; no code is executed.\n'
        '    Physics assessment must reject expressions in numeric parameter fields.\n'
        '    Arrays, macros, single-quoted strings, and nonliteral scalar values are\n'
        "    outside this parser's supported subset.\n"
        '    """\n'
        '    text = "\\n".join(_strip_elegant_comment(line) for line in text.splitlines())\n'
        '    commands = []\n'
        '    position = 0\n'
        '    while position < len(text):\n'
        '        while position < len(text) and text[position].isspace():\n'
        '            position += 1\n'
        '        if position == len(text):\n'
        '            break\n'
        '        if text[position] != "&":\n'
        '            raise ConversionError("Expected \'&command\' in Elegant command file")\n'
        '        match = _ELEGANT_KEY.match(text, position + 1)\n'
        '        if not match or match.group().upper() == "END":\n'
        '            raise ConversionError("Missing command name or unexpected \'&end\'")\n'
        '        name = match.group().upper()\n'
        '        start = position = match.end()\n'
        '        while position < len(text):\n'
        '            if text[position] == \'"\':\n'
        '                _, position = _read_elegant_string(text, position)\n'
        '            elif text[position] == "&":\n'
        '                end_match = _ELEGANT_KEY.match(text, position + 1)\n'
        '                if not end_match or end_match.group().upper() != "END":\n'
        '                    raise ConversionError("Nested command or missing \'&end\' in &" + name)\n'
        '                attributes = _parse_elegant_assignments(text[start:position])\n'
        '                commands.append({"name": name, "attributes": attributes})\n'
        '                position = end_match.end()\n'
        '                break\n'
        '            else:\n'
        '                position += 1\n'
        '        else:\n'
        '            raise ConversionError("Unterminated Elegant command: &" + name)\n'
        '    return commands\n'
        '\n'
        '\n'
        'def _elegant_lattice_lines(text):\n'
        '    """Join trailing-ampersand lattice statements and normalize unquoted layout."""\n'
        '    statements = []\n'
        '    pending = ""\n'
        '    continued = False\n'
        '    for line in text.splitlines():\n'
        '        line = _strip_elegant_comment(line).strip()\n'
        '        if not line:\n'
        '            continue\n'
        '        if line.startswith("%"):\n'
        '            raise ConversionError("Lattice RPN directives are unsupported")\n'
        '        if line.startswith("#"):\n'
        '            raise ConversionError("Lattice includes and preprocessor directives are unsupported")\n'
        '        if _ELEGANT_MACRO.search(line):\n'
        '            raise ConversionError("Command-line macro substitution is unsupported")\n'
        '        compact = []\n'
        '        position = 0\n'
        '        while position < len(line):\n'
        '            if line[position] == \'"\':\n'
        '                start = position\n'
        '                _, position = _read_elegant_string(line, position)\n'
        '                compact.append(line[start:position])\n'
        '            else:\n'
        '                if not line[position].isspace():\n'
        '                    compact.append(line[position].upper())\n'
        '                position += 1\n'
        '        line = "".join(compact)\n'
        '        continued = line.endswith("&")\n'
        '        pending += line[:-1] if continued else line\n'
        '        if not continued:\n'
        '            statements.append(pending)\n'
        '            pending = ""\n'
        '    if continued or pending:\n'
        '        raise ConversionError("Unterminated lattice continuation")\n'
        '    return statements\n'
        '\n'
        '\n'
        'def _expand_elegant_line(expression, elements, lines, max_elements):\n'
        '    """Expand a bounded LINE expression using only previously defined objects."""\n'
        '    position = 0\n'
        '\n'
        '    def append_checked(destination, source, repeat):\n'
        '        if repeat < 1:\n'
        '            raise ConversionError("LINE repetition must be a positive integer")\n'
        '        if len(source) * repeat > max_elements - len(destination):\n'
        '            raise ConversionError("Expanded LINE exceeds max_elements")\n'
        '        destination.extend(source * repeat)\n'
        '\n'
        '    def group(depth):\n'
        '        nonlocal position\n'
        '        if depth > _ELEGANT_MAX_DEPTH:\n'
        '            raise ConversionError("LINE nesting exceeds the supported depth")\n'
        '        if position >= len(expression) or expression[position] != "(":\n'
        '            raise ConversionError("LINE definition requires a parenthesized list")\n'
        '        position += 1\n'
        '        result = []\n'
        '        while True:\n'
        '            if position >= len(expression) or expression[position] in ",)":\n'
        '                raise ConversionError("Empty or unterminated LINE member")\n'
        '            if expression[position] == "-":\n'
        '                raise ConversionError("Reversed LINE members are unsupported")\n'
        '            repeat = 1\n'
        '            if expression[position] in "0123456789":\n'
        '                start = position\n'
        '                while position < len(expression) and expression[position] in "0123456789":\n'
        '                    position += 1\n'
        '                count_text = expression[start:position].lstrip("0") or "0"\n'
        '                if len(count_text) > len(str(max_elements)):\n'
        '                    raise ConversionError("Expanded LINE exceeds max_elements")\n'
        '                repeat = int(count_text)\n'
        '                if position >= len(expression) or expression[position] != "*":\n'
        '                    raise ConversionError("Expected \'*\' after LINE repetition count")\n'
        '                position += 1\n'
        '            if position < len(expression) and expression[position] == "(":\n'
        '                members = group(depth + 1)\n'
        '            else:\n'
        '                if position < len(expression) and expression[position] == \'"\':\n'
        '                    raise ConversionError("Quoted element and LINE names are unsupported")\n'
        '                match = _ELEGANT_NAME.match(expression, position)\n'
        '                if not match:\n'
        '                    raise ConversionError("Expected an element, LINE, or parenthesized group")\n'
        '                name = match.group().upper()\n'
        '                position = match.end()\n'
        '                if name in elements:\n'
        '                    members = [name]\n'
        '                elif name in lines:\n'
        '                    members = lines[name]\n'
        '                else:\n'
        '                    raise ConversionError("Undefined or forward LINE member: " + name)\n'
        '            append_checked(result, members, repeat)\n'
        '            if position >= len(expression):\n'
        '                raise ConversionError("Unterminated LINE list")\n'
        '            character = expression[position]\n'
        '            position += 1\n'
        '            if character == ")":\n'
        '                return result\n'
        '            if character != ",":\n'
        '                raise ConversionError("Expected \',\' or \')\' after LINE member")\n'
        '\n'
        '    result = group(1)\n'
        '    if position != len(expression):\n'
        '        raise ConversionError("Unexpected text after LINE definition")\n'
        '    return result\n'
        '\n'
        '\n'
        'def parse_lattice(text, max_elements=100000):\n'
        '    """Parse static Elegant elements and immediately expanded nested LINEs.\n'
        '\n'
        '    Unquoted ASCII names are normalized to uppercase and must start with a\n'
        '    letter; subsequent characters may be letters, digits, underscores, periods,\n'
        '    or hyphens. Element inheritance refers only to earlier element definitions\n'
        '    and merges literal parameters with child overrides. All attributes remain\n'
        '    subject to later physics assessment. Includes, RPN directives, macros,\n'
        '    reversals, quoted names, and lattice-edit commands are explicitly refused.\n'
        '    Each LINE has a bounded expansion and nesting depth.\n'
        '    """\n'
        '    if isinstance(max_elements, bool) or not isinstance(max_elements, int) or max_elements < 1:\n'
        '        raise ConversionError("max_elements must be a positive integer")\n'
        '    elements = {}\n'
        '    lines = {}\n'
        '    for statement in _elegant_lattice_lines(text):\n'
        '        if statement.startswith(\'"\'):\n'
        '            raise ConversionError("Quoted element and LINE names are unsupported")\n'
        '        match = _ELEGANT_NAME.match(statement)\n'
        '        if not match or match.end() == len(statement) or statement[match.end()] != ":":\n'
        '            raise ConversionError("Expected \'name: TYPE\' lattice definition")\n'
        '        name = match.group().upper()\n'
        '        if name in elements or name in lines:\n'
        '            raise ConversionError("Duplicate element or LINE name: " + name)\n'
        '        position = match.end() + 1\n'
        '        type_match = _ELEGANT_NAME.match(statement, position)\n'
        '        if not type_match:\n'
        '            raise ConversionError("Missing element type or parent name for " + name)\n'
        '        element_type = type_match.group().upper()\n'
        '        remainder = statement[type_match.end():]\n'
        '        if element_type == "LINE":\n'
        '            if not remainder.startswith("="):\n'
        '                raise ConversionError("Expected \'=\' after LINE")\n'
        '            lines[name] = _expand_elegant_line(remainder[1:], elements, lines, max_elements)\n'
        '            continue\n'
        '        if remainder and not remainder.startswith(","):\n'
        '            raise ConversionError("Expected \',\' before element parameters")\n'
        '        parameters = _parse_elegant_assignments(remainder[1:] if remainder else "")\n'
        '        if element_type in lines:\n'
        '            raise ConversionError("Element inheritance cannot refer to a LINE")\n'
        '        if element_type in elements:\n'
        '            parent = elements[element_type]\n'
        '            inherited = dict(parent["parameters"])\n'
        '            inherited.update(parameters)\n'
        '            parameters = inherited\n'
        '            element_type = parent["type"]\n'
        '        elements[name] = {"type": element_type, "parameters": parameters}\n'
        '    return {"elements": elements, "lines": lines}\n'
        '\n'
        '\n'
        'import math\n'
        'import re\n'
        '\n'
        '\n'
        'def _sdds_uncomment(text):\n'
        '    """Remove unquoted SDDS comments, preserving lines and quoted escapes."""\n'
        '    result = []\n'
        '    quoted = escaped = comment = False\n'
        '    for char in text:\n'
        "        if char == '\\n':\n"
        '            result.append(char)\n'
        '            comment = False\n'
        '            escaped = False\n'
        '            continue\n'
        '        if comment:\n'
        '            continue\n'
        '        if escaped:\n'
        '            result.append(char)\n'
        '            escaped = False\n'
        "        elif char == '\\\\':\n"
        '            result.append(char)\n'
        '            escaped = True\n'
        '        elif char == \'"\':\n'
        '            result.append(char)\n'
        '            quoted = not quoted\n'
        "        elif char == '!' and not quoted:\n"
        '            comment = True\n'
        '        else:\n'
        '            result.append(char)\n'
        '    if quoted:\n'
        "        raise ConversionError('Unterminated quoted SDDS value')\n"
        "    return ''.join(result)\n"
        '\n'
        '\n'
        'def _sdds_tokens(text, *, punctuation=False):\n'
        '    """Decode whitespace-delimited SDDS tokens without shell evaluation."""\n'
        '    result = []\n'
        '    index = 0\n'
        '    while index < len(text):\n'
        '        if text[index].isspace():\n'
        '            index += 1\n'
        '            continue\n'
        "        if punctuation and text[index] in '=,':\n"
        '            result.append((text[index], False))\n'
        '            index += 1\n'
        '            continue\n'
        '        quoted = text[index] == \'"\'\n'
        '        if quoted:\n'
        '            index += 1\n'
        '        chars = []\n'
        '        closed = not quoted\n'
        '        while index < len(text):\n'
        '            char = text[index]\n'
        '            if quoted and char == \'"\':\n'
        '                index += 1\n'
        '                closed = True\n'
        '                break\n'
        "            if not quoted and (char.isspace() or (punctuation and char in '=,')):\n"
        '                break\n'
        '            if not quoted and char == \'"\':\n'
        "                raise ConversionError('A quoted SDDS token must start at a token boundary')\n"
        "            if char == '\\\\':\n"
        '                index += 1\n'
        '                if index == len(text):\n'
        "                    raise ConversionError('Incomplete SDDS escape sequence')\n"
        '                char = text[index]\n'
        "                if char in '01234567':\n"
        '                    end = index + 1\n'
        "                    while end < min(index + 3, len(text)) and text[end] in '01234567':\n"
        '                        end += 1\n'
        '                    integer = int(text[index:end], 8)\n'
        '                    if integer > 255:\n'
        "                        raise ConversionError('SDDS octal escape exceeds one byte')\n"
        '                    chars.append(chr(integer))\n'
        '                    index = end\n'
        '                    continue\n'
        '                if char not in \'\\\\"!\':\n'
        "                    raise ConversionError('Unsupported SDDS escape sequence')\n"
        '            chars.append(char)\n'
        '            index += 1\n'
        '        if not closed:\n'
        "            raise ConversionError('Unterminated quoted SDDS token')\n"
        '        if quoted and index < len(text) and not text[index].isspace() and not (\n'
        "                punctuation and text[index] in '=,'):\n"
        "            raise ConversionError('Missing delimiter after a quoted SDDS token')\n"
        "        result.append((''.join(chars), quoted))\n"
        '    return result\n'
        '\n'
        '\n'
        'def _sdds_attributes(body):\n'
        '    """Parse SDDS header assignments and reject duplicate or malformed keys."""\n'
        '    tokens = _sdds_tokens(body, punctuation=True)\n'
        '    attributes = {}\n'
        '    index = 0\n'
        '    while index < len(tokens):\n'
        "        if tokens[index] == (',', False):\n"
        "            raise ConversionError('Unexpected comma in SDDS header')\n"
        '        key, quoted = tokens[index]\n'
        "        if quoted or not re.fullmatch(r'[A-Za-z_][A-Za-z_0-9]*', key):\n"
        "            raise ConversionError('Invalid SDDS header attribute')\n"
        "        if index + 2 >= len(tokens) or tokens[index + 1] != ('=', False):\n"
        "            raise ConversionError('Expected SDDS header assignment')\n"
        '        value, value_quoted = tokens[index + 2]\n'
        "        if not value_quoted and value in '=,':\n"
        "            raise ConversionError('Missing SDDS header value')\n"
        '        key = key.lower()\n'
        '        if key in attributes:\n'
        "            raise ConversionError('Duplicate SDDS header attribute: ' + key)\n"
        '        attributes[key] = value\n'
        '        index += 3\n'
        "        if index < len(tokens) and tokens[index] == (',', False):\n"
        '            index += 1\n'
        '    return attributes\n'
        '\n'
        '\n'
        'def _sdds_value(value, datatype, context):\n'
        '    """Convert one SDDS1 scalar while retaining integer identity and finiteness."""\n'
        "    if datatype == 'string':\n"
        '        return value\n'
        "    if datatype == 'character':\n"
        '        if len(value) != 1:\n'
        "            raise ConversionError(context + ': SDDS character must have length one')\n"
        '        return value\n'
        "    if datatype in ('short', 'long'):\n"
        "        if not re.fullmatch(r'[+-]?[0-9]+', value):\n"
        "            raise ConversionError(context + ': expected an SDDS integer')\n"
        "        digits = value.lstrip('+-').lstrip('0') or '0'\n"
        '        if len(digits) > 10:\n'
        "            raise ConversionError(context + ': SDDS integer is outside its declared range')\n"
        "        integer = int(('-' if value.startswith('-') else '') + digits)\n"
        "        bits = 16 if datatype == 'short' else 32\n"
        '        if not -(1 << (bits - 1)) <= integer < (1 << (bits - 1)):\n'
        "            raise ConversionError(context + ': SDDS integer is outside its declared range')\n"
        '        return integer\n'
        "    if datatype not in ('float', 'double'):\n"
        "        raise ConversionError(context + ': unsupported SDDS1 type ' + datatype)\n"
        "    if not re.fullmatch(r'[+-]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?', value):\n"
        "        raise ConversionError(context + ': expected a decimal SDDS number')\n"
        '    try:\n'
        '        number = float(value)\n'
        '    except (ValueError, OverflowError):\n'
        "        raise ConversionError(context + ': expected an SDDS number') from None\n"
        '    if not math.isfinite(number):\n'
        "        raise ConversionError(context + ': nonfinite SDDS number')\n"
        "    if datatype == 'float' and abs(number) > 3.4028234663852886e38:\n"
        "        raise ConversionError(context + ': value exceeds the declared SDDS float range')\n"
        '    return number\n'
        '\n'
        '\n'
        'def _sdds_definition(kind, attributes, seen):\n'
        '    """Validate a scalar SDDS definition, retaining descriptive metadata."""\n'
        "    allowed = {'name', 'type', 'units', 'symbol', 'description', 'format_string'}\n"
        "    allowed |= {'fixed_value'} if kind == 'parameter' else {'field_length'}\n"
        '    unknown = set(attributes) - allowed\n'
        '    if unknown:\n'
        "        raise ConversionError('Unsupported SDDS ' + kind + ' attributes: ' + ', '.join(sorted(unknown)))\n"
        "    name = attributes.get('name', '')\n"
        "    datatype = attributes.get('type', '').lower()\n"
        "    if not re.fullmatch(r'[A-Za-z_@:#.+%$&/\\-][A-Za-z_0-9@:#.+%$&/\\-]*', name):\n"
        "        raise ConversionError('Invalid or missing SDDS ' + kind + ' name')\n"
        '    if name in seen:\n'
        "        raise ConversionError('Duplicate SDDS ' + kind + ' name: ' + name)\n"
        "    if datatype not in ('short', 'long', 'float', 'double', 'character', 'string'):\n"
        "        raise ConversionError('Unsupported or missing SDDS1 scalar type: ' + datatype)\n"
        "    if 'field_length' in attributes and _sdds_value(\n"
        "            attributes['field_length'], 'long', name + '.field_length') != 0:\n"
        "        raise ConversionError('Fixed-width SDDS columns are unsupported')\n"
        '    result = dict(attributes)\n'
        "    result['type'] = datatype\n"
        "    result.setdefault('units', '')\n"
        '    seen.add(name)\n'
        '    return result\n'
        '\n'
        '\n'
        'def read_sdds_ascii(text):\n'
        '    """Read one explicit-row-count SDDS1 ASCII page using only the stdlib.\n'
        '\n'
        '    Arrays, includes, binary data and extra pages are rejected, rather than\n'
        '    interpreted as particle data. The order of variable scalar parameters is\n'
        '    the header declaration order; fixed_value parameters consume no data line.\n'
        '    """\n'
        '    if not isinstance(text, str):\n'
        "        raise ConversionError('SDDS input must be decoded text')\n"
        "    first, separator, remainder = text.partition('\\n')\n"
        "    if first.strip() != 'SDDS1' or not separator:\n"
        "        raise ConversionError('Only SDDS1 ASCII input is supported')\n"
        '    remainder = _sdds_uncomment(remainder)\n'
        '    columns, definitions = [], []\n'
        "    names = {'column': set(), 'parameter': set()}\n"
        '    offset = 0\n'
        '    while True:\n'
        '        while offset < len(remainder) and remainder[offset].isspace():\n'
        '            offset += 1\n'
        "        match = re.match(r'&([A-Za-z_][A-Za-z_0-9]*)\\b', remainder[offset:])\n"
        '        if not match:\n'
        "            raise ConversionError('Expected an SDDS header command')\n"
        '        kind = match.group(1).lower()\n'
        '        offset += match.end()\n'
        '        start = offset\n'
        '        quoted = escaped = False\n'
        '        while offset < len(remainder):\n'
        '            char = remainder[offset]\n'
        '            if escaped:\n'
        '                escaped = False\n'
        "            elif char == '\\\\':\n"
        '                escaped = True\n'
        '            elif char == \'"\':\n'
        '                quoted = not quoted\n'
        "            elif not quoted and re.match(r'&end\\b', remainder[offset:], re.IGNORECASE):\n"
        '                break\n'
        '            offset += 1\n'
        '        if offset == len(remainder):\n'
        "            raise ConversionError('Unterminated SDDS header command')\n"
        '        attributes = _sdds_attributes(remainder[start:offset])\n'
        '        offset += 4\n'
        "        if kind in ('array', 'include', 'associate'):\n"
        "            raise ConversionError('Unsupported SDDS header command: ' + kind)\n"
        "        if kind == 'description':\n"
        "            if set(attributes) - {'text', 'contents'}:\n"
        "                raise ConversionError('Unsupported SDDS description attribute')\n"
        "        elif kind in ('column', 'parameter'):\n"
        '            definition = _sdds_definition(kind, attributes, names[kind])\n'
        "            (columns if kind == 'column' else definitions).append(definition)\n"
        "        elif kind == 'data':\n"
        "            unknown = set(attributes) - {'mode', 'lines_per_row', 'no_row_counts',\n"
        "                                          'column_major_order', 'additional_header_lines'}\n"
        '            if unknown:\n'
        "                raise ConversionError('Unsupported SDDS data attributes: ' + ', '.join(sorted(unknown)))\n"
        "            if attributes.get('mode', '').lower() != 'ascii':\n"
        "                raise ConversionError('Only ASCII SDDS data is supported; use sddsconvert -ascii')\n"
        "            for flag, expected in (('lines_per_row', 1), ('no_row_counts', 0),\n"
        "                                   ('column_major_order', 0), ('additional_header_lines', 0)):\n"
        "                if _sdds_value(attributes.get(flag, str(expected)), 'long', flag) != expected:\n"
        "                    raise ConversionError('Unsupported SDDS data setting: ' + flag)\n"
        '            break\n'
        '        else:\n'
        "            raise ConversionError('Unsupported SDDS header command: ' + kind)\n"
        '    if not columns:\n'
        "        raise ConversionError('SDDS input has no tabular columns')\n"
        '    lines = [line.strip() for line in remainder[offset:].splitlines() if line.strip()]\n'
        '    parameters = {}\n'
        '    position = 0\n'
        '    for definition in definitions:\n'
        "        name, datatype = definition['name'], definition['type']\n"
        "        if 'fixed_value' in definition:\n"
        "            value = definition['fixed_value']\n"
        '        else:\n'
        '            if position == len(lines):\n'
        "                raise ConversionError('Missing SDDS parameter value: ' + name)\n"
        '            raw = lines[position]\n'
        '            position += 1\n'
        '            tokens = _sdds_tokens(raw)\n'
        '            if datatype == \'string\' and not raw.startswith(\'"\'):\n'
        '                value = _sdds_tokens(\'"\' + raw + \'"\')[0][0]\n'
        '            elif len(tokens) == 1:\n'
        '                value = tokens[0][0]\n'
        '            else:\n'
        "                raise ConversionError('Invalid SDDS parameter value: ' + name)\n"
        '        parameters[name] = _sdds_value(value, datatype, name)\n'
        '    if position == len(lines):\n'
        "        raise ConversionError('Missing SDDS row count')\n"
        "    count = _sdds_value(lines[position], 'long', 'SDDS row count')\n"
        '    position += 1\n'
        '    if count < 0:\n'
        "        raise ConversionError('SDDS row count must be nonnegative')\n"
        '    if len(lines) - position != count:\n'
        "        raise ConversionError('SDDS row count mismatch or multiple pages are unsupported')\n"
        '    rows = []\n'
        '    for row_index, line in enumerate(lines[position:], 1):\n'
        '        tokens = _sdds_tokens(line)\n'
        '        if len(tokens) != len(columns):\n'
        "            raise ConversionError('SDDS row ' + str(row_index) + ' has an incorrect column count')\n"
        "        rows.append({definition['name']: _sdds_value(token[0], definition['type'],\n"
        "                     'row ' + str(row_index) + ' ' + definition['name'])\n"
        '                     for definition, token in zip(columns, tokens)})\n'
        "    return {'columns': columns, 'parameters': parameters,\n"
        "            'parameter_definitions': definitions, 'rows': rows}\n"
        '\n'
        '\n'
        'def _sdds_quote(value):\n'
        '    """Quote an SDDS string using explicit octal escapes for control bytes."""\n'
        '    if not isinstance(value, str):\n'
        "        raise ConversionError('SDDS strings must be text')\n"
        '    result = []\n'
        '    for char in value:\n'
        '        if char in \'\\\\"\':\n'
        "            result.append('\\\\' + char)\n"
        '        elif ord(char) < 32 or ord(char) == 127:\n'
        "            result.append('\\\\' + format(ord(char), '03o'))\n"
        '        else:\n'
        '            result.append(char)\n'
        '    return \'"\' + \'\'.join(result) + \'"\'\n'
        '\n'
        '\n'
        'def render_sdds_ascii(rows, charge_C=None):\n'
        '    """Render a single standard Elegant particle page without dependencies."""\n'
        '    rows = list(rows)\n'
        '    if not rows:\n'
        "        raise ConversionError('Cannot render an empty Elegant particle page')\n"
        "    base = ('x', 'xp', 'y', 'yp', 't', 'p')\n"
        "    particle_ids = 'particleID' in rows[0]\n"
        "    expected = set(base) | ({'particleID'} if particle_ids else set())\n"
        "    names = base + (('particleID',) if particle_ids else ())\n"
        "    units = ('m', '', 'm', '', 's', 'm$be$nc') + (('',) if particle_ids else ())\n"
        "    lines = ['SDDS1']\n"
        '    for name, unit in zip(names, units):\n'
        "        datatype = 'long' if name == 'particleID' else 'double'\n"
        "        lines.append('&column name=' + name + ', type=' + datatype + ', units=' + _sdds_quote(unit) + ' &end')\n"
        '    if charge_C is not None:\n'
        "        charge = _sdds_value(str(charge_C), 'double', 'Charge')\n"
        "        lines.append('&parameter name=Charge, type=double, units=C, fixed_value=' + format(charge, '.17g') + ' &end')\n"
        "    lines.extend(['&data mode=ascii, no_row_counts=0 &end', str(len(rows))])\n"
        '    for row in rows:\n'
        '        if set(row) != expected:\n'
        "            raise ConversionError('Elegant particle rows must have consistent standard columns')\n"
        '        values = []\n'
        '        for name in names:\n'
        "            datatype = 'long' if name == 'particleID' else 'double'\n"
        '            value = _sdds_value(str(row[name]), datatype, name)\n'
        "            values.append(str(value) if datatype == 'long' else format(value, '.17g'))\n"
        "        lines.append(' '.join(values))\n"
        "    return '\\n'.join(lines) + '\\n'\n"
        '\n'
        '\n'
        '# Conversion policy and CLI. The assembled file has no sibling dependencies.\n'
        'import argparse\n'
        'from collections import Counter\n'
        'import hashlib\n'
        'import json\n'
        'from pathlib import Path\n'
        'import shutil\n'
        'import sys\n'
        '\n'
        "VERSION = '0.3.0'\n"
        'SOURCE_REST_EV = 510999.06  # Elegant 2026.4 native p_central_mev audit.\n'
        'TARGET_REST_EV = 510998.95\n'
        'C_LIGHT = 299792458.0\n'
        '\n'
        '\n'
        'def finite_number(value, label, *, positive=False):\n'
        '    """Require a literal finite scalar, with an optional strictly positive bound."""\n'
        '    if isinstance(value, bool) or not isinstance(value, (int, float)):\n'
        "        raise ConversionError(label + ' must be a numeric literal, not an expression')\n"
        '    try:\n'
        '        result = float(value)\n'
        '    except (ValueError, OverflowError):\n'
        "        raise ConversionError(label + ' is outside the finite numeric range') from None\n"
        '    if not math.isfinite(result) or (positive and result <= 0):\n'
        "        raise ConversionError(label + ' must be finite' + (' and positive' if positive else ''))\n"
        '    return result\n'
        '\n'
        '\n'
        'def integer_setting(value, label, low, high):\n'
        '    """Require a bounded exact integer without accepting logicals or truncation."""\n'
        '    number = finite_number(value, label)\n'
        '    if not number.is_integer() or not low <= number <= high:\n'
        "        raise ConversionError(f'{label} must be an integer in {low}..{high}')\n"
        '    return int(number)\n'
        '\n'
        '\n'
        'def source_integer(value, label):\n'
        '    """Require integer source syntax: Elegant\'s %ld/%hd reads differ from float.\n'
        '\n'
        '    For example, Elegant reads the leading 1 in a long field written 1e-999,\n'
        '    while float decoding underflows to zero. Never treat that as disabled.\n'
        '    """\n'
        '    if isinstance(value, bool) or not isinstance(value, int):\n'
        "        raise ConversionError(label + ' requires an integer literal in source syntax')\n"
        '    return value\n'
        '\n'
        '\n'
        'def literal_string(value, label):\n'
        '    """Keep filenames/labels as data and refuse source macro or shell syntax."""\n'
        "    if not isinstance(value, str) or not value or any(c in value for c in '\\r\\n\\x00<>$`{}'):\n"
        "        raise ConversionError(label + ' must be a nonempty literal string without macros or shell substitutions')\n"
        '    return value\n'
        '\n'
        '\n'
        'def validate_command_policy(commands, source_rest_energy_eV=SOURCE_REST_EV):\n'
        '    """Validate one static, single-pass injected-electron tracking sequence."""\n'
        "    mass = finite_number(source_rest_energy_eV, 'source rest energy [eV]', positive=True)\n"
        "    if [c['name'] for c in commands] != ['RUN_SETUP', 'RUN_CONTROL', 'SDDS_BEAM', 'TRACK']:\n"
        "        raise ConversionError('Require exactly run_setup, run_control, sdds_beam, track in that order; generation, scans, optimization and other commands are unsupported')\n"
        "    setup, control, beam, track = [c['attributes'] for c in commands]\n"
        "    setup_outputs = {'ROOTNAME','OUTPUT','CENTROID','BPM_CENTROID','SIGMA','FINAL','ACCEPTANCE','LOSSES','MAGNETS','PROFILE','PARAMETERS','SEMAPHORE_FILE'}\n"
        "    setup_zero = {'COMBINE_BUNCH_STATISTICS','COUPLED_SIGMA','FINAL_PASS','CONCAT_ORDER','ALWAYS_CHANGE_P0','ELEMENT_DIVISIONS','LOAD_BALANCING_ON','BACK_TRACKING','S_START','SPIN_TRACKING','LOSSES_INCLUDE_GLOBAL_COORDINATES'}\n"
        "    setup_flags = {'PRINT_STATISTICS','SHOW_ELEMENT_TIMING','MONITOR_MEMORY_USAGE','TRACKING_UPDATES','ECHO_LATTICE','SUPPRESS_PARAMETER_DEFAULTS','WRAP_AROUND'}\n"
        "    allowed = setup_outputs | setup_zero | setup_flags | {'LATTICE','USE_BEAMLINE','P_CENTRAL','P_CENTRAL_MEV','DEFAULT_ORDER','RANDOM_NUMBER_SEED','CORRECTION_ITERATIONS','EXPAND_FOR','SEARCH_PATH'}\n"
        '    unknown = set(setup)-allowed\n'
        '    if unknown:\n'
        "        raise ConversionError('Unsupported run_setup attributes: '+', '.join(sorted(unknown)))\n"
        "    source_ints = (setup_zero-{'S_START'}) | setup_flags | {'DEFAULT_ORDER','RANDOM_NUMBER_SEED','CORRECTION_ITERATIONS'}\n"
        '    for key in source_ints & set(setup):\n'
        "        source_integer(setup[key], 'run_setup.'+key)\n"
        '    for key in setup_zero & set(setup):\n'
        "        if finite_number(setup[key], 'run_setup.'+key) != 0:\n"
        "            raise ConversionError('Unsupported nondefault run_setup.'+key)\n"
        '    for key in setup_flags & set(setup):\n'
        "        integer_setting(setup[key], 'run_setup.'+key, 0, 1)\n"
        "    for key in ('EXPAND_FOR','SEARCH_PATH'):\n"
        "        if key in setup and setup[key] not in ('', 'NULL', 'null'):\n"
        "            raise ConversionError('Unsupported run_setup.'+key)\n"
        '    for key in setup_outputs & set(setup):\n'
        "        literal_string(setup[key], 'run_setup.'+key)\n"
        "    if 'RANDOM_NUMBER_SEED' in setup:\n"
        "        integer_setting(setup['RANDOM_NUMBER_SEED'], 'random_number_seed', 0, 2147483647)\n"
        "    if 'CORRECTION_ITERATIONS' in setup:\n"
        "        integer_setting(setup['CORRECTION_ITERATIONS'], 'correction_iterations', 1, 1)\n"
        "    order = integer_setting(setup.get('DEFAULT_ORDER', 2), 'default_order', 1, 3)\n"
        "    lattice_path = literal_string(setup.get('LATTICE'), 'run_setup.lattice')\n"
        "    beamline = literal_string(setup.get('USE_BEAMLINE'), 'run_setup.use_beamline').upper()\n"
        "    p = finite_number(setup.get('P_CENTRAL', 0), 'p_central')\n"
        "    pm = finite_number(setup.get('P_CENTRAL_MEV', 0), 'p_central_mev')\n"
        '    if p < 0 or pm < 0 or (p == 0 and pm == 0):\n'
        "        raise ConversionError('Need a positive electron p_central [mc] or p_central_mev [MeV/c]')\n"
        "    momentum_eVc = finite_number(p*mass if p else pm*1e6, 'derived reference momentum [eV/c]', positive=True)\n"
        "    defaults = {'N_STEPS':1,'BUNCH_FREQUENCY':0,'STEP_FREQUENCY':0,'N_INDICES':0,'N_PASSES':1,'N_PASSES_FIDUCIAL':0,'RESET_RF_FOR_EACH_STEP':1,'FIRST_IS_FIDUCIAL':0,'RESTRICT_FIDUCIALIZATION':0,'RESTART_FILES':0}\n"
        '    for key, value in control.items():\n'
        "        if key in defaults and key not in ('BUNCH_FREQUENCY','STEP_FREQUENCY'):\n"
        "            source_integer(value, 'run_control.'+key)\n"
        "        if key not in defaults or finite_number(value, 'run_control.'+key) != defaults[key]:\n"
        "            raise ConversionError('Unsupported run_control.'+key+'; only one ordinary step/pass is supported')\n"
        "    beam_defaults = {'N_PARTICLES_PER_RING':0,'ONE_RANDOM_BUNCH':0,'REUSE_BUNCH':0,'TRACK_PAGES_SEPARATELY':0,'USE_BUNCHED_MODE':0,'FIDUCIALIZATION_BUNCH':0,'SAMPLE_INTERVAL':1,'N_TABLES_TO_SKIP':0,'CENTER_TRANSVERSELY':0,'CENTER_ARRIVAL_TIME':0,'SAMPLE_FRACTION':1,'P_LOWER':0,'P_UPPER':0,'SAVE_INITIAL_COORDINATES':1,'REVERSE_T_SIGN':0,'N_DUPLICATES':0}\n"
        '    for key, value in beam.items():\n'
        "        if key in (set(beam_defaults)-{'SAMPLE_FRACTION','P_LOWER','P_UPPER'}) | {'PREBUNCHED'}:\n"
        "            source_integer(value, 'sdds_beam.'+key)\n"
        "        if key in ('INPUT','INPUT_TYPE'):\n"
        '            continue\n'
        "        if key == 'PREBUNCHED' and finite_number(value, 'prebunched') in (-1,0,1):\n"
        '            continue  # Exactly one page is separately enforced by the SDDS reader.\n'
        "        if key not in beam_defaults or finite_number(value, 'sdds_beam.'+key) != beam_defaults[key]:\n"
        "            raise ConversionError('Unsupported sdds_beam.'+key+'; filtering/recentering/duplication is refused')\n"
        "    if literal_string(beam.get('INPUT_TYPE','elegant'), 'sdds_beam.input_type').lower() != 'elegant':\n"
        "        raise ConversionError('Only Elegant electron SDDS input_type is supported')\n"
        "    particle_path = literal_string(beam.get('INPUT'), 'sdds_beam.input')\n"
        "    track_defaults = {'CENTER_ON_ORBIT':0,'CENTER_MOMENTUM_ALSO':1,'OFFSET_BY_ORBIT':0,'OFFSET_MOMENTUM_ALSO':1,'SOFT_FAILURE':1,'STOP_TRACKING_PARTICLE_LIMIT':-1,'CHECK_BEAM_STRUCTURE':0}\n"
        '    for key, value in track.items():\n'
        '        if key in track_defaults:\n'
        "            source_integer(value, 'track.'+key)\n"
        "        if key == 'SOFT_FAILURE':\n"
        "            integer_setting(value, 'track.soft_failure', 0, 1)\n"
        "        elif key not in track_defaults or finite_number(value, 'track.'+key) != track_defaults[key]:\n"
        "            raise ConversionError('Unsupported track.'+key)\n"
        "    return {'lattice_file':lattice_path, 'particle_file':particle_path, 'beamline':beamline,\n"
        "            'source_rest_energy_eV':mass, 'reference_momentum_eVc':momentum_eVc,\n"
        "            'reference_momentum_GeVc':momentum_eVc*1e-9, 'default_order':order,\n"
        "            'p_central_takes_precedence':bool(p and pm), 'source_diagnostics':{k:v for k,v in setup.items() if k in setup_outputs}}\n"
        '\n'
        '\n'
        '# RFCA extension: assembled into the standalone converter; no sibling imports.\n'
        '# Official contracts:\n'
        '# https://ops.aps.anl.gov/manuals/elegant_latest/elegantsu230.html\n'
        '# https://github.com/rtsoliday/elegant/blob/master/src/simple_rfca.c\n'
        '# PHASE_REFERENCE/N_KICKS are C long; STANDING_WAVE/CHANGE_P0/CHANGE_T/\n'
        '# END1_FOCUS/END2_FOCUS/LINEARIZE/LOCK_PHASE are C short in track_data.c.\n'
        '\n'
        '\n'
        'def rfca_spec(name, attrs):\n'
        '    """Validate a uniform standing-wave, longitudinal-kick RFCA source model.\n'
        '\n'
        "    Elegant's finite N_KICKS drift/kick discretization and OPALX's continuous\n"
        '    IDEAL field integration share a pure-Ez model, but are not identical at\n'
        '    finite resolution. Matrix, traveling-wave, fringe/body-focus, shared phase\n'
        '    reference, automatic fiducial timing and reference-momentum changes are\n'
        '    deliberately refused. Source integer fields retain their C long/short\n'
        '    literal syntax rather than accepting floating values that round to zero.\n'
        '    """\n'
        "    name = literal_string(name, 'RFCA name')\n"
        '    if not isinstance(attrs, dict):\n'
        "        raise ConversionError(name + ': RFCA attributes must be a dictionary')\n"
        "    integer_zero = {'PHASE_REFERENCE', 'CHANGE_P0', 'CHANGE_T', 'END1_FOCUS',\n"
        "                    'END2_FOCUS', 'LINEARIZE', 'LOCK_PHASE'}\n"
        "    real_zero = {'Q', 'DX', 'DY'}\n"
        "    allowed = integer_zero | real_zero | {'L', 'VOLT', 'PHASE', 'FREQ', 'FIDUCIAL',\n"
        "                                         'STANDING_WAVE', 'BODY_FOCUS_MODEL', 'N_KICKS',\n"
        "                                         'T_REFERENCE', 'GROUP'}\n"
        '    unknown = set(attrs) - allowed\n'
        '    if unknown:\n'
        "        raise ConversionError(name + ': unsupported RFCA attributes ' + ', '.join(sorted(unknown)))\n"
        '    for key in integer_zero:\n'
        "        if source_integer(attrs.get(key, 0), name + '.' + key) != 0:\n"
        "            raise ConversionError(name + ': RFCA requires ' + key + '=0')\n"
        '    for key in real_zero:\n'
        "        if finite_number(attrs.get(key, 0), name + '.' + key) != 0:\n"
        "            raise ConversionError(name + ': active RFCA ' + key + ' is unsupported')\n"
        "    standing = source_integer(attrs.get('STANDING_WAVE', 0), name + '.STANDING_WAVE')\n"
        '    if standing != 1:\n'
        "        raise ConversionError(name + ': RFCA requires explicit STANDING_WAVE=1; traveling-wave phase is unsupported')\n"
        "    kicks = source_integer(attrs.get('N_KICKS', 0), name + '.N_KICKS')\n"
        '    if not 1 <= kicks <= 1000000:\n'
        "        raise ConversionError(name + ': RFCA N_KICKS must be in 1..1000000; the default matrix model is unsupported')\n"
        "    if 'BODY_FOCUS_MODEL' in attrs:\n"
        "        focus = literal_string(attrs['BODY_FOCUS_MODEL'], name + '.BODY_FOCUS_MODEL')\n"
        "        if focus.lower() != 'none':\n"
        '            raise ConversionError(name + \': RFCA body focusing is unsupported; use BODY_FOCUS_MODEL="none" or omit it\')\n'
        "    if 'FIDUCIAL' in attrs:\n"
        "        fiducial = literal_string(attrs['FIDUCIAL'], name + '.FIDUCIAL')\n"
        "        if fiducial.lower() not in ('light', 'tmean', 'first', 'pmaximum'):\n"
        "            raise ConversionError(name + ': unknown RFCA FIDUCIAL mode')\n"
        '    else:\n'
        '        fiducial = None\n'
        "    if 'GROUP' in attrs:\n"
        "        literal_string(attrs['GROUP'], name + '.GROUP')\n"
        "    length = finite_number(attrs.get('L', 0), name + '.L [m]', positive=True)\n"
        "    voltage = finite_number(attrs.get('VOLT', 0), name + '.VOLT [V]')\n"
        "    frequency = finite_number(attrs.get('FREQ', 500000000), name + '.FREQ [Hz]')\n"
        "    phase = finite_number(attrs.get('PHASE', 0), name + '.PHASE [deg]')\n"
        "    reference = finite_number(attrs.get('T_REFERENCE', -1), name + '.T_REFERENCE [s]')\n"
        '    if frequency < 0:\n'
        "        raise ConversionError(name + ': RFCA FREQ must be nonnegative')\n"
        '    if reference < 0:\n'
        "        raise ConversionError(name + ': RFCA requires explicit T_REFERENCE>=0; automatic fiducial phase is unsupported')\n"
        "    omega = finite_number(2 * math.pi * frequency, name + ' angular RF frequency')\n"
        "    finite_number(omega * reference, name + ' reference RF phase')\n"
        "    finite_number(phase * math.pi, name + ' source phase conversion')\n"
        "    gradient = finite_number(voltage / length / 1e6, name + ' RF gradient [MV/m]')\n"
        "    return {'kind': 'rf', 'length_m': length, 'voltage_V': voltage,\n"
        "            'frequency_Hz': frequency, 'phase_deg': phase, 't_reference_s': reference,\n"
        "            'n_kicks': kicks, 'source_fiducial_mode_ignored_by_explicit_time': fiducial,\n"
        "            'gradient_MVm': gradient,\n"
        "            'model': 'standing-wave longitudinal RFCA kicks mapped to continuous uniform IDEAL Ez',\n"
        "            'source_discretization': 'finite N_KICKS symmetric drift/kick splitting; transverse mechanical momenta conserved',\n"
        "            'target_discretization': 'time integration of uniform longitudinal Ez; no transverse, magnetic or fringe fields',\n"
        "            'model_limitation': 'same continuous pure-Ez model; finite Elegant kick count and OPALX timestep can give different results'}\n"
        '\n'
        '\n'
        'def rfca_phase_lag(phase_deg, frequency_Hz, t_reference_s, clock_origin_s):\n'
        '    """Translate source sine energy-gain phase to target electron cosine Ez.\n'
        '\n'
        '    Source energy gain per length is +V/L*sin(omega*(t-T_REFERENCE)+PHASE).\n'
        '    Target signed electron charge requires Ez=-V/L*sin(...), so the native\n'
        '    cosine lag is PHASE+pi/2+omega*(clock_origin-T_REFERENCE), in radians.\n'
        '    Both the absolute source reference and rebased snapshot clock are retained.\n'
        '    """\n'
        "    phase = finite_number(phase_deg, 'RFCA PHASE [deg]')\n"
        "    frequency = finite_number(frequency_Hz, 'RFCA FREQ [Hz]')\n"
        "    reference = finite_number(t_reference_s, 'RFCA T_REFERENCE [s]')\n"
        "    clock = finite_number(clock_origin_s, 'RFCA launch clock origin [s]')\n"
        '    if frequency < 0 or reference < 0:\n'
        "        raise ConversionError('RFCA frequency and explicit reference time must be nonnegative')\n"
        "    omega = finite_number(2 * math.pi * frequency, 'RFCA angular frequency')\n"
        "    finite_number(phase * math.pi, 'RFCA source phase conversion')\n"
        "    finite_number(omega * reference, 'RFCA source reference phase')\n"
        "    finite_number(omega * clock, 'RFCA launch clock phase')\n"
        "    advance = finite_number(omega * finite_number(clock-reference, 'RFCA relative clock'),\n"
        "                            'RFCA clock phase advance')\n"
        '    lag = finite_number(math.radians(math.remainder(phase, 360.)) + math.pi/2 + advance,\n'
        "                        'RFCA target cosine phase')\n"
        '    return math.remainder(lag, 2 * math.pi)\n'
        '\n'
        '\n'
        'def rf_target_parameters(spec, clock_origin_s):\n'
        '    """Return explicit native IDEAL gradient [MV/m], frequency [MHz], and lag."""\n'
        "    length = finite_number(spec['length_m'], 'RFCA length [m]', positive=True)\n"
        "    voltage = finite_number(spec['voltage_V'], 'RFCA voltage [V]')\n"
        "    frequency = finite_number(spec['frequency_Hz'], 'RFCA frequency [Hz]')\n"
        "    gradient = finite_number(voltage / length / 1e6, 'RFCA target gradient [MV/m]')\n"
        "    mhz = finite_number(frequency * 1e-6, 'RFCA target frequency [MHz]')\n"
        "    lag = rfca_phase_lag(spec['phase_deg'], frequency, spec['t_reference_s'], clock_origin_s)\n"
        "    return {'gradient_MVm': gradient, 'frequency_MHz': mhz, 'lag_rad': lag}\n"
        '\n'
        '\n'
        "# Standalone assembly fragment. Requires the converter's scalar-policy helpers.\n"
        '\n'
        '\n'
        'def _bend_sinc(angle):\n'
        '    """Return sin(angle)/angle continuously at zero without cancellation."""\n'
        '    if abs(angle) < 1e-4:\n'
        '        square = angle * angle\n'
        '        return 1.0 - square / 6.0 + square * square / 120.0 - square**3 / 5040.0\n'
        '    return math.sin(angle) / angle\n'
        '\n'
        '\n'
        'def planar_advance(origin_xyz, heading_rad, arc_length_m, angle_rad=0):\n'
        '    """Advance a planar design path embedded in 3D lab coordinates.\n'
        '\n'
        '    A positive Elegant angle bends toward local -x, and changes the lab yaw\n'
        '    from heading to heading-angle. Length is design-orbit arc length. The\n'
        '    stable local displacement is (-L*a*sinc(a/2)^2/2, 0, L*sinc(a)). Neither\n'
        '    transport of real particles nor numerical tracking is performed here.\n'
        '    """\n'
        '    if not isinstance(origin_xyz, (tuple, list)) or len(origin_xyz) != 3:\n'
        "        raise ConversionError('Design-path origin must contain three coordinates')\n"
        "    origin = [finite_number(value, 'design-path origin [m]') for value in origin_xyz]\n"
        "    heading = finite_number(heading_rad, 'design-path heading [rad]')\n"
        "    length = finite_number(arc_length_m, 'design-path arc length [m]')\n"
        "    angle = finite_number(angle_rad, 'design-path bend angle [rad]')\n"
        '    if length < 0 or abs(angle) >= math.pi or (length == 0 and angle != 0):\n'
        "        raise ConversionError('Design path requires nonnegative length and |bend angle| < pi; a finite bend needs positive length')\n"
        '    local_x = length * (-0.5 * angle * _bend_sinc(angle / 2.0)**2)\n'
        '    local_z = length * _bend_sinc(angle)\n'
        '    cosine, sine = math.cos(heading), math.sin(heading)\n'
        '    endpoint = [origin[0] + cosine * local_x + sine * local_z,\n'
        '                origin[1], origin[2] - sine * local_x + cosine * local_z]\n'
        "    return {'origin_m': [finite_number(v, 'design-path endpoint [m]') for v in endpoint],\n"
        "            'heading_rad': finite_number(heading - angle, 'design-path exit heading [rad]')}\n"
        '\n'
        '\n'
        'def bend_spec(name, kind, attrs, default_order=2):\n'
        '    """Validate a pure, aligned, zero-gap Elegant sector bending magnet.\n'
        '\n'
        '    SBEN lengths are arc lengths; SBEND is the same Elegant element spelling.\n'
        '    Preserve that source spelling while dispatching both through SBEN physics.\n'
        '    Their finite-order matrices remain source model metadata. CSBEND keeps its\n'
        '    documented exact-Hamiltonian integrator settings as metadata; no radiation,\n'
        '    higher multipoles, steering, field errors, alignment errors, or finite-gap\n'
        '    fringe model is inferred.\n'
        '\n'
        '    Target bends use positive |ANGLE| and K0, with a pi roll for a negative\n'
        '    source angle. Native bend fields already divide by the reference charge;\n'
        '    applying the separate standalone-quadrupole electron sign rule here would\n'
        '    reverse the requested orbit. P0 must equal the source local reference\n'
        '    rigidity, a condition enforced by the surrounding conversion policy.\n'
        '\n'
        '    RBEN is deliberately refused: setting its edge flags to zero removes BOTH\n'
        '    source horizontal and vertical edge matrices. A uniform zero-gap native\n'
        '    rectangular field retains horizontal geometrical effects but lacks the\n'
        '    Maxwell vertical fringe kick, so either flag setting loses source physics.\n'
        '    """\n'
        '    source_kind = kind\n'
        "    if kind == 'SBEND':\n"
        "        kind = 'SBEN'\n"
        "    if kind == 'RBEN':\n"
        "        raise ConversionError(name + ': RBEN rectangular edge focusing is unsupported; a zero-gap target field cannot preserve both transverse edge models')\n"
        "    if kind not in ('SBEN', 'CSBEND'):\n"
        "        raise ConversionError(name + ': unsupported dipole type ' + kind)\n"
        '\n'
        "    common_zero = {'K1', 'K2', 'H1', 'H2', 'HGAP', 'TILT', 'ETILT', 'DX', 'DY', 'DZ',\n"
        "                   'FSE', 'FSE_DIPOLE', 'FSE_QUADRUPOLE', 'B1', 'B2'}\n"
        "    common_integer_zero = {'USE_BN'}\n"
        "    common = {'L', 'ANGLE', 'E1', 'E2', 'FINT', 'GROUP', 'EDGE1_EFFECTS',\n"
        "              'EDGE2_EFFECTS', 'EDGE_ORDER', 'ETILT_SIGN'}\n"
        "    if kind == 'SBEN':\n"
        "        allowed = common | common_zero | common_integer_zero | {'ORDER', 'TRANSPORT'}\n"
        '        zero_fields = common_zero\n'
        "        integer_zero = common_integer_zero | {'TRANSPORT'}\n"
        '    else:\n'
        "        extra_zero = {'EPITCH', 'EYAW', 'XKICK', 'YKICK', 'XREFERENCE'}\n"
        "        extra_zero |= {'K' + str(i) for i in range(3, 9)}\n"
        "        extra_zero |= {'B' + str(i) for i in range(3, 9)}\n"
        "        extra_zero |= {'F' + str(i) for i in range(1, 9)}\n"
        "        extra_zero |= {'G' + str(i) for i in range(1, 9)}\n"
        "        extra_zero |= {'FRINGE' + str(face) + 'K' + str(i) for face in (1, 2) for i in range(7)}\n"
        "        integer_zero = common_integer_zero | {'SYNCH_RAD', 'ISR', 'SR_IN_ORDINARY_MATRIX',\n"
        "                       'USE_RAD_DIST', 'EXPAND_HAMILTONIAN', 'KICK_LIMIT_SCALING',\n"
        "                       'EXPANSION_ORDER', 'SQRT_ORDER', 'REFERENCE_CORRECTION',\n"
        "                       'TRACKING_MATRIX', 'FSE_CORRECTION', 'MALIGN_METHOD', 'XSTEERING', 'YSTEERING'}\n"
        '        zero_fields = common_zero | extra_zero\n'
        "        allowed = common | zero_fields | integer_zero | {'FINT1', 'FINT2', 'N_SLICES', 'N_KICKS',\n"
        "                   'INTEGRATION_ORDER', 'NONLINEAR', 'ISR1PART', 'ADD_OPENING_ANGLE',\n"
        "                   'EDGE1_KICK_LIMIT', 'EDGE2_KICK_LIMIT'}\n"
        '    unknown = set(attrs) - allowed\n'
        '    if unknown:\n'
        "        raise ConversionError(name + ': unsupported ' + kind + ' attributes ' + ', '.join(sorted(unknown)))\n"
        "    if 'GROUP' in attrs:\n"
        "        literal_string(attrs['GROUP'], name + '.GROUP')\n"
        '    for key in zero_fields & set(attrs):\n'
        "        if finite_number(attrs[key], name + '.' + key) != 0:\n"
        "            raise ConversionError(name + ': unsupported active dipole ' + key)\n"
        '    for key in integer_zero & set(attrs):\n'
        "        if source_integer(attrs[key], name + '.' + key) != 0:\n"
        "            raise ConversionError(name + ': unsupported active dipole ' + key)\n"
        "    for key in ('E1', 'E2'):\n"
        "        if finite_number(attrs.get(key, 0), name + '.' + key) != 0:\n"
        "            raise ConversionError(name + ': nonzero sector pole-face angles are unsupported')\n"
        '    # With exactly zero HGAP, finite FINT/FINT1/FINT2 coefficients multiply zero\n'
        '    # and produce no source finite-gap fringe correction.\n'
        "    source_fint = finite_number(attrs.get('FINT', 0.5), name + '.FINT')\n"
        "    edge_flags = [integer_setting(source_integer(attrs.get(key, 1), name + '.' + key),\n"
        "                                 name + '.' + key, 0, 1)\n"
        "                  for key in ('EDGE1_EFFECTS', 'EDGE2_EFFECTS')]\n"
        "    if 'ETILT_SIGN' in attrs:\n"
        "        integer_setting(source_integer(attrs['ETILT_SIGN'], name + '.ETILT_SIGN'), name + '.ETILT_SIGN', 1, 1)\n"
        "    length = finite_number(attrs.get('L', 0), name + '.L', positive=True)\n"
        "    angle = finite_number(attrs.get('ANGLE', 0), name + '.ANGLE')\n"
        '    if angle == 0 or abs(angle) >= math.pi:\n'
        "        raise ConversionError(name + ': a sector bend requires 0 < |ANGLE| < pi')\n"
        '\n'
        "    if kind == 'SBEN':\n"
        "        order = integer_setting(source_integer(attrs.get('ORDER', 0), name + '.ORDER'),\n"
        "                                name + '.ORDER', 0, 2) or integer_setting(\n"
        "                                    source_integer(default_order, 'default_order'), 'default_order', 1, 2)\n"
        "        edge_order = integer_setting(source_integer(attrs.get('EDGE_ORDER', 0), name + '.EDGE_ORDER'),\n"
        "                                     name + '.EDGE_ORDER', 0, 2) or order\n"
        '        # Upstream bend_matrix otherwise intentionally substitutes a drift.\n'
        '        if abs(angle) < 1e-10 or abs(length / angle) > 1e6:\n'
        "            raise ConversionError(name + ': SBEN enters Elegant\\'s weak-bend drift fallback; use an explicit drift instead')\n"
        '        integrator = None\n'
        '    else:\n'
        '        order = None\n'
        "        edge_order = integer_setting(source_integer(attrs.get('EDGE_ORDER', 1), name + '.EDGE_ORDER'),\n"
        "                                     name + '.EDGE_ORDER', 1, 2)\n"
        "        if 'N_SLICES' in attrs and 'N_KICKS' in attrs:\n"
        "            raise ConversionError(name + ': specify N_SLICES or its deprecated N_KICKS alias, not both')\n"
        "        slices = integer_setting(source_integer(attrs.get('N_SLICES', attrs.get('N_KICKS', 4)), name + '.N_SLICES'),\n"
        "                                 name + '.N_SLICES', 1, 1000000)\n"
        "        integration_order = source_integer(attrs.get('INTEGRATION_ORDER', 4), name + '.INTEGRATION_ORDER')\n"
        '        if integration_order not in (2, 4, 6):\n'
        "            raise ConversionError(name + ': CSBEND INTEGRATION_ORDER must be 2, 4 or 6')\n"
        "        for key in ('NONLINEAR', 'ISR1PART', 'ADD_OPENING_ANGLE'):\n"
        '            if key in attrs:\n'
        "                integer_setting(source_integer(attrs[key], name + '.' + key), name + '.' + key, 1, 1)\n"
        "        for key in ('FINT1', 'FINT2'):\n"
        '            if key in attrs:\n'
        "                finite_number(attrs[key], name + '.' + key)\n"
        "        for key in ('EDGE1_KICK_LIMIT', 'EDGE2_KICK_LIMIT'):\n"
        "            if key in attrs and finite_number(attrs[key], name + '.' + key) >= 0:\n"
        "                raise ConversionError(name + ': finite edge kick limits are unsupported')\n"
        "        integrator = {'n_slices': slices, 'integration_order': integration_order,\n"
        "                      'expanded_hamiltonian': False, 'nonlinear': True}\n"
        "    curvature = finite_number(abs(angle) / length, name + ' target curvature [1/m]', positive=True)\n"
        "    return {'kind': 'bend', 'source_type': source_kind, 'source_length_m': length,\n"
        "            'length_m': length, 'target_type': 'SBEND', 'target_length_m': length,\n"
        "            'angle_rad': angle, 'target_angle_rad': abs(angle),\n"
        "            'target_roll_rad': math.pi if angle < 0 else 0.0,\n"
        "            'target_yaw_offset_rad': 0.0, 'target_k0_m1': curvature,\n"
        "            'source_order': order, 'source_edge_order': edge_order,\n"
        "            'source_edge_flags': edge_flags, 'source_fint': source_fint,\n"
        "            'source_integrator': integrator}\n"
        '\n'
        '\n'
        'def lattice_specs(lattice, beamline, default_order=2, *, replace_unavailable=False):\n'
        '    """Resolve element models and cumulative poses, optionally replacing unknown types.\n'
        '\n'
        '    A replacement requires an explicit finite nonnegative literal L [m]. Its\n'
        '    original fields, apertures and deflection are omitted; supported element\n'
        '    types retain all existing configuration guards. The default remains strict.\n'
        '    """\n'
        '    if not isinstance(replace_unavailable, bool):\n'
        "        raise ConversionError('replace_unavailable must be a boolean')\n"
        "    if beamline not in lattice['lines']:\n"
        "        raise ConversionError('Undefined selected beamline: '+beamline)\n"
        '    specs, unavailable, position, total_charge, leading = [], [], 0.0, None, 0.0\n'
        '    prefix_field_free = True\n'
        "    for index, name in enumerate(lattice['lines'][beamline]):\n"
        "        element = lattice['elements'][name]\n"
        "        kind, attrs = element['type'], element['parameters']\n"
        "        base = {'name':name,'source_type':kind,'s_m':position,'length_m':0.0}\n"
        "        metadata = {'GROUP'}\n"
        "        supported = kind in ('DRIF','DRIFT','EDRIFT','QUAD','SBEN','SBEND',\n"
        "                             'CSBEND','RFCA','MARK','CHARGE')\n"
        "        if 'GROUP' in attrs and not (replace_unavailable and not supported):\n"
        "            literal_string(attrs['GROUP'], name+'.GROUP')\n"
        '        if replace_unavailable and not supported:\n'
        "            if 'L' not in attrs:\n"
        "                raise ConversionError(name+': unavailable '+kind+' needs explicit L for drift replacement')\n"
        "            length = finite_number(attrs['L'], name+'.L for drift replacement')\n"
        '            if length < 0:\n'
        "                raise ConversionError(name+': drift replacement length must be nonnegative')\n"
        "            replacement = {'name': name, 'source_type': kind, 'occurrence': index+1,\n"
        "                           'length_m': length, 's_m': position, 'replacement_type': 'DRIFT',\n"
        "                           'reason': 'Elegant element type is unavailable in this converter; original physics omitted',\n"
        "                           'discarded_attributes': sorted(set(attrs)-{'L'})}\n"
        '            unavailable.append(replacement)\n'
        "            base.update(kind='drift', length_m=length, source_order=None,\n"
        '                        replaced_with_drift=True)\n'
        '            if prefix_field_free:\n'
        '                leading += length\n'
        "        elif kind in ('DRIF','DRIFT','EDRIFT'):\n"
        "            unknown = set(attrs)-metadata-{'L','ORDER'}\n"
        '            if unknown:\n'
        "                raise ConversionError(name+': unsupported drift attributes '+', '.join(sorted(unknown)))\n"
        "            length = finite_number(attrs.get('L',0), name+'.L')\n"
        '            if length < 0:\n'
        "                raise ConversionError('Negative element lengths are unsupported')\n"
        "            if kind == 'EDRIFT' and 'ORDER' in attrs:\n"
        "                raise ConversionError('EDRIFT has no matrix ORDER attribute')\n"
        "            order = integer_setting(source_integer(attrs.get('ORDER',0), name+'.ORDER'), name+'.ORDER', 0, 3) or default_order\n"
        "            base.update(kind='drift',length_m=length,source_order=None if kind=='EDRIFT' else order)\n"
        '            if prefix_field_free:\n'
        '                leading += length\n'
        "        elif kind == 'QUAD':\n"
        "            zero = {'TILT','DX','DY','DZ','PITCH','YAW','HKICK','VKICK','HSTEERING','VSTEERING','FFRINGE','I0P','I1P','I2P','I3P','I0M','I1M','I2M','I3M','RADIAL'}\n"
        "            allowed = metadata | zero | {'L','K1','FSE','ORDER','LEFFECTIVE','FRINGE_TYPE','EDGE1_EFFECTS','EDGE2_EFFECTS','HCALIBRATION','VCALIBRATION','MALIGN_METHOD'}\n"
        '            if set(attrs)-allowed:\n'
        "                raise ConversionError(name+': unsupported QUAD attributes '+', '.join(sorted(set(attrs)-allowed)))\n"
        "            for key in {'HSTEERING','VSTEERING','ORDER','EDGE1_EFFECTS','EDGE2_EFFECTS','RADIAL','MALIGN_METHOD'} & set(attrs):\n"
        "                source_integer(attrs[key], name+'.'+key)\n"
        '            for key in zero & set(attrs):\n'
        "                if finite_number(attrs[key], name+'.'+key) != 0:\n"
        "                    raise ConversionError(name+': unsupported active '+key)\n"
        "            if 'LEFFECTIVE' in attrs and finite_number(attrs['LEFFECTIVE'],name+'.LEFFECTIVE') > 0:\n"
        "                raise ConversionError(name+': positive LEFFECTIVE is unsupported')\n"
        "            if str(attrs.get('FRINGE_TYPE','fixed-strength')).lower() != 'fixed-strength':\n"
        "                raise ConversionError(name+': only zero fixed-strength fringes are supported')\n"
        "            for key in ('EDGE1_EFFECTS','EDGE2_EFFECTS','MALIGN_METHOD'):\n"
        '                if key in attrs:\n'
        "                    integer_setting(attrs[key],name+'.'+key,0,1)\n"
        "            for key in ('HCALIBRATION','VCALIBRATION'):\n"
        "                if key in attrs and finite_number(attrs[key],name+'.'+key) != 1:\n"
        "                    raise ConversionError(name+': unsupported nondefault '+key)\n"
        "            length = finite_number(attrs.get('L',0),name+'.L')\n"
        "            k1 = finite_number(finite_number(attrs.get('K1',0),name+'.K1')*(1+finite_number(attrs.get('FSE',0),name+'.FSE')),name+' effective K1')\n"
        '            if length < 0 or (length == 0 and k1 != 0):\n'
        "                raise ConversionError(name+': nonzero zero-length QUAD and negative lengths are unsupported')\n"
        "            order = integer_setting(attrs.get('ORDER',0),name+'.ORDER',0,3) or default_order\n"
        "            base.update(kind='quad',length_m=length,k1_m2=k1,opalx_k1_m2=-k1,source_order=order)\n"
        '            prefix_field_free = False\n'
        "        elif kind in ('SBEN','SBEND','CSBEND','RBEN'):\n"
        '            base.update(bend_spec(name,kind,attrs,default_order))\n'
        '            prefix_field_free = False\n'
        "        elif kind == 'RFCA':\n"
        '            base.update(rfca_spec(name, attrs))\n'
        '            prefix_field_free = False\n'
        "        elif kind == 'MARK':\n"
        "            if set(attrs)-metadata-{'FITPOINT'}:\n"
        "                raise ConversionError(name+': unsupported MARK attributes')\n"
        "            integer_setting(source_integer(attrs.get('FITPOINT',0),name+'.FITPOINT'),name+'.FITPOINT',0,1)\n"
        "            base.update(kind='marker',fitpoint_metadata=attrs.get('FITPOINT',0))\n"
        "        elif kind == 'CHARGE':\n"
        "            if index != 0 or total_charge is not None or set(attrs)-metadata-{'TOTAL','PER_PARTICLE','ALLOW_TOTAL_CHANGE'}:\n"
        "                raise ConversionError('Support exactly one CHARGE at the start of the selected line')\n"
        "            if 'ALLOW_TOTAL_CHANGE' in attrs:\n"
        "                source_integer(attrs['ALLOW_TOTAL_CHANGE'],name+'.ALLOW_TOTAL_CHANGE')\n"
        "            for key in ('PER_PARTICLE','ALLOW_TOTAL_CHANGE'):\n"
        "                if finite_number(attrs.get(key,0),name+'.'+key) != 0:\n"
        "                    raise ConversionError(name+': only fixed TOTAL bunch charge is supported')\n"
        "            total_charge = finite_number(attrs.get('TOTAL',0),name+'.TOTAL',positive=True)\n"
        "            base.update(kind='charge',charge_magnitude_C=total_charge)\n"
        '        else:\n'
        "            raise ConversionError(name+': unsupported active element type '+kind)\n"
        "        position = finite_number(position+base['length_m'],'total line length')\n"
        '        specs.append(base)\n'
        '    if position <= 0:\n'
        "        raise ConversionError('Selected line must have positive total length')\n"
        "    pose = {'origin_m':[0.,0.,0.], 'heading_rad':0.}\n"
        '    for element in specs:\n'
        "        element['entrance_pose'] = pose\n"
        "        pose = planar_advance(pose['origin_m'],pose['heading_rad'],element['length_m'],element.get('angle_rad',0.))\n"
        "        if abs(pose['heading_rad']) >= math.pi/2:\n"
        "            raise ConversionError('Require a forward open planar lattice: cumulative design heading must remain within (-pi/2,pi/2)')\n"
        "        element['exit_pose'] = pose\n"
        "    heading = pose['heading_rad']\n"
        "    last_field = max((e['s_m']+e['length_m'] for e in specs if e['kind'] in ('quad','rf','bend')),default=0.)\n"
        "    endpoint_plane = {'origin_m':pose['origin_m'], 'normal':[math.sin(heading),0.,math.cos(heading)],\n"
        "                      'axis_x':[math.cos(heading),0.,-math.sin(heading)], 'axis_y':[0.,1.,0.]}\n"
        "    return {'elements':specs,'length_m':position,'leading_drift_m':leading,\n"
        "            'unavailable_elements':unavailable,\n"
        "            'last_field_end_m':last_field,'last_field_exit_s_m':last_field,\n"
        "            'terminal_drift_m':position-last_field,'endpoint_plane':endpoint_plane,\n"
        "            'geometry_contract':'initially +z, forward horizontal design path; absolute entrance poses',\n"
        "            'charge_magnitude_C':total_charge}\n"
        '\n'
        '\n'
        'def beam_snapshot(data, leading_drift_m, source_rest_energy_eV=SOURCE_REST_EV):\n'
        '    """Convert crossing events to one simultaneous state inside a proven drift.\n'
        '\n'
        '    T=max(t_i); r(T)=r(plane)+v_i*(T-t_i) for ALL three coordinates.\n'
        '    p is normalized by the source mass on input and by target mass on output.\n'
        '    A centroid translation is applied to particles and all element poses together.\n'
        '    """\n'
        "    mass = finite_number(source_rest_energy_eV,'source rest energy [eV]',positive=True)\n"
        "    leading = finite_number(leading_drift_m,'leading drift length')\n"
        "    required = {'x':'m','xp':'','y':'m','yp':'','t':'s','p':'m$be$nc'}\n"
        "    definitions = {c['name']:c for c in data['columns']}\n"
        "    if set(definitions)-set(required)-{'particleID'} or not set(required) <= set(definitions):\n"
        "        raise ConversionError('Require exactly x,xp,y,yp,t,p with optional particleID; weights and extra columns are unsupported')\n"
        '    for key, units in required.items():\n'
        "        actual = definitions[key].get('units','')\n"
        "        if actual != units or definitions[key]['type'] not in ('double','float','longdouble'):\n"
        "            raise ConversionError(f'SDDS {key} requires floating values with units {units!r}')\n"
        "    rows = data['rows']\n"
        '    if not 2 <= len(rows) <= 1000000:\n'
        "        raise ConversionError('Require 2..1000000 particles in one page')\n"
        "    if 'particleID' in definitions and definitions['particleID']['type'] not in ('long','ulong','long64','ulong64','short','ushort'):\n"
        "        raise ConversionError('particleID must have an integer SDDS type')\n"
        "    ids = [r.get('particleID',i+1) for i,r in enumerate(rows)]\n"
        '    if any(isinstance(i,bool) or not isinstance(i,int) or i <= 0 for i in ids) or len(set(ids)) != len(ids):\n'
        "        raise ConversionError('particleID must be unique positive integers')\n"
        "    times = [finite_number(r['t'],'arrival time [s]') for r in rows]\n"
        '    clock = max(times)\n'
        '    physical = []\n'
        '    for row, arrival in zip(rows,times):\n'
        "        x,xp,y,yp,p = [finite_number(row[k],k,positive=(k=='p')) for k in ('x','xp','y','yp','p')]\n"
        '        pz = p/math.hypot(1.0,xp,yp)\n'
        '        px,py = xp*pz,yp*pz\n'
        '        velocity = [C_LIGHT*v/math.hypot(1.0,p) for v in (px,py,pz)]\n'
        '        elapsed = clock-arrival\n'
        '        position = [x+velocity[0]*elapsed,y+velocity[1]*elapsed,velocity[2]*elapsed]\n'
        '        if elapsed > 0 and not 0 <= position[2] < leading:\n'
        "            raise ConversionError('Arrival-time alignment leaves the explicitly field-free leading drift; no upstream extension or transport through fields is assumed')\n"
        '        normalized = [v*mass/TARGET_REST_EV for v in (px,py,pz)]\n'
        '        if not all(math.isfinite(v) for v in position+normalized) or normalized[2] <= 0:\n'
        "            raise ConversionError('Nonfinite or nonforward derived particle state')\n"
        '        physical.append(position+normalized)\n'
        '    n = len(rows)\n'
        '    origin = [math.fsum(r[d]/n for r in physical) for d in range(3)]\n'
        '    shifted = [[r[d]-origin[d] for d in range(3)]+r[3:] for r in physical]\n'
        "    return {'count':n,'particles':shifted,'source_particle_ids':ids,'clock_origin_s':clock,\n"
        "            'coordinate_origin_m':origin,'source_rest_energy_eV':mass,'target_rest_energy_eV':TARGET_REST_EV,\n"
        "            'source_arrival_time_range_s':[min(times),max(times)],\n"
        "            'aligned_world_z_range_m':[min(r[2] for r in physical),max(r[2] for r in physical)],\n"
        "            'source_sdds_charge_parameter_C':data['parameters'].get('Charge'),\n"
        "            'charge_note':'Elegant ignores input SDDS Charge; selected CHARGE.TOTAL or explicit converter --charge-c establishes target macro weights.'}\n"
        '\n'
        '\n'
        'def render_particles(snapshot):\n'
        '    """Render normalized mechanical momentum; preserve row order exactly."""\n'
        "    return str(snapshot['count'])+'\\nx px y py z pz\\n'+''.join(' '.join(format(r[d],'.17g') for d in (0,3,1,4,2,5))+'\\n' for r in snapshot['particles'])\n"
        '\n'
        '\n'
        'def render_target(config, layout, snapshot, charge_C, *, dt_s=1e-12, max_steps=100000, dump_frequency=100000000, stat_frequency=100):\n'
        '    """Render a static electron candidate with explicit rigidity and field signs."""\n'
        "    dt = finite_number(dt_s,'target DT [s]',positive=True)\n"
        "    steps = integer_setting(max_steps,'MAXSTEPS',1,10000000)\n"
        "    dump = integer_setting(dump_frequency,'PSDUMPFREQ',1,1000000000)\n"
        "    stats = integer_setting(stat_frequency,'STATDUMPFREQ',1,1000000000)\n"
        "    charge = finite_number(charge_C,'target charge magnitude [C]',positive=True)\n"
        "    ox,oy,oz = snapshot['coordinate_origin_m']\n"
        "    distance = finite_number(layout['length_m']-oz,'target observation path length',positive=True)\n"
        '    declarations, names = [], []\n'
        "    for i, element in enumerate(layout['elements']):\n"
        "        name=f'E{i:05d}'\n"
        "        if element['kind']=='charge':\n"
        '            continue\n'
        "        pose=element['entrance_pose']\n"
        "        x,y,z=[a-b for a,b in zip(pose['origin_m'],(ox,oy,oz))]\n"
        "        yaw=pose['heading_rad']+element.get('target_yaw_offset_rad',0.)\n"
        "        placement=f'X={x:.17g}, Y={y:.17g}, Z={z:.17g}, THETA={yaw:.17g}'\n"
        "        if element['kind']=='bend':\n"
        '            definition=(f\'{name}: SBEND, L={element["target_length_m"]:.17g}, ANGLE={element["target_angle_rad"]:.17g}, \'\n'
        '                        f\'K0={element["target_k0_m1"]:.17g}, HGAP=0, FINT=0, PSI={element["target_roll_rad"]:.17g}, {placement};\')\n'
        "        elif element['kind']=='rf':\n"
        "            rf=rf_target_parameters(element,snapshot['clock_origin_s'])\n"
        '            definition=(f\'{name}: RFCAVITY, TYPE="IDEAL", L={element["length_m"]:.17g}, VOLT={rf["gradient_MVm"]:.17g}, \'\n'
        '                        f\'FREQ={rf["frequency_MHz"]:.17g}, LAG={rf["lag_rad"]:.17g}, APVETO=TRUE, {placement};\')\n'
        "        elif element['kind']=='quad' and element['length_m']>0:\n"
        '            definition=f\'{name}: QUADRUPOLE, L={element["length_m"]:.17g}, K1={element["opalx_k1_m2"]:.17g}, {placement};\'\n'
        "        elif element['length_m']>0 or element.get('replaced_with_drift', False):\n"
        '            definition=f\'{name}: DRIFT, L={element["length_m"]:.17g}, {placement};\'\n'
        '        else:\n'
        "            definition=f'{name}: MARKER, {placement};'\n"
        '        declarations.append(definition);names.append(name)\n'
        "    n=snapshot['count']\n"
        "    return f'''// Elegant conversion candidate; review report.json. Static injected electrons; no collective effects.\n"
        'OPTION, VERSION=10900, AUTOPHASE=0, STATDUMPFREQ={stats}, PSDUMPFREQ={dump}, BOUNDPDESTROY=1000;\n'
        "REAL P0={config['reference_momentum_GeVc']:.17g};\n"
        '{chr(10).join(declarations)}\n'
        "L: LINE=({','.join(names)});\n"
        'F: FIELDSOLVER, TYPE=NONE, NX=8, NY=8, NZ=8, PARFFTX=TRUE, PARFFTY=TRUE, PARFFTZ=TRUE, BCFFTX=OPEN, BCFFTY=OPEN, BCFFTZ=OPEN;\n'
        'P: DISTRIBUTION, TYPE=FROMFILE, FNAME="particles.opalx", NPARTDIST={n};\n'
        'S: EMISSIONSOURCE, DISTRIBUTION=P;\n'
        'SL: EMISSIONSOURCELIST=(S);\n'
        'B: BEAM, PARTICLE=ELECTRON, CHARGE=-1, MASS={TARGET_REST_EV*1e-9:.17g}, NALLOC={n}, BCHARGE={charge:.17g}, SOURCES=SL;\n'
        'TRACK, LINE=L, BEAM=B, DT={{{dt:.17g}}}, MAXSTEPS={steps}, ZSTOP={distance:.17g};\n'
        'RUN, METHOD=PARALLEL, FIELDSOLVER=F;\n'
        'ENDTRACK;\n'
        'QUIT;\n'
        "'''\n"
        '\n'
        '\n'
        'def inspect_source(source, *, source_rest_energy_eV=SOURCE_REST_EV, replace_unavailable=False):\n'
        '    """Classify a command/lattice input without reading particles or running code."""\n'
        '    path=Path(source).resolve()\n'
        '    commands=parse_commands(path.read_text())\n'
        "    result={'converter':'elegant2opalx','version':VERSION,'source_file':str(path),'issues':[],\n"
        "            'unavailable_elements':[],\n"
        "            'fieldsolver_policy':{'target_type':'NONE','forced_off':True,\n"
        "                                  'reason':'Space charge is disabled for non-OPAL conversion'},\n"
        "            'command_inventory':dict(Counter(c['name'] for c in commands))}\n"
        '    try:\n'
        '        config=validate_command_policy(commands,source_rest_energy_eV)\n'
        "        lattice_path=(path.parent/config['lattice_file']).resolve()\n"
        '        lattice=parse_lattice(lattice_path.read_text())\n'
        '        result.update(config=config,lattice_file=str(lattice_path),\n'
        "            definition_inventory=dict(Counter(e['type'] for e in lattice['elements'].values())))\n"
        "        result['layout']=lattice_specs(lattice,config['beamline'],config['default_order'],\n"
        '                                       replace_unavailable=replace_unavailable)\n'
        "        result['unavailable_elements']=result['layout']['unavailable_elements']\n"
        '    except ConversionError as exc:\n'
        "        result['issues'].append(str(exc))\n"
        "    result['status']='unsupported' if result['issues'] else 'review-required'\n"
        '    return result\n'
        '\n'
        '\n'
        'def convert(source, output, *, source_rest_energy_eV=SOURCE_REST_EV, charge_C=None, dt_s=1e-12, max_steps=100000, dump_frequency=100000000, stat_frequency=100, replace_unavailable=False):\n'
        '    """Validate all inputs before creating a fresh output; never install or track."""\n'
        '    source=Path(source).resolve();output=Path(output).resolve()\n'
        '    if output.exists():\n'
        "        raise ConversionError('Output already exists; use a fresh directory')\n"
        '    report=inspect_source(source,source_rest_energy_eV=source_rest_energy_eV,\n'
        '                          replace_unavailable=replace_unavailable)\n'
        "    if report['issues']:\n"
        "        raise ConversionError('; '.join(report['issues']))\n"
        "    config,layout=report['config'],report['layout']\n"
        "    particles=(source.parent/config['particle_file']).resolve()\n"
        '    data=read_sdds_ascii(particles.read_text())\n'
        "    snapshot=beam_snapshot(data,layout['leading_drift_m'],source_rest_energy_eV)\n"
        "    total=layout['charge_magnitude_C']\n"
        '    if charge_C is not None:\n'
        "        explicit=finite_number(charge_C,'--charge-c',positive=True)\n"
        '        if total is not None and explicit != total:\n'
        "            raise ConversionError('--charge-c must agree with selected CHARGE.TOTAL')\n"
        '        total=explicit\n'
        '    if total is None:\n'
        "        raise ConversionError('Need leading CHARGE,TOTAL=positive C or explicit --charge-c; input SDDS Charge is ignored by Elegant')\n"
        '    deck=render_target(config,layout,snapshot,total,dt_s=dt_s,max_steps=max_steps,dump_frequency=dump_frequency,stat_frequency=stat_frequency)\n'
        '    particle_text=render_particles(snapshot)\n'
        "    report.update(status='review-required',space_charge=False,species='electron',charge_magnitude_C=total,\n"
        "        source_charge_declared_by_element=layout['charge_magnitude_C'] is not None,\n"
        "        snapshot={k:v for k,v in snapshot.items() if k!='particles'},\n"
        "        rules=['explicit-reference-rigidity','electron-quadrupole-sign','fractional-strength-error','line-expansion','arrival-plane-to-common-time-in-leading-drift','consistent-centroid-translation','no-collective-effects'],\n"
        "        extension_rules={'rf_cavities':[{'name':e['name'],**rf_target_parameters(e,snapshot['clock_origin_s'])} for e in layout['elements'] if e['kind']=='rf'],\n"
        "                         'dipoles':[{'name':e['name'],'signed_source_angle_rad':e['angle_rad'],'target_k0_m1':e['target_k0_m1'],'target_roll_rad':e['target_roll_rad']} for e in layout['elements'] if e['kind']=='bend']},\n"
        "        input_sha256={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in (source,Path(report['lattice_file']),particles)},\n"
        "        target_controls={'dt_s':dt_s,'max_steps':max_steps,'particle_dump_frequency':dump_frequency},\n"
        "        track_controls={'dt_s':dt_s,'max_steps':max_steps,'particle_dump_frequency':dump_frequency,'statistics_frequency':stat_frequency,'zstop_path_m':layout['length_m']-snapshot['coordinate_origin_m'][2]},\n"
        "        limitations=['Elegant QUAD/DRIF finite-order matrices and OPALX field integration are different models; EDRIFT is exact.',\n"
        "          'Target ZSTOP is reference path length, not a per-particle observation plane; compare in a verified terminal drift.',\n"
        "          'Original particle IDs are retained in report row order; native FROMFILE assigns its own IDs.',\n"
        "          'No RPN, includes, binary/multipage SDDS, rectangular bends, traveling-wave/matrix RFCA, apertures, radiation, collective effects, scans or optimization.',\n"
        "          'No native boost or previous converter code is changed.'])\n"
        "    if report['unavailable_elements']:\n"
        "        report['rules'].append('unavailable-element-to-drift')\n"
        "        report['limitations'].append('Unavailable element drifts preserve lengths but omit original fields, apertures, errors and bend deflections.')\n"
        "    contents={'converted.in':deck,'particles.opalx':particle_text,'report.json':json.dumps(report,indent=2,allow_nan=False)+'\\n'}\n"
        '    created=False\n'
        '    try:\n'
        '        output.mkdir();created=True\n'
        '        for name,text in contents.items():\n'
        '            (output/name).write_text(text)\n'
        '    except Exception:\n'
        '        if created:\n'
        '            shutil.rmtree(output)\n'
        '        raise\n'
        '    return report\n'
        '\n'
        '\n'
        'def main(argv=None):\n'
        '    """Inspect or convert without executing input expressions or external programs."""\n'
        '    parser=argparse.ArgumentParser(description=__doc__)\n'
        "    parser.add_argument('--version',action='version',version=VERSION)\n"
        "    sub=parser.add_subparsers(dest='command',required=True)\n"
        "    for name in ('inspect','convert'):\n"
        '        p=sub.add_parser(name)\n'
        "        p.add_argument('source',type=Path)\n"
        "        p.add_argument('--source-rest-energy-ev',type=float,default=SOURCE_REST_EV)\n"
        "        if name=='convert':\n"
        "            p.add_argument('output',type=Path)\n"
        "            p.add_argument('--charge-c',type=float)\n"
        "            p.add_argument('--dt',type=float,default=1e-12)\n"
        "            p.add_argument('--max-steps',type=int,default=100000)\n"
        "            p.add_argument('--particle-dump-frequency',type=int,default=100000000)\n"
        "            p.add_argument('--statistics-frequency',type=int,default=100)\n"
        '    args=parser.parse_args(argv)\n'
        '    try:\n'
        "        if args.command=='inspect':\n"
        '            result=inspect_source(args.source,source_rest_energy_eV=args.source_rest_energy_ev)\n'
        '            print(json.dumps(result,indent=2,allow_nan=False))\n'
        "            return 2 if result['issues'] else 0\n"
        '        result=convert(args.source,args.output,source_rest_energy_eV=args.source_rest_energy_ev,\n'
        '                       charge_C=args.charge_c,dt_s=args.dt,max_steps=args.max_steps,dump_frequency=args.particle_dump_frequency,stat_frequency=args.statistics_frequency)\n'
        "        print(json.dumps({'status':result['status'],'particles':result['snapshot']['count'],'output':str(args.output.resolve())},indent=2))\n"
        '        return 0\n'
        '    except (ConversionError,OSError,UnicodeError) as exc:\n'
        "        print(json.dumps({'status':'refused','error':str(exc)}),file=sys.stderr)\n"
        '        return 2\n'
        '\n'
        '\n'
        "if __name__=='__main__':\n"
        '    raise SystemExit(main())\n'
    ),
}
_ENGINE_VERSIONS = {
    'opal': '0.11.1',
    'astra': '0.7.0',
    'elegant': '0.3.0',
}
_ENGINE_HASHES = {
    'opal': '2cf365bb118757f9b8cc54430847d20c077931ed32a7ecd5ee4a4b3842304547',
    'astra': 'd792adf2af6321c62337f6ccfda932f2b3f79716a7832f5ade45ed27209152e8',
    'elegant': 'd262c247cccef44888d1e3cc7681503ea2427954e90bc947cda8a0a7927ac453',
}


if __name__ == "__main__":
    raise SystemExit(main())
