Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-02 10:29:07

0001 """What's new: developments as versioned entry-store items (docs/WHATS_NEW.md).
0002 
0003 Every write to the What's new entries goes through this module: the pages,
0004 the REST API and the MCP tools call it, and nothing else writes them. Items are ``Entry`` rows of kind ``development``
0005 in the ``whats-new`` context; comments are ``comment`` entries whose parent
0006 is the item. The entry versioning signal (monitor_app/signals.py) keeps
0007 each substantive edit; votes are an operational key and are not versioned.
0008 """
0009 import re
0010 import time
0011 from datetime import date
0012 
0013 from django.db import transaction
0014 
0015 from monitor_app.models import Entry, EntryContext, EntryVersion
0016 from monitor_app.signals import set_changed_by
0017 
0018 CONTEXT = 'whats-new'
0019 KIND_ITEM = 'development'
0020 KIND_COMMENT = 'comment'
0021 IMPORTANCE = ('urgent', 'high', 'routine', 'minor')
0022 IMPORTANCE_LABELS = {
0023     'urgent': 'Urgent', 'high': 'High', 'routine': 'Routine', 'minor': 'Minor',
0024 }
0025 SUMMARY_MAX = 600
0026 _TAG_RE = re.compile(r'^[a-z0-9][a-z0-9-]*$')
0027 # Item fields a creation or an edit may set.
0028 FIELDS = ('title', 'summary', 'details', 'refs', 'tags', 'importance',
0029           'shipped', 'contact', 'builds_on')
0030 
0031 
0032 class WhatsNewError(Exception):
0033     """A refused write, with an HTTP-shaped status and a reader's message."""
0034 
0035     def __init__(self, detail, status=400):
0036         self.detail = detail
0037         self.status = status
0038         super().__init__(detail)
0039 
0040 
0041 def _today():
0042     from monitor_app.alarms_data import _today_eastern
0043     return _today_eastern()
0044 
0045 
0046 def _ensure_context():
0047     EntryContext.objects.get_or_create(
0048         name=CONTEXT,
0049         defaults={'title': "What's new",
0050                   'description': 'Developments in SWF that users, operators '
0051                                  'and developers should know about '
0052                                  '(docs/WHATS_NEW.md).'})
0053 
0054 
0055 def _items():
0056     return Entry.objects.filter(context_id=CONTEXT, kind=KIND_ITEM,
0057                                 deleted_at__isnull=True)
0058 
0059 
0060 def slug_for(title):
0061     """The URL slug a title gives: lowercase words joined by hyphens."""
0062     slug = re.sub(r'[^a-z0-9]+', '-', (title or '').strip().lower()).strip('-')
0063     return slug[:80].rstrip('-') or 'item'
0064 
0065 
0066 def get_entry(slug, *, include_archived=True):
0067     """The item entry with this slug, or None."""
0068     qs = _items().filter(data__entry_id=slug)
0069     if not include_archived:
0070         qs = qs.filter(archived=False)
0071     return qs.first()
0072 
0073 
0074 def _require(slug):
0075     entry = get_entry(slug)
0076     if entry is None:
0077         raise WhatsNewError(f'no What\'s new item {slug!r}', status=404)
0078     return entry
0079 
0080 
0081 def normalize_tags(raw):
0082     """Tags as a sorted list of lowercase hyphenated words; an importance
0083     level given as a tag is not a tag. Raises on a malformed tag."""
0084     if isinstance(raw, str):
0085         raw = re.split(r'[,\s]+', raw)
0086     tags = set()
0087     for t in raw or []:
0088         tag = re.sub(r'[\s_]+', '-', str(t).strip().lower()).strip('-')
0089         if not tag or tag in IMPORTANCE:
0090             continue
0091         if not _TAG_RE.match(tag) or len(tag) > 40:
0092             raise WhatsNewError(
0093                 f'tag {t!r}: a tag is lowercase letters, digits and hyphens')
0094         tags.add(tag)
0095     return sorted(tags)
0096 
0097 
0098 def contacts():
0099     """The accounts an item's contact may name: people known here who hold
0100     the operations role (docs/AUTHORITY.md), sorted."""
0101     from monitor_app.authority import all_authority, is_ops, may_act
0102     return sorted(u for u, record in all_authority().items()
0103                   if is_ops(record) and may_act(record))
0104 
0105 
0106 def _validate(fields, *, current=None, changed_by=''):
0107     """The item's data after applying ``fields`` to ``current`` (None for
0108     a new item). Every rule an item obeys is checked here."""
0109     cur = dict(current or {})
0110     out = {}
0111     for key in FIELDS:
0112         if key in fields and fields[key] is not None:
0113             out[key] = fields[key]
0114         else:
0115             out[key] = cur.get(key)
0116 
0117     title = ' '.join(str(out['title'] or '').split())
0118     if not title:
0119         raise WhatsNewError('a title is required')
0120     if len(title) > 255:
0121         raise WhatsNewError('the title is one line, at most 255 characters')
0122     summary = str(out['summary'] or '').strip()
0123     if not summary:
0124         raise WhatsNewError('a summary of one to three lines is required')
0125     if len(summary) > SUMMARY_MAX or summary.count('\n') > 2:
0126         raise WhatsNewError(
0127             f'the summary is one to three lines, at most {SUMMARY_MAX} '
0128             f'characters; longer text belongs in the details')
0129     tags = normalize_tags(out['tags'])
0130     if not tags:
0131         raise WhatsNewError('at least one tag is required (e.g. users, ops, '
0132                             'dev, or the area of the system)')
0133     importance = str(out['importance'] or '').strip().lower()
0134     if importance not in IMPORTANCE:
0135         raise WhatsNewError(
0136             f'importance must be one of {", ".join(IMPORTANCE)}')
0137     shipped_raw = str(out['shipped'] or '').strip()
0138     if shipped_raw:
0139         try:
0140             shipped = date.fromisoformat(shipped_raw[:10]).isoformat()
0141         except ValueError:
0142             raise WhatsNewError(
0143                 f'shipped must be a date (YYYY-MM-DD); got {shipped_raw!r}')
0144     else:
0145         shipped = _today().isoformat()
0146     contact = str(out['contact'] or changed_by or '').strip()
0147     if not contact:
0148         raise WhatsNewError('a contact (the principal developer) is required')
0149     if contact not in contacts():
0150         raise WhatsNewError(
0151             f'contact {contact!r}: the contact is an account with the operations '
0152             f'role, one of {", ".join(contacts())}')
0153     builds_on = out['builds_on'] or []
0154     if isinstance(builds_on, str):
0155         builds_on = re.split(r'[,\s]+', builds_on)
0156     links = []
0157     for raw in builds_on:
0158         slug = str(raw).strip().rstrip('/').rsplit('/', 1)[-1]
0159         if not slug or slug in links:
0160             continue
0161         if get_entry(slug) is None:
0162             raise WhatsNewError(f'builds on {slug!r}: no such item')
0163         links.append(slug)
0164     return {
0165         'title': title, 'summary': summary,
0166         'details': str(out['details'] or '').strip(),
0167         'refs': str(out['refs'] or '').strip(),
0168         'tags': tags, 'importance': importance, 'shipped': shipped,
0169         'contact': contact, 'builds_on': links,
0170     }
0171 
0172 
0173 def validate_new(fields, *, changed_by=''):
0174     """Check a new item's fields without writing; returns the normalized
0175     fields with the slug the item would take. The same checks item_create
0176     makes; used by scripts/whats-new-ingest.py --dry-run."""
0177     clean = _validate(fields, changed_by=changed_by)
0178     clean['slug'] = slug_for(clean['title'])
0179     return clean
0180 
0181 
0182 def _write(entry, clean):
0183     entry.title = clean['title']
0184     entry.content = clean['details']
0185     data = dict(entry.data or {})
0186     for key in ('summary', 'refs', 'tags', 'importance', 'shipped',
0187                 'contact', 'builds_on'):
0188         data[key] = clean[key]
0189     entry.data = data
0190 
0191 
0192 def item_create(fields, *, changed_by, origin=None):
0193     """Create an item: the call the New item form, the API and the MCP add
0194     tool make (an LLM session adds an item as part of the task that ships
0195     the change, WHATS_NEW.md). Items made before 2026-11-12 from approved
0196     AI proposals carry the proposal's origin. Logs one origin-stamped
0197     ``whats_new_create`` event, which epicprod-live posts and the live
0198     screen shows at INFO (Torre Wenaus, 2026-10-30). Returns (entry, action
0199     log id)."""
0200     from monitor_app.alarms_data import _origin_attrs
0201     from monitor_app.epicprod_logging import log_epicprod_action
0202 
0203     if not changed_by:
0204         raise WhatsNewError('an authenticated person is required', status=403)
0205     clean = _validate(fields, changed_by=changed_by)
0206     slug = slug_for(clean['title'])
0207     attrs = _origin_attrs(origin)
0208     with transaction.atomic():
0209         _ensure_context()
0210         if get_entry(slug) is not None:
0211             raise WhatsNewError(
0212                 f'an item with this title already exists ({slug}); edit it '
0213                 f'or choose another title', status=409)
0214         now = time.time()
0215         entry = Entry(kind=KIND_ITEM, context_id=CONTEXT, name=slug,
0216                       status='active', timestamp_created=now,
0217                       timestamp_modified=now,
0218                       data={'entry_id': slug, 'votes': {},
0219                             'created_by': changed_by,
0220                             'origin': attrs.get('proposal_ref') or 'manual'})
0221         _write(entry, clean)
0222         entry.save()
0223     log_id = log_epicprod_action(
0224         'web', 'whats_new_create', subject_type='whats_new', subject_key=slug,
0225         subject_label=entry.title, username=changed_by,
0226         sublevel='normal', live_default=True,
0227         title=(entry.title if entry.title.lower().startswith("what's new")
0228                else f"What's new: {entry.title}"),
0229         summary=clean['summary'],
0230         importance=clean['importance'],
0231         url=f'/help/whats-new/{slug}/', **attrs)
0232     return entry, log_id
0233 
0234 
0235 def item_edit(slug, fields, *, changed_by):
0236     """Apply an edit to any of an item's fields; the previous state is kept
0237     as a version attributed to ``changed_by``. The slug never changes."""
0238     if not changed_by:
0239         raise WhatsNewError('an authenticated person is required', status=403)
0240     unknown = set(fields) - set(FIELDS)
0241     if unknown:
0242         raise WhatsNewError(f'unknown fields: {", ".join(sorted(unknown))}')
0243     with transaction.atomic():
0244         entry = Entry.objects.select_for_update().get(pk=_require(slug).pk)
0245         current = dict(entry.data or {}, title=entry.title,
0246                        details=entry.content)
0247         clean = _validate(fields, current=current, changed_by=changed_by)
0248         if slug in clean['builds_on']:
0249             raise WhatsNewError('an item cannot build on itself')
0250         _write(entry, clean)
0251         entry.timestamp_modified = time.time()
0252         set_changed_by(changed_by)
0253         entry.save()
0254     return entry
0255 
0256 
0257 def item_restore(slug, version_num, *, changed_by):
0258     """Restore a version's title, details and fields as the current state;
0259     the state it replaces becomes a version in turn."""
0260     if not changed_by:
0261         raise WhatsNewError('an authenticated person is required', status=403)
0262     entry = _require(slug)
0263     version = EntryVersion.objects.filter(entry=entry,
0264                                           version_num=version_num).first()
0265     if version is None:
0266         raise WhatsNewError(f'{slug} has no version {version_num}', status=404)
0267     old = version.data or {}
0268     fields = {k: old.get(k) for k in FIELDS if k not in ('title', 'details')}
0269     fields.update(title=version.title, details=version.content)
0270     return item_edit(slug, fields, changed_by=changed_by)
0271 
0272 
0273 def item_archive(slug, *, changed_by, archived=True):
0274     """Take an item off the list (or return it). Logged on the action
0275     stream, since the archive flag is not part of an item's versions."""
0276     from monitor_app.epicprod_logging import log_epicprod_action
0277 
0278     if not changed_by:
0279         raise WhatsNewError('an authenticated person is required', status=403)
0280     entry = _require(slug)
0281     entry.archived = bool(archived)
0282     entry.save(update_fields=['archived'])
0283     log_epicprod_action(
0284         'web', 'whats_new_archive', subject_type='whats_new',
0285         subject_key=slug, subject_label=entry.title, username=changed_by,
0286         sublevel='normal', live_default=False, archived=entry.archived,
0287         url=f'/help/whats-new/{slug}/')
0288     return entry
0289 
0290 
0291 def vote(slug, *, username, value):
0292     """Set the person's vote on an item: +1, -1, or 0 to withdraw.
0293     Returns (up votes, down votes, the person's vote)."""
0294     if not username:
0295         raise WhatsNewError('an authenticated person is required', status=403)
0296     try:
0297         value = int(value)
0298     except (TypeError, ValueError):
0299         value = None
0300     if value not in (-1, 0, 1):
0301         raise WhatsNewError('a vote is 1, -1, or 0 to withdraw')
0302     with transaction.atomic():
0303         entry = Entry.objects.select_for_update().get(pk=_require(slug).pk)
0304         data = dict(entry.data or {})
0305         votes = dict(data.get('votes') or {})
0306         if value:
0307             votes[username] = value
0308         else:
0309             votes.pop(username, None)
0310         data['votes'] = votes
0311         entry.data = data
0312         entry.save(update_fields=['data'])
0313     up, down = _tally(votes)
0314     return up, down, votes.get(username, 0)
0315 
0316 
0317 def _tally(votes):
0318     """(up votes, down votes); there is no combined score."""
0319     values = list(votes.values())
0320     return values.count(1), values.count(-1)
0321 
0322 
0323 def comment_add(slug, text, *, author):
0324     """Add a comment to an item's thread."""
0325     if not author:
0326         raise WhatsNewError('an authenticated person is required', status=403)
0327     text = (text or '').strip()
0328     if not text:
0329         raise WhatsNewError('the comment is empty')
0330     item = _require(slug)
0331     now = time.time()
0332     return Entry.objects.create(
0333         kind=KIND_COMMENT, context_id=CONTEXT, parent=item,
0334         content=text, data={'author': author},
0335         timestamp_created=now, timestamp_modified=now)
0336 
0337 
0338 def comment_edit(comment_id, text, *, editor):
0339     """Edit a comment; only its author may. The previous text is kept as
0340     a version."""
0341     text = (text or '').strip()
0342     if not text:
0343         raise WhatsNewError('the comment is empty')
0344     comment = Entry.objects.filter(
0345         pk=comment_id, context_id=CONTEXT, kind=KIND_COMMENT,
0346         deleted_at__isnull=True).first()
0347     if comment is None:
0348         raise WhatsNewError('no such comment', status=404)
0349     if (comment.data or {}).get('author') != editor:
0350         raise WhatsNewError('a comment is edited by its author', status=403)
0351     comment.content = text
0352     comment.timestamp_modified = time.time()
0353     set_changed_by(editor)
0354     comment.save()
0355     return comment
0356 
0357 
0358 # ---------------------------------------------------------------- reading
0359 
0360 def _iso(ts):
0361     from datetime import datetime, timezone
0362     return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat() if ts else ''
0363 
0364 
0365 def _comment_threads(item_ids):
0366     """Comments per item id, oldest first."""
0367     threads = {}
0368     for c in (Entry.objects
0369               .filter(context_id=CONTEXT, kind=KIND_COMMENT,
0370                       parent_id__in=item_ids, deleted_at__isnull=True)
0371               .order_by('timestamp_created')):
0372         threads.setdefault(c.parent_id, []).append(c)
0373     return threads
0374 
0375 
0376 def _row(entry, comments, developed_in, username=''):
0377     data = entry.data or {}
0378     votes = data.get('votes') or {}
0379     last = comments[-1] if comments else None
0380     last_author = (last.data or {}).get('author', '') if last else ''
0381     contact = data.get('contact', '')
0382     return {
0383         'slug': data.get('entry_id', ''),
0384         'title': entry.title,
0385         'summary': data.get('summary', ''),
0386         'details': entry.content or '',
0387         'refs': data.get('refs', ''),
0388         'tags': list(data.get('tags') or []),
0389         'importance': data.get('importance', ''),
0390         'shipped': data.get('shipped', ''),
0391         'contact': contact,
0392         'builds_on': list(data.get('builds_on') or []),
0393         'developed_in': developed_in,
0394         'up': _tally(votes)[0],
0395         'down': _tally(votes)[1],
0396         'my_vote': votes.get(username, 0) if username else 0,
0397         'comment_count': len(comments),
0398         'awaiting_reply': bool(last and last_author and last_author != contact),
0399         'archived': entry.archived,
0400         'created': _iso(entry.timestamp_created),
0401         'modified': _iso(entry.timestamp_modified),
0402         'created_by': data.get('created_by', ''),
0403         'origin': data.get('origin', 'manual'),
0404     }
0405 
0406 
0407 def list_items(*, username='', include_archived=False):
0408     """Every item as a dict, newest shipped first, with comment counts,
0409     up and down votes, and the links in both directions."""
0410     qs = _items()
0411     if not include_archived:
0412         qs = qs.filter(archived=False)
0413     entries = list(qs)
0414     threads = _comment_threads([e.pk for e in entries])
0415     titles = {(e.data or {}).get('entry_id'): e.title for e in entries}
0416     developed = {}
0417     for e in entries:
0418         for earlier in (e.data or {}).get('builds_on') or []:
0419             developed.setdefault(earlier, []).append(
0420                 {'slug': (e.data or {}).get('entry_id'), 'title': e.title})
0421     rows = []
0422     for e in entries:
0423         slug = (e.data or {}).get('entry_id')
0424         row = _row(e, threads.get(e.pk, []), developed.get(slug, []), username)
0425         row['builds_on_items'] = [{'slug': s, 'title': titles.get(s, s)}
0426                                   for s in row['builds_on']]
0427         rows.append(row)
0428     rows.sort(key=lambda r: (r['shipped'], r['created']), reverse=True)
0429     return rows
0430 
0431 
0432 def get_item(slug, *, username=''):
0433     """One item in full: fields, links both ways, comments and versions."""
0434     entry = _require(slug)
0435     comments = _comment_threads([entry.pk]).get(entry.pk, [])
0436     later = [{'slug': (e.data or {}).get('entry_id'), 'title': e.title}
0437              for e in _items().filter(archived=False)
0438              if slug in ((e.data or {}).get('builds_on') or [])]
0439     row = _row(entry, comments, later, username)
0440     row['builds_on_items'] = []
0441     for s in row['builds_on']:
0442         earlier = get_entry(s)
0443         row['builds_on_items'].append(
0444             {'slug': s, 'title': earlier.title if earlier else s})
0445     row['comments'] = [{
0446         'id': c.pk, 'author': (c.data or {}).get('author', ''),
0447         'text': c.content, 'created': _iso(c.timestamp_created),
0448         'edited': c.timestamp_modified - c.timestamp_created > 1,
0449     } for c in comments]
0450     row['versions'] = [{
0451         'num': v.version_num, 'by': v.changed_by, 'at': _iso(v.timestamp),
0452         'title': v.title,
0453     } for v in EntryVersion.objects.filter(entry=entry).order_by('-version_num')]
0454     return row
0455 
0456 
0457 def get_version(slug, version_num):
0458     """A version of an item as it stood, in the item's field layout."""
0459     entry = _require(slug)
0460     v = EntryVersion.objects.filter(entry=entry, version_num=version_num).first()
0461     if v is None:
0462         raise WhatsNewError(f'{slug} has no version {version_num}', status=404)
0463     data = v.data or {}
0464     return {
0465         'slug': slug, 'num': v.version_num, 'by': v.changed_by,
0466         'at': _iso(v.timestamp), 'title': v.title, 'details': v.content,
0467         'summary': data.get('summary', ''), 'refs': data.get('refs', ''),
0468         'tags': list(data.get('tags') or []),
0469         'importance': data.get('importance', ''),
0470         'shipped': data.get('shipped', ''), 'contact': data.get('contact', ''),
0471         'builds_on': list(data.get('builds_on') or []),
0472     }
0473 
0474 
0475 def tags_in_use():
0476     """{tag: number of items carrying it}, the vocabulary in use."""
0477     counts = {}
0478     for e in _items().filter(archived=False):
0479         for t in (e.data or {}).get('tags') or []:
0480             counts[t] = counts.get(t, 0) + 1
0481     return dict(sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])))