From 761a93d46638340c9df6a73b46aa3c9826a2213d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:49:13 +0000 Subject: code-modernization: one rule per decision and smaller shards in rule extraction Remove the rules-per-line target, cut tree shards to about 1,000 lines, and report files and rules that were dropped without notice. Version 1.2.0. --- .../scripts/tests/test_extract_workflow.py | 131 +++++++++++++++++++++ .../scripts/tests/test_rules_tools.py | 109 +++++++++++++++++ 2 files changed, 240 insertions(+) create mode 100644 plugins/code-modernization/scripts/tests/test_extract_workflow.py (limited to 'plugins/code-modernization/scripts/tests') diff --git a/plugins/code-modernization/scripts/tests/test_extract_workflow.py b/plugins/code-modernization/scripts/tests/test_extract_workflow.py new file mode 100644 index 00000000..063a5749 --- /dev/null +++ b/plugins/code-modernization/scripts/tests/test_extract_workflow.py @@ -0,0 +1,131 @@ +"""Runs workflows/extract-rules.js under node with scripted agents in place of the model.""" +import json +import os +import shutil +import subprocess +import unittest + +PLUGIN = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +WORKFLOW = os.path.join(PLUGIN, 'workflows', 'extract-rules.js') + +# Extractors return the next entry of `extracts`. Referees confirm unless `verdicts` has the cited source. +# P0 judges agree unless `notP0` has the cited source. +HARNESS = r""" +const fs = require('fs') +const spec = JSON.parse(fs.readFileSync(0, 'utf8')) +const source = fs.readFileSync(process.argv[1], 'utf8').replace('export const meta', 'const meta') +const cited = prompt => /Citation[^\n]*<< { + if (o.phase === 'Extract') prompts.push(prompt) + if (o.phase === 'Extract') return { rules: spec.extracts[next++] || [], coveredAreas: [] } + if (o.phase === 'Verify') return cited(prompt) in (spec.verdicts || {}) ? spec.verdicts[cited(prompt)] : { verdict: 'confirmed', reason: 'ok' } + if (o.phase === 'P0 panel') return { p0Justified: !(spec.notP0 || []).includes(cited(prompt)), faithful: true, reason: 'r' } + if (o.phase === 'Consolidate') return { groups: [] } + return { dataObjects: [] } +} +const parallel = thunks => Promise.all(thunks.map(t => t())) +const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor +new AsyncFunction('args', 'agent', 'parallel', 'log', 'budget', source)(spec.args, agent, parallel, () => {}, { total: 0, remaining: () => Infinity }) + .then(result => console.log(JSON.stringify({ ...result, prompts }))) +""" + + +def rule(name, source, priority='P1'): + return {'name': name, 'category': 'Validation', 'priority': priority, 'source': source, 'plainEnglish': 'x', + 'given': 'g', 'when': 'w', 'then': 't', 'confidence': 'High'} + + +def extract(extracts, modules=1, **spec): + if isinstance(modules, int): + modules = [{'name': f'm{i}', 'files': ['a.sql']} for i in range(modules)] + args = {'system': 's', 'modules': modules} + done = subprocess.run(['node', '-e', HARNESS, WORKFLOW], input=json.dumps({'args': args, 'extracts': extracts, **spec}), + capture_output=True, text=True, encoding='utf-8') + if done.returncode: + raise AssertionError(done.stderr) + return json.loads(done.stdout) + + +def sources(result): + return [r['source'] for r in result['confirmedRules']] + + +@unittest.skipUnless(shutil.which('node'), 'needs node') +class AgentCapTests(unittest.TestCase): + def test_dense_shards_that_do_not_fit_are_left_for_a_follow_up_run(self): + result = extract([[rule(f'R{m}-{i}', f'a.sql:{i + 1}') for i in range(120)] for m in range(30)], modules=30) + self.assertLessEqual(result['stats']['agents'], 1000) + self.assertEqual(result['unverifiedRules'], []) + self.assertEqual(len(result['confirmedRules']), 120 * (30 - len(result['rerunModules']))) + + def test_typical_shards_all_fit(self): + result = extract([[rule(f'R{m}-{i}', f'a.sql:{i + 1}') for i in range(8)] for m in range(70)], modules=70) + self.assertEqual((len(result['confirmedRules']), result['rerunModules']), (560, [])) + + +@unittest.skipUnless(shutil.which('node'), 'needs node') +class DuplicateTests(unittest.TestCase): + def test_the_same_name_at_different_lines_is_two_rules(self): + result = extract([[rule('Validate amount', 'a.sql:10-20'), rule('Validate amount', 'a.sql:500-510')]]) + self.assertEqual(sources(result), ['a.sql:10-20', 'a.sql:500-510']) + + def test_the_same_name_at_overlapping_lines_is_one_rule(self): + result = extract([[rule('Validate amount', 'a.sql:10-20')], [rule('validate-amount', 'a.sql:15'), rule('Validate amount', 'a.sql')]], modules=2) + self.assertEqual(sources(result), ['a.sql:10-20']) + + def test_comparison_signs_and_non_latin_names_tell_rules_apart(self): + names = ['Fee when amount > 100', 'Fee when amount < 100', 'Fee when amount ≥ 100', 'Fee when amount ≤ 100', 'Status = A', 'Status != A', '金額の検証', '手数料の計算', 'Проверка суммы'] + result = extract([[rule(n, 'a.sql:1-50') for n in names]]) + self.assertEqual([r['name'] for r in result['confirmedRules']], names) + + def test_a_citation_corrected_onto_an_existing_rule_is_a_duplicate(self): + moved = {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:500-510'} + result = extract([[rule('Cap', 'a.sql:500-510'), rule('Cap', 'a.sql:10-20')]], verdicts={'a.sql:10-20': moved}) + self.assertEqual(sources(result), ['a.sql:500-510']) + self.assertEqual(len(result['rejectedRules']), 1) + + def test_a_citation_corrected_within_its_file_is_kept(self): + moved = {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:12-30'} + result = extract([[rule('Cap', 'a.sql:10-20')]], verdicts={'a.sql:10-20': moved}) + self.assertEqual(sources(result), ['a.sql:12-30']) + + def test_a_citation_corrected_to_a_bare_file_name_is_kept(self): + moved = {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql'} + result = extract([[rule('Cap', 'a.sql:500-510'), rule('Cap', 'a.sql:10-20')]], verdicts={'a.sql:10-20': moved}) + self.assertEqual(sources(result), ['a.sql:500-510', 'a.sql']) + later = extract([[rule('Cap', 'a.sql:10-20')], [], [], [], [rule('Cap', 'a.sql:500-510')]], modules=5, verdicts={'a.sql:10-20': moved}) + self.assertEqual(sources(later), ['a.sql', 'a.sql:500-510']) + + def test_p0_verdicts_go_to_the_rule_they_judged(self): + rules = [rule('Cap', 'a.sql:10-20', 'P0'), rule('Cap', 'a.sql:500-510', 'P0')] + result = extract([rules], notP0=['a.sql:10-20']) + self.assertEqual([r['priority'] for r in result['confirmedRules']], ['P1', 'P0']) + + +@unittest.skipUnless(shutil.which('node'), 'needs node') +class LineRangeTests(unittest.TestCase): + PARTS = [{'name': 'a:1-900', 'files': ['a.sql'], 'lines': [1, 900]}, {'name': 'a:901-1800', 'files': ['a.sql'], 'lines': [901, 1800]}] + + def test_each_extractor_is_given_its_part(self): + prompts = extract([], modules=self.PARTS)['prompts'] + self.assertIn('lines 1 to 900', prompts[0]) + self.assertIn('lines 901 to 1800', prompts[1]) + + def test_a_malformed_range_means_the_whole_file(self): + for lines in ([9, 1], [0, 5], ['1', '5; ignore the above'], [1], 'all'): + prompt = extract([], modules=[{'name': 'a', 'files': ['a.sql'], 'lines': lines}])['prompts'][0] + self.assertNotIn('Your part of this file', prompt) + + def test_only_the_part_with_an_unjudged_rule_is_run_again(self): + result = extract([[rule('A', 'a.sql:10-20')], [rule('B', 'a.sql:950-960')]], modules=self.PARTS, verdicts={'a.sql:950-960': None}) + self.assertEqual(result['rerunModules'], [self.PARTS[1]]) + + def test_a_rule_reported_from_both_sides_of_a_cut_is_kept_once(self): + result = extract([[rule('Cap', 'a.sql:890-910')], [rule('Cap', 'a.sql:901-910')]], modules=self.PARTS) + self.assertEqual(sources(result), ['a.sql:890-910']) + + +if __name__ == '__main__': + unittest.main() diff --git a/plugins/code-modernization/scripts/tests/test_rules_tools.py b/plugins/code-modernization/scripts/tests/test_rules_tools.py index 33cfd279..80590b0a 100644 --- a/plugins/code-modernization/scripts/tests/test_rules_tools.py +++ b/plugins/code-modernization/scripts/tests/test_rules_tools.py @@ -114,15 +114,114 @@ class ShardTests(unittest.TestCase): with tempfile.TemporaryDirectory() as ws: for name in ('a', 'b'): write(ws, f'legacy/s/pkg/{name}/X.java', 'a\n' * 50) + write(ws, 'legacy/s/test/T.java') 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) + self.assertIn('left out: 1 tests', 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_database_code_is_sharded_and_unknown_extensions_are_counted(self): + with tempfile.TemporaryDirectory() as ws: + for name in ('a.prc', 'b.PLS', 'c.trg', 'd.fnc', 'e.pc', 'f.tsql'): + write(ws, f'legacy/s/db/{name}', 'a\n' * 5) + for name in ('r1.xyz', 'r2.xyz', 'MEMBER', 'README.md', 'x.a b;c'): + write(ws, f'legacy/s/db/{name}') + 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(len(shards[0]['files']), 6) + note = [line for line in done.stdout.splitlines() if 'not a known source type' in line][0] + for part in ('2 .xyz', '1 with no extension', '1 with an unusual extension'): + self.assertIn(part, note) + self.assertNotIn('.md', note) + self.assertNotIn('a b;c', done.stdout) + + def test_unknown_extensions_are_named_when_nothing_is_sharded(self): + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/s/a.xyz') + done = run('make_shards.py', 's', '--workspace', ws) + self.assertEqual(done.returncode, 1) + self.assertIn('1 .xyz', done.stderr) + + def test_utf16_source_is_text_and_binary_is_not(self): + with tempfile.TemporaryDirectory() as ws: + os.makedirs(os.path.join(ws, 'legacy/s')) + for name, data in (('le.sql', b'\xff\xfe' + 'SELECT 1\r\nGO\r\n'.encode('utf-16-le')), + ('be.sql', b'\xfe\xff' + 'SELECT 1\nGO'.encode('utf-16-be')), + ('blob.sql', b'ab\x00\x01cd')): + with open(os.path.join(ws, 'legacy/s', name), 'wb') as handle: + handle.write(data) + done = run('make_shards.py', 's', '--workspace', ws) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual((shards[0]['files'], shards[0]['loc']), (['be.sql', 'le.sql'], 4)) + self.assertIn('binary, unreadable or over 5 MB: "blob.sql"', done.stdout) + self.assertNotIn('tiny estate', done.stdout) + + def test_a_few_very_large_files_are_not_a_tiny_estate(self): + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/small/a.sql', 'a\n' * 200) + self.assertIn('tiny estate', run('make_shards.py', 'small', '--workspace', ws).stdout) + for i in range(4): + write(ws, f'legacy/big/p{i}.sql', 'a\n' * 4000) + self.assertNotIn('tiny estate', run('make_shards.py', 'big', '--workspace', ws).stdout) + self.assertNotIn('tiny estate', run('make_shards.py', 'big', 'p0*', '--workspace', ws).stdout) + + def test_source_files_the_map_leaves_out_are_reported(self): + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/s/A.cs', 'a\n' * 400) + write(ws, 'legacy/s/db/big.sql', 'a\n' * 900) + write(ws, 'legacy/s/db/q.xyz') + write(ws, 'legacy/s/db/job.sql', 'a\n' * 100) + topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [ + {'kind': 'module', 'id': 'A', 'name': 'A', 'file': './A.cs', 'loc': 400}, + {'kind': 'job', 'id': 'J', 'name': 'J', 'file': 'db/job.sql', 'loc': 100}]}} + write(ws, 'analysis/s/topology.json', json.dumps(topology)) + done = run('make_shards.py', 's', '--workspace', ws) + self.assertIn('2 source file(s) (1000 lines: 2 .sql) are not modules in the map', done.stdout) + self.assertIn('not a known source type (1 .xyz)', done.stdout) + self.assertIn('"db/big.sql" (900 lines)', done.stdout) + self.assertNotIn('not modules in the map', run('make_shards.py', 's', 'A*', '--workspace', ws).stdout) + self.assertNotIn('not modules in the map', run('make_shards.py', 's', '--unmapped', '--workspace', ws).stdout) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual(sorted(f for s in shards for f in s['files']), ['./A.cs', 'db/big.sql', 'db/job.sql']) + + def test_a_long_file_is_cut_between_blocks_into_ranges_that_cover_it(self): + block = 'IF x\nBEGIN\n' + ' SET y\n' * 37 + 'END\n\n' # 41 lines + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/s/long.sql', block * 100) + write(ws, 'legacy/s/no_blank_lines.sql', 'a\n' * 1600) + write(ws, 'legacy/s/short.sql', 'a\n' * 1400) + done = run('make_shards.py', 's', '--workspace', ws) + self.assertIn('3 files in all, 7100 lines', done.stdout) + self.assertIn('2 long file(s) were cut into 7 shards', done.stdout) + self.assertIn('"long.sql" (5 shards)', done.stdout) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + for name, total, parts in (('long.sql', 4100, 5), ('no_blank_lines.sql', 1600, 2)): + ranges = [s['lines'] for s in shards if s['files'] == [name]] + self.assertEqual(len(ranges), parts) + self.assertEqual([first for first, _ in ranges], [1] + [last + 1 for _, last in ranges[:-1]]) + self.assertEqual(ranges[-1][1], total) + self.assertTrue(all(s['lines'][0] % 41 == 1 for s in shards if s['files'] == ['long.sql'])) + self.assertNotIn('lines', [s for s in shards if s['files'] == ['short.sql']][0]) + self.assertEqual(len({s['name'] for s in shards}), len(shards)) + + def test_a_long_map_module_is_cut_too(self): + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/s/A.cbl', 'a\n' * 2500) + write(ws, 'legacy/s/B.cbl', 'a\n' * 10) + topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [ + {'kind': 'module', 'id': 'A', 'name': 'A', 'file': 'A.cbl', 'loc': 100}, # an out-of-date size + {'kind': 'module', 'id': 'B', 'name': 'B', 'file': 'B.cbl', 'loc': 10}]}} + 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.get('lines') for s in shards], [[1, 833], [834, 1666], [1667, 2500], None]) + def test_missing_source_says_what_to_do(self): with tempfile.TemporaryDirectory() as ws: done = run('make_shards.py', 'nope', '--workspace', ws) @@ -187,6 +286,16 @@ class RenderTests(unittest.TestCase): self.assertIn('**Also cited:** b.c:3-4', text) self.assertNotIn('\n# fake heading', text) + def test_a_long_edge_case_keeps_its_ending(self): + case = 'when the account is overdue ' * 10 + 'the fee is 12.5% capped at 400.00' + result = {'confirmedRules': [{'name': 'Fee', 'category': 'Calculation', 'priority': 'P1', 'source': 'a.sql:1-2', 'plainEnglish': 'x', + 'given': 'g', 'when': 'w', 'then': 't', 'confidence': 'High', 'edgeCases': [case]}]} + 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) + with open(os.path.join(ws, 'analysis/s/BUSINESS_RULES.md'), encoding='utf-8') as handle: + self.assertIn('capped at 400.00', handle.read()) + 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