File indexing completed on 2026-12-02 10:29:02
0001
0002 """Correct a registered AI assessment's text in place, keeping its history.
0003
0004 A scheduled assessment states what was true when it ran; a statement
0005 overtaken later the same day (a fix "still waiting" that was installed an
0006 hour later) stays on the report page and on the dashboard, which reads the
0007 narration from the assessment's ``assessment_register`` record. This
0008 applies exact text replacements to both, so the report reads correctly
0009 where people read it:
0010
0011 - the corun-ai Page (``--group-id``) gets a new published version, the
0012 correction path corun keeps history for (``src/ai/corun_client.py``,
0013 ``create_version``): the Markdown content, ``data.narration`` and
0014 ``data.structured`` (its ``generation`` audit record excepted, which
0015 stays as the run left it), with ``--note`` inserted after the summary
0016 paragraph and the correction listed in ``data.corrections``;
0017 - the ``assessment_register`` record (``--record-id``) gets the same
0018 replacements in its ``narration``, with ``corrected_at`` and
0019 ``corrected_by``.
0020
0021 Every replacement must match the content at least once, or nothing is
0022 written. Replacements come from a JSON file: a list of ``[old, new]``
0023 pairs. Assessments are otherwise append-only (swf-epicprod
0024 docs/EPICPROD_OPS.md, AI assessments); this is for a report's own text,
0025 on the operator's word.
0026
0027 By hand (docs/SCRIPTS.md):
0028
0029 cd /data/wenauseic/github/swf-monitor/src
0030 ../../swf-testbed/.venv/bin/python ../scripts/assessment-correct.py \\
0031 --group-id <corun page group> --record-id <AppLog id> \\
0032 --replacements fixes.json --note '**Corrected ...**' --by swf-1 \\
0033 [--dry-run]
0034 """
0035 import argparse
0036 import copy
0037 import json
0038 import logging
0039 import os
0040 import sys
0041 import time
0042
0043 THIS_DIR = os.path.dirname(os.path.abspath(__file__))
0044 sys.path.insert(0, os.path.join(THIS_DIR, '..', 'src'))
0045 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'swf_monitor_project.settings')
0046
0047 import django
0048 django.setup()
0049
0050 from ai.corun_client import CorunAPIError, CorunClient
0051 from monitor_app.epicprod_logging import log_epicprod_action
0052 from monitor_app.models import AppLog
0053
0054 log = logging.getLogger('assessment-correct')
0055
0056
0057 def _apply(text, pairs, counts):
0058 for i, (old, new) in enumerate(pairs):
0059 n = text.count(old)
0060 if n:
0061 counts[i] += n
0062 text = text.replace(old, new)
0063 return text
0064
0065
0066 def _apply_tree(value, pairs, counts):
0067 if isinstance(value, str):
0068 return _apply(value, pairs, counts)
0069 if isinstance(value, list):
0070 return [_apply_tree(v, pairs, counts) for v in value]
0071 if isinstance(value, dict):
0072 return {k: (v if k == 'generation' else _apply_tree(v, pairs, counts))
0073 for k, v in value.items()}
0074 return value
0075
0076
0077 def _insert_note(content, note):
0078 """The note goes after the summary paragraph (its first blank line)."""
0079 lines = content.split('\n')
0080 for i, line in enumerate(lines):
0081 if line.startswith('**Summary:**'):
0082 return '\n'.join(lines[:i + 1] + ['', note] + lines[i + 1:])
0083 raise ValueError('no **Summary:** line to place the note after')
0084
0085
0086 def main():
0087 p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
0088 p.add_argument('--group-id', required=True)
0089 p.add_argument('--record-id', type=int, required=True)
0090 p.add_argument('--replacements', required=True)
0091 p.add_argument('--note', required=True)
0092 p.add_argument('--by', required=True)
0093 p.add_argument('--dry-run', action='store_true')
0094 a = p.parse_args()
0095 logging.basicConfig(level=logging.INFO, stream=sys.stderr)
0096
0097 with open(a.replacements) as f:
0098 pairs = [tuple(x) for x in json.load(f)]
0099 client = CorunClient()
0100 page = client.get_page(a.group_id)
0101 rec = AppLog.objects.get(id=a.record_id)
0102 extra = dict(rec.extra_data or {})
0103 if extra.get('corun_page_group_id') != a.group_id:
0104 raise SystemExit(f'record {a.record_id} is not this page\'s registration')
0105
0106 counts = [0] * len(pairs)
0107 content = _insert_note(_apply(page.get('content') or '', pairs, counts),
0108 a.note)
0109 data = page.get('data') or {}
0110 changed = {k: _apply_tree(copy.deepcopy(data[k]), pairs, counts)
0111 for k in ('narration', 'structured') if k in data}
0112 narration = _apply(extra.get('narration') or '', pairs, counts)
0113 missing = [old for (old, _new), n in zip(pairs, counts) if not n]
0114 if missing:
0115 raise SystemExit(f'not found, nothing written: {missing}')
0116 stamp = time.strftime('%Y-%m-%dT%H:%M:%S%z')
0117 changed['corrections'] = list(data.get('corrections') or []) + [
0118 {'at': stamp, 'by': a.by, 'note': a.note,
0119 'replacements': [list(x) for x in pairs]}]
0120
0121 summary = {'group_id': a.group_id, 'record_id': a.record_id,
0122 'matches': counts, 'dry_run': a.dry_run}
0123 if a.dry_run:
0124 log.info('content would read:\n%s', content)
0125 log.info('record narration would read: %s', narration)
0126 print(json.dumps(summary))
0127 return 0
0128 try:
0129 result = client.create_version(
0130 a.group_id, content=content, title=page.get('title', ''),
0131 status='published', data=changed)
0132 except CorunAPIError as exc:
0133 log_epicprod_action('mcp', 'assessment_corrected',
0134 subject_type='campaign',
0135 subject_key=extra.get('subject_key', ''),
0136 username=a.by, outcome='error', sublevel='normal',
0137 message=f'assessment correction failed: {exc}',
0138 level=logging.ERROR)
0139 log.error('corun version failed: %s', exc)
0140 return 1
0141 extra['narration'] = narration
0142 extra['corrected_at'] = stamp
0143 extra['corrected_by'] = a.by
0144 rec.extra_data = extra
0145 rec.save(update_fields=['extra_data'])
0146 summary['version'] = result.get('version')
0147 log_epicprod_action('mcp', 'assessment_corrected',
0148 subject_type='campaign',
0149 subject_key=extra.get('subject_key', ''),
0150 username=a.by, outcome='ok', sublevel='normal',
0151 message=(f'corrected {extra.get("report_title", a.group_id)}'
0152 f' to version {result.get("version")}'),
0153 corun_page_group_id=a.group_id,
0154 record_id=a.record_id, note=a.note)
0155 print(json.dumps(summary))
0156 return 0
0157
0158
0159 if __name__ == '__main__':
0160 sys.exit(main())