summaryrefslogtreecommitdiff
path: root/plugins/code-modernization/scripts
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-12-01 09:19:25 +0000
committerClaude <noreply@anthropic.com>2026-12-01 09:19:25 +0000
commit6f410661a18fefb6768fe37f5f6ffc599204eb10 (patch)
tree584170c8d2106dedbc66c98bc658f23de82277ad /plugins/code-modernization/scripts
parent761a93d46638340c9df6a73b46aa3c9826a2213d (diff)
code-modernization: choose rule-extraction depth and approve a number of agentscode-modernization-1.2.0
Add --depth standard|thorough. Standard, the default, keeps the previous extraction wording; Thorough writes one rule per decision and costs more. Every run shows the estimate for both and never starts more agents than were approved. Spread batches over the system and size them by the densest shards seen, so dense code that comes late is not extracted and left unrefereed. Keep same-named rules whose citations a referee swaps or moves. Merge follow-up runs with a script that never drops a confirmed rule because a re-run failed.
Diffstat (limited to 'plugins/code-modernization/scripts')
-rw-r--r--plugins/code-modernization/scripts/make_shards.py27
-rw-r--r--plugins/code-modernization/scripts/merge_rules.py253
-rw-r--r--plugins/code-modernization/scripts/render_rules.py10
-rw-r--r--plugins/code-modernization/scripts/tests/test_extract_workflow.py216
-rw-r--r--plugins/code-modernization/scripts/tests/test_merge_rules.py171
-rw-r--r--plugins/code-modernization/scripts/tests/test_rules_tools.py31
6 files changed, 700 insertions, 8 deletions
diff --git a/plugins/code-modernization/scripts/make_shards.py b/plugins/code-modernization/scripts/make_shards.py
index 1365d9bc..54ee208f 100644
--- a/plugins/code-modernization/scripts/make_shards.py
+++ b/plugins/code-modernization/scripts/make_shards.py
@@ -13,6 +13,7 @@ import codecs
import collections
import fnmatch
import json
+import math
import os
import re
import sys
@@ -48,6 +49,13 @@ CUT_WINDOW = 100 # how far a cut may move to land between two blocks of cod
SMALL = 300
TINY_ESTATE = 30 # files; a tiny estate also fits in one shard (MAX_LOC lines)
MAX_BYTES = 5_000_000
+# Estimated agents per 1,000 lines for each depth: code that is mostly plumbing, and very dense business logic. Taken from
+# simulated runs (T-SQL procedures, C utilities) and, for the low end of standard, from a 30,000-line estate.
+AGENTS_PER_KLOC = {'Standard': (15, 55), 'Thorough': (20, 190)}
+SMALL_SHARD = {'Standard': 40, 'Thorough': 125} # a short dense file needs more per line: 10 + lines / 5, up to this
+LENS_AGENTS = {'Standard': (15, 100), 'Thorough': (20, 250)} # a tiny estate, about 1,000 lines
+LENS_MIN_TOP = {'Standard': 100, 'Thorough': 150}
+TOKENS_PER_AGENT = 16_000
def too_broad(path):
@@ -276,6 +284,23 @@ def split_long_files(shards, source):
return out
+def estimate(sizes, tiny):
+ """One line with the agents and tokens each depth is expected to need, from the number of lines in each shard."""
+ def rounded(n):
+ return math.ceil(n / 10) * 10
+
+ parts = []
+ for depth in AGENTS_PER_KLOC:
+ if tiny:
+ low, top = LENS_AGENTS[depth][0], max(LENS_MIN_TOP[depth], LENS_AGENTS[depth][1] * sum(sizes) / 1000)
+ else:
+ low = AGENTS_PER_KLOC[depth][0] * sum(sizes) / 1000
+ top = sum(max(AGENTS_PER_KLOC[depth][1] * n / 1000, min(SMALL_SHARD[depth], 10 + n / 5)) for n in sizes)
+ low, top = max(rounded(low), 20), max(rounded(top), 30)
+ parts.append(f'{depth} {low} to {top} agents (about {low * TOKENS_PER_AGENT / 1e6:.1f}M to {top * TOKENS_PER_AGENT / 1e6:.1f}M tokens)')
+ return 'estimate: ' + '; '.join(parts) + ', from mostly plumbing to very dense business logic'
+
+
def quoted(names):
"""Up to five file names for a note, quoted and shortened."""
return ', '.join(json.dumps(name[-80:]) + extra for name, extra in names[:5])
@@ -371,6 +396,8 @@ def main(argv):
tiny = max(len(mapped), len(tree)) < TINY_ESTATE and max(loc, sum(n for _, n in tree)) <= MAX_LOC and not unread
if unmapped_note and not tiny: # lens mode reads every file
notes.append(unmapped_note)
+ # The map's sizes can be missing or out of date, so the files are counted.
+ print(estimate([s['loc'] if 'lines' in s else sum(count_lines(os.path.join(source, f)) or 0 for f in s['files']) or s['loc'] or 0 for s in shards], tiny))
if tiny:
print(f'tiny estate: the system has fewer than {TINY_ESTATE} source files and at most {MAX_LOC} lines, so sharding adds little (run the workflow in lens mode).')
for note in notes:
diff --git a/plugins/code-modernization/scripts/merge_rules.py b/plugins/code-modernization/scripts/merge_rules.py
new file mode 100644
index 00000000..3d60c26f
--- /dev/null
+++ b/plugins/code-modernization/scripts/merge_rules.py
@@ -0,0 +1,253 @@
+#!/usr/bin/env python3
+"""Merge another extract-rules run (a follow-up, or the next part of a large job) into the saved result.
+
+ python3 merge_rules.py <system> <new-result.json> [--workspace DIR]
+
+Reads analysis/<system>/rules_result.json and the object the new run returned, writes the merged
+rules_result.json and renames the new file to <name>.merged so it is not merged twice. A second
+extraction names and cites the same logic differently, so a shard that the new run extracted and
+judged in full replaces the saved rules of that shard, unless it found fewer. Otherwise every saved
+rule stays and only new rules at other lines are added: a run that failed, or stopped at a limit,
+never costs a rule that was already confirmed. Standard library only.
+"""
+import functools
+import json
+import os
+import posixpath
+import re
+import sys
+import unicodedata
+
+ALSO = ' ; also ' # how the workflow joins the citations of rules it folded together
+
+
+def clean_path(path, system):
+ path = posixpath.normpath(str(path).strip().strip('`').replace('\\', '/'))
+ prefix = f'legacy/{system}/'
+ return path[len(prefix):] if path.startswith(prefix) else path
+
+
+@functools.lru_cache(maxsize=None)
+def place(source, system):
+ """(file, first line, last line) of a citation; the lines are None when it names none."""
+ m = re.match(r'([^:]*):\s*(\d+)(?:\s*[-–]\s*(\d+))?', source)
+ if not m:
+ return clean_path(source.split(':')[0], system), None, None
+ a, b = int(m.group(2)), int(m.group(3) or m.group(2))
+ return clean_path(m.group(1), system), min(a, b), max(a, b)
+
+
+def name_key(name):
+ """The workflow's nameKey: letters, marks, digits, mathematical signs and `!` tell names apart."""
+ kept = ''.join(c if c == '!' or unicodedata.category(c)[0] in 'LMN' or unicodedata.category(c) == 'Sm' else ' ' for c in name.lower())
+ return ' '.join(kept.split())
+
+
+def meet(a, b):
+ """Two citations with lines of one file that overlap."""
+ return a[0] == b[0] and a[1] is not None and b[1] is not None and a[1] <= b[2] and b[1] <= a[2]
+
+
+class Rules:
+ """The places of one system's rules and shards."""
+
+ def __init__(self, system):
+ self.system = system
+
+ def cites(self, rule):
+ return [place(part, self.system) for part in str(rule.get('source') or '').split(ALSO)]
+
+ def overlaps(self, a, b):
+ """The lines `a` cites meet lines `b` cites, as its own or as another place of the same behavior."""
+ return any(meet(self.cites(a)[0], cite) for cite in self.cites(b))
+
+ def same(self, a, b):
+ """The workflow's sameRule: one file, one name, and lines that meet or are not given."""
+ x, y = self.cites(a)[0], self.cites(b)[0]
+ return (x[0] == y[0] and (x[1] is None or y[1] is None or meet(x, y))
+ and name_key(str(a.get('name') or '')) == name_key(str(b.get('name') or '')))
+
+ def files(self, shard):
+ return {clean_path(f, self.system) for f in shard.get('files') or []}
+
+ def holds(self, shard, cite):
+ file, first, _ = cite
+ lines = shard.get('lines')
+ return file in self.files(shard) and (not lines or (first is not None and lines[0] <= first <= lines[1]))
+
+ def held(self, shards, cite):
+ return any(self.holds(shard, cite) for shard in shards)
+
+ def within(self, shard, other):
+ """`shard` is the same code as `other`, or a part of it."""
+ lines, outer = shard.get('lines'), other.get('lines')
+ return self.files(shard) <= self.files(other) and (not outer or bool(lines and outer[0] <= lines[0] and lines[1] <= outer[1]))
+
+
+def dicts(value):
+ return [v for v in value or [] if isinstance(v, dict)]
+
+
+def union(*lists):
+ return list(dict.fromkeys(str(v) for items in lists for v in items or []))
+
+
+def merge_objects(saved, new, system):
+ """Every run catalogs the whole system, so one object comes back with the same name and file."""
+ def key(obj):
+ return str(obj.get('name')).lower(), place(str(obj.get('source') or ''), system)[0]
+
+ out = [dict(o) for o in saved]
+ at = {key(o): o for o in out}
+ for obj in new:
+ old = at.get(key(obj))
+ if old is None:
+ out.append(obj)
+ else:
+ if len(obj.get('fields') or []) > len(old.get('fields') or []):
+ old['fields'] = obj['fields']
+ old['consumedBy'] = union(old.get('consumedBy'), obj.get('consumedBy'))
+ return out
+
+
+def merge(system, saved, new):
+ """The merged result, and counts for the report line."""
+ code = Rules(system)
+ old_rules, new_rules = dicts(saved.get('confirmedRules')), dicts(new.get('confirmedRules'))
+ covered, again = dicts(new.get('coveredModules')), dicts(new.get('rerunModules'))
+
+ def count(rules, shard):
+ return sum(1 for rule in rules for cite in code.cites(rule) if code.holds(shard, cite))
+
+ def keep(replaced):
+ """The saved rules that stay, and the places that became a rule's own citation."""
+ kept, moved = [], set()
+ for rule in old_rules:
+ parts = str(rule.get('source') or '').split(ALSO)
+ if code.held(replaced, place(parts[0], system)):
+ # The same behavior in code the new run does not replace: the rule stays there.
+ parts = [part for part in parts[1:] if not code.held(replaced, place(part, system))]
+ if not parts:
+ continue
+ rule = {**rule, 'source': ALSO.join(parts)}
+ moved.add(parts[0])
+ kept.append(rule)
+ return kept, moved
+
+ # A shard is replaced when what the new run adds to it cites it at least as often as what that removes. What is
+ # added depends on what stays, so shards drop out until that holds for all.
+ replaced = covered
+ while True:
+ kept, moved = keep(replaced)
+ added = [rule for rule in new_rules
+ if not any(code.same(rule, old) for old in kept)
+ and (code.held(replaced, code.cites(rule)[0]) or not any(code.overlaps(rule, old) for old in kept))]
+ still = [shard for shard in replaced if count(kept + added, shard) >= count(old_rules, shard)]
+ if len(still) == len(replaced):
+ break
+ replaced = still
+ confirmed = kept + added
+
+ # A saved candidate is settled once the new run has a verdict, or a new candidate, at its lines.
+ old_open, new_open = ([rule for rule in dicts(r.get('unverifiedRules')) if not any(code.same(rule, other) for other in confirmed)]
+ for r in (saved, new))
+ settled = added + new_open + dicts(new.get('rejectedRules'))
+ unverified = [rule for rule in old_open if not any(code.overlaps(rule, other) for other in settled)] + new_open
+
+ def key(shard):
+ return sorted(code.files(shard)), shard.get('lines')
+
+ rerun = [shard for shard in dicts(saved.get('rerunModules'))
+ if not any(code.within(shard, done) for done in covered) and key(shard) not in [key(s) for s in again]]
+ waiting = {shard.get('name') for shard in rerun}
+ rerun += again
+
+ s, n = (r.get('stats') if isinstance(r.get('stats'), dict) else {} for r in (saved, new))
+ attempted = {shard.get('name') for shard in covered + again}
+
+ def names(field):
+ return [x for x in s.get(field) or [] if re.sub(r'~\d+$', '', str(x)) in waiting]
+
+ def total(field):
+ return (s.get(field) or 0) + (n.get(field) or 0)
+
+ def still_true(phase):
+ if phase.startswith('extraction stopped with '):
+ return bool(names('skippedModules'))
+ return not (phase.startswith('DTO catalog') and new.get('dataObjects'))
+
+ present = {' '.join(str(rule.get('name')).split())[:120] for rule in confirmed}
+ reruns = sum(1 for shard in dicts(saved.get('rerunModules')) if key(shard) in [key(x) for x in covered + again])
+ merged = {
+ **saved, **new,
+ 'mode': saved.get('mode') or new.get('mode'),
+ 'rounds': max(saved.get('rounds') or 0, new.get('rounds') or 0),
+ 'confirmedRules': confirmed,
+ 'foldedRules': [f for f in dicts(saved.get('foldedRules')) if f.get('into') in present and f.get('source') not in moved] + dicts(new.get('foldedRules')),
+ 'rejectedRules': dicts(saved.get('rejectedRules')) + dicts(new.get('rejectedRules')),
+ 'unverifiedRules': unverified,
+ 'rerunModules': rerun,
+ 'coveredModules': [shard for shard in dicts(saved.get('coveredModules')) if key(shard) not in [key(x) for x in covered + again]] + covered,
+ 'dataObjects': merge_objects(dicts(saved.get('dataObjects')), dicts(new.get('dataObjects')), system),
+ 'injectionFlags': union(saved.get('injectionFlags'), new.get('injectionFlags')),
+ }
+ merged['stats'] = {
+ **s, **n,
+ 'confirmed': len(confirmed),
+ 'rejected': len(merged['rejectedRules']),
+ 'unverified': len(unverified),
+ 'p0': sum(1 for rule in confirmed if rule.get('priority') == 'P0'),
+ 'needsSme': sum(1 for rule in confirmed if rule.get('confidence') != 'High'),
+ 'depth': ', '.join(union((s.get('depth') or 'standard').split(', '), [n.get('depth') or 'standard'])),
+ 'agents': total('agents'),
+ 'consolidated': total('consolidated'),
+ 'modules': total('modules') - reruns,
+ 'batches': total('batches'),
+ 'skippedModules': union(names('skippedModules'), n.get('skippedModules')),
+ 'failedModules': union(names('failedModules'), n.get('failedModules')),
+ 'droppedModules': union([d for d in s.get('droppedModules') or [] if str(d).rsplit(': ', 1)[0] not in attempted], n.get('droppedModules')),
+ 'skippedPhases': union([p for p in s.get('skippedPhases') or [] if still_true(str(p))], n.get('skippedPhases')),
+ }
+ for field in ('maxAgents', 'estimate'): # these describe one run
+ merged['stats'].pop(field, None)
+ return merged, {'kept': len(kept), 'added': len(added), 'left out': len(new_rules) - len(added)}
+
+
+def main(argv):
+ args = list(argv[1:])
+ workspace = '.'
+ if '--workspace' in args:
+ at = args.index('--workspace')
+ workspace = args[at + 1] if at + 1 < len(args) else '.'
+ del args[at:at + 2]
+ if len(args) != 2:
+ print('usage: merge_rules.py <system> <new-result.json> [--workspace DIR]', file=sys.stderr)
+ return 2
+ system, new_path = args
+ saved_path = os.path.join(workspace, 'analysis', system, 'rules_result.json')
+ results = []
+ for path in (saved_path, new_path):
+ try:
+ with open(path, encoding='utf-8') as handle:
+ results.append(json.load(handle))
+ except (OSError, ValueError) as error:
+ print(f'Cannot read {path}: {error}. Nothing was merged.', file=sys.stderr)
+ return 1
+ if not isinstance(results[-1], dict) or not isinstance(results[-1].get('confirmedRules'), list):
+ print(f'{path} is not an extract-rules result (no confirmedRules list). Nothing was merged.', file=sys.stderr)
+ return 1
+ merged, counts = merge(system, *results)
+ tmp = saved_path + '.tmp'
+ with open(tmp, 'w', encoding='utf-8') as handle:
+ json.dump(merged, handle, indent=1)
+ os.replace(tmp, saved_path)
+ os.replace(new_path, new_path + '.merged')
+ print(f"merged: {counts['kept']} saved rules kept, {counts['added']} added"
+ + (f", {counts['left out']} left out (they cite lines a kept rule already covers)" if counts['left out'] else '')
+ + f"; {len(merged['unverifiedRules'])} unverified, {len(merged['rerunModules'])} shard(s) left to run; "
+ f"{merged['stats']['agents']} agents used in all")
+ 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
index 6f04e0c1..d04e1d6f 100644
--- a/plugins/code-modernization/scripts/render_rules.py
+++ b/plugins/code-modernization/scripts/render_rules.py
@@ -116,7 +116,9 @@ def main(argv):
f"At extraction: {len(rules)} confirmed rules ({sum(1 for r in rules if r.get('priority') == 'P0')} P0); "
f"later steps may add or correct rules below. "
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.", '',
+ f"{len(result.get('rejectedRules') or [])} candidate rules were refuted and left out."
+ + (f" Extraction depth: {one_line(stats['depth'], 40)}; {stats.get('agents')} agents." if stats.get('depth') else '')
+ + (f" Estimated before the run: {one_line(stats['estimate'], 400)}." if stats.get('estimate') else ''), '',
'| 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)} | "
@@ -156,17 +158,17 @@ def main(argv):
doc.append(f'- … and {len(folded) - 100} more')
doc.append('')
- gaps = [('never attempted (token budget or agent cap)', stats.get('skippedModules')),
+ gaps = [('never attempted (token budget or agent limit)', 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:
+ if gaps or result.get('rerunModules'):
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 ''))
+ doc.append(f"- **{len(items)} {label}:** " + ', '.join(one_line(i, 250) 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('')
diff --git a/plugins/code-modernization/scripts/tests/test_extract_workflow.py b/plugins/code-modernization/scripts/tests/test_extract_workflow.py
index 063a5749..73394c58 100644
--- a/plugins/code-modernization/scripts/tests/test_extract_workflow.py
+++ b/plugins/code-modernization/scripts/tests/test_extract_workflow.py
@@ -1,6 +1,8 @@
"""Runs workflows/extract-rules.js under node with scripted agents in place of the model."""
+import itertools
import json
import os
+import re
import shutil
import subprocess
import unittest
@@ -8,7 +10,7 @@ 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.
+# Extractors return the next entry of `extracts`, or with `byModule` the entry of their module (null: the extractor dies). Referees confirm unless `verdicts` has the cited source.
# P0 judges agree unless `notP0` has the cited source.
HARNESS = r"""
const fs = require('fs')
@@ -17,8 +19,16 @@ const source = fs.readFileSync(process.argv[1], 'utf8').replace('export const me
const cited = prompt => /Citation[^\n]*<<<UNTRUSTED\n([^\n]*)/.exec(prompt)[1]
let next = 0
const prompts = []
+const calls = []
const agent = async (prompt, o) => {
+ calls.push(`${o.label}\n${prompt}`)
+ // The later an agent starts, the sooner it ends: completion order must not matter.
+ if (spec.shuffle) await new Promise(done => setTimeout(done, Math.max(0, 40 - calls.length % 40)))
if (o.phase === 'Extract') prompts.push(prompt)
+ if (o.phase === 'Extract' && spec.byModule) {
+ const rules = spec.byModule[/\(module ([^,)]*)/.exec(prompt)[1]]
+ return rules === null ? null : { rules: rules || [], coveredAreas: [] }
+ }
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' }
@@ -28,7 +38,7 @@ const agent = async (prompt, o) => {
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 })))
+ .then(result => console.log(JSON.stringify({ ...result, prompts, calls })))
"""
@@ -37,10 +47,11 @@ def rule(name, source, priority='P1'):
'given': 'g', 'when': 'w', 'then': 't', 'confidence': 'High'}
-def extract(extracts, modules=1, **spec):
+def extract(extracts, modules=1, args=None, **spec):
+ """Module mode with `modules` (a number, or the list), lens mode with modules=None."""
if isinstance(modules, int):
modules = [{'name': f'm{i}', 'files': ['a.sql']} for i in range(modules)]
- args = {'system': 's', 'modules': modules}
+ args = {'system': 's', **({'modules': modules} if modules else {}), **(args or {})}
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:
@@ -52,8 +63,149 @@ def sources(result):
return [r['source'] for r in result['confirmedRules']]
+# What extractors were told before 1.2.0, word for word.
+STANDARD = (
+ 'How fine to cut rules: one rule per business decision or calculation, not one per branch, case, field or line. Group cases that share one '
+ 'decision into a single rule and list them in edgeCases. Skip plumbing (argument parsing, formatting a value for display, loops that only walk '
+ 'a list). Write the rules a domain expert would put on a one-page specification of this code: usually one rule per 40 to 80 lines of real '
+ "logic, fewer for boilerplate. Rate P0 only for the few rules that would defeat the system's purpose if they were wrong; if more than one in "
+ 'four of your rules is P0, re-rate the rest.')
+THOROUGH = ('There is no target number of rules', 'every business condition, threshold, rate and outcome must appear in some rule')
+
+
+@unittest.skipUnless(shutil.which('node'), 'needs node')
+class DepthTests(unittest.TestCase):
+ def test_standard_is_the_default_and_keeps_the_old_wording(self):
+ for modules in (1, None):
+ default = extract([], modules=modules)
+ self.assertEqual(default['stats']['depth'], 'standard')
+ self.assertEqual(default['prompts'], extract([], modules=modules, args={'depth': 'standard'})['prompts'])
+ for prompt in default['prompts']:
+ # Nothing was added before the wording either: the line above it is the one it has always followed.
+ self.assertIn('state-transition logic over plumbing.\n' + STANDARD + '\n', prompt)
+ for text in THOROUGH + ('to its last line',):
+ self.assertNotIn(text, prompt)
+
+ def test_thorough_has_no_target(self):
+ for modules in (1, None):
+ result = extract([], modules=modules, args={'depth': 'thorough'})
+ self.assertEqual(result['stats']['depth'], 'thorough')
+ for prompt in result['prompts']:
+ for text in THOROUGH + ('to its last line',):
+ self.assertIn(text, prompt)
+ self.assertNotIn('40 to 80 lines', prompt)
+
+ def test_a_part_of_a_long_file_is_mined_at_the_chosen_depth(self):
+ modules = [{'name': 'a', 'files': ['a.sql'], 'lines': [1, 900]}]
+ for depth, text in (('standard', STANDARD), ('thorough', THOROUGH[0])):
+ prompt = extract([], modules=modules, args={'depth': depth})['prompts'][0]
+ self.assertIn('lines 1 to 900', prompt)
+ self.assertIn(text, prompt)
+
+ def test_the_estimate_is_returned_and_reaches_no_agent(self):
+ for modules in (1, None):
+ result = extract([[rule('A', 'a.sql:1', 'P0')]], modules=modules, args={'estimate': 'Standard 20 to 100;\n Thorough 20 to 150'})
+ self.assertEqual(result['stats']['estimate'], 'Standard 20 to 100; Thorough 20 to 150')
+ self.assertNotIn('Thorough 20 to 150', ''.join(result['calls']))
+
+ def test_an_unknown_depth_is_an_error(self):
+ for modules in (1, None):
+ for depth in ('deep', 'Thorough', '', 2, ['thorough']):
+ with self.assertRaisesRegex(AssertionError, 'must be "standard" or "thorough"'):
+ extract([], modules=modules, args={'depth': depth})
+
+
+def shards(*rules_per_shard, p0_every=5):
+ """The module list and what each module's extractor returns."""
+ modules = [{'name': f'm{m}', 'files': [f'f{m}.sql']} for m in range(len(rules_per_shard))]
+ found = {f'm{m}': n if n is None else [rule(f'R{m}-{i}', f'f{m}.sql:{i + 1}', 'P1' if i % p0_every else 'P0') for i in range(n)]
+ for m, n in enumerate(rules_per_shard)}
+ return modules, found
+
+
+@unittest.skipUnless(shutil.which('node'), 'needs node')
+class ApprovedLimitTests(unittest.TestCase):
+ SHAPES = {'light': [2] * 12, 'typical': [8] * 30, 'dense': [95] * 6, 'one dense': [120], 'mixed': [3, 60, 0, None, 8, 90, 1, 30],
+ 'empty': [0] * 5}
+
+ def test_no_phase_goes_past_the_limit(self):
+ for limit in (20, 23, 60, 333):
+ for shape, counts in self.SHAPES.items():
+ for depth in ('standard', 'thorough'):
+ for p0_every in (1, 5):
+ with self.subTest(limit=limit, shape=shape, depth=depth, p0_every=p0_every):
+ modules, found = shards(*counts, p0_every=p0_every)
+ result = extract([], modules=modules, byModule=found, args={'maxAgents': limit, 'depth': depth})
+ self.assertLessEqual(len(result['calls']), limit)
+ self.assertEqual(len(result['calls']), result['stats']['agents'])
+ # Nothing is lost without a word: every shard is either done or listed, every candidate confirmed or unverified.
+ self.assertEqual(sorted(m['name'] for m in result['coveredModules'] + result['rerunModules']), sorted(m['name'] for m in modules))
+ ran = [m['name'] for m in modules if m['name'] not in result['stats']['skippedModules']]
+ self.assertEqual(len(result['confirmedRules']) + len(result['unverifiedRules']), sum(len(found[m] or []) for m in ran))
+ self.assertTrue(ran)
+
+ def test_lens_mode_keeps_to_the_limit(self):
+ for limit in (20, 25, 40, 100):
+ for n in (0, 4, 40):
+ found = [[rule(f'R{r}-{i}', f'f{r}.sql:{i + 1}', 'P0') for i in range(n)] for r in range(24)]
+ result = extract(found, modules=None, args={'maxAgents': limit, 'maxRounds': 8})
+ self.assertLessEqual(len(result['calls']), limit)
+ self.assertEqual(len(result['calls']), result['stats']['agents'])
+ self.assertGreaterEqual(len(result['prompts']), 3)
+
+ def test_the_approved_limit_is_named_where_it_cut_the_run(self):
+ modules, found = shards(*[30] * 5, p0_every=1)
+ result = extract([], modules=modules, byModule=found, args={'maxAgents': 60})
+ for reason in [r['unverifiedReason'] for r in result['unverifiedRules']] + result['stats']['skippedPhases']:
+ self.assertIn('the approved limit of 60 agents', reason)
+ self.assertTrue(result['stats']['skippedModules'])
+ self.assertTrue(any('extraction stopped with' in phase for phase in result['stats']['skippedPhases']))
+ self.assertEqual(result['stats']['maxAgents'], 60)
+
+ def test_without_a_lower_limit_the_runtime_cap_is_named(self):
+ modules, found = shards(*[95] * 20)
+ for limit in ({}, {'maxAgents': 5000}):
+ result = extract([], modules=modules, byModule=found, args=limit)
+ self.assertLessEqual(len(result['calls']), 1000)
+ self.assertIn('the runtime cap of 1000 agents', result['stats']['skippedPhases'][0])
+ self.assertEqual(result['stats']['maxAgents'], limit.get('maxAgents'))
+
+ def test_a_limit_that_is_no_number_of_agents_is_an_error(self):
+ for limit in (0, 19, -40, 40.5, '200', True, [200]):
+ with self.assertRaisesRegex(AssertionError, 'must be a whole number of at least 20'):
+ extract([], args={'maxAgents': limit})
+
+ def test_agents_start_in_the_same_order_every_time(self):
+ modules, found = shards(3, 60, 0, None, 8, 90, 1, 30, 12, 12)
+ for args in ({}, {'maxAgents': 120}, {'maxAgents': 60, 'depth': 'thorough'}):
+ first = extract([], modules=modules, byModule=found, args=args)['calls']
+ self.assertEqual(extract([], modules=modules, byModule=found, args=args, shuffle=True)['calls'], first)
+
+
@unittest.skipUnless(shutil.which('node'), 'needs node')
class AgentCapTests(unittest.TestCase):
+ def test_dense_shards_after_light_ones_are_not_extracted_past_the_cap(self):
+ for counts in ([2] * 40 + [95] * 16, [2] * 25 + [95] * 16 + [2] * 15, [95] * 16 + [2] * 40):
+ modules, found = shards(*counts)
+ result = extract([], modules=modules, byModule=found)
+ self.assertLessEqual(result['stats']['agents'], 1000)
+ self.assertEqual(result['unverifiedRules'], [])
+ self.assertGreater(len(result['confirmedRules']), 500)
+
+ def test_dense_shards_found_late_overshoot_by_less_than_one_shard(self):
+ for counts, args in (([8] * 60 + [95] * 10, {}), ([5] * 40 + [120] * 9 + [5], {'maxAgents': 600}), ([8] * 30 + [95] * 6 + [8] * 30, {'maxAgents': 500})):
+ modules, found = shards(*counts)
+ result = extract([], modules=modules, byModule=found, args=args)
+ self.assertLess(len(result['unverifiedRules']), max(counts))
+ self.assertGreater(len(result['confirmedRules']), 200)
+
+ def test_every_batch_is_spread_over_the_list(self):
+ modules, found = shards(*[1] * 60)
+ order = [int(re.search(r'module m(\d+)', prompt).group(1)) for prompt in extract([], modules=modules, byModule=found)['prompts']]
+ self.assertEqual(sorted(order), list(range(60)))
+ for batch in [order[:4]] + [order[i:i + 8] for i in range(4, 60, 8)]:
+ self.assertEqual({m // 20 for m in batch}, {0, 1, 2}, batch)
+
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)
@@ -98,6 +250,56 @@ class DuplicateTests(unittest.TestCase):
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_citations_swapped_by_their_referees_keep_both_rules(self):
+ verdicts = {'a.sql:10-20': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:500-510'},
+ 'a.sql:500-510': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:10-20'}}
+ result = extract([[rule('Cap', 'a.sql:10-20'), rule('Cap', 'a.sql:500-510')]], verdicts=verdicts)
+ self.assertEqual(sources(result), ['a.sql:500-510', 'a.sql:10-20'])
+
+ def test_a_rule_corrected_onto_a_refuted_one_is_kept(self):
+ verdicts = {'a.sql:10-20': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:500-510'},
+ 'a.sql:500-510': {'verdict': 'refuted', 'reason': 'r'}}
+ result = extract([[rule('Cap', 'a.sql:10-20'), rule('Cap', 'a.sql:500-510')]], verdicts=verdicts)
+ self.assertEqual(sources(result), ['a.sql:500-510'])
+
+ def test_a_rule_corrected_onto_lines_another_was_corrected_away_from_is_kept(self):
+ verdicts = {'a.sql:10-20': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:500-510'},
+ 'a.sql:500-510': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:900-910'}}
+ for rules in itertools.permutations([rule('Cap', 'a.sql:10-20'), rule('Cap', 'a.sql:500-510')]):
+ self.assertEqual(sorted(sources(extract([list(rules)], verdicts=verdicts))), ['a.sql:500-510', 'a.sql:900-910'])
+
+ def test_rules_corrected_onto_one_place_are_one_rule_in_any_order(self):
+ at = {'a.sql:10-20': 'a.sql:300-310', 'a.sql:500-510': 'a.sql:305-320', 'a.sql:700-710': 'a.sql:318-330'}
+ verdicts = {src: {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': to} for src, to in at.items()}
+ for rules in itertools.permutations([rule('Cap', src) for src in at]):
+ result = extract([list(rules)], verdicts=verdicts)
+ self.assertEqual(sorted(sources(result)), ['a.sql:300-310', 'a.sql:318-330'])
+ self.assertEqual(len(result['rejectedRules']), 1)
+
+ def test_a_bare_file_name_hides_no_rule_whose_lines_are_known(self):
+ def corrected(**to):
+ return {f'{src}.sql:{line}': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': at} for (src, line), at in
+ ((key.split('_')[:2], at) for key, at in to.items())}
+ for rules in itertools.permutations([rule('Cap', 'a.sql:10'), rule('Cap', 'a.sql:500')]):
+ result = extract([list(rules)], verdicts=corrected(a_10='a.sql', a_500='a.sql:10-18'))
+ self.assertEqual(sorted(sources(result)), ['a.sql', 'a.sql:10-18'])
+ for rules in itertools.permutations([rule('Cap', 'a.sql:1'), rule('Cap', 'c.sql:2'), rule('Cap', 'd.sql:3')]):
+ result = extract([list(rules)], verdicts=corrected(a_1='b.sql', c_2='b.sql:5', d_3='b.sql:500'))
+ self.assertEqual(sorted(sources(result)), ['b.sql:5', 'b.sql:500'])
+ self.assertEqual(len(extract([list(rules)], verdicts=corrected(a_1='b.sql', c_2='b.sql', d_3='b.sql'))['confirmedRules']), 1)
+
+ def test_a_citation_corrected_to_a_workspace_path_is_the_same_place(self):
+ moved = {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'legacy/s/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'])
+
+ def test_a_duplicate_moved_off_its_lines_does_not_block_a_rule_there(self):
+ moved = {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:500-510'}
+ other = {'verdict': 'confirmed', 'reason': 'ok'}
+ result = extract([[rule('Cap', 'a.sql:500-510'), rule('Cap', 'a.sql:10-20')], [], [], [], [rule('Cap', 'a.sql:12-18')]],
+ modules=5, verdicts={'a.sql:10-20': moved, 'a.sql:12-18': other})
+ self.assertEqual(sources(result), ['a.sql:500-510', 'a.sql:12-18'])
+
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'])
@@ -122,6 +324,12 @@ class LineRangeTests(unittest.TestCase):
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_the_shard_that_returned_an_unjudged_rule_is_run_again(self):
+ modules = [{'name': 'app/lib', 'files': ['app/lib/tax.c']}, {'name': 'lib', 'files': ['lib/tax.c']}]
+ for source, expected in (('lib/tax.c:5', ['lib']), ('tax.c:5', ['app/lib', 'lib']), ('lib\\tax.c:5', ['lib']), ('other.c:5', ['lib'])):
+ result = extract([], modules=modules, byModule={'lib': [rule('A', source)]}, verdicts={source: None})
+ self.assertEqual([m['name'] for m in result['rerunModules']], expected, source)
+
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'])
diff --git a/plugins/code-modernization/scripts/tests/test_merge_rules.py b/plugins/code-modernization/scripts/tests/test_merge_rules.py
new file mode 100644
index 00000000..0ec5c6e4
--- /dev/null
+++ b/plugins/code-modernization/scripts/tests/test_merge_rules.py
@@ -0,0 +1,171 @@
+import json
+import os
+import shutil
+import sys
+import tempfile
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from test_extract_workflow import extract, rule, shards # noqa: E402
+from test_rules_tools import load, run, write # noqa: E402
+
+A, B = {'name': 'A', 'files': ['a.sql']}, {'name': 'B', 'files': ['b.sql']}
+
+
+def result(confirmed=(), covered=(), rerun=(), unverified=(), **more):
+ stats = {'agents': 10, 'modules': len(covered) + len(rerun), 'batches': 1, 'depth': 'standard', 'skippedModules': [], 'failedModules': [],
+ 'droppedModules': [], 'skippedPhases': [], **more.pop('stats', {})}
+ return {'system': 's', 'mode': 'modules', 'confirmedRules': list(confirmed), 'coveredModules': list(covered), 'rerunModules': list(rerun),
+ 'unverifiedRules': list(unverified), 'rejectedRules': [], 'foldedRules': [], 'dataObjects': [], 'injectionFlags': [], 'stats': stats, **more}
+
+
+class MergeTests(unittest.TestCase):
+ def merge(self, saved, new):
+ with tempfile.TemporaryDirectory() as ws:
+ write(ws, 'analysis/s/rules_result.json', json.dumps(saved))
+ write(ws, 'new.json', json.dumps(new))
+ done = run('merge_rules.py', 's', os.path.join(ws, 'new.json'), '--workspace', ws)
+ self.assertEqual(done.returncode, 0, done.stderr)
+ self.assertFalse(os.path.exists(os.path.join(ws, 'new.json')), 'a merged file is not merged twice')
+ merged = load(os.path.join(ws, 'analysis/s/rules_result.json'))
+ 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.text = handle.read()
+ return merged
+
+ def names(self, merged, field='confirmedRules'):
+ return [r['name'] for r in merged[field]]
+
+ def test_a_shard_extracted_and_judged_in_full_replaces_its_saved_rules(self):
+ saved = result([rule('Old', 'legacy/s/a.sql:1-5'), rule('Other', 'b.sql:1')], [B], [A], [rule('Open', 'a.sql:9')])
+ merged = self.merge(saved, result([rule('New', 'a.sql:1-5'), rule('New 2', 'a.sql:9-12')], [A]))
+ self.assertEqual(self.names(merged), ['Other', 'New', 'New 2'])
+ self.assertEqual((merged['unverifiedRules'], merged['rerunModules']), ([], []))
+ self.assertEqual((merged['stats']['confirmed'], merged['stats']['agents'], merged['stats']['modules']), (3, 20, 2))
+
+ def test_a_failed_re_run_keeps_every_saved_rule(self):
+ saved = result([rule('Old', 'a.sql:1-5')], [B], [A], [rule('Open', 'a.sql:9')])
+ merged = self.merge(saved, result([], [], [A], stats={'failedModules': ['A']}))
+ self.assertEqual((self.names(merged), self.names(merged, 'unverifiedRules'), merged['rerunModules']), (['Old'], ['Open'], [A]))
+ self.assertEqual(merged['stats']['failedModules'], ['A'])
+
+ def test_a_capped_re_run_adds_only_rules_at_other_lines(self):
+ saved = result([rule('Old', 'a.sql:1-5')], [], [A], [rule('Open', 'a.sql:9'), rule('Far', 'a.sql:80')])
+ new = result([rule('Old, renamed', 'a.sql:2-6'), rule('Added', 'a.sql:9-12')], [], [A], [rule('Old', 'a.sql:1-5'), rule('Cut', 'a.sql:40')])
+ merged = self.merge(saved, new)
+ self.assertEqual(self.names(merged), ['Old', 'Added'])
+ self.assertEqual(self.names(merged, 'unverifiedRules'), ['Far', 'Cut']) # a confirmed rule never becomes unverified
+ self.assertEqual(merged['rerunModules'], [A])
+
+ def test_a_re_run_that_found_fewer_rules_replaces_nothing(self):
+ saved = result([rule(f'Old {i}', f'a.sql:{10 * i + 1}') for i in range(4)], [], [A], [rule('Open', 'a.sql:99')])
+ merged = self.merge(saved, result([rule('New', 'a.sql:1'), rule('More', 'a.sql:70')], [A]))
+ self.assertEqual(self.names(merged), ['Old 0', 'Old 1', 'Old 2', 'Old 3', 'More'])
+ self.assertEqual((merged['rerunModules'], self.names(merged, 'unverifiedRules')), ([], ['Open']))
+ self.assertEqual(self.names(self.merge(saved, result([], [A]))), ['Old 0', 'Old 1', 'Old 2', 'Old 3'])
+
+ def test_a_new_rule_that_is_left_out_does_not_count_for_a_replacement(self):
+ part = {'name': 'a:901-1800', 'files': ['a.sql'], 'lines': [901, 1800]}
+ saved = result([rule('First', 'a.sql:895-905'), rule('Old', 'a.sql:950')], [], [part])
+ self.assertEqual(self.names(self.merge(saved, result([rule('First', 'a.sql:901-905')], [part]))), ['First', 'Old'])
+ saved = result([rule('Cap', 'a.sql:1-5'), rule('Floor', 'b.sql:1-9'), rule('Ceil', 'b.sql:50'), rule('Round', 'b.sql:90')], [], [A, B])
+ merged = self.merge(saved, result([rule('Cap limit', 'b.sql:2-6 ; also a.sql:1-5')], [A, B]))
+ self.assertEqual(self.names(merged), ['Cap', 'Floor', 'Ceil', 'Round'])
+
+ def test_a_candidate_stays_listed_until_the_new_run_judges_its_lines(self):
+ saved = result([], [], [A], [rule('Refuted', 'a.sql:5'), rule('Confirmed', 'a.sql:20-30'), rule('Missed', 'a.sql:60')])
+ merged = self.merge(saved, result([rule('Renamed', 'a.sql:25')], [A], rejectedRules=[rule('Other', 'a.sql:4-6')]))
+ self.assertEqual((self.names(merged), self.names(merged, 'unverifiedRules')), (['Renamed'], ['Missed']))
+ self.assertIn('Missed (a.sql:60)', self.text)
+
+ def test_shards_still_to_run_are_shown_when_nothing_else_is_open(self):
+ merged = self.merge(result([rule('Old', 'a.sql:1-5')], [], [A], [rule('Open', 'a.sql:9')]), result([rule('New', 'a.sql:9')], [], [A], [rule('Old', 'a.sql:1-5')]))
+ self.assertEqual(merged['unverifiedRules'], [])
+ self.assertIn('follow-up run for the 1 affected shard(s)', self.text)
+
+ def test_a_citation_in_code_that_was_not_run_again_survives(self):
+ saved = result([rule('Cap', 'a.sql:1-5 ; also b.sql:7-9 ; also a.sql:30 ; also c.sql:2')], [B], [A],
+ foldedRules=[{'name': 'Cap (b)', 'source': 'b.sql:7-9', 'into': 'Cap'}, {'name': 'Cap (c)', 'source': 'c.sql:2', 'into': 'Cap'}])
+ merged = self.merge(saved, result([rule('Limit', 'a.sql:1-5'), rule('Limit 2', 'a.sql:30')], [A]))
+ self.assertEqual([r['source'] for r in merged['confirmedRules']], ['b.sql:7-9 ; also c.sql:2', 'a.sql:1-5', 'a.sql:30'])
+ self.assertEqual([f['name'] for f in merged['foldedRules']], ['Cap (c)'])
+ self.assertIn('**Source:** `b.sql:7-9`\n**Also cited:** c.sql:2', self.text)
+
+ def test_only_the_lines_that_were_run_again_are_replaced(self):
+ part = {'name': 'a:901-1800', 'files': ['a.sql'], 'lines': [901, 1800]}
+ saved = result([rule('First', 'a.sql:895-905'), rule('Old', 'a.sql:901'), rule('Whole', 'a.sql')], [], [part])
+ merged = self.merge(saved, result([rule('New', 'a.sql:901-902'), rule('First', 'a.sql:899-903')], [part]))
+ self.assertEqual(self.names(merged), ['First', 'Whole', 'New'])
+
+ def test_gaps_the_new_run_did_not_close_are_kept(self):
+ c = {'name': 'C', 'files': ['c.sql']}
+ saved = result([rule('Old', 'a.sql:1')], [], [A, B, c], [rule('Open', 'b.sql:3')], injectionFlags=['a.sql:5'], dataObjects=[],
+ stats={'skippedModules': ['A', 'C'], 'failedModules': ['B'], 'droppedModules': ['#4: missing or empty name', 'A: no usable files'],
+ 'skippedPhases': ['P0 panel ran for 1 of 3 P0 rules (x)', 'DTO catalog not run (x)', 'extraction stopped with 2 of 3 modules left: x']})
+ new = result([rule('New', 'a.sql:1')], [A], [], injectionFlags=['a.sql:5', 'c.sql:8'],
+ dataObjects=[{'name': 'Account', 'source': 'a.sql:1', 'fields': []}], stats={'skippedPhases': ['P0 panel ran for 2 of 4 P0 rules (x)']})
+ merged = self.merge(saved, new)
+ stats = merged['stats']
+ self.assertEqual(merged['rerunModules'], [B, c])
+ self.assertEqual((stats['skippedModules'], stats['failedModules'], stats['droppedModules']), (['C'], ['B'], ['#4: missing or empty name']))
+ self.assertEqual(stats['skippedPhases'], ['P0 panel ran for 1 of 3 P0 rules (x)', 'extraction stopped with 2 of 3 modules left: x',
+ 'P0 panel ran for 2 of 4 P0 rules (x)'])
+ self.assertEqual(merged['injectionFlags'], ['a.sql:5', 'c.sql:8'])
+ self.assertEqual(self.names(merged, 'unverifiedRules'), ['Open'])
+ text = self.text
+ again = self.merge(merged, result([], [], [B, c], stats={'skippedModules': ['B', 'C'], 'skippedPhases': ['extraction stopped with 2 of 2 modules left: y']}))
+ self.assertEqual([p for p in again['stats']['skippedPhases'] if p.startswith('extraction')], ['extraction stopped with 2 of 2 modules left: y'])
+ self.assertEqual(again['stats']['skippedModules'], ['B', 'C'])
+ for shown in ('P0 panel ran for 1 of 3', 'missing or empty name', 'c.sql:8'):
+ self.assertIn(shown, text)
+
+ def test_the_parts_of_a_large_job_add_up(self):
+ saved = result([rule('One', 'a.sql:1-5')], [A], dataObjects=[{'name': 'Account', 'source': 'a.sql:1', 'fields': [], 'consumedBy': ['One']}])
+ new = result([rule('One', 'a.sql:3'), rule('Two', 'b.sql:3')], [B], stats={'depth': 'thorough'},
+ dataObjects=[{'name': 'account', 'source': 'legacy/s/a.sql:1-20', 'fields': [{'name': 'id', 'type': 'int'}], 'consumedBy': ['Two']}])
+ merged = self.merge(saved, new)
+ self.assertEqual(self.names(merged), ['One', 'Two'])
+ self.assertEqual([(len(o['fields']), o['consumedBy']) for o in merged['dataObjects']], [(1, ['One', 'Two'])])
+ self.assertEqual((merged['stats']['modules'], merged['stats']['depth']), (2, 'standard, thorough'))
+ self.assertEqual(self.merge(merged, result(stats={'depth': 'thorough'}))['stats']['depth'], 'standard, thorough')
+
+ def test_a_whole_system_run_that_was_cut_is_finished_shard_by_shard(self):
+ saved = result([rule('Old', 'a.sql:1'), rule('Extra', 'z.inc:4')], unverified=[rule('Open', 'a.sql:9')], mode='lenses')
+ merged = self.merge(saved, result([rule('New', 'a.sql:1'), rule('New 2', 'a.sql:9')], [A]))
+ self.assertEqual((self.names(merged), merged['unverifiedRules']), (['Extra', 'New', 'New 2'], []))
+
+ def test_names_are_compared_as_the_workflow_compares_them(self):
+ saved = result([rule('Fee > 100', 'a.sql:1-9'), rule('金額', 'a.sql')], [B])
+ merged = self.merge(saved, result([rule('fee > 100!', 'b.sql:1'), rule('FEE (> 100)', 'a.sql'), rule('Fee < 100', 'a.sql'), rule('数量', 'a.sql')], [B]))
+ self.assertEqual(self.names(merged), ['Fee > 100', '金額', 'fee > 100!', 'Fee < 100', '数量'])
+
+ def test_a_bad_file_changes_nothing(self):
+ with tempfile.TemporaryDirectory() as ws:
+ write(ws, 'analysis/s/rules_result.json', json.dumps(result([rule('Old', 'a.sql:1')])))
+ for text in ('not json', '[]', '{"rules": []}'):
+ write(ws, 'new.json', text)
+ self.assertEqual(run('merge_rules.py', 's', os.path.join(ws, 'new.json'), '--workspace', ws).returncode, 1)
+ self.assertEqual(run('merge_rules.py', 's', os.path.join(ws, 'missing.json'), '--workspace', ws).returncode, 1)
+ self.assertEqual(run('merge_rules.py', 's').returncode, 2)
+ self.assertEqual(load(os.path.join(ws, 'analysis/s/rules_result.json'))['confirmedRules'][0]['name'], 'Old')
+
+ @unittest.skipUnless(shutil.which('node'), 'needs node')
+ def test_follow_ups_of_a_limited_run_finish_the_system(self):
+ modules, found = shards(12, 20, 3, 40, 8, 25, 0, 9)
+ saved = extract([], modules=modules, byModule=found, args={'maxAgents': 60})
+ agents = len(saved['calls'])
+ for _ in range(12):
+ if not saved['rerunModules']:
+ break
+ before = {(r['name'], r['source']) for r in saved['confirmedRules']}
+ new = extract([], modules=saved['rerunModules'], byModule=found, args={'maxAgents': 90})
+ agents += len(new['calls'])
+ saved = self.merge(saved, new)
+ self.assertLessEqual(before, {(r['name'], r['source']) for r in saved['confirmedRules']})
+ self.assertEqual((saved['rerunModules'], saved['unverifiedRules']), ([], []))
+ self.assertEqual(sorted(self.names(saved)), sorted(r['name'] for rules in found.values() for r in rules))
+ self.assertEqual((saved['stats']['agents'], saved['stats']['modules'], saved['stats']['skippedModules']), (agents, 8, []))
+
+
+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 80590b0a..7ff5af6c 100644
--- a/plugins/code-modernization/scripts/tests/test_rules_tools.py
+++ b/plugins/code-modernization/scripts/tests/test_rules_tools.py
@@ -222,6 +222,29 @@ class ShardTests(unittest.TestCase):
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)
@@ -296,6 +319,14 @@ class RenderTests(unittest.TestCase):
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)