From b10dab2f5ad83f642a03b5f800dea71651830beb Mon Sep 17 00:00:00 2001 From: Morgan Lunt Date: Thu, 24 Sep 2026 18:26:30 -0700 Subject: code-modernization: extract-rules uses a shard builder and a rules renderer that ship with the plugin The command used to carry a 35-line shard-building script inline and asked the model to write a rules renderer on every run, so the shard list and the BUSINESS_RULES.md layout varied from run to run and could not be tested. scripts/make_shards.py builds the shard list from topology.json when the map has run, and from the directory tree when it has not (skipping vendored, generated and test-fixture directories, one shard per directory, split at 25 files or about 5,000 lines). scripts/render_rules.py turns the workflow's result into BUSINESS_RULES.md and DATA_OBJECTS.md with RULE-NNN headings, the SME section and the coverage gaps, and writes every value from the analysis as plain text. The workflow takes an optional sourceDir, so the code can live outside the workspace, and shard files are kept relative to it. The command drops from 305 to about 150 lines. --- .../scripts/tests/test_rules_tools.py | 110 +++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 plugins/code-modernization/scripts/tests/test_rules_tools.py (limited to 'plugins/code-modernization/scripts/tests/test_rules_tools.py') diff --git a/plugins/code-modernization/scripts/tests/test_rules_tools.py b/plugins/code-modernization/scripts/tests/test_rules_tools.py new file mode 100644 index 00000000..4551209f --- /dev/null +++ b/plugins/code-modernization/scripts/tests/test_rules_tools.py @@ -0,0 +1,110 @@ +import json +import os +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +SCRIPTS = os.path.dirname(HERE) + + +def run(script, *args): + return subprocess.run([sys.executable, os.path.join(SCRIPTS, script), *args], capture_output=True, text=True) + + +def load(path): + with open(path, encoding='utf-8') as handle: + return json.load(handle) + + +def write(root, rel, text='x\n'): + path = os.path.join(root, rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, 'w', encoding='utf-8') as handle: + handle.write(text) + + +class ShardTests(unittest.TestCase): + def test_tree_shards_by_directory_and_skips_vendored_code(self): + with tempfile.TemporaryDirectory() as ws: + for i in range(30): + write(ws, f'legacy/erp/lib/pay/p{i}.pl', 'a\n' * 10) + write(ws, 'legacy/erp/lib/tax/t.pl', 'a\n' * 400) + write(ws, 'legacy/erp/node_modules/x/y.js', 'a\n') + write(ws, 'legacy/erp/tests/t.pl', 'a\n') + write(ws, 'legacy/erp/README.md', 'text\n') + done = run('make_shards.py', 'erp', '--workspace', ws) + self.assertEqual(done.returncode, 0, done.stderr) + shards = load(os.path.join(ws, 'analysis/erp/extract-rules.modules.json')) + names = [s['name'] for s in shards] + self.assertEqual(names, ['lib/pay', 'lib/pay#2', 'lib/tax']) + self.assertEqual(len(shards[0]['files']), 25) + self.assertNotIn('node_modules', json.dumps(shards)) + self.assertNotIn('tests/t.pl', json.dumps(shards)) + self.assertTrue(all(not f.startswith('legacy/') for s in shards for f in s['files'])) + + def test_source_marker_moves_the_tree_and_files_stay_relative_to_it(self): + with tempfile.TemporaryDirectory() as ws, tempfile.TemporaryDirectory() as elsewhere: + write(elsewhere, 'src/a.cbl', 'a\n' * 50) + write(ws, 'analysis/big/SOURCE', elsewhere + '\n') + self.assertEqual(run('make_shards.py', 'big', '--workspace', ws).returncode, 0) + shards = load(os.path.join(ws, 'analysis/big/extract-rules.modules.json')) + self.assertEqual(shards[0]['files'], ['src/a.cbl']) + + def test_topology_merges_small_modules_and_normalizes_paths(self): + with tempfile.TemporaryDirectory() as ws: + for name in ('A', 'B', 'C'): + write(ws, f'legacy/s/{name}.cbl', 'a\n' * 50) + topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [{'kind': 'domain', 'name': 'D1', 'id': 'dom:d1', 'children': [ + {'kind': 'module', 'id': 'A', 'name': 'A', 'file': 'A.cbl', 'loc': 50}, + {'kind': 'module', 'id': 'B', 'name': 'B', 'file': 'legacy/s/B.cbl', 'loc': 50}, + {'kind': 'module', 'id': 'C', 'name': 'C', 'file': os.path.join(ws, 'legacy/s/C.cbl'), 'loc': 900}]}]}} + write(ws, 'analysis/s/topology.json', json.dumps(topology)) + self.assertEqual(run('make_shards.py', 's', '--workspace', ws).returncode, 0) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual([s['files'] for s in shards], [['A.cbl', 'B.cbl'], ['C.cbl']]) + self.assertEqual(run('make_shards.py', 's', 'C*', '--workspace', ws).returncode, 0) + self.assertEqual(run('make_shards.py', 's', 'nothing*', '--workspace', ws).returncode, 1) + + def test_missing_source_says_what_to_do(self): + with tempfile.TemporaryDirectory() as ws: + done = run('make_shards.py', 'nope', '--workspace', ws) + self.assertEqual(done.returncode, 1) + self.assertIn('preflight', done.stderr) + + +class RenderTests(unittest.TestCase): + def test_rules_render_with_rule_headings_and_hostile_text_stays_inert(self): + result = {'confirmedRules': [ + {'name': 'Late fee', 'category': 'Calculation', 'priority': 'P0', 'source': 'a.cbl:10-20', 'plainEnglish': 'A fee.', + 'given': 'a late payment', 'when': 'month end', 'then': 'fee 5%', 'confidence': 'High'}, + {'name': 'Bad `name` | pipe\n# Heading', 'category': 'Validation', 'priority': 'P1', 'source': 'b.cbl:1-2', 'plainEnglish': 'x', + 'given': 'g\n# injected heading\n```', 'when': 'w', 'then': 't', 'confidence': 'Low', 'smeQuestion': 'Is it 5 or 6?'}], + 'dataObjects': [{'name': 'Account', 'source': 'a.cbl:1', 'fields': [{'name': 'id', 'type': 'int'}], 'consumedBy': ['Late fee']}], + 'injectionFlags': ['a.cbl:5'], 'rejectedRules': [{}], 'unverifiedRules': [], 'rerunModules': [], + 'stats': {'skippedModules': ['M9']}} + with tempfile.TemporaryDirectory() as ws: + write(ws, 'analysis/s/rules_result.json', json.dumps(result)) + done = run('render_rules.py', 's', '--workspace', ws) + self.assertEqual(done.returncode, 0, done.stderr) + text = open(os.path.join(ws, 'analysis/s/BUSINESS_RULES.md'), encoding='utf-8').read() + self.assertIn('### RULE-001: Late fee', text) + self.assertIn('### RULE-002: Bad', text) + headings = [line for line in text.splitlines() if line.startswith('### ')] + self.assertEqual(len(headings), 2, headings) + self.assertNotIn('\n# injected heading', text) + self.assertIn('Rules requiring SME confirmation', text) + self.assertIn('Is it 5 or 6?', text) + self.assertIn('Coverage gaps', text) + self.assertIn('Instruction-shaped content', text) + dto = open(os.path.join(ws, 'analysis/s/DATA_OBJECTS.md'), encoding='utf-8').read() + self.assertIn('## Account', dto) + + def test_unreadable_result_is_an_error(self): + with tempfile.TemporaryDirectory() as ws: + self.assertEqual(run('render_rules.py', 's', '--workspace', ws).returncode, 1) + + +if __name__ == '__main__': + unittest.main() -- cgit From cafefb304bde4070c6c0877528ee49c1252eff85 Mon Sep 17 00:00:00 2001 From: Morgan Lunt Date: Thu, 24 Sep 2026 20:14:51 -0700 Subject: code-modernization: simpler commands, a source option, a report page and an equivalence check Commands hardcoded legacy/, so code too big to copy, or living at an absolute path, needed a hand-made symlink. Preflight now takes --source and makes the legacy/ link for you (a junction on Windows); nothing is copied, and every command says where the link points before it starts. The harden patch is applied with patch -p1 -d. Each command ends by naming the next command to run, and the commands are about a third shorter with no step removed: - map accepts an existing dependency graph (--graph) or the stack's own tooling, maps very large estates in resumable chunks, records reflection targets as unresolved instead of dead, asks before describing more than 40 nodes, and never gives two nodes the same location. - transform can take its module and target from the brief, counts the equivalence cases that executed (zero is a failure and a comparison never skips), shows the tests can fail with a deliberate one-line break, and hands "same or different" to a script when both systems can run. - brief writes each phase in one fixed shape: one command, module ids as in the map, and criteria written as conditions a build command may tick but not reword. - reimagine reuses the discovery artifacts instead of extracting them again. - status names the exact command to paste next. scripts/build_report.py turns whatever the commands wrote into one self-contained, offline REPORT.html (Mermaid is vendored, all text from the analysis is escaped, the quarantined secrets file is never read), and scripts/compare.py decides byte-for-byte whether two outputs match, records why, and checks it can fail. The shard builder ignores symbolic links and paths that leave the source, matches a plain name against what lies beneath it, and falls back to the directory tree when the map's modules share a location. The README drops from 275 to about 100 lines; the pane's reference moves to hooks/README.md. --- .../scripts/tests/test_rules_tools.py | 61 ++++++++++++++++++++-- 1 file changed, 58 insertions(+), 3 deletions(-) (limited to 'plugins/code-modernization/scripts/tests/test_rules_tools.py') diff --git a/plugins/code-modernization/scripts/tests/test_rules_tools.py b/plugins/code-modernization/scripts/tests/test_rules_tools.py index 4551209f..f0bbc391 100644 --- a/plugins/code-modernization/scripts/tests/test_rules_tools.py +++ b/plugins/code-modernization/scripts/tests/test_rules_tools.py @@ -44,11 +44,13 @@ class ShardTests(unittest.TestCase): self.assertNotIn('tests/t.pl', json.dumps(shards)) self.assertTrue(all(not f.startswith('legacy/') for s in shards for f in s['files'])) - def test_source_marker_moves_the_tree_and_files_stay_relative_to_it(self): + def test_a_symlinked_source_is_followed_and_files_stay_relative_to_it(self): with tempfile.TemporaryDirectory() as ws, tempfile.TemporaryDirectory() as elsewhere: write(elsewhere, 'src/a.cbl', 'a\n' * 50) - write(ws, 'analysis/big/SOURCE', elsewhere + '\n') - self.assertEqual(run('make_shards.py', 'big', '--workspace', ws).returncode, 0) + os.makedirs(os.path.join(ws, 'legacy')) + os.symlink(elsewhere, os.path.join(ws, 'legacy', 'big')) + done = run('make_shards.py', 'big', '--workspace', ws) + self.assertEqual(done.returncode, 0, done.stderr) shards = load(os.path.join(ws, 'analysis/big/extract-rules.modules.json')) self.assertEqual(shards[0]['files'], ['src/a.cbl']) @@ -67,6 +69,59 @@ class ShardTests(unittest.TestCase): self.assertEqual(run('make_shards.py', 's', 'C*', '--workspace', ws).returncode, 0) self.assertEqual(run('make_shards.py', 's', 'nothing*', '--workspace', ws).returncode, 1) + def test_links_and_paths_that_leave_the_source_are_not_shards(self): + with tempfile.TemporaryDirectory() as ws, tempfile.TemporaryDirectory() as outside: + write(ws, 'legacy/s/ok.pl', 'a\n' * 5) + write(outside, 'secret.pl', 'not part of the system\n') + os.symlink(os.path.join(outside, 'secret.pl'), os.path.join(ws, 'legacy/s/link.pl')) + self.assertEqual(run('make_shards.py', 's', '--workspace', ws).returncode, 0) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual([f for s in shards for f in s['files']], ['ok.pl']) + topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [{'kind': 'domain', 'name': 'D', 'id': 'd', 'children': [ + {'kind': 'module', 'id': 'A', 'name': 'A', 'file': 'ok.pl', 'loc': 500}, + {'kind': 'module', 'id': 'B', 'name': 'B', 'file': '../../../etc/hosts', 'loc': 500}, + {'kind': 'module', 'id': 'C', 'name': 'C', 'file': 'link.pl', 'loc': 500}]}]}} + write(ws, 'analysis/s/topology.json', json.dumps(topology)) + done = run('make_shards.py', 's', '--workspace', ws) + self.assertEqual(done.returncode, 0, done.stderr) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual([f for s in shards for f in s['files']], ['ok.pl']) + self.assertIn('outside the source directory', done.stdout) + + def test_a_link_to_the_home_directory_or_root_is_refused(self): + with tempfile.TemporaryDirectory() as ws: + os.makedirs(os.path.join(ws, 'legacy')) + for broad in (os.path.expanduser('~'), '/', '/usr'): + link = os.path.join(ws, 'legacy', 's') + if os.path.islink(link): + os.unlink(link) + os.symlink(broad, link) + done = run('make_shards.py', 's', '--workspace', ws) + self.assertEqual(done.returncode, 1, broad) + self.assertIn('too broad', done.stderr) + + def test_a_plain_name_matches_what_lies_beneath_it(self): + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/s/jetty-util/src/A.java', 'a\n' * 5) + write(ws, 'legacy/s/jetty-util-ajax/src/B.java', 'a\n' * 5) + write(ws, 'legacy/s/other/C.java', 'a\n' * 5) + self.assertEqual(run('make_shards.py', 's', 'jetty-util', '--workspace', ws).returncode, 0) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual([f for sh in shards for f in sh['files']], ['jetty-util/src/A.java']) + + def test_a_map_whose_modules_share_one_directory_falls_back_to_the_tree(self): + with tempfile.TemporaryDirectory() as ws: + for name in ('a', 'b'): + write(ws, f'legacy/s/pkg/{name}/X.java', 'a\n' * 50) + children = [{'kind': 'module', 'id': f'pkg/{n}', 'name': f'pkg/{n}', 'file': 'pkg', 'loc': 900} for n in ('a', 'b')] + topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [{'kind': 'domain', 'name': 'D', 'id': 'd', 'children': children}]}} + write(ws, 'analysis/s/topology.json', json.dumps(topology)) + done = run('make_shards.py', 's', '--workspace', ws) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn('cannot be sharded by module', done.stdout) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual(sorted(f for sh in shards for f in sh['files']), ['pkg/a/X.java', 'pkg/b/X.java']) + def test_missing_source_says_what_to_do(self): with tempfile.TemporaryDirectory() as ws: done = run('make_shards.py', 'nope', '--workspace', ws) -- cgit From 696904602b2bdf3e0ddd07ae1221f9eb3e3b8e62 Mon Sep 17 00:00:00 2001 From: Morgan Lunt Date: Thu, 24 Sep 2026 20:15:45 -0700 Subject: code-modernization: rate rules by what the system is for, and make live runs finish Two problems from running the commands on real repositories: - The P0 definition was money- and regulation-shaped, so a music-library tool got no P0 rules and its behavior contract came out empty. P0 now means the system's core purpose depends on the rule, or a wrong result is costly or irreversible (money, legal, data integrity, security or safety, or the central calculation or decision the system exists to perform). - Citations came back as lists of ranges, and the rule renderer numbered RULE-NNN in a different order from the document. Each rule now cites one range and the numbers read in sequence. Commands that start subagents now say to run them in the foreground and wait, because a headless session ends when the model stops talking even if it said it was waiting for a background agent. --- plugins/code-modernization/scripts/tests/test_rules_tools.py | 3 +++ 1 file changed, 3 insertions(+) (limited to 'plugins/code-modernization/scripts/tests/test_rules_tools.py') diff --git a/plugins/code-modernization/scripts/tests/test_rules_tools.py b/plugins/code-modernization/scripts/tests/test_rules_tools.py index f0bbc391..632b2250 100644 --- a/plugins/code-modernization/scripts/tests/test_rules_tools.py +++ b/plugins/code-modernization/scripts/tests/test_rules_tools.py @@ -1,5 +1,6 @@ import json import os +import re import subprocess import sys import tempfile @@ -149,6 +150,8 @@ class RenderTests(unittest.TestCase): headings = [line for line in text.splitlines() if line.startswith('### ')] self.assertEqual(len(headings), 2, headings) self.assertNotIn('\n# injected heading', text) + ids = [int(n) for n in re.findall(r'^### RULE-(\d+): ', text, re.M)] + self.assertEqual(ids, list(range(1, len(ids) + 1)), 'rule numbers read in sequence down the document') self.assertIn('Rules requiring SME confirmation', text) self.assertIn('Is it 5 or 6?', text) self.assertIn('Coverage gaps', text) -- cgit From e662d6d338a7abb1a03ba97e1a47fb98d669c81f Mon Sep 17 00:00:00 2001 From: Morgan Lunt Date: Thu, 24 Sep 2026 20:29:13 -0700 Subject: code-modernization: keep one citation per rule when rendering business rules The extractor is told to cite a single file range per rule, but on a large Perl codebase it kept returning two or three files and a sentence of explanation in the source field, which the report and the pane cannot resolve to a line. The renderer now takes the first path:line-range as the rule's citation and puts anything after it on an "Also cited" line. --- .../code-modernization/scripts/tests/test_rules_tools.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'plugins/code-modernization/scripts/tests/test_rules_tools.py') diff --git a/plugins/code-modernization/scripts/tests/test_rules_tools.py b/plugins/code-modernization/scripts/tests/test_rules_tools.py index 632b2250..59d9a30b 100644 --- a/plugins/code-modernization/scripts/tests/test_rules_tools.py +++ b/plugins/code-modernization/scripts/tests/test_rules_tools.py @@ -159,6 +159,21 @@ class RenderTests(unittest.TestCase): dto = open(os.path.join(ws, 'analysis/s/DATA_OBJECTS.md'), encoding='utf-8').read() self.assertIn('## Account', dto) + def test_a_rule_keeps_one_citation_and_the_rest_moves_to_also_cited(self): + sources = ['wwwroot/a.pl:100-120 (aggregation); family table at lib/b.pm:31-40', + 'lib/x.pm:966,1018,1238 (order lists)', 'no citation here', 'c.cbl:7'] + result = {'confirmedRules': [ + {'name': f'R{i}', 'category': 'Policy', 'priority': 'P1', 'source': src, 'plainEnglish': 'x', + 'given': 'g', 'when': 'w', 'then': 't', 'confidence': 'High'} for i, src in enumerate(sources)]} + with tempfile.TemporaryDirectory() as ws: + write(ws, 'analysis/s/rules_result.json', json.dumps(result)) + self.assertEqual(run('render_rules.py', 's', '--workspace', ws).returncode, 0) + text = open(os.path.join(ws, 'analysis/s/BUSINESS_RULES.md'), encoding='utf-8').read() + cites = re.findall(r'^\*\*Source:\*\* `([^`]*)`', text, re.M) + self.assertEqual(sorted(cites), sorted(['wwwroot/a.pl:100-120', 'lib/x.pm:966', 'no citation here', 'c.cbl:7'])) + self.assertIn('**Also cited:** (aggregation); family table at lib/b.pm:31-40', text) + self.assertEqual(text.count('**Also cited:**'), 2) + def test_unreadable_result_is_an_error(self): with tempfile.TemporaryDirectory() as ws: self.assertEqual(run('render_rules.py', 's', '--workspace', ws).returncode, 1) -- cgit From ff833bd7231262a8521ab3728c5625dc6c4f4a1d Mon Sep 17 00:00:00 2001 From: Morgan Lunt Date: Thu, 24 Sep 2026 21:22:06 -0700 Subject: code-modernization: make rule consolidation auditable and injection-safe Follow-ups from review of the consolidation pass: - The agent is a restricted type with the same read-only wording as its siblings, and every field on its numbered list is a single bounded line, so a rule name containing a newline cannot fake another entry. - A group with any number out of range or not an integer is rejected whole instead of being coerced into a different merge. - A merge keeps the most conservative review state: the highest priority, the lowest confidence, and every suspected defect and SME question of the folded rules. - Every folded rule is returned with the rule it went into, and the rules document lists them under "Rules folded into another", so nothing disappears untraceably. Extra citations show as "Also cited" without the joining word. --- .../code-modernization/scripts/tests/test_rules_tools.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'plugins/code-modernization/scripts/tests/test_rules_tools.py') diff --git a/plugins/code-modernization/scripts/tests/test_rules_tools.py b/plugins/code-modernization/scripts/tests/test_rules_tools.py index 59d9a30b..33cfd279 100644 --- a/plugins/code-modernization/scripts/tests/test_rules_tools.py +++ b/plugins/code-modernization/scripts/tests/test_rules_tools.py @@ -174,6 +174,19 @@ class RenderTests(unittest.TestCase): self.assertIn('**Also cited:** (aggregation); family table at lib/b.pm:31-40', text) self.assertEqual(text.count('**Also cited:**'), 2) + def test_folded_rules_are_listed_so_nothing_disappears_untraceably(self): + result = {'confirmedRules': [{'name': 'Twiddle table', 'category': 'Calculation', 'priority': 'P0', 'source': 'a.c:1-2 ; also b.c:3-4', + 'plainEnglish': 'x', 'given': 'g', 'when': 'w', 'then': 't', 'confidence': 'Low'}], + 'foldedRules': [{'name': 'Twiddle factors', 'source': 'b.c:3-4', 'into': 'Twiddle table'}, 'junk', {'name': 'X\n# fake heading', 'source': 's', 'into': 'i'}]} + with tempfile.TemporaryDirectory() as ws: + write(ws, 'analysis/s/rules_result.json', json.dumps(result)) + self.assertEqual(run('render_rules.py', 's', '--workspace', ws).returncode, 0) + text = open(os.path.join(ws, 'analysis/s/BUSINESS_RULES.md'), encoding='utf-8').read() + self.assertIn('## Rules folded into another', text) + self.assertIn('- Twiddle factors (b.c:3-4) into Twiddle table', text) + self.assertIn('**Also cited:** b.c:3-4', text) + self.assertNotIn('\n# fake heading', text) + def test_unreadable_result_is_an_error(self): with tempfile.TemporaryDirectory() as ws: self.assertEqual(run('render_rules.py', 's', '--workspace', ws).returncode, 1) -- cgit