import json import os import re 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_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) 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']) 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_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) 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_both_depths_are_estimated(self): with tempfile.TemporaryDirectory() as ws: write(ws, 'legacy/tiny/a.sql', 'a\n' * 200) self.assertIn('Standard 20 to 100 agents (about 0.3M to 1.6M tokens); Thorough 20 to 150 agents', run('make_shards.py', 'tiny', '--workspace', ws).stdout) write(ws, 'legacy/big/a.sql', 'a\n' * 10000) self.assertIn('Standard 150 to 550 agents (about 2.4M to 8.8M tokens); Thorough 200 to 1900 agents (about 3.2M to 30.4M tokens)', run('make_shards.py', 'big', '--workspace', ws).stdout) for i in range(40): write(ws, f'legacy/many/d{i}/a.sql', 'a\n' * 5) self.assertIn('Standard 20 to 440 agents', run('make_shards.py', 'many', '--workspace', ws).stdout) write(ws, 'legacy/small/a.sql', 'a\n' * 1001) write(ws, 'legacy/small/x/b.sql', 'a\n' * 184) self.assertIn('Standard 20 to 100 agents', run('make_shards.py', 'small', '--workspace', ws).stdout) def test_the_estimate_counts_the_files_whatever_the_map_says(self): with tempfile.TemporaryDirectory() as ws: write(ws, 'legacy/s/A.cbl', 'a\n' * 1400) for size in ({}, {'loc': 400}): topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [{'kind': 'module', 'id': 'A', 'name': 'A', 'file': 'A.cbl', **size}]}} write(ws, 'analysis/s/topology.json', json.dumps(topology)) self.assertIn('Standard 30 to 80 agents', run('make_shards.py', 's', '--workspace', ws).stdout) 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) 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) 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_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_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_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_the_depth_is_shown(self): with tempfile.TemporaryDirectory() as ws: for stats, times in (({'depth': 'thorough', 'agents': 7, 'estimate': 'Standard 20 to 100 agents;\nThorough 20 to 150'}, 1), ({}, 0)): write(ws, 'analysis/s/rules_result.json', json.dumps({'confirmedRules': [], 'stats': stats})) 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.assertEqual(handle.read().count('Extraction depth: thorough; 7 agents. Estimated before the run: Standard 20 to 100 agents; Thorough 20 to 150.'), times) 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()