From 350cd3b00fce828ca6a178922770b51eff8c1fd8 Mon Sep 17 00:00:00 2001 From: jungdaesuh <78460559+jungdaesuh@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:39:28 -0500 Subject: [PATCH] Fix agent skill validation and safe uninstall --- .agents/install.py | 20 +++++-- .agents/skills/thincurr-model/SKILL.md | 5 ++ .../thincurr-model/scripts/inspect_model.py | 42 ++++++++++++--- .agents/skills/thincurr-run/SKILL.md | 4 ++ .../thincurr-run/scripts/run_thincurr.py | 5 ++ .agents/skills/tokamaker-equilibrium/SKILL.md | 4 +- .../skills/tokamaker-equilibrium/reference.md | 6 ++- .../scripts/run_equilibrium.py | 26 ++++++++-- .agents/tests/test_inspect_model.py | 50 ++++++++++++++++++ .agents/tests/test_install.py | 52 +++++++++++++++++++ AGENTS.md | 11 ++-- 11 files changed, 203 insertions(+), 22 deletions(-) create mode 100644 .agents/tests/test_inspect_model.py create mode 100644 .agents/tests/test_install.py diff --git a/.agents/install.py b/.agents/install.py index 6f7360e9f..973c67ed4 100755 --- a/.agents/install.py +++ b/.agents/install.py @@ -10,7 +10,7 @@ python .agents/install.py --target anthropic --scope user python .agents/install.py --target openai google --scope project --project-dir ~/my_study python .agents/install.py --list - python .agents/install.py --target openai --scope user --uninstall + python .agents/install.py --target openai --scope user --uninstall --dry-run Destinations: anthropic (Claude Code) skills: .claude/skills/ agents: .claude/agents/.md @@ -284,7 +284,15 @@ def plan(args, model_map, agents): for target in args.target: info = TARGETS[target] skill_dir = os.path.join(base, *info['skills']) - for skill in args.skills: + skills = args.skills + if args.uninstall: + shared_with = [name for name, other in TARGETS.items() + if name not in args.target and other['skills'] == info['skills']] + if shared_with: + warnings.append('Keeping shared skills in {0}. Include {1} in --target to remove them.' + .format(skill_dir, ' '.join(shared_with))) + skills = [] + for skill in skills: dest = os.path.join(skill_dir, skill) if dest in seen: continue @@ -360,12 +368,12 @@ def main(): help='Agents to install (default: every agent whose skills are installed); give none to skip agents') parser.add_argument('--model-map', default=None, help='JSON file with model-map entries overriding model_map.json') parser.add_argument('--link', action='store_true', help='Symlink skills to this repository instead of copying them') - parser.add_argument('--force', action='store_true', help='Replace existing skills/agents with the same names') - parser.add_argument('--uninstall', action='store_true', help='Remove the selected skills/agents from the destination') + parser.add_argument('--force', action='store_true', help='Allow replacement or removal of existing skills/agents') + parser.add_argument('--uninstall', action='store_true', + help='Remove selected skills/agents. Use --dry-run to preview or --force to remove.') parser.add_argument('--dry-run', action='store_true', help='Show what would be done without changing anything') parser.add_argument('--list', action='store_true', help='List the available skills and agents, then exit') args = parser.parse_args() - agents = read_agents() skills = available_skills() if args.list: @@ -378,6 +386,8 @@ def main(): agent['fields'].get('model', 'inherit'))) return 0 + if args.uninstall and not (args.dry_run or args.force): + parser.error('--uninstall can delete existing user files. Use --dry-run to preview or --force to remove.') interactive = sys.stdin.isatty() if args.target is None: if not interactive: diff --git a/.agents/skills/thincurr-model/SKILL.md b/.agents/skills/thincurr-model/SKILL.md index 020e969a0..a22dc5270 100644 --- a/.agents/skills/thincurr-model/SKILL.md +++ b/.agents/skills/thincurr-model/SKILL.md @@ -33,6 +33,11 @@ of a `thincurr-run` case file (`mesh_file`, `xml_file`, `jumper_start`, ## Before anything else +To verify a model with native setup, use an OFT source build whose +`ThinCurr.setup_model()` accepts `insulated_junctions`. The 26.9 release +can import successfully but lacks this option. File-only inspection +(`--no-setup`) does not need an OFT build. + ```bash python -c "from OpenFUSIONToolkit.ThinCurr import ThinCurr; print('ok')" ``` diff --git a/.agents/skills/thincurr-model/scripts/inspect_model.py b/.agents/skills/thincurr-model/scripts/inspect_model.py index 19fead825..a801e4b82 100644 --- a/.agents/skills/thincurr-model/scripts/inspect_model.py +++ b/.agents/skills/thincurr-model/scripts/inspect_model.py @@ -17,6 +17,7 @@ failed hole verification). """ import argparse +import inspect import json import os import sys @@ -114,18 +115,28 @@ def read_file_info(mesh_file): # Legacy (Cubit) nodesets: used as holes when no "thincurr/holes" group exists nodesets = [] if 'mesh/NUM_NODESETS' in fid: - i = 1 - while 'mesh/NODESET{0:04d}'.format(i) in fid: + count = int(numpy.asarray(fid['mesh/NUM_NODESETS'][()]).flat[0]) + for i in range(1, count + 1): nodesets.append(fid['mesh/NODESET{0:04d}'.format(i)][()] - 1) - i += 1 info['nodesets'] = nodesets tc = fid['thincurr'] if 'thincurr' in fid else {} info['holes'] = [] - if 'holes' in tc: + info['modern_holes'] = 'holes' in tc + if info['modern_holes']: nholes = tc['holes/NHOLES'][0] info['holes'] = [tc['holes/HOLE{0:04d}'.format(i+1)][()] - 1 for i in range(nholes)] info['holes_version'] = int(tc['HOLES_VERSION'][0]) if 'HOLES_VERSION' in tc else None - info['closures'] = (tc['CLOSURES'][()] - 1).tolist() if 'CLOSURES' in tc else [] + # The native reader uses the first legacy sideset unless modern closures are present. + info['legacy_closures'] = ( + 'CLOSURES' not in tc and 'mesh/NUM_SIDESETS' in fid + and int(numpy.asarray(fid['mesh/NUM_SIDESETS'][()]).flat[0]) > 0 + ) + if 'CLOSURES' in tc: + info['closures'] = (tc['CLOSURES'][()] - 1).tolist() + elif info['legacy_closures']: + info['closures'] = (fid['mesh/SIDESET0001'][()] - 1).tolist() + else: + info['closures'] = [] info['junctions'] = 'junctions' in tc info['junction_holes'] = int(tc['junctions/NHOLES'][0]) if info['junctions'] else 0 info['njumpers'] = int(tc['jumpers/NJUMPERS'][0]) if 'jumpers' in tc else 0 @@ -228,6 +239,10 @@ def setup_and_query(mesh_file, xml_file, jumper_start, insulated, nthreads): _load_oft() from OpenFUSIONToolkit import OFT_env from OpenFUSIONToolkit.ThinCurr import ThinCurr + setup_model = getattr(ThinCurr, 'setup_model', None) + if setup_model is None or 'insulated_junctions' not in inspect.signature(setup_model).parameters: + raise ValueError('This skill requires ThinCurr.setup_model() with insulated_junctions. ' + 'Use an OpenFUSIONToolkit source build that provides it. See the oft-build skill.') myOFT = OFT_env(nthreads=nthreads) tw_model = ThinCurr(myOFT) tw_model.setup_model(mesh_file=oft_path(mesh_file), xml_filename=oft_path(xml_file), jumper_start=jumper_start, @@ -314,6 +329,8 @@ def main(): # Hole/closure definition source if info['junctions']: hole_source = 'junction-split mesh ({0} junction holes)'.format(info['junction_holes']) + elif info['legacy_closures'] and info['closures']: + hole_source = 'mesh/SIDESET0001 ({0} legacy closures)'.format(len(info['closures'])) elif info['holes'] or info['closures'] or (info['holes_version'] is not None): hole_source = 'thincurr/holes ({0} holes, {1} closures{2})'.format( len(info['holes']), len(info['closures']), @@ -331,7 +348,7 @@ def main(): errors.append('Mesh topology needs {holes} hole(s) and {closures} closure(s) but none are defined; ' 'run OFT_ThinCurr_holes (compute_homology) on it'.format(**expected)) skip_setup = True - elif hole_source.startswith('legacy'): + elif not info['modern_holes']: nsets = len(info['nodesets']) if args.jumper_start == 0 and nsets > expected['holes']: errors.append('{0} legacy nodesets but the topology needs only {1} hole(s); the extra nodesets are ' @@ -339,6 +356,17 @@ def main(): 'recreate the holes with OFT_ThinCurr_holes'.format(nsets, expected['holes'], expected['holes'] - nsets)) skip_setup = True + # The native wrapper treats later nodesets as jumpers, not holes. + nholes = nsets + if 0 < args.jumper_start <= nsets: + nholes = args.jumper_start - 1 + elif -nsets <= args.jumper_start < 0: + nholes = nsets + args.jumper_start + # Raw topology counts can be misleading for periodic meshes. + if info['nfp'] is None and not info['has_pmap'] and nholes < expected['holes']: + errors.append('Legacy nodesets define {0} hole(s), but the topology needs {1}. ' + 'Recreate the holes with OFT_ThinCurr_holes.'.format(nholes, expected['holes'])) + skip_setup = True elif len(info['holes']) != expected['holes'] or len(info['closures']) != expected['closures']: warnings.append('File defines {0} hole(s) and {1} closure(s); the topology suggests {2} and {3}'.format( len(info['holes']), len(info['closures']), expected['holes'], expected['closures'])) @@ -386,7 +414,7 @@ def main(): print(' {0:4d}: {1:8d} cells, area {2:.4E} m^2'.format(reg_id, reg_info['cells'], reg_info['area'])) if skip_setup: - print('\nSkipping ThinCurr setup: it would abort on the problem reported below') + print('\nSkipping ThinCurr setup because the file failed validation') if not (args.no_setup or skip_setup): print('\n--- ThinCurr setup (verifies holes and closures) ---', flush=True) try: diff --git a/.agents/skills/thincurr-run/SKILL.md b/.agents/skills/thincurr-run/SKILL.md index 4e917ebc1..8d02d9eb2 100644 --- a/.agents/skills/thincurr-run/SKILL.md +++ b/.agents/skills/thincurr-run/SKILL.md @@ -18,6 +18,10 @@ Supported analyses: ## Before anything else +Use an OFT source build whose `ThinCurr.setup_model()` accepts +`insulated_junctions`. The 26.9 release can import successfully but lacks +this option. The driver checks for it before setting up the model. + ```bash python -c "from OpenFUSIONToolkit.ThinCurr import ThinCurr; print('ok')" ``` diff --git a/.agents/skills/thincurr-run/scripts/run_thincurr.py b/.agents/skills/thincurr-run/scripts/run_thincurr.py index c79f3d234..71c221320 100644 --- a/.agents/skills/thincurr-run/scripts/run_thincurr.py +++ b/.agents/skills/thincurr-run/scripts/run_thincurr.py @@ -12,6 +12,7 @@ examples. Build and verify the model first (thincurr-model skill). """ import argparse +import inspect import json import os import sys @@ -36,6 +37,10 @@ def _load_thincurr(): sys.path.append(os.path.join(root_path, 'python')) from OpenFUSIONToolkit import OFT_env from OpenFUSIONToolkit.ThinCurr import ThinCurr + setup_model = getattr(ThinCurr, 'setup_model', None) + if setup_model is None or 'insulated_junctions' not in inspect.signature(setup_model).parameters: + raise SystemExit('ERROR: This skill requires ThinCurr.setup_model() with insulated_junctions. ' + 'Use an OpenFUSIONToolkit source build that provides it. See the oft-build skill.') return OFT_env, ThinCurr diff --git a/.agents/skills/tokamaker-equilibrium/SKILL.md b/.agents/skills/tokamaker-equilibrium/SKILL.md index 768407e64..de5aba2ba 100644 --- a/.agents/skills/tokamaker-equilibrium/SKILL.md +++ b/.agents/skills/tokamaker-equilibrium/SKILL.md @@ -13,7 +13,9 @@ Two modes: ## Before anything else -Check that the Python package imports. It needs a built/installed OFT: +Use an OFT source build that provides `TokaMaker.setup_model()`. The 26.9 +release can import successfully but lacks this method. The driver checks +for the method before setting up the model. ```bash python -c "from OpenFUSIONToolkit.TokaMaker import TokaMaker; print('ok')" diff --git a/.agents/skills/tokamaker-equilibrium/reference.md b/.agents/skills/tokamaker-equilibrium/reference.md index 3ffe8f21b..892687b17 100644 --- a/.agents/skills/tokamaker-equilibrium/reference.md +++ b/.agents/skills/tokamaker-equilibrium/reference.md @@ -106,7 +106,11 @@ Only the shape matters. Forcing `y[-1] = 0` at the edge is usual. ``` - `vsc` — gains defining a vertical stability coil set. Nearly every elongated equilibrium needs one or it will not converge. Pair real up/down coils with opposite gains (`{"F9A": 1.0, "F9B": -1.0}`), or name a dedicated VS coil set (`{"VS": 1.0}`). -- `bounds` — hard current limits. `default` applies to every coil set; named entries override. +- `bounds` — current limits in amperes for physical coil sets. `default` applies + to all sets, and named entries override it. The solver bounds individual coil + variables. The driver checks total physical currents, including virtual + vertical control, and exits before writing equilibrium outputs if a limit is + exceeded. Use `regularization.vsc_weight` to tune `#VSC` itself. - `regularization` — one soft term per coil set, `weight * (I_coil - target)^2`. The driver adds every coil set automatically, so you only name the ones that differ. Higher weight ⇒ the coil stays nearer its target and the shape error grows. - `vsc_weight` — weight on the virtual `#VSC` coil. Use a **small** value (~1e-2) to let it adjust vertical position, or a **large** value (~1e2) to disable it when you have defined a real VS coil set that already does that job. diff --git a/.agents/skills/tokamaker-equilibrium/scripts/run_equilibrium.py b/.agents/skills/tokamaker-equilibrium/scripts/run_equilibrium.py index 35d5b2701..35a934304 100644 --- a/.agents/skills/tokamaker-equilibrium/scripts/run_equilibrium.py +++ b/.agents/skills/tokamaker-equilibrium/scripts/run_equilibrium.py @@ -28,6 +28,9 @@ def _load_tokamaker(): sys.path.append(os.path.join(root_path, 'python')) from OpenFUSIONToolkit import OFT_env from OpenFUSIONToolkit.TokaMaker import TokaMaker + if not callable(getattr(TokaMaker, 'setup_model', None)): + raise SystemExit('ERROR: This skill requires TokaMaker.setup_model(). Use an OpenFUSIONToolkit ' + 'source build that provides it. See the oft-build skill.') from OpenFUSIONToolkit.TokaMaker.meshing import gs_Domain, load_gs_mesh from OpenFUSIONToolkit.TokaMaker.util import (create_isoflux, create_isoflux_xpts, @@ -259,15 +262,18 @@ def apply_coil_settings(mygs, coil_spec): Args: mygs: TokaMaker instance. coil_spec: "coils" block of the case file. + + Returns: + Bounds by physical coil set, for checking the reported currents after solving. """ vsc = coil_spec.get('vsc') if vsc: mygs.set_coil_vsc(vsc) # bounds_spec = coil_spec.get('bounds') + coil_bounds = {} if bounds_spec: default_bound = bounds_spec.get('default') - coil_bounds = {} if default_bound is not None: coil_bounds = {name: list(default_bound) for name in mygs.coil_sets} for name, bound in bounds_spec.items(): @@ -297,6 +303,7 @@ def apply_coil_settings(mygs, coil_spec): weight=float(reg_spec.get('vsc_weight', 1.0E-2)))) if reg_terms: mygs.set_coil_reg(reg_terms=reg_terms) + return coil_bounds def init_psi_args(case, moments): @@ -406,8 +413,9 @@ def main(): mygs.setup_model(order=int(case.get('order', 2)), F0=F0, **mesh_args) # Coils (free boundary only) + coil_bounds = {} if mode == 'free': - apply_coil_settings(mygs, case.get('coils', {})) + coil_bounds = apply_coil_settings(mygs, case.get('coils', {})) # Global targets targets = dict(case.get('targets', {})) @@ -445,15 +453,23 @@ def main(): if nl_its < 0: print('\nERROR: G-S solve did not converge after {0} iterations'.format(-nl_its), file=sys.stderr) return 1 + coil_currents = {} + if mode == 'free': + currents, _ = mygs.get_coil_currents() + coil_currents = {key: float(value) for key, value in currents.items()} + # Reported physical currents include the contribution from virtual vertical control. + for name, (lower, upper) in coil_bounds.items(): + current = coil_currents[name] + if not numpy.isfinite(current) or not float(lower) <= current <= float(upper): + print('\nERROR: Coil {0} has physical current {1:.9g} A outside its bounds [{2}, {3}] A.' + .format(name, current, lower, upper), file=sys.stderr) + return 1 print('\nConverged in {0} nonlinear iterations'.format(nl_its)) # Outputs mygs.print_info() stats = mygs.get_stats() - coil_currents = {} if mode == 'free': - currents, _ = mygs.get_coil_currents() - coil_currents = {key: float(value) for key, value in currents.items()} print('\nCoil currents [MA]:') for key, current in coil_currents.items(): print(' {0:12} {1:10.3F}'.format(key+':', current/1.0E6)) diff --git a/.agents/tests/test_inspect_model.py b/.agents/tests/test_inspect_model.py new file mode 100644 index 000000000..7d4ed19ea --- /dev/null +++ b/.agents/tests/test_inspect_model.py @@ -0,0 +1,50 @@ +# SPDX-License-Identifier: LGPL-3.0-only +"""Inspect small native meshes without a compiled ThinCurr runtime.""" +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +import h5py +import numpy + + +SCRIPT = Path(__file__).resolve().parents[1] / 'skills/thincurr-model/scripts/inspect_model.py' + + +class InspectModelTests(unittest.TestCase): + def inspect(self, points, cells, mesh_sets, *args): + with tempfile.TemporaryDirectory() as directory: + mesh = Path(directory) / 'mesh.h5' + with h5py.File(mesh, 'w') as mesh_file: + mesh_file['mesh/R'] = points + mesh_file['mesh/LC'] = cells + mesh_file['mesh/REG'] = numpy.ones(len(cells), dtype='i4') + for name, values in mesh_sets.items(): + mesh_file['mesh/' + name] = values + return subprocess.run( + [sys.executable, str(SCRIPT), str(mesh), '--no-setup', *args], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False, + ) + + def test_legacy_sideset_supplies_closure(self): + points = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)] + cells = [(1, 3, 2), (1, 2, 4), (2, 3, 4), (3, 1, 4)] + result = self.inspect(points, cells, {'NUM_SIDESETS': [1], 'SIDESET0001': [1]}) + self.assertEqual(result.returncode, 0, result.stdout) + self.assertIn('SIDESET0001', result.stdout) + + def test_legacy_jumpers_do_not_count_as_holes(self): + # A square annulus has one hole. Its only nodeset is reserved for a jumper. + points = [(-2, -2, 0), (2, -2, 0), (2, 2, 0), (-2, 2, 0), + (-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0)] + cells = [(1, 2, 6), (1, 6, 5), (2, 3, 7), (2, 7, 6), + (3, 4, 8), (3, 8, 7), (4, 1, 5), (4, 5, 8)] + sets = {'NUM_NODESETS': [1], 'NODESET0001': [5, 6, 7, 8]} + valid = self.inspect(points, cells, sets) + self.assertEqual(valid.returncode, 0, valid.stdout) + for start in ('1', '-1'): + result = self.inspect(points, cells, sets, '--jumper-start', start) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertIn('Legacy nodesets define 0 hole(s), but the topology needs 1', result.stdout) diff --git a/.agents/tests/test_install.py b/.agents/tests/test_install.py new file mode 100644 index 000000000..9a42955a1 --- /dev/null +++ b/.agents/tests/test_install.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: LGPL-3.0-only +"""Exercise uninstall from the command line in an isolated project.""" +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +INSTALL = Path(__file__).resolve().parents[1] / 'install.py' + + +class UninstallTests(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.project = Path(directory.name) + + def install(self, *args, expected_exit=0): + result = subprocess.run( + [sys.executable, str(INSTALL), '--scope', 'project', '--project-dir', + str(self.project), *args], + stdin=subprocess.DEVNULL, capture_output=True, text=True, check=False, + ) + self.assertEqual(result.returncode, expected_exit, result.stdout + result.stderr) + return result.stdout + result.stderr + + def test_uninstall_requires_force(self): + marker = self.project / '.claude/skills/thincurr-run/user-file' + marker.parent.mkdir(parents=True) + marker.write_text('user content') + target = ('--target', 'anthropic', '--skills', 'thincurr-run') + self.assertIn('exists', self.install(*target)) + self.assertIn('--force', self.install(*target, '--uninstall', expected_exit=2)) + self.assertIn(str(marker.parent), self.install(*target, '--uninstall', '--dry-run')) + self.assertEqual(marker.read_text(), 'user content') + self.install(*target, '--uninstall', '--force') + self.assertFalse(marker.exists()) + + def test_uninstall_one_tool_keeps_shared_skills(self): + self.install('--target', 'openai', 'google') + skills = self.project / '.agents/skills/thincurr-run' + codex = self.project / '.codex/agents' + gemini = self.project / '.gemini/agents' + self.assertTrue(list(codex.iterdir()) and list(gemini.iterdir())) + self.assertIn('Keeping shared skills', self.install('--target', 'openai', '--uninstall', '--force')) + self.assertTrue(skills.is_dir()) + self.assertFalse(list(codex.iterdir())) + self.assertTrue(list(gemini.iterdir())) + self.install('--target', 'openai', 'google', '--uninstall', '--force') + self.assertFalse(skills.exists()) + self.assertFalse(list(gemini.iterdir())) diff --git a/AGENTS.md b/AGENTS.md index 882dd49ac..1bba84f93 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,9 +94,14 @@ python .agents/install.py --target anthropic openai --scope user Skills are copied unchanged (`--link` symlinks them instead); agents are translated from `.claude/agents/` to each tool's format. Hardcoded agent models are mapped -through `.agents/model_map.json` (edit it, or pass `--model-map FILE`). `--list`, -`--dry-run`, `--force`, and `--uninstall` do what they say. Keep skills and agents -free of paths into this repository (use `/scripts/...`), and when adding +through `.agents/model_map.json` (edit it, or pass `--model-map FILE`). +Preview removal with `--uninstall --dry-run`. Actual removal requires +`--uninstall --force` because the installer can delete existing user files. +Select both `openai` and `google` to remove their shared skills. Selecting +only one removes that tool's agents and keeps the shared skills. + +Keep skills and agents free of paths into this repository (use +`/scripts/...`), and when adding agent frontmatter fields, check that `install.py` translates or drops them: Codex and Gemini CLI reject agent files with unknown keys.