File indexing completed on 2026-12-02 10:29:05
0001
0002 """segfault-finding-append.py — add a reading to an existing segfault
0003 finding without re-sending its text: a paragraph appended to its reading
0004 (``what``), a dated line appended to its notes, signatures and sources
0005 added (each once), a sentence of the reading replaced where it is, and
0006 the title replaced. Writes through ``segfaults.set_finding``, so the
0007 finding keeps its version history and the write is an action on the
0008 stream (swf-epicprod docs/SEGFAULT_DIAGNOSIS.md, Findings). A new
0009 finding is written with the MCP tool ``panda_segfault_finding_set``.
0010
0011 Usage::
0012
0013 cd /data/wenauseic/github/swf-monitor/src
0014 source ~/.env
0015 /data/wenauseic/github/swf-testbed/.venv/bin/python \\
0016 ../scripts/segfault-finding-append.py --finding f-23 \\
0017 --paragraph-file reading.txt --notes-file notes.txt \\
0018 --add-signatures memory:task38538 memory:task38558 \\
0019 --add-source 'Signature memory:task38538' https://... \\
0020 --sources-file sources.json \\
0021 --replace-file replace.json --title '...' --by swf-1 [--apply]
0022
0023 ``--replace-file`` holds a JSON list of [old, new] pairs; each old text
0024 must occur exactly once in the reading. Dry run by default: the changes
0025 are printed and nothing is written.
0026 """
0027 import argparse
0028 import json
0029 import os
0030 import sys
0031
0032 THIS_DIR = os.path.dirname(os.path.abspath(__file__))
0033 sys.path.insert(0, os.path.join(THIS_DIR, '..', 'src'))
0034 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'swf_monitor_project.settings')
0035
0036 import django
0037 django.setup()
0038
0039 from monitor_app import segfaults
0040 from monitor_app.models import Entry
0041
0042
0043 def _read(path):
0044 with open(path, encoding='utf-8') as f:
0045 return f.read().strip()
0046
0047
0048 def _entry(ref):
0049 """The finding named ``ref``, or numbered by it (f-23 or 23)."""
0050 ctx = segfaults._finding_context()
0051 qs = Entry.objects.filter(kind=segfaults.FINDING_KIND, context=ctx)
0052 entry = qs.filter(name=ref).first()
0053 if entry is not None:
0054 return entry
0055 serial = ref[2:] if ref.lower().startswith('f-') else ref
0056 if serial.isdigit():
0057 for e in qs.only('name', 'data', 'content', 'title'):
0058 if int((e.data or {}).get('serial') or 0) == int(serial):
0059 return e
0060 sys.exit(f'no finding {ref!r}')
0061
0062
0063 def main():
0064 ap = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
0065 ap.add_argument('--finding', required=True, help='f-N, N or the finding name')
0066 ap.add_argument('--paragraph-file', help='a paragraph appended to the reading')
0067 ap.add_argument('--notes-file', help='a line appended to the notes')
0068 ap.add_argument('--add-signatures', nargs='*', default=[])
0069 ap.add_argument('--add-source', nargs=2, action='append', default=[],
0070 metavar=('LABEL', 'URL'))
0071 ap.add_argument('--sources-file', help='JSON [{"label": ..., "url": ...}, ...] added')
0072 ap.add_argument('--replace-file', help='JSON [[old, new], ...] in the reading')
0073 ap.add_argument('--title')
0074 ap.add_argument('--by', required=True, help='who writes (the version stamp)')
0075 ap.add_argument('--apply', action='store_true')
0076 args = ap.parse_args()
0077
0078 entry = _entry(args.finding)
0079 data = entry.data or {}
0080 fid = f"f-{data.get('serial')}"
0081 fields = {}
0082
0083 what = entry.content or ''
0084 if args.replace_file:
0085 for old, new in json.loads(_read(args.replace_file)):
0086 n = what.count(old)
0087 if n != 1:
0088 sys.exit(f'{fid}: replace text occurs {n} times, not once: {old[:80]!r}')
0089 what = what.replace(old, new)
0090 if args.paragraph_file:
0091 what = what.rstrip() + '\n\n' + _read(args.paragraph_file)
0092 if what != (entry.content or ''):
0093 fields['what'] = what
0094
0095 if args.notes_file:
0096 fields['notes'] = ((data.get('notes') or '').rstrip() + '\n\n' + _read(args.notes_file)).strip()
0097
0098 sigs = list(data.get('signatures') or [entry.name])
0099 added = [k for k in args.add_signatures if k not in sigs]
0100 if added:
0101 fields['signatures'] = sigs + added
0102
0103 sources = list(data.get('sources') or [])
0104 urls = {s.get('url') for s in sources}
0105 wanted = [{'label': label, 'url': url} for label, url in args.add_source]
0106 if args.sources_file:
0107 wanted += json.loads(_read(args.sources_file))
0108 new_sources = []
0109 for s in wanted:
0110 if s['url'] not in urls:
0111 urls.add(s['url'])
0112 new_sources.append({'label': s['label'], 'url': s['url']})
0113 if new_sources:
0114 fields['sources'] = sources + new_sources
0115
0116 if args.title and args.title != entry.title:
0117 fields['title'] = args.title
0118
0119 print(f'{fid} ({entry.name}): {", ".join(sorted(fields)) or "no change"}')
0120 if 'what' in fields:
0121 print(f' reading {len(entry.content or "")} -> {len(fields["what"])} chars')
0122 if added:
0123 print(f' signatures added: {added}')
0124 if new_sources:
0125 print(f' sources added: {[s["label"] for s in new_sources]}')
0126 if 'title' in fields:
0127 print(f' title: {fields["title"]}')
0128 if not fields:
0129 return 0
0130 if not args.apply:
0131 print('dry run: nothing written (--apply to write)')
0132 return 0
0133 segfaults.set_finding(entry.name, fields, changed_by=args.by)
0134 print('written')
0135 return 0
0136
0137
0138 if __name__ == '__main__':
0139 sys.exit(main())