summaryrefslogtreecommitdiff
path: root/plugins/code-modernization/scripts
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/code-modernization/scripts')
-rw-r--r--plugins/code-modernization/scripts/make_shards.py219
-rw-r--r--plugins/code-modernization/scripts/render_rules.py168
-rw-r--r--plugins/code-modernization/scripts/tests/test_rules_tools.py110
3 files changed, 497 insertions, 0 deletions
diff --git a/plugins/code-modernization/scripts/make_shards.py b/plugins/code-modernization/scripts/make_shards.py
new file mode 100644
index 00000000..ff6671cc
--- /dev/null
+++ b/plugins/code-modernization/scripts/make_shards.py
@@ -0,0 +1,219 @@
+#!/usr/bin/env python3
+"""Split a system's source into shards for per-module rule extraction.
+
+ python3 make_shards.py <system> [module-pattern] [--workspace DIR] [--all]
+
+The source directory is the first line of analysis/<system>/SOURCE when that file
+exists, else legacy/<system>. With analysis/<system>/topology.json, one shard per map
+module (small modules of a domain merged); without it, one shard per directory of source
+files. The list is written to analysis/<system>/extract-rules.modules.json as
+[{"name", "domain", "files": [relative to the source dir], "loc"}], the form the
+extract-rules workflow takes. Standard library only.
+"""
+import fnmatch
+import json
+import os
+import sys
+
+SOURCE_EXT = {
+ # mainframe and legacy business languages
+ '.cbl', '.cob', '.cobol', '.cpy', '.pli', '.pl1', '.jcl', '.proc', '.rpg', '.rpgle', '.sqlrpgle', '.clle', '.nat', '.ada', '.adb', '.ads',
+ '.asm', '.bms', '.map', '.pas', '.dpr', '.prg', '.f', '.for', '.f90', '.f77',
+ # general purpose
+ '.java', '.kt', '.scala', '.groovy', '.cs', '.vb', '.vbs', '.bas', '.cls', '.frm', '.fs', '.c', '.h', '.cc', '.cpp', '.cxx', '.hpp', '.m', '.mm',
+ '.go', '.rs', '.py', '.rb', '.php', '.pl', '.pm', '.js', '.jsx', '.ts', '.tsx', '.swift', '.lua', '.tcl', '.erl', '.ex', '.exs', '.clj',
+ '.hs', '.ml', '.r', '.sh', '.bat', '.ps1',
+ # web and data
+ '.asp', '.aspx', '.ascx', '.cshtml', '.jsp', '.jspx', '.sql', '.pks', '.pkb', '.plsql', '.tf',
+}
+SKIP_DIRS = {
+ '.git', '.svn', '.hg', 'node_modules', 'vendor', 'third_party', 'thirdparty', 'dist', 'build', 'target', 'bin', 'obj', 'out',
+ '__pycache__', '.venv', 'venv', '.tox', '.gradle', '.idea', 'coverage', 'fixtures', 'testdata', 'test-data', 'generated',
+}
+TEST_DIRS = {'test', 'tests', '__tests__', 'spec', 'specs'}
+MAX_FILES = 25
+MAX_LOC = 5000
+SMALL = 300
+TINY_ESTATE = 30
+MAX_BYTES = 5_000_000
+
+
+def source_dir(workspace, system):
+ marker = os.path.join(workspace, 'analysis', system, 'SOURCE')
+ if os.path.isfile(marker):
+ with open(marker, encoding='utf-8', errors='replace') as handle:
+ first = handle.readline().strip()
+ if first:
+ return first if os.path.isabs(first) else os.path.join(workspace, first)
+ return os.path.join(workspace, 'legacy', system)
+
+
+def count_lines(path):
+ try:
+ if os.path.getsize(path) > MAX_BYTES:
+ return None
+ with open(path, 'rb') as handle:
+ data = handle.read()
+ except OSError:
+ return None
+ if b'\x00' in data[:4096]:
+ return None
+ return data.count(b'\n') + (1 if data and not data.endswith(b'\n') else 0)
+
+
+def relative_to_source(path, source, system):
+ """A topology `file` may be absolute, workspace-relative or source-relative: return it source-relative."""
+ path = path.replace('\\', '/')
+ if os.path.isabs(path):
+ rel = os.path.relpath(path, source).replace(os.sep, '/')
+ return None if rel.startswith('..') else rel
+ for prefix in (f'legacy/{system}/', os.path.normpath(source).replace(os.sep, '/') + '/'):
+ if path.startswith(prefix):
+ return path[len(prefix):]
+ return path
+
+
+def from_topology(topology, source, system, pattern):
+ modules, names = [], set()
+
+ def walk(node, domain):
+ kind = node.get('kind')
+ if kind == 'domain':
+ domain = node.get('name') or node.get('id', '')
+ if kind == 'module' and node.get('file'):
+ rel = relative_to_source(str(node['file']), source, system)
+ if rel:
+ name = str(node.get('name') or node.get('id'))
+ if name in names:
+ name = str(node.get('id') or name) # names can repeat across domains; ids are unique
+ names.add(name)
+ modules.append({'name': name, 'domain': domain, 'files': [rel], 'loc': node.get('loc') or None})
+ for child in node.get('children', []):
+ walk(child, domain)
+
+ walk(topology['root'], '')
+ if pattern:
+ def match(text):
+ return fnmatch.fnmatch(text, pattern) or fnmatch.fnmatch(os.path.basename(text), pattern)
+ modules = [m for m in modules if match(m['name']) or any(match(f) for f in m['files'])]
+ # merge small modules of the same domain; never split one
+ shards, pool, counter = [], {}, {}
+ for module in modules:
+ if module['loc'] and module['loc'] < SMALL:
+ current = pool.get(module['domain'])
+ if current is None or current['loc'] >= SMALL or len(current['files']) >= MAX_FILES:
+ counter[module['domain']] = counter.get(module['domain'], 0) + 1
+ current = pool[module['domain']] = {
+ 'name': f"{module['domain'] or 'misc'}:small-{counter[module['domain']]}",
+ 'domain': module['domain'], 'files': [], 'loc': 0,
+ }
+ shards.append(current)
+ current['files'] += module['files']
+ current['loc'] += module['loc']
+ else:
+ shards.append(module)
+ return shards, len(modules)
+
+
+def from_tree(source, pattern, include_all):
+ by_dir, skipped = {}, {'vendored or generated': 0, 'tests': 0, 'unreadable or binary': 0}
+ for root, dirs, files in os.walk(source):
+ kept = []
+ for d in sorted(dirs):
+ if d in SKIP_DIRS or (d.startswith('.') and d not in ('.',)):
+ skipped['vendored or generated'] += 1
+ elif d.lower() in TEST_DIRS and not include_all:
+ skipped['tests'] += 1
+ else:
+ kept.append(d)
+ dirs[:] = kept
+ for name in sorted(files):
+ if os.path.splitext(name)[1].lower() not in SOURCE_EXT or name.endswith('.min.js'):
+ continue
+ path = os.path.join(root, name)
+ lines = count_lines(path)
+ if lines is None:
+ skipped['unreadable or binary'] += 1
+ continue
+ rel = os.path.relpath(path, source).replace(os.sep, '/')
+ by_dir.setdefault(os.path.dirname(rel), []).append((rel, lines))
+ if pattern:
+ def match(text):
+ return fnmatch.fnmatch(text, pattern) or fnmatch.fnmatch(os.path.basename(text), pattern)
+ by_dir = {d: [f for f in fs if match(f[0])] for d, fs in by_dir.items()}
+ shards, total = [], 0
+ for directory in sorted(by_dir):
+ entries = by_dir[directory]
+ total += len(entries)
+ chunk, chunk_loc, part = [], 0, 1
+ label = directory or '.'
+ for rel, lines in entries + [(None, 0)]:
+ if rel is None or (chunk and (len(chunk) >= MAX_FILES or chunk_loc + lines > MAX_LOC)):
+ if chunk:
+ shards.append({'name': label if part == 1 else f'{label}#{part}', 'domain': directory,
+ 'files': [f for f, _ in chunk], 'loc': chunk_loc or None})
+ part += 1
+ chunk, chunk_loc = [], 0
+ if rel is not None:
+ chunk.append((rel, lines))
+ chunk_loc += lines
+ return shards, total, skipped
+
+
+def main(argv):
+ args = [a for a in argv[1:] if not a.startswith('--')]
+ flags = [a for a in argv[1:] if a.startswith('--')]
+ workspace = '.'
+ if '--workspace' in argv:
+ workspace = argv[argv.index('--workspace') + 1]
+ args = [a for a in args if a != workspace]
+ if not args:
+ print('usage: make_shards.py <system> [module-pattern] [--workspace DIR] [--all]', file=sys.stderr)
+ return 2
+ system, pattern = args[0], (args[1] if len(args) > 1 else '')
+ source = source_dir(workspace, system)
+ if not os.path.isdir(source):
+ print(f'No source directory at {source}. Run preflight (with --source <path> if the code is elsewhere) first.', file=sys.stderr)
+ return 1
+ out = os.path.join(workspace, 'analysis', system, 'extract-rules.modules.json')
+ topo_path = os.path.join(workspace, 'analysis', system, 'topology.json')
+ notes = []
+ if os.path.isfile(topo_path):
+ try:
+ with open(topo_path, encoding='utf-8') as handle:
+ topology = json.load(handle)
+ shards, modules = from_topology(topology, source, system, pattern)
+ origin = f'{modules} map modules'
+ missing = [f for s in shards for f in s['files'] if not os.path.exists(os.path.join(source, f))]
+ if missing:
+ notes.append(f'{len(missing)} file(s) named by the map do not exist under the source directory (first: {missing[0]})')
+ except (ValueError, KeyError, OSError) as error:
+ print(f'topology.json is unusable ({error}); reading the directory tree instead.', file=sys.stderr)
+ shards, files, skipped = from_tree(source, pattern, '--all' in flags)
+ origin = f'{files} source files (tree)'
+ else:
+ shards, files, skipped = from_tree(source, pattern, '--all' in flags)
+ origin = f'{files} source files (no topology.json: read from the directory tree)'
+ left_out = ', '.join(f'{n} {k}' for k, n in skipped.items() if n)
+ if left_out:
+ notes.append(f'left out: {left_out}')
+ if not shards:
+ print('0 shards: the pattern matched nothing, or no source files were found. Nothing was written.', file=sys.stderr)
+ return 1
+ os.makedirs(os.path.dirname(out), exist_ok=True)
+ tmp = out + '.tmp'
+ with open(tmp, 'w', encoding='utf-8') as handle:
+ json.dump(shards, handle, indent=1)
+ os.replace(tmp, out)
+ file_count = sum(len(s['files']) for s in shards)
+ loc = sum(s['loc'] or 0 for s in shards)
+ print(f'{len(shards)} shards from {origin}, {file_count} files, {loc} lines -> {os.path.relpath(out, workspace)}')
+ if file_count < TINY_ESTATE:
+ print(f'tiny estate: fewer than {TINY_ESTATE} source files, so sharding adds little (run the workflow in lens mode).')
+ for note in notes:
+ print(f'note: {note}')
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
diff --git a/plugins/code-modernization/scripts/render_rules.py b/plugins/code-modernization/scripts/render_rules.py
new file mode 100644
index 00000000..da375f55
--- /dev/null
+++ b/plugins/code-modernization/scripts/render_rules.py
@@ -0,0 +1,168 @@
+#!/usr/bin/env python3
+"""Render the extract-rules workflow's result into BUSINESS_RULES.md and DATA_OBJECTS.md.
+
+ python3 render_rules.py <system> [--workspace DIR] [--result FILE]
+
+Reads analysis/<system>/rules_result.json (the object the workflow returned, saved by the
+command) and writes analysis/<system>/BUSINESS_RULES.md and DATA_OBJECTS.md. Rules are
+numbered RULE-001, RULE-002, ... in priority then category order and the heading is always
+`### RULE-NNN: <name>`, the pattern later commands and the pane look for. Every value comes
+from analysis of untrusted code, so it is written as plain text on one line where it is
+a heading or a table cell. Standard library only.
+"""
+import json
+import os
+import sys
+
+CATEGORIES = ['Calculation', 'Validation', 'Lifecycle', 'Policy']
+PRIORITY = {'P0': 0, 'P1': 1, 'P2': 2}
+
+
+def one_line(value, limit=300):
+ text = ' '.join(str(value if value is not None else '').split())
+ text = text.replace('|', '/').replace('`', "'")
+ return text if len(text) <= limit else text[: limit - 1].rstrip() + '…'
+
+
+def block(value):
+ """Multi-line text: keep the lines, but never let a value open a heading or a fence."""
+ lines = []
+ for raw in str(value if value is not None else '').splitlines():
+ line = raw.rstrip()
+ if line.lstrip().startswith(('#', '```', '~~~')):
+ line = '\\' + line.lstrip()
+ lines.append(line)
+ return '\n'.join(lines).strip()
+
+
+def render_rule(number, rule):
+ rid = f'RULE-{number:03d}'
+ out = [f"### {rid}: {one_line(rule.get('name'), 120)}",
+ f"**Category:** {one_line(rule.get('category'), 20)}",
+ f"**Priority:** {one_line(rule.get('priority'), 4)}",
+ f"**Source:** `{one_line(rule.get('source'), 200).replace(chr(39), '')}`",
+ f"**Plain English:** {one_line(rule.get('plainEnglish'), 400)}",
+ '**Specification:**',
+ f" Given {block(rule.get('given'))}",
+ f" When {block(rule.get('when'))}",
+ f" Then {block(rule.get('then'))}"]
+ if rule.get('and'):
+ out.append(f" And {block(rule['and'])}")
+ if rule.get('parameters'):
+ out.append(f"**Parameters:** {block(rule['parameters'])}")
+ cases = rule.get('edgeCases') or []
+ if cases:
+ out.append('**Edge cases handled:** ' + '; '.join(one_line(c, 200) for c in cases))
+ if rule.get('suspectedDefect'):
+ out.append(f"**Suspected defect:** {block(rule['suspectedDefect'])}")
+ confidence = one_line(rule.get('confidence'), 10)
+ question = rule.get('smeQuestion')
+ out.append(f"**Confidence:** {confidence}" + (f" — {one_line(question, 400)}" if question and confidence != 'High' else ''))
+ return rid, '\n'.join(out)
+
+
+def main(argv):
+ args = [a for a in argv[1:] if not a.startswith('--')]
+ workspace, result_path = '.', None
+ if '--workspace' in argv:
+ workspace = argv[argv.index('--workspace') + 1]
+ args = [a for a in args if a != workspace]
+ if '--result' in argv:
+ result_path = argv[argv.index('--result') + 1]
+ args = [a for a in args if a != result_path]
+ if not args:
+ print('usage: render_rules.py <system> [--workspace DIR] [--result FILE]', file=sys.stderr)
+ return 2
+ system = args[0]
+ base = os.path.join(workspace, 'analysis', system)
+ result_path = result_path or os.path.join(base, 'rules_result.json')
+ try:
+ with open(result_path, encoding='utf-8') as handle:
+ result = json.load(handle)
+ except (OSError, ValueError) as error:
+ print(f'Cannot read {result_path}: {error}', file=sys.stderr)
+ return 1
+
+ rules = sorted(result.get('confirmedRules') or [],
+ key=lambda r: (PRIORITY.get(r.get('priority'), 1),
+ CATEGORIES.index(r['category']) if r.get('category') in CATEGORIES else 9,
+ str(r.get('source'))))
+ numbered = [(i + 1, r) for i, r in enumerate(rules)]
+ rendered = {n: render_rule(n, r) for n, r in numbered}
+ stats = result.get('stats') or {}
+
+ doc = [f'# Business Rules — {one_line(system, 80)}', '',
+ f"{len(rules)} confirmed rules ({sum(1 for r in rules if r.get('priority') == 'P0')} P0). "
+ f"Each citation was checked by a second agent that read the cited lines; "
+ f"{len(result.get('rejectedRules') or [])} candidate rules were refuted and left out.", '',
+ '| ID | Name | Category | Priority | Source | Confidence |', '|---|---|---|---|---|---|']
+ for n, r in numbered:
+ doc.append(f"| RULE-{n:03d} | {one_line(r.get('name'), 80)} | {one_line(r.get('category'), 20)} | "
+ f"{one_line(r.get('priority'), 4)} | `{one_line(r.get('source'), 80).replace(chr(39), '')}` | {one_line(r.get('confidence'), 10)} |")
+ doc.append('')
+ for category in CATEGORIES + [None]:
+ group = [n for n, r in numbered if (r.get('category') if r.get('category') in CATEGORIES else None) == category]
+ if not group:
+ continue
+ doc += [f"## {category or 'Other'}", '']
+ for n in group:
+ doc += [rendered[n][1], '']
+ sme = [(n, r) for n, r in numbered if r.get('confidence') != 'High']
+ doc += ['## Rules requiring SME confirmation', '']
+ if sme:
+ for n, r in sme:
+ doc.append(f"- **RULE-{n:03d}** ({one_line(r.get('confidence'), 10)}): "
+ f"{one_line(r.get('smeQuestion') or 'Confirm this rule with someone who knows the system.', 400)}")
+ else:
+ doc.append('None: every confirmed rule has High confidence.')
+ doc.append('')
+
+ flags = result.get('injectionFlags') or []
+ if flags:
+ doc += ['## ⚠ Instruction-shaped content found in source', '',
+ 'These lines of the source tried to steer automated analysis. A person should look at them.', '']
+ doc += [f'- {one_line(f, 300)}' for f in flags]
+ doc.append('')
+
+ gaps = [('never attempted (token budget or agent cap)', stats.get('skippedModules')),
+ ('extractor returned nothing', stats.get('failedModules')),
+ ('malformed entries, fix by hand', stats.get('droppedModules')),
+ ('phases cut short', stats.get('skippedPhases')),
+ ('candidate rules no referee judged (not in the catalog)',
+ [f"{one_line(u.get('name'), 80)} ({one_line(u.get('source'), 80)})" for u in (result.get('unverifiedRules') or [])])]
+ gaps = [(label, items) for label, items in gaps if items]
+ if gaps:
+ doc += ['## Coverage gaps', '', 'These parts were NOT fully mined:', '']
+ for label, items in gaps:
+ doc.append(f"- **{len(items)} {label}:** " + ', '.join(one_line(i, 100) for i in items[:30]) + (' …' if len(items) > 30 else ''))
+ if result.get('rerunModules'):
+ doc.append(f"\nA follow-up run for the {len(result['rerunModules'])} affected shard(s) covers them.")
+ doc.append('')
+
+ with open(os.path.join(base, 'BUSINESS_RULES.md'), 'w', encoding='utf-8') as handle:
+ handle.write('\n'.join(doc))
+
+ objects = result.get('dataObjects') or []
+ dto = [f'# Data Objects — {one_line(system, 80)}', '']
+ if not objects:
+ dto.append('No data objects were cataloged.')
+ for obj in objects:
+ dto += [f"## {one_line(obj.get('name'), 100)}", f"Source: `{one_line(obj.get('source'), 160).replace(chr(39), '')}`", '',
+ '| Field | Type | Note |', '|---|---|---|']
+ for field in obj.get('fields') or []:
+ dto.append(f"| {one_line(field.get('name'), 80)} | {one_line(field.get('type'), 60)} | {one_line(field.get('note'), 160)} |")
+ used = obj.get('consumedBy') or []
+ if used:
+ dto += ['', 'Used by: ' + ', '.join(one_line(u, 80) for u in used)]
+ dto.append('')
+ with open(os.path.join(base, 'DATA_OBJECTS.md'), 'w', encoding='utf-8') as handle:
+ handle.write('\n'.join(dto))
+
+ p0 = sum(1 for r in rules if r.get('priority') == 'P0')
+ print(f"BUSINESS_RULES.md: {len(rules)} rules ({p0} P0, {len(sme)} need SME review); DATA_OBJECTS.md: {len(objects)} objects; "
+ f"rejected {len(result.get('rejectedRules') or [])}, unverified {len(result.get('unverifiedRules') or [])}")
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
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()