# Collector source reference

## fetch_updates.py

```python
#!/usr/bin/env python3
"""Collect public escalation reporting with a local matrix and zero LLM tokens.

X is supported through explicitly configured public RSS-Bridge/Nitter RSS
bindings and reviewed post records. No paid API, random-instance probing,
authentication bypass or cookie fallback exists. Missing coverage is published.
"""
from monitoring.engine import run, contains

GEOGRAPHY = ('Eritrea', 'Eritrean', 'Ethiopia', 'Ethiopian', 'Red Sea', 'Assab', 'Massawa', 'Horn of Africa')
MATRIX = {
    'military-posturing': ('military', 'army', 'troops', 'mobilization', 'clashes', 'fighting', 'attack', 'defense', 'war'),
    'red-sea-statecraft': ('Red Sea', 'maritime', 'sovereignty', 'port access', 'diplomatic', 'envoy', 'foreign minister'),
    'border-dynamics': ('border', 'boundary', 'demarcation', 'territorial', 'territory', 'Badme', 'Zalambessa'),
    'bilateral-conflict': ('Eritrea-Ethiopia', 'Eritrea–Ethiopia', 'escalation', 'de-escalation', 'peace', 'sanctions', 'security')
}
PROVISIONS = {'military-posturing': ['defense', 'regional'], 'red-sea-statecraft': ['us', 'regional', 'gateway'],
              'border-dynamics': ['regional', 'diplomatic-continuity'], 'bilateral-conflict': ['regional', 'us']}


def classify(item, context):
    title, text = item['title'], item['title'] + ' ' + item.get('text', '')
    flags, score = [], 0
    for flag, terms in MATRIX.items():
        points = sum(3 if contains(title, t) else 1 for t in terms if contains(text, t))
        if points:
            flags.append(flag)
            score += points
    relevant = any(contains(text, g) for g in GEOGRAPHY) and score >= 3
    refs = list(dict.fromkeys(p for f in flags for p in PROVISIONS[f]))
    known = {p['id'] for p in context['provisions']}
    if not set(refs).issubset(known):
        raise ValueError('Unknown chapter mapping')
    return {'relevant': relevant, 'category': 'Regional-Commerce', 'flags': flags, 'score': score,
            'provision_ids': refs, 'suggested_action': 'append_section',
            'summary': item['source']['label'] + ' published this source. Local matching identifies ' +
                       ', '.join(f.replace('-', ' ') for f in flags) +
                       '. Read the original for the account and its evidence; a match is not confirmation of an event.'}


if __name__ == '__main__':
    run('escalation', classify)
```

## monitor.py

```python
#!/usr/bin/env python3
"""Zero-cost, broader chapter-linked official policy source watch."""
from monitoring.engine import run, contains, read, ROOT


def classify(item, context):
    text = item['title'] + ' ' + item.get('text', '')
    config = read(ROOT / 'monitoring/config.json')
    topics = [t for t in config['policy_topics'] if any(contains(text, w) for w in t['terms'])]
    reviewed_theater = item.get('reviewed') and item['source'].get('scope') in ('united-states', 'israel', 'ethiopia')
    geographic = reviewed_theater or item['source'].get('scope') == 'eritrea' or any(contains(text, w) for w in ('Eritrea', 'Eritrean', 'Red Sea', 'Horn of Africa'))
    macro = item['source'].get('scope') == 'us-macro' and any(contains(text, w) for w in ('federal funds', 'FOMC', 'monetary policy', 'inflation'))
    category = 'US-Strategy' if macro or any(t['id'] == 'us' for t in topics) else 'Institutions'
    refs = list(dict.fromkeys(p for t in topics for p in t['provisions']))
    return {'relevant': bool(topics) and (geographic or macro), 'category': category,
            'flags': [t['id'] for t in topics], 'provision_ids': refs,
            'summary': item['source']['label'] + ' published this item. Local topic matching links it to ' + ', '.join(t['label'] for t in topics) + '. Read the original for details; the source does not amend the governing framework.',
            'suggested_action': 'append_section'}


if __name__ == '__main__':
    run('policy', classify)
```

## election_hooks.py

```python
#!/usr/bin/env python3
"""Set review flags from the verified election ledger, never rewrite law by inference.

The existing election-watch automation obtains AP and official state records.
This hook consumes that ledger and any explicitly verified certification input.
AP calls are never promoted to governmental certification by keyword matching.
"""
import json
from pathlib import Path
from urllib.parse import urlsplit
from monitoring.engine import read, write, hash_text, stamp, ROOT


def evaluate(root=ROOT):
    ledger = read(root / 'public/data/us-election-record.json', {})
    previous = read(root / 'monitoring/election-hook-state.json', {'seen_certifications': []})
    events = []
    for file in sorted((root / 'monitoring/election-certifications').glob('*.json')):
        row = read(file)
        host = urlsplit(row.get('source_url', '')).hostname or ''
        if row.get('status') != 'certified' or row.get('verified_primary_record') is not True or not host.endswith('.gov'):
            continue
        if not row.get('jurisdiction') or not row.get('certified_at'):
            raise ValueError('Certification lacks issuer or date')
        ident = hash_text(json.dumps(row, sort_keys=True))
        if ident not in previous.get('seen_certifications', []):
            events.append({**row, 'fingerprint': ident})
    ledger_hash = hash_text(json.dumps(ledger, sort_keys=True))
    changed = previous.get('ledger_hash') not in (None, ledger_hash)
    pending = read(root / 'public/data/policy-review-flags.json', {'reviews': []})
    if events or changed:
        fingerprint = hash_text(ledger_hash + ''.join(x['fingerprint'] for x in events))
        if not any(x['id'] == fingerprint for x in pending['reviews']):
            pending['reviews'].append({'id': fingerprint, 'created_at': stamp(), 'status': 'needs-source-reviewed-policy-review',
                'trigger': 'official-certification-input' if events else 'updated-election-ledger',
                'events': events, 'ledger_revision': ledger.get('revision'),
                'review_modules': ['congressional-sanctions', 'AGOA-eligibility', 'ITAR-and-export-controls', 'EO-14046-current-legal-status'],
                'constraint': 'An election outcome does not itself change sanctions, eligibility, export law, an executive order or a financial institution decision. Check the controlling primary legal record before editing analysis.'})
    write(root / 'public/data/policy-review-flags.json', pending)
    write(root / 'monitoring/election-hook-state.json', {'ledger_hash': ledger_hash, 'checked_at': stamp(),
        'seen_certifications': previous.get('seen_certifications', []) + [x['fingerprint'] for x in events]})
    print(f'Election hooks: {len(events)} new certification inputs; ledger changed: {changed}; no PDF edited.')
    return pending


if __name__ == '__main__':
    evaluate()
```

## monitoring/engine.py

```python
"""Bounded public-source collection shared by the two command-line entrypoints.

All article bodies exist in memory for matching. The public feed contains short
records and links, never complete copied articles or tactical map coordinates.
"""
import calendar
import gzip
import hashlib
import io
import json
import os
import re
import tempfile
import urllib.error
import urllib.parse
import urllib.request
import urllib.robotparser
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path
import feedparser
from bs4 import BeautifulSoup

ROOT = Path(__file__).resolve().parents[1]
UTC = timezone.utc
UA = 'ProjectEritreaSourceWatch/1.0 (+https://eritrea2042.marinespoon.chatgpt.site/watch/)'


def stamp():
    return datetime.now(UTC).replace(microsecond=0).isoformat().replace('+00:00', 'Z')


def hash_text(text):
    return hashlib.sha256(text.encode()).hexdigest()


def read(path, default=None):
    return json.loads(path.read_text('utf-8')) if path.exists() else default


def write(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    content = json.dumps(value, ensure_ascii=False, indent=2) + '\n'
    if path.exists() and path.read_text('utf-8') == content:
        return
    with tempfile.NamedTemporaryFile('w', encoding='utf-8', dir=path.parent, delete=False) as f:
        f.write(content)
        temporary = f.name
    os.replace(temporary, path)


def date(value):
    if not value:
        return None
    try:
        d = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
    except ValueError:
        try:
            d = parsedate_to_datetime(str(value))
        except (ValueError, TypeError):
            return None
    return d.replace(tzinfo=UTC).isoformat().replace('+00:00', 'Z') if d.tzinfo is None else d.astimezone(UTC).isoformat().replace('+00:00', 'Z')


def contains(text, phrase):
    return re.search(r'(?<!\w)' + re.escape(phrase.casefold()) + r'(?!\w)', text.casefold()) is not None


def clean(text):
    soup = BeautifulSoup(str(text), 'html.parser')
    for e in soup.select('script,style,iframe,nav,footer,form,noscript'):
        e.decompose()
    return re.sub(r'\s+', ' ', soup.get_text(' ', strip=True)).strip()


def safe_url(url, hosts):
    p = urllib.parse.urlsplit(url)
    if p.scheme != 'https' or p.hostname not in hosts or p.username or p.password or p.port not in (None, 443):
        raise ValueError('Outside configured public HTTPS hosts')
    q = urllib.parse.urlencode([(k, v) for k, v in urllib.parse.parse_qsl(p.query) if not k.startswith('utm_') and k not in ('fbclid', 'gclid')])
    return urllib.parse.urlunsplit(('https', p.netloc.lower(), p.path or '/', q, ''))


class SourceError(Exception):
    def __init__(self, reason, retry=None):
        self.reason, self.retry = reason, retry
        super().__init__(reason)


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


class HTTP:
    def __init__(self, config, state):
        self.config, self.state, self.count = config, state, 0
        self.hosts = set(config['allowed_hosts'])
        self.opener = urllib.request.build_opener(NoRedirect())

    def fetch(self, url, conditional=False, robots=True):
        url = safe_url(url, self.hosts)
        if robots:
            self.robots(url)
        cache = self.state.setdefault('http', {}).get(url, {})
        headers = {'User-Agent': UA, 'Accept-Encoding': 'identity'}
        if conditional and cache.get('etag'):
            headers['If-None-Match'] = cache['etag']
        if conditional and cache.get('modified'):
            headers['If-Modified-Since'] = cache['modified']
        for _ in range(5):
            if self.count >= self.config['max_requests']:
                raise SourceError('request-budget')
            self.count += 1
            try:
                with self.opener.open(urllib.request.Request(url, headers=headers), timeout=12) as r:
                    if not any(x in r.headers.get('Content-Type', '').lower() for x in ('text', 'xml', 'json')):
                        raise SourceError('unsupported-content-type')
                    b = r.read(2500001)
                    if len(b) > 2500000:
                        raise SourceError('response-too-large')
                    if r.headers.get('Content-Encoding') == 'gzip' or b.startswith(b'\x1f\x8b'):
                        b = gzip.GzipFile(fileobj=io.BytesIO(b)).read(2500001)
                    if len(b) > 2500000:
                        raise SourceError('response-too-large')
                    self.state['http'][url] = {'etag': r.headers.get('ETag'), 'modified': r.headers.get('Last-Modified')}
                    return b
            except urllib.error.HTTPError as e:
                if e.code == 304:
                    return None
                if e.code in (301, 302, 303, 307, 308):
                    url = safe_url(urllib.parse.urljoin(url, e.headers.get('Location', '')), self.hosts)
                    if robots:
                        self.robots(url)
                    headers = {'User-Agent': UA, 'Accept-Encoding': 'identity'}
                    continue
                after = e.headers.get('Retry-After', '')
                retry = (datetime.now(UTC) + timedelta(seconds=min(int(after), 172800))).isoformat() if after.isdigit() else date(after)
                raise SourceError('http-' + str(e.code), retry) from None
            except (urllib.error.URLError, OSError, TimeoutError, EOFError):
                raise SourceError('network-or-encoding-error') from None
        raise SourceError('redirect-limit')

    def robots(self, url):
        p = urllib.parse.urlsplit(url)
        origin = 'https://' + p.netloc
        cache = self.state.setdefault('robots', {}).get(origin)
        if not cache or cache['checked'][:10] != stamp()[:10]:
            try:
                b = self.fetch(origin + '/robots.txt', robots=False)
                text = b.decode('utf-8', 'replace')
            except SourceError as e:
                if e.reason not in ('http-404', 'http-410'):
                    raise SourceError('robots-unavailable') from None
                text = 'User-agent: *\nAllow: /'
            cache = {'checked': stamp(), 'text': text[:100000]}
            self.state['robots'][origin] = cache
        r = urllib.robotparser.RobotFileParser()
        r.parse(cache['text'].splitlines())
        if not r.can_fetch(UA, url):
            raise SourceError('robots-disallowed')


def rss(body, source, hosts):
    feed = feedparser.parse(body)
    if not feed.version or (feed.bozo and not feed.entries):
        raise SourceError('invalid-feed')
    result = []
    for e in feed.entries[:30]:
        try:
            url = safe_url(e.get('link', ''), hosts)
        except ValueError:
            continue
        text = e.get('content', [{}])[0].get('value', '') or e.get('summary', '')
        result.append({'url': url, 'title': ' '.join(clean(e.get('title', 'Untitled source')).split()[:24])[:240], 'text': clean(text)[:60000],
                       'published_at': date(e.get('published') or e.get('updated')), 'source_id': source['id']})
    return result


def listing(body, source, hosts):
    soup = BeautifulSoup(body, 'html.parser')
    if source['adapter'] == 'map-log':
        title = soup.select_one('h1')
        return [{'url': source['url'], 'title': title.get_text(' ', strip=True) if title else 'Publisher map record',
                 'text': clean(str(soup.select_one('main') or soup))[:60000], 'published_at': None,
                 'source_id': source['id'], 'map_log': True}]
    found = {}
    for a in soup.select(source.get('selector', 'h2 a[href],h3 a[href],article a[href]')):
        try:
            url = safe_url(urllib.parse.urljoin(source['url'], a.get('href', '')), hosts)
        except ValueError:
            continue
        title = a.get_text(' ', strip=True)
        if len(title) < 12 or not re.search(source.get('path_pattern', r'/20\d{2}/'), urllib.parse.urlsplit(url).path):
            continue
        found[url] = {'url': url, 'title': ' '.join(title.split()[:24])[:240], 'text': '', 'published_at': None, 'source_id': source['id']}
    return list(found.values())[:30]


def article(body, item):
    soup = BeautifulSoup(body, 'html.parser')
    # Shabait also uses .entry-content for an off-canvas social-counter box.
    # Prefer a body inside the article/main before considering generic classes.
    box = None
    for selector in ('article .entry-content', 'main .entry-content',
                     'article .post-content', 'main .post-content',
                     '.article-body', '.field--name-body',
                     '.entry-content', '.post-content', 'article', 'main'):
        box = soup.select_one(selector)
        if box is not None:
            break
    if box:
        item['text'] = clean(str(box))[:80000]
    meta = soup.select_one('meta[property="article:published_time"],meta[name="date"],time[datetime]')
    if meta:
        item['published_at'] = date(meta.get('content') or meta.get('datetime')) or item['published_at']
    item['case_codes'] = sorted(set(re.findall(r'\bAR-\d{4}-\d{3}\b', item['title'] + ' ' + item['text'])))


def run(mode, classifier, root=ROOT, http_factory=HTTP):
    config = read(root / 'monitoring/config.json')
    if config['monthly_budget_usd'] != 0 or config['paid_services_enabled'] is not False:
        raise ValueError('Installation locked to $0 and no paid services')
    context = read(root / 'monitoring/policy-context.json')
    for e in context['editions']:
        if hashlib.sha256((root / e['local_path']).read_bytes()).hexdigest() != e['sha256']:
            raise ValueError('Approved PDF changed: refresh the chapter map before collecting')
    state = read(root / f'monitoring/state-{mode}.json', {'seen': {}, 'sources': {}, 'inbox': {}})
    state.setdefault('inbox', {})
    path = root / ('escalation_feed.json' if mode == 'escalation' else 'policy_feed.json')
    feed = read(path, {'schema_version': 1, 'items': []})
    old_items = {i['url']: i for i in feed['items']}
    http = http_factory(config, state)
    coverage, candidates, failures, changes = [], {}, [], []
    sources = [s for s in config['sources'] if mode in s['modes']]
    # Only explicitly supplied, public, permitted feeds are supported for X.
    # There is no random-instance probing, paid fallback or cookie-based bypass.
    for bridge in config.get('x_rss_feeds', []):
        if bridge['handle'].casefold() not in {x['handle'].casefold() for x in read(root / 'monitoring/x-accounts.json')['accounts']}:
            raise ValueError('RSS binding has an unregistered X handle')
        sources.append({**bridge, 'id': 'x-' + bridge['handle'].casefold(), 'label': bridge.get('label', '@' + bridge['handle']),
                        'adapter': 'rss', 'publisher_kind': bridge.get('publisher_kind', 'public-post'), 'scope': 'regional'})
    for s in sources:
        previous = state['sources'].get(s['id'], {})
        status = {'id': s['id'], 'label': s['label'], 'url': s['url'], 'status': 'pending', 'last_success': previous.get('last_success')}
        if previous.get('next_attempt') and previous['next_attempt'] > stamp():
            status.update(status='backoff', next_attempt=previous['next_attempt'])
            if previous.get('reason'):
                status['reason'] = previous['reason']
            coverage.append(status)
            continue
        try:
            body = http.fetch(s['url'])
            entries = rss(body, s, config['allowed_hosts']) if s['adapter'] == 'rss' else listing(body, s, config['allowed_hosts'])
            for item in entries:
                if re.match(r'^(Eritrea Alhaditha|Haddas Ertra|Eritrea Haddas|Eritrea Profile) \d', item['title']):
                    continue
                seen = state['seen'].get(item['url'], {})
                fingerprint = hash_text(item['title'] + item['text'] + str(item['published_at']))
                if seen.get('entry_hash') == fingerprint and seen.get('context') == context['sha256'] and seen.get('checked', '')[:10] > (datetime.now(UTC) - timedelta(days=7)).isoformat()[:10]:
                    continue
                item.update(source=s, entry_hash=fingerprint, priority=0 if not seen else 1)
                candidates.setdefault(item['url'], item)
            status.update(status='ok', last_success=stamp())
            state['sources'][s['id']] = {'last_success': status['last_success']}
        except (SourceError, ValueError) as e:
            reason = getattr(e, 'reason', 'invalid-url')
            retry = getattr(e, 'retry', None) or (datetime.now(UTC) + timedelta(hours=12)).isoformat()
            status.update(status='unavailable', reason=reason, next_attempt=date(retry))
            state['sources'][s['id']] = {**previous, 'reason': reason, 'next_attempt': status['next_attempt']}
            failures.append({'source': s['id'], 'reason': reason})
        coverage.append(status)
    inbox = {}
    for f in sorted((root / 'monitoring/inbox').glob('*.json')):
        row = read(f)
        if row.get('reviewed') and mode in row.get('modes', []):
            inbox[row['url']] = row
    for url, row in inbox.items():
        key = hash_text(json.dumps(row, sort_keys=True))
        if state['inbox'].get(url) == key:
            continue
        row.update(source=row['source'], entry_hash=key, inbox_hash=key, priority=-1)
        safe_url(url, set(config['allowed_hosts']) | {'x.com'})
        if urllib.parse.urlsplit(url).hostname == 'x.com':
            handle = urllib.parse.urlsplit(url).path.strip('/').split('/')[0]
            handles = {a['handle'].casefold() for a in read(root / 'monitoring/x-accounts.json')['accounts']}
            if handle.casefold() not in handles or not re.fullmatch(r'/[A-Za-z0-9_]{1,15}/status/\d+/?', urllib.parse.urlsplit(url).path):
                raise ValueError('Invalid X post or unregistered handle')
        candidates[url] = row
    ordered = sorted(candidates.values(), key=lambda x: x.get('published_at') or '', reverse=True)
    ordered.sort(key=lambda x: x['priority'])
    # A busy source must not starve another publisher's older statement or map
    # log. Reviewed inputs go first; other sources receive round-robin slots.
    reviewed = [x for x in ordered if x['priority'] < 0]
    buckets = {}
    for item in ordered:
        if item['priority'] >= 0:
            buckets.setdefault(item['source']['id'], []).append(item)
    ordered = reviewed[:]
    while any(buckets.values()):
        for bucket in buckets.values():
            if bucket:
                ordered.append(bucket.pop(0))
    for item in ordered[:config['max_articles']]:
        url, s = item['url'], item['source']
        seen = state['seen'].get(url, {})
        try:
            if not item.get('reviewed') and not item.get('map_log') and s['publisher_kind'] != 'public-post' and not s.get('handle'):
                body = http.fetch(url, conditional=seen.get('context') == context['sha256'])
                if body is None:
                    seen.update(checked=stamp(), entry_hash=item['entry_hash'])
                    continue
                article(body, item)
            published = date(item.get('published_at'))
            if published and datetime.fromisoformat(published.replace('Z', '+00:00')) > datetime.now(UTC) + timedelta(hours=36):
                raise SourceError('future-dated-source')
            decision = classifier(item, context)
            content_hash = hash_text(item['title'] + item.get('text', '') + str(published))
            old = old_items.get(url)
            if item.get('observed_content_hash'):
                if seen.get('content_hash') and seen['content_hash'] != item['observed_content_hash']:
                    raise SourceError('stale-reviewed-summary')
                content_hash = item['observed_content_hash']
            keep_review = old and old['review_status'] == 'source-reviewed' and old['content_hash'] == content_hash
            summary = clean(item['summary'])[:1400] if item.get('reviewed') else old['summary'] if keep_review else decision['summary']
            review_hash = hash_text(summary) if item.get('reviewed') or keep_review else None
            old_state = dict(seen)
            state['seen'][url] = {'entry_hash': seen.get('entry_hash', item['entry_hash']) if item.get('reviewed') else item['entry_hash'],
                                  'content_hash': content_hash, 'review_hash': review_hash, 'context': context['sha256'], 'checked': stamp()}
            if item.get('reviewed'):
                state['inbox'][url] = item['inbox_hash']
            if not decision['relevant']:
                continue
            if old and content_hash == old_state.get('content_hash') and review_hash == old_state.get('review_hash') and old_state.get('context') == context['sha256']:
                continue
            ident = hash_text(url)[:20]
            record = {**decision, 'id': ident, 'url': url, 'title': item['title'], 'summary': summary,
                      'publisher': s['label'], 'publisher_kind': s['publisher_kind'], 'source_id': s['id'],
                      'published_at': published, 'collected_at': old['collected_at'] if old else stamp(), 'updated_at': stamp(),
                      'revision': old['revision'] + 1 if old else 1, 'case_codes': item.get('case_codes', []),
                      'content_hash': content_hash, 'review_hash': review_hash,
                      'review_status': 'source-reviewed' if item.get('reviewed') or keep_review else 'automatic-topic-match',
                      'evidence_label': 'Attributed publisher report; not independently verified', 'method': 'local-string-matrix'}
            if old and record == {**old, 'revision': record['revision'], 'updated_at': record['updated_at']}:
                continue
            old_items[url] = record
            write(root / f'monitoring/history/{mode}/{ident}/{record["revision"]:04}.json', record)
            changes.append(record)
        except (SourceError, ValueError) as e:
            failures.append({'source': s['id'], 'record': hash_text(url)[:20], 'reason': getattr(e, 'reason', 'invalid-record')})
    feed['items'] = sorted(old_items.values(), key=lambda x: x.get('published_at') or x['collected_at'], reverse=True)
    if changes:
        feed['updated_at'] = stamp()
    feed['context_sha256'] = context['sha256']
    write(path, feed)
    write(root / 'public/data' / path.name, feed)
    write(root / f'monitoring/state-{mode}.json', state)
    report = {'checked_at': stamp(), 'mode': mode, 'monthly_budget_usd': 0, 'paid_api_calls': 0,
              'sources': coverage, 'failures': failures, 'pending': max(0, len(ordered) - config['max_articles']),
              'changed_items': len(changes), 'requests': http.count, 'x_coverage': 'partial-public-access',
              'x_rss_bindings': len(config.get('x_rss_feeds', [])),
              'x_notice': 'No complete X timeline access is configured. Registered account links and reviewed accessible posts are retained.'}
    write(root / f'public/data/{mode}-status.json', report)
    log = root / 'changelog.md'
    text = log.read_text() if log.exists() else '# Source monitoring change log\n\nGoverning PDFs are unchanged by these collectors.\n'
    for r in changes:
        marker = f'<!-- {mode}:{r["id"]}:{r["revision"]} -->'
        if marker not in text:
            title = r['title'].replace('[', '').replace(']', '').replace('\n', ' ')
            text += f'\n## {r["updated_at"]} / {mode}\n\n- [{title}](<{r["url"]}>)\n- {r["publisher"]}; {r["review_status"]}; revision {r["revision"]}.\n- {r["summary"]}\n{marker}\n'
    log.write_text(text)
    waiting = sum(row['status'] == 'backoff' for row in coverage)
    message = (f'{mode}: {len(changes)} changed records; {report["pending"]} articles pending; '
               f'{len(failures)} access errors; {waiting} sources waiting to retry. Paid API calls: 0.')
    print(message)
    if os.getenv('GITHUB_STEP_SUMMARY'):
        with open(os.environ['GITHUB_STEP_SUMMARY'], 'a') as f:
            f.write(message + '\n')
    return report
```

## monitoring/config.json

```json
{
  "schema_version": 1,
  "monthly_budget_usd": 0,
  "paid_services_enabled": false,
  "max_requests": 48,
  "max_articles": 24,
  "allowed_hosts": [
    "shabait.com",
    "adulisnews.org",
    "adulisreview.org",
    "us.embassyeritrea.org",
    "ofac.treasury.gov",
    "www.federalreserve.gov",
    "news.un.org",
    "x.com",
    "twitter.com",
    "acleddata.com",
    "www.justice.gov",
    "www.govinfo.gov",
    "www.ukmto.org",
    "www.foreign.senate.gov",
    "www.canada.ca",
    "data.unhcr.org",
    "www.gov.uk",
    "www.ohchr.org",
    "www.aol.com",
    "sonna.so",
    "www.imo.org",
    "wazema.substack.com",
    "www.cruz.senate.gov",
    "www.kenyanews.go.ke",
    "www.radiotamazuj.org",
    "srnnews.com",
    "transcripts.un.org",
    "www.wfp.org",
    "www.suna.sd",
    "sudantribune.com",
    "sntv.so",
    "dalkajournal.so",
    "www.the-star.co.ke",
    "www.criticalthreats.org",
    "kituochasheria.or.ke",
    "www.nau.ch",
    "www.reuters.com",
    "www.icrc.org",
    "igad.int",
    "www.aljazeera.com",
    "dcoc.org",
    "apnews.com",
    "www.afp.com",
    "logcluster.org",
    "m.knesset.gov.il",
    "nbe.gov.et",
    "um.fi",
    "www.boi.org.il",
    "www.eeas.europa.eu",
    "www.who.int",
    "baird.house.gov",
    "www.bea.gov"
  ],
  "x_rss_feeds": [],
  "sources": [
    {
      "id": "shabait-general",
      "label": "Shabait · Ministry of Information",
      "access_label": "General articles",
      "url": "https://shabait.com/category/articles/general/",
      "adapter": "html",
      "publisher_kind": "official-eritrean",
      "scope": "eritrea",
      "modes": [
        "policy",
        "escalation"
      ],
      "selector": "h2 a[href],h3 a[href],.listing-item a[href]"
    },
    {
      "id": "shabait-local",
      "label": "Shabait · Ministry of Information",
      "access_label": "Local news",
      "url": "https://shabait.com/category/news/local-news/",
      "adapter": "html",
      "publisher_kind": "official-eritrean",
      "scope": "eritrea",
      "modes": [
        "policy",
        "escalation"
      ],
      "selector": "h2 a[href],h3 a[href],.listing-item a[href]"
    },
    {
      "id": "shabait-rss",
      "label": "Shabait · Ministry of Information",
      "access_label": "All posts",
      "url": "https://shabait.com/feed/",
      "adapter": "rss",
      "publisher_kind": "official-eritrean",
      "scope": "eritrea",
      "modes": [
        "policy",
        "escalation"
      ]
    },
    {
      "id": "shabait-press",
      "label": "Shabait · Ministry of Information",
      "access_label": "Press releases",
      "url": "https://shabait.com/category/press-release/feed/",
      "adapter": "rss",
      "publisher_kind": "official-eritrean",
      "scope": "eritrea",
      "modes": [
        "policy",
        "escalation"
      ]
    },
    {
      "id": "adulis-news",
      "label": "Adulis News",
      "url": "https://adulisnews.org/rss.xml",
      "adapter": "rss",
      "publisher_kind": "independent",
      "scope": "regional",
      "modes": [
        "escalation"
      ]
    },
    {
      "id": "adulis-review-claims",
      "label": "Adulis Review",
      "access_label": "Claim reviews",
      "url": "https://adulisreview.org/claims/rss.xml",
      "adapter": "rss",
      "publisher_kind": "independent",
      "scope": "regional",
      "modes": [
        "escalation"
      ]
    },
    {
      "id": "adulis-review-analysis",
      "label": "Adulis Review",
      "access_label": "Analysis articles",
      "url": "https://adulisreview.org/articles/rss.xml",
      "adapter": "rss",
      "publisher_kind": "independent",
      "scope": "regional",
      "modes": [
        "escalation"
      ]
    },
    {
      "id": "adulis-review-map",
      "label": "Adulis Review",
      "access_label": "Map log",
      "url": "https://adulisreview.org/map/",
      "adapter": "map-log",
      "publisher_kind": "independent",
      "scope": "regional",
      "modes": [
        "escalation"
      ]
    },
    {
      "id": "ofac",
      "label": "U.S. Treasury · OFAC",
      "url": "https://ofac.treasury.gov/recent-actions",
      "adapter": "html",
      "publisher_kind": "official-us",
      "scope": "global",
      "modes": [
        "policy"
      ],
      "selector": "a[href*=\"/recent-actions/\"]",
      "path_pattern": "^/recent-actions/[0-9]{8}/?$"
    },
    {
      "id": "fed",
      "label": "Federal Reserve",
      "url": "https://www.federalreserve.gov/feeds/press_all.xml",
      "adapter": "rss",
      "publisher_kind": "official-us",
      "scope": "us-macro",
      "modes": [
        "policy"
      ]
    },
    {
      "id": "un",
      "label": "UN News · Africa",
      "url": "https://news.un.org/feed/subscribe/en/news/region/africa/feed/rss.xml",
      "adapter": "rss",
      "publisher_kind": "intergovernmental",
      "scope": "global",
      "modes": [
        "policy"
      ]
    }
  ],
  "policy_topics": [
    {
      "id": "us",
      "label": "U.S. relations",
      "terms": [
        "United States",
        "U.S.",
        "Washington",
        "Congress",
        "sanctions",
        "American",
        "US"
      ],
      "provisions": [
        "us",
        "diplomatic-continuity"
      ]
    },
    {
      "id": "finance",
      "label": "banking and finance",
      "terms": [
        "bank",
        "banking",
        "payments",
        "foreign exchange",
        "financial intelligence",
        "currency",
        "monetary policy",
        "federal funds"
      ],
      "provisions": [
        "finance",
        "fiu"
      ]
    },
    {
      "id": "education",
      "label": "education and science",
      "terms": [
        "education",
        "teacher",
        "teachers",
        "training",
        "university",
        "science",
        "research",
        "technology"
      ],
      "provisions": [
        "education",
        "science"
      ]
    },
    {
      "id": "regional",
      "label": "regional diplomacy and commerce",
      "terms": [
        "Red Sea",
        "Ethiopia",
        "Sudan",
        "diplomatic",
        "bilateral",
        "envoy",
        "trade",
        "ports",
        "shipping",
        "logistics"
      ],
      "provisions": [
        "regional",
        "gateway"
      ]
    },
    {
      "id": "institutions",
      "label": "institutional delivery",
      "terms": [
        "constitution",
        "legislation",
        "institutional",
        "health",
        "healthcare",
        "veterans",
        "public administration"
      ],
      "provisions": [
        "institutions",
        "delivery"
      ]
    },
    {
      "id": "land",
      "label": "land and environment",
      "terms": [
        "land tenure",
        "customary",
        "agriculture",
        "environment",
        "climate",
        "water",
        "irrigation"
      ],
      "provisions": [
        "land-institutions",
        "customary-land",
        "environment"
      ]
    },
    {
      "id": "enterprise",
      "label": "enterprise and infrastructure",
      "terms": [
        "investment",
        "enterprise",
        "manufacturing",
        "mining",
        "solar",
        "energy",
        "infrastructure"
      ],
      "provisions": [
        "economic-model",
        "infrastructure",
        "project-gates"
      ]
    },
    {
      "id": "service",
      "label": "national service and professional capability",
      "terms": [
        "national service",
        "military education",
        "reserve force",
        "conscription"
      ],
      "provisions": [
        "service",
        "defense"
      ]
    },
    {
      "id": "heritage",
      "label": "religious institutions and heritage",
      "terms": [
        "Holy Synod",
        "Orthodox Tewahdo Church"
      ],
      "provisions": [
        "heritage"
      ]
    }
  ]
}
```

## monitoring/export-context.mjs

```javascript
import {readFile,writeFile,mkdir}from'node:fs/promises';import{createHash}from'node:crypto';
import{VISION_DATA as d}from'../public/implementation/vision_data.js';
const load=async p=>JSON.parse(await readFile(p,'utf8'));const hash=x=>createHash('sha256').update(x).digest('hex');
const edition=await load('public/data/us-study-edition.json');const report=await load('docs/us-policy/report-data.json');
const editions=[{title:d.authority.title,local_path:'public/downloads/eritrea2042-en.pdf',sha256:d.authority.sha256,pages:d.authority.pages},{title:edition.fileName,local_path:'public/downloads/'+edition.fileName,sha256:edition.sha256,pages:edition.pages}];
for(const e of editions)if(hash(await readFile(e.local_path))!==e.sha256)throw Error('Approved edition checksum mismatch: '+e.title);
const c={schema_version:1,editions,provisions:d.provisions,modules:d.modules.map(m=>({id:m.id,title:m.title,provision_ids:m.provisionIds})),us_study:report.pages.map((p,i)=>({title:p.title,page:i+4,summary:p.deck||''})),constraints:['The English PDF governs this project.','The NBE stays under sovereign state authority.','Keep the 2% diaspora starting rate; voluntary bonds are separate.','Source reports do not amend the framework or establish implementation.','No paid service or external LLM API may be used.']};c.sha256=hash(JSON.stringify(c));await mkdir('monitoring',{recursive:true});await writeFile('monitoring/policy-context.json',JSON.stringify(c,null,2)+'\n');
console.log('Approved PDF checksums verified; chapter map refreshed.');
```

## .github/workflows/track_escalation.yml

```yaml
name: Zero-cost escalation source watch
on:
  schedule:
    - cron: '37 */12 * * *'
  workflow_dispatch:
concurrency:
  group: eritrea2042-static-writer
  cancel-in-progress: false
permissions:
  contents: read
jobs:
  update:
    if: github.event.repository.private == false
    runs-on: ubuntu-latest
    timeout-minutes: 12
    permissions:
      contents: write
    outputs:
      deploy: ${{ steps.target.outputs.deploy }}
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event.repository.default_branch }}
      - uses: actions/setup-python@v7
        with:
          python-version: '3.12'
      - uses: actions/setup-node@v7
        with:
          node-version: '22'
          package-manager-cache: false
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: '17'
      - name: Install fixed collection dependencies
        run: python -m pip install --disable-pip-version-check -r monitoring/requirements.txt
      - name: Verify approved editions and refresh context
        run: node monitoring/export-context.mjs
      - name: Collect public sources without paid APIs
        run: python fetch_updates.py
      - name: Evaluate election review hooks
        run: python election_hooks.py
      - name: Test the collectors
        run: python -m unittest discover -s monitoring/tests -v
      - name: Install locked static build dependencies
        run: |
          npm install --global --ignore-scripts --no-audit --no-fund pnpm@11.25.0
          pnpm install --frozen-lockfile --ignore-scripts
      - name: Validate and build the static mirror
        env:
          SITE_STATIC_MIRROR: '1'
        run: npm run check:publish
      - name: Commit only generated public records and state
        run: |
          git config user.name 'Project Eritrea source monitor'
          git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
          git add -- escalation_feed.json public/data monitoring/state-*.json monitoring/history monitoring/policy-context.json monitoring/election-hook-state.json changelog.md
          if ! git diff --cached --quiet; then
            git commit -m 'Update attributed public-source records and review flags'
            git push
          fi
      - name: Select the optional Pages target
        id: target
        env:
          PAGES_ENABLED: ${{ vars.DEPLOY_GITHUB_PAGES }}
        run: |
          if [ "$PAGES_ENABLED" = 'true' ]; then
            echo 'deploy=true' >> "$GITHUB_OUTPUT"
          else
            echo 'deploy=false' >> "$GITHUB_OUTPUT"
          fi
      - name: Request optional Vercel deployment
        if: vars.DEPLOY_VERCEL == 'true'
        env:
          DEPLOY_VERCEL: 'true'
          VERCEL_DEPLOY_HOOK: ${{ secrets.VERCEL_DEPLOY_HOOK }}
        run: python monitoring/deploy-vercel.py
      - name: Upload Pages artifact
        if: steps.target.outputs.deploy == 'true'
        uses: actions/upload-pages-artifact@v3
        with:
          path: dist/client
          retention-days: 1
  deploy:
    needs: update
    if: needs.update.outputs.deploy == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      pages: write
      id-token: write
    environment:
      name: github-pages
      url: ${{ steps.publish.outputs.page_url }}
    steps:
      # An explicit deploy is needed: bot commits do not trigger another workflow.
      - name: Deploy static artifact
        id: publish
        uses: actions/deploy-pages@v4
```

## .github/workflows/check.yml

```yaml
name: Zero-cost policy source watch
on:
  schedule:
    - cron: '43 8 * * *'
  workflow_dispatch:
concurrency:
  group: eritrea2042-static-writer
  cancel-in-progress: false
permissions:
  contents: read
jobs:
  update:
    if: github.event.repository.private == false
    runs-on: ubuntu-latest
    timeout-minutes: 12
    permissions:
      contents: write
    outputs:
      deploy: ${{ steps.target.outputs.deploy }}
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event.repository.default_branch }}
      - uses: actions/setup-python@v7
        with:
          python-version: '3.12'
      - uses: actions/setup-node@v7
        with:
          node-version: '22'
          package-manager-cache: false
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: '17'
      - name: Install fixed collection dependencies
        run: python -m pip install --disable-pip-version-check -r monitoring/requirements.txt
      - name: Verify approved editions and refresh context
        run: node monitoring/export-context.mjs
      - name: Collect public sources without paid APIs
        run: python monitor.py
      - name: Evaluate election review hooks
        run: python election_hooks.py
      - name: Test the collectors
        run: python -m unittest discover -s monitoring/tests -v
      - name: Install locked static build dependencies
        run: |
          npm install --global --ignore-scripts --no-audit --no-fund pnpm@11.25.0
          pnpm install --frozen-lockfile --ignore-scripts
      - name: Validate and build the static mirror
        env:
          SITE_STATIC_MIRROR: '1'
        run: npm run check:publish
      - name: Commit only generated public records and state
        run: |
          git config user.name 'Project Eritrea source monitor'
          git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
          git add -- policy_feed.json public/data monitoring/state-*.json monitoring/history monitoring/policy-context.json monitoring/election-hook-state.json changelog.md
          if ! git diff --cached --quiet; then
            git commit -m 'Update attributed public-source records and review flags'
            git push
          fi
      - name: Select the optional Pages target
        id: target
        env:
          PAGES_ENABLED: ${{ vars.DEPLOY_GITHUB_PAGES }}
        run: |
          if [ "$PAGES_ENABLED" = 'true' ]; then
            echo 'deploy=true' >> "$GITHUB_OUTPUT"
          else
            echo 'deploy=false' >> "$GITHUB_OUTPUT"
          fi
      - name: Request optional Vercel deployment
        if: vars.DEPLOY_VERCEL == 'true'
        env:
          DEPLOY_VERCEL: 'true'
          VERCEL_DEPLOY_HOOK: ${{ secrets.VERCEL_DEPLOY_HOOK }}
        run: python monitoring/deploy-vercel.py
      - name: Upload Pages artifact
        if: steps.target.outputs.deploy == 'true'
        uses: actions/upload-pages-artifact@v3
        with:
          path: dist/client
          retention-days: 1
  deploy:
    needs: update
    if: needs.update.outputs.deploy == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      pages: write
      id-token: write
    environment:
      name: github-pages
      url: ${{ steps.publish.outputs.page_url }}
    steps:
      # An explicit deploy is needed: bot commits do not trigger another workflow.
      - name: Deploy static artifact
        id: publish
        uses: actions/deploy-pages@v4
```

## scripts/watch-pages.mjs

```javascript
import { proposedFeed, regionMap } from './hub-pages.mjs';
import {readFile}from'node:fs/promises';import{esc}from'../src/js/core.js';
import {coveragePanel, sourceAccessTable, sourceStatus, watchTime} from './watch-coverage.mjs';
import {badge, badgeLegend, isoDate, regionalScope, site} from '../tools/build.mjs';
import {collectXPosts, watchPostsPage, watchPostsWindow} from './watch-posts.mjs';
const ORIGIN='https://eritrea2042.marinespoon.chatgpt.site';
const load=async(p,fallback)=>{try{return JSON.parse(await readFile(p,'utf8'));}catch(e){if(e.code==='ENOENT')return fallback;throw e;}};
const href=u=>{try{const p=new URL(u,ORIGIN);return p.protocol==='https:'&&!p.username&&!p.password?esc(u.startsWith('#')||u.startsWith('/')&&!u.startsWith('//')?u:p.href):'#';}catch{return '#';}};
const a=(url,text)=>`<a href="${href(url)}"${url.startsWith('https://')?' target="_blank" rel="noopener noreferrer"':''}>${esc(text)}</a>`;
export const projectStatement = `<aside class="project-scope"><p>${esc(site.scope)}</p></aside>`;
export const electionImage=`<figure class="election-feature"><a href="/assets/community/eritrean-americans-2026.jpeg"><picture><source type="image/webp" srcset="/assets/community/eritrean-americans-2026-480.webp 480w, /assets/community/eritrean-americans-2026-800.webp 800w" sizes="(max-width:620px) 80vw, 310px"><img src="/assets/community/eritrean-americans-2026.jpeg" width="1170" height="1595" loading="lazy" decoding="async" alt="User-supplied graphic titled Eritrean-Americans in U.S. Politics, 2026 Election Highlights, showing eight public figures."></picture></a><figcaption>Reader-supplied election graphic, displayed unchanged. Consult the source-linked profiles for election calls, offices and term status. <a href="/assets/community/eritrean-americans-2026.jpeg">Open full image ↗</a></figcaption></figure>`;

// STRUCTURE: one account-link template for homepage previews and the source register.
export function renderSocialRow(source, {register = false, posts = []} = {}) {
 const {handle, url, id, platform = 'x', identity, group} = source;
 const category = group ? ` data-account-group="${esc(group)}"` : '';
 const tier = platform === 'x' ? ` data-account-tier="${source.evidenceTier === 'registration-only' ? 'registration' : 'prior'}"` : '';
 const attrs = register ? ` class="account-row"${category}${tier}`
   : ` class="news-source account-row" data-source-id="${esc(id)}" data-platform="${esc(platform)}" data-handle="${esc(handle)}"${category}${tier}`;
 const icon = register ? '' : `<span class="platform-mark platform-${esc(platform)}" aria-hidden="true">${platform === 'x' ? '𝕏' : '♪'}</span>`;
 const label = register ? `@${esc(handle)}` : `<span>@${esc(handle)}${source.displayName ? `<small class="news-account-name">${esc(source.displayName)}</small>` : ''}</span><span class="external-arrow" aria-hidden="true">↗</span>`;
 const postCount = posts.length === 1 ? '1 selected post' : posts.length + ' selected posts';
 const review = source.evidenceTier === 'registration-only' ? `<span class="source-review-badge">Registration only</span>` : '';
 const name = source.displayName ? `<span class="source-display-name">${esc(source.displayName)}</span>` : '';
 const role = source.watchRole ? `<span>${esc(source.watchRole)}</span>` : '';
 const suffix = register ? `${name}${badge('social')}${review}<span>${esc(identity)}</span>${role}${posts.length ? `<a class="watch-account-posts" aria-label="${postCount} from @${esc(handle)}" href="/watch/posts/?account=${encodeURIComponent(handle.toLowerCase())}#post-${posts[0].id}">${postCount}</a>` : ''}`
   : `<button class="account-preview" type="button" data-preview aria-label="Preview @${esc(handle)} on ${platform === 'x' ? 'X' : 'TikTok'}" aria-expanded="false" aria-controls="news-preview" hidden>Preview</button>`;
 return `<div${attrs}>${icon}<a${register ? '' : ' class="account-link"'} href="${href(url)}"${group ? ` data-group="${esc(group)}"` : ''} target="_blank" rel="noopener noreferrer">${label}</a>${suffix}</div>`;
}

export async function loadWatch(){
 const [context, registry, config, policy, escalation, policyStatus, escalationStatus, selectedPosts, catalog, xReview, directory] = await Promise.all([
  load('monitoring/policy-context.json', null),
  load('monitoring/x-accounts.json', {accounts: []}),
  load('monitoring/config.json', {sources: []}),
  load('policy_feed.json', {items: []}),
  load('escalation_feed.json', {items: []}),
  load('public/data/policy-status.json', null),
  load('public/data/escalation-status.json', null),
  load('monitoring/selected-x-posts.json', []),
  load('data/sources.json', null),
  load('public/data/x-review-log.json', null),
  load('data/accounts.json', []),
 ]);
 const activeXAccounts = directory.length;
 return {context, registry, config, policy, escalation, policyStatus, escalationStatus, selectedPosts, activeXAccounts, xReview, catalog};
}
function refs(item,d){return `<details class="watch-refs"><summary>Governing chapter links</summary><ul>${item.provision_ids.map(id=>d.context.provisions.find(p=>p.id===id)).filter(Boolean).map(p=>`<li>${a('/downloads/eritrea2042-en.pdf#page='+p.pages[0],`Book ${p.book}${p.chapter?' · Ch. '+p.chapter:''} · ${p.provision}`)}</li>`).join('')}</ul><p>${a('/implementation/#concordance','Full concordance')} · ${a('/downloads/BestPFDJPolicyTowardsUS.pdf','Current U.S. strategy study')}</p></details>`;}
function card(item,d,mode,{compact=false,prefix=mode,heading='h3'}={}){
 const kind = item.publisher_kind === 'public-post' ? 'social' : /^(official|intergovernmental)/.test(item.publisher_kind) ? 'official' : 'independent';
 const independent=kind==='independent';const label='Published by '+item.publisher;
 const title = item.title.replace(/^(Misleading|Unsupported):\s*/, '');
 const rating = item.title.slice(0,item.title.length-title.length).replace(/:\s*$/, '');
 return `<article class="watch-card${independent?' watch-independent':''}" id="${esc(prefix)}-${esc(item.id)}" data-source-id="${esc(item.source_id)}" data-record-id="${esc(item.id)}"><p class="watch-attribution">${badge(kind)} ${esc(label)}${rating ? ` <span class="site-badge" data-badge="independent">Publisher rating: ${esc(rating)}</span>` : ''}</p><div class="watch-tags">${badge(item.review_status==='source-reviewed'?'reviewed':'automatic')}${(item.case_codes||[]).map(c=>`<span>${esc(c)}</span>`).join('')}</div><${heading}>${a('/'+(mode==='escalation'?'watch':'updates')+'/records/'+item.id+'/',item.title)}</${heading}><p class="watch-date">${item.published_at?`Published ${isoDate(item.published_at)}`:'Publication date not supplied'} · Collected ${isoDate(item.collected_at)}</p>${compact?'':`<p>${esc(item.summary)}</p>`}<p class="watch-original">${a(item.url,'Read the original publisher ↗')}</p>${compact?'':refs(item,d)}</article>`;
}
export function watchWindow(d,{id='current-policy-sources',module=null,mode='policy',title='Current policy sources',limit=3}={}){
 let items=d[mode].items;
 if(module){const ids=d.context.modules.find(m=>m.id===module)?.provision_ids||[];items=items.filter(x=>x.provision_ids.some(p=>ids.includes(p)));if(!items.length)return '';}
 return `<section class="source-watch watch-window" id="${esc(id)}"><header><div><h2>${esc(title)}</h2></div>${a(mode==='escalation'?'/watch/':'/updates/','Browse the source watch ↗')}</header><p class="watch-intro">Attributed reports alongside the governing framework. Publication does not establish implementation or amend the PDF.</p><div class="watch-grid">${items.slice(0,limit).map(x=>card(x,d,mode,{compact:true,prefix:id})).join('')||'<p>No reports have been published for this view yet.</p>'}</div></section>`;
}
function shell(title,content,path){return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="description" content="Attributed public-source reporting and chapter-linked independent commentary."><title>${esc(title)} | Eritrea 2042</title><link rel="canonical" href="${ORIGIN}${path}"><link rel="stylesheet" href="/assets/site.css"><link rel="stylesheet" href="/watch/watch.css"><link rel="icon" href="/favicon.svg"></head><body><a class="skip-link" href="#content">Skip to content</a><!--nav--><!--/nav--><main class="wrap source-watch watch-page" id="content">${content}</main><!--foot--><!--/foot--></body></html>`;}

export async function buildWatch(output,d,socialSources,sourceFeed,sourceFeedAssets,atlas){
 const groupByHandle = new Map(socialSources.filter(s => s.platform === 'x').map(s => [s.handle.toLowerCase(), s.group]));
 const posts = collectXPosts(d);
 const postsByHandle = new Map();
 for (const post of posts) {
  const handle = post.account.handle.toLowerCase();
  if (!postsByHandle.has(handle)) postsByHandle.set(handle, []);
  postsByHandle.get(handle).push(post);
 }
 const urls=[];
 const summarized = mode => {
   const report = sourceStatus(d, mode);
   return { records: d[mode].items.length, checkedAt: report?.checked_at ?? null,
     queuedArticles: report?.pending ?? null, sourceChecks: report?.sources.length ?? 0,
     articleAccessErrors: (report?.failures ?? []).filter(failure => failure.record).length };
 };
 await output('data/watch-status.json', JSON.stringify({
   schemaVersion: 1, reviewedOn: site.reviewedOn, enabledXAccounts: d.activeXAccounts,
   enabledWebPublishers: d.catalog?.sources.filter(source => source.active && source.platform === 'web').length ?? 0,
   previousRegisterAccounts: d.registry.accounts.length, selectedPosts: posts.length,
   policy: summarized('policy'), regional: summarized('escalation')
 }, null, 2) + '\n');
 const page=async(path,title,html,{interactive = false} = {})=>{
  urls.push(path);
  const markup = shell(title, html, path);
  const source = html.includes('data-source-feed') ? markup.replace('</head>', sourceFeedAssets + '</head>') : markup;
  await output(path.slice(1)+'index.html', interactive ? source.replace('</body>', '<script type="module" src="/assets/watch.js"></script></body>') : source);
 };
 for(const mode of ['escalation','policy']){
  const path=mode==='escalation'?'/watch/':'/updates/';const title=mode==='escalation'?'Regional Watch':'News & Policy Updates';const items=d[mode].items;
  const intro=`<header class="hub-hero"><h1>${esc(title)}</h1>
    <p class="lede">${mode === 'escalation'
      ? 'Dated public reporting on Eritrea, Ethiopia and the Red Sea, with chapter-linked sources and regional analysis.'
      : 'Official statements and independent reporting relevant to the project’s governing chapters.'}</p>
    <nav class="catalog-actions" aria-label="Browse the watch">${a(path+'archive/','Dated archive')}
    ${mode === 'escalation' ? a('/regional/','Regional analysis & atlas') : a('/#diaspora-politics','Diaspora directory')}
    ${a('/watch/posts/','Selected X posts')}${a('/sources/','Sources & X Directory')}</nav></header>
    ${mode === 'escalation' ? regionMap(atlas) : ''}
    ${coveragePanel(d, mode)}
    ${badgeLegend(['official', 'independent', 'social', 'reviewed', 'automatic'])}`;
  await page(path,title,intro+(mode==='escalation'?sourceFeed+watchPostsWindow(posts,a):'')+
    proposedFeed(mode === 'escalation' ? 'regional' : 'policy')+
    (mode === 'policy' ? `<section class="hub-band" id="news-collections"><div><h2>More news collections</h2><p>Browse regional media, election files and diaspora profiles.</p></div><div class="catalog-actions">${a('/#news-sources','Media sources')} ${a('/#diaspora-politics','Diaspora directory')}</div></section>` : '')+`<p>${a(path+'archive/','All source records ↗')} · ${a('/watch/sources/','Access and identity register ↗')}</p>`);
  const count=Math.max(1,Math.ceil(items.length/18));for(let n=1;n<=count;n++){
   const p=path+'archive/'+(n===1?'':'page-'+n+'/');
   await page(p,title+' archive',`<p class="section-label">DATED SOURCE RECORDS</p><h1>${esc(title)} archive</h1><p>${a(path,'← Source watch')}</p><div class="watch-grid">${items.slice((n-1)*18,n*18).map(x=>card(x,d,mode,{heading:'h2'})).join('')}</div><nav class="pagination">${n>1?a(path+'archive/'+(n===2?'':'page-'+(n-1)+'/'),'← Previous'):''}<span>Page ${n} of ${count}</span>${n<count?a(path+'archive/page-'+(n+1)+'/','Next →'):''}</nav>`);
  }
  for(const i of items)await page(path+'records/'+i.id+'/',i.title,`<p class="section-label">ATTRIBUTED SOURCE / REVISION ${i.revision}</p><h1>${esc(i.title)}</h1>${card(i,d,mode,{heading:'h2'})}<section class="watch-record"><h2>Record boundaries</h2><p>${esc(i.evidence_label)}. ${i.publisher_kind==='independent' ? 'The publisher has no formal ties to Eritrea 2042. ' : ''}Local keyword scoring routes the record; it does not determine whether a military event, legal change or claimed project occurred.</p><dl><dt>First collected</dt><dd>${watchTime(i.collected_at)}</dd><dt>Last record update</dt><dd>${watchTime(i.updated_at)}</dd><dt>Content fingerprint</dt><dd><code>${esc(i.content_hash)}</code></dd></dl></section>`);
 }
 await page('/watch/posts/', 'Posts from registered X accounts', watchPostsPage(posts, d.registry.accounts.length, a), {interactive: true});
 await page('/watch/sources/','Source and account register',`<header class="hub-hero"><h1>Legacy source and account register</h1><p class="lede">Browse the current source catalog, inspect publisher access, and search the earlier X register.</p><p>${a('/sources/','Open the current X directory')}</p></header>
 ${badgeLegend(['official', 'independent', 'social'])}
 <nav class="watch-links" aria-label="Browse the register">${a('#source-access','Source access')}${a('#source-feed','Current source catalog')}${a('#registered-account-groups','Earlier X register')}${a('/watch/posts/','X posts')}</nav>
 <p class="watch-checks">Latest checks · ${a('/watch/','Regional watch')} ${watchTime(sourceStatus(d,'escalation')?.checked_at)} · ${a('/updates/','Policy updates')} ${watchTime(sourceStatus(d,'policy')?.checked_at)}</p>
 ${sourceFeed}
 ${sourceAccessTable(d,a)}
 <details><summary>Earlier X register · ${d.registry.accounts.length} handles</summary>
 <h2>Earlier X register</h2>
 ${d.xReview ? `<p>Latest bounded review: ${isoDate(d.xReview.checkedAt)}. ${d.xReview.selectedCount} registered priorities and rotating handles were selected across the four theaters. X coverage remains incomplete. Access attempts, read posts and verified identities are distinct. <a href="/data/x-review-log.json">Dated handle and access log ↗</a></p>` : ''}
 <p>The ${isoDate('2026-11-21')} import registers 125 handles, including one already listed. Registration records the supplied account link. Read original posts and corroborating evidence before relying on an identity, affiliation or claim. <a href="/data/source-batch-2026-11-21.json">Import record ↗</a></p><p>Public RSS bindings and reviewed accessible posts are supported; no paid timeline service is connected. <a href="/project-roadmap/#recurring-check-protocol">Read the recurring check protocol</a> · <a href="/data/source-batch-2026-11-21.json">Account import ledger</a></p>
 <div class="watch-account-grid">${d.registry.accounts.map(account => renderSocialRow({
   ...account, group: groupByHandle.get(account.handle.toLowerCase()) ?? 'analyst'
 }, {register:true, posts:postsByHandle.get(account.handle.toLowerCase())})).join('')}</div></details><p>Adulis News and Adulis Review are independent publishers with no formal ties to Eritrea 2042.</p><p><a href="/data/watch-status.json">Coverage data (JSON)</a> · <a href="/watch/setup/">Source collection setup</a> · <a href="/watch/changelog.md">Production change log</a></p>`, {interactive: true});
 await page('/watch/setup/','Zero-cost deployment setup',`<p class="section-label">SOURCE CODE / CONFIGURATION</p><h1>Deploy the zero-cost hub</h1><p class="lede">The complete site and runnable collectors are provided together. No paid APIs or model credentials are required.</p><p>${a('/downloads/eritrea2042-monitoring-source.zip','Download the complete source ZIP')} · ${a('/watch/QUICKSTART.md','Source feed quickstart')} · ${a('/watch/DEPLOYMENT.md','Step-by-step setup')} · ${a('/watch/CODE_REFERENCE.md','Complete, unabridged code blocks')}</p><h2>GitHub Pages</h2><ol><li>Create a new public <code>YOUR-USERNAME.github.io</code> repository, preserving any existing site by using a separate repository/account if necessary.</li><li>Upload the ZIP contents, including <code>.github</code> and the package-manager lock/config files. The supplied workflows refuse private repositories.</li><li>Keep paid usage disabled or enforce a $0 Actions budget. Allow workflows to write to the new repository’s default branch.</li><li>Choose GitHub Actions in Pages settings and set <code>DEPLOY_GITHUB_PAGES=true</code> as a repository variable.</li><li>Run either workflow manually once. The escalation job then checks sources every 12 hours; the policy job runs daily.</li></ol><p>A GitHub deployment creates an independent Pages copy. The current chatgpt.site address uses its linked update task and supported publishing workflow.</p>`);
 for(const name of ['DEPLOYMENT.md','CODE_REFERENCE.md'])await output('watch/'+name,await readFile('docs/monitoring/'+name,'utf8'));
 await output('watch/changelog.md',await readFile('changelog.md','utf8'));
 await output('watch/QUICKSTART.md',await readFile('QUICKSTART.md','utf8'));
 return urls;
}
```

## scripts/watch-coverage.mjs

```javascript
import {esc} from '../src/js/core.js';
import {isoDate} from '../tools/build.mjs';

const statusLabels = {
  ok: 'Responded',
  backoff: 'Waiting to retry',
  unavailable: 'Unavailable',
  pending: 'Awaiting first check',
};
const reasonLabels = {
  'http-403': 'Access refused by the publisher',
  'http-429': 'Publisher rate limit',
  'invalid-feed': 'Response could not be parsed as a feed',
  'robots-disallowed': 'Publisher robots rules restrict collection',
  'robots-unavailable': 'Publisher robots rules were unreachable',
  'network-or-encoding-error': 'Network or response decoding error',
  'request-budget': 'Check reached the request limit',
};
const methodLabels = {rss: 'Publisher RSS', html: 'Website listing', 'map-log': 'Publisher map'};

export function watchTime(value, fallback = 'Awaiting first check') {
  if (!value) return fallback;
  const date = new Date(value);
  if (!Number.isFinite(date.getTime())) return fallback;
  if (!value.includes('T')) return isoDate(value);
  const stamp = date.toISOString().replace(/\.\d+Z$/, 'Z');
  return `<time datetime="${stamp}">${stamp.slice(0, 16).replace('T', ' ')} UTC</time>`;
}

export function sourceStatus(d, mode) {
  return mode === 'escalation' ? d.escalationStatus : d.policyStatus;
}

export function coveragePanel(d, mode) {
  const report = sourceStatus(d, mode);
  const sources = new Map((report?.sources ?? []).map(source => [source.id, source.status]));
  const publisherFeeds = d.config.sources.filter(source => source.adapter === 'rss' && source.modes.includes(mode));
  const count = status => [...sources.values()].filter(value => value === status).length;
  const responded = publisherFeeds.filter(source => sources.get(source.id) === 'ok').length;
  const articleErrors = (report?.failures ?? []).filter(failure => failure.record).length;
  return `<aside class="watch-coverage" id="watch-coverage" aria-label="Source coverage">
    <div class="watch-metrics">
      <div><strong>Latest recorded collection</strong><p>${watchTime(report?.checked_at)}</p>${report ? `<p>${report.pending} queued articles · ${articleErrors} article access errors</p>` : ''}</div>
      <div><strong>Publisher feeds</strong><p>${responded} of ${publisherFeeds.length} RSS feeds responded</p><p>${count('backoff')} sources waiting to retry · ${count('unavailable')} unavailable</p></div>
      <div><strong>X coverage</strong><p>${d.activeXAccounts.toLocaleString('en-US')} X accounts enabled in the catalog</p><p>Selected public posts · partial access</p></div>
    </div>
    <div class="watch-coverage-details">
      <div class="watch-coverage-links"><a href="/watch/sources/#source-access">See source access and retry times</a><span>$0 in source-service fees</span></div>
      ${report?.public_search_notice ? `<details><summary>Public search results</summary><p>${esc(report.public_search_notice)}</p></details>` : ''}
      ${report?.x_notice ? `<details><summary>X collection notes</summary><p>${esc(report.x_notice)}</p></details>` : ''}
    </div>
  </aside>`;
}

export function sourceAccessTable(d, link) {
  const snapshots = [d.escalationStatus, d.policyStatus].filter(Boolean)
    .sort((left, right) => left.checked_at.localeCompare(right.checked_at));
  const latest = new Map(snapshots.flatMap(report => report.sources.map(row => [row.id, row])));
  const configured = new Map(d.config.sources.map(source => [source.id, source]));
  const ids = new Set([...configured.keys(), ...latest.keys()]);
  const rows = [...ids].map(id => {
    const source = configured.get(id) ?? latest.get(id);
    const check = latest.get(id);
    const state = Object.hasOwn(statusLabels, check?.status) ? check.status : 'pending';
    const method = methodLabels[source.adapter] ?? 'X RSS';
    const reason = check?.reason;
    return `<tr data-watch-row><th scope="row">${link(source.url, source.label)}
      ${source.access_label ? `<span class="watch-access-detail">${esc(source.access_label)}</span>` : ''}</th>
      <td>${esc(method)}</td>
      <td><span class="watch-state" data-state="${state}">${statusLabels[state]}</span>
        ${reason ? `<span class="watch-access-detail">${esc(reasonLabels[reason] ?? reason)}</span>` : ''}</td>
      <td>${watchTime(check?.last_success, 'No successful check')}</td>
      <td>${watchTime(check?.next_attempt, '—')}</td></tr>`;
  });
  const checked = snapshots.at(-1)?.checked_at;
  return `<section id="source-access" data-watch-filter>
    <h2>Source access</h2>
    <label class="watch-field" hidden>Filter sources and status
      <input type="search" data-watch-query aria-controls="source-access-rows" placeholder="Search publishers, feeds or status" maxlength="160">
    </label>
    <p class="watch-filter-status" data-watch-result role="status" hidden></p>
    <div class="table-scroll"><table class="data-table watch-access-table"><caption>Website source access${checked ? ` · ${watchTime(checked)}` : ''}</caption>
      <thead><tr><th scope="col">Source</th><th scope="col">Method</th><th scope="col">Latest status</th><th scope="col">Last success</th><th scope="col">Retry eligible</th></tr></thead>
      <tbody id="source-access-rows">${rows.join('')}</tbody>
    </table></div>
  </section>`;
}
```

## scripts/watch-posts.mjs

```javascript
import {esc} from '../src/js/core.js';

// Accept exact public status links from the registered account. Store IDs as
// strings because X post identifiers exceed JavaScript's safe integer range.
function postLink(value) {
  const match = /^https:\/\/(?:x|twitter)\.com\/([a-z0-9_]{1,15})\/status\/([0-9]{15,22})\/?(?:[?#].*)?$/i.exec(value);
  return match && {handle: match[1].toLowerCase(), id: match[2]};
}

export function collectXPosts(watch) {
  const accounts = new Map(watch.registry.accounts.map(account => [account.handle.toLowerCase(), account]));
  const posts = new Map();
  function add(record, topic, selected = false) {
    const link = postLink(record.url);
    const account = accounts.get(link?.handle);
    if (!account) {
      if (selected) throw new Error('Selected X post needs a registered handle and an exact status URL: ' + record.url);
      return;
    }
    const entry = posts.get(link.id);
    if (entry && entry.account.handle !== account.handle) throw new Error('Conflicting X post authors for ' + link.id);
    if (!entry || (!selected && (record.updated_at ?? '') > entry.updatedAt)) {
      posts.set(link.id, {
        id: link.id, account, url: `https://x.com/${account.handle}/status/${link.id}`,
        title: record.title, summary: record.summary, publishedAt: record.published_at,
        updatedAt: record.updated_at ?? '', topic: entry?.topic ?? topic,
      });
    }
  }
  for (const selected of watch.selectedPosts) add(selected, selected.topic, true);
  for (const record of watch.escalation.items) {
    if (record.review_status === 'source-reviewed') add(record, 'Regional affairs');
  }
  for (const record of watch.policy.items) {
    if (record.review_status === 'source-reviewed') add(record, 'Policy');
  }
  return [...posts.values()].sort((left, right) => (right.publishedAt ?? '').localeCompare(left.publishedAt ?? '') || right.id.localeCompare(left.id));
}

function postDate(value) {
  if (!value) return 'Date unavailable';
  const day = value.slice(0, 10);
  const label = new Intl.DateTimeFormat('en', {dateStyle:'medium', timeZone:'UTC'}).format(new Date(day));
  return `<time datetime="${esc(day)}">${esc(label)}</time>`;
}

function postCard(post, link, preview) {
  const handle = post.account.handle;
  const heading = preview ? 'h2' : 'h3';
  return `<article class="watch-post" id="post-${post.id}" data-watch-row data-post-account="${esc(handle.toLowerCase())}" data-post-topic="${esc(post.topic)}">
    <header class="watch-post-meta"><span>${link(post.account.url, '@' + handle)}</span>${postDate(post.publishedAt)}</header>
    <p class="watch-post-topic">${esc(post.topic)}</p>
    <${heading}>${esc(post.title)}</${heading}>
    <p>${esc(post.summary)}</p>
    ${link(post.url, 'Open original post on X')}
    ${preview ? `<details class="watch-post-preview" data-x-preview data-x-post="${post.id}" data-x-handle="${esc(handle)}" hidden>
      <summary>Load X preview</summary>
      <div data-x-frame></div>
    </details>` : ''}
  </article>`;
}

export function watchPostsPage(posts, registrySize, link) {
  const accounts = [...new Set(posts.map(post => post.account.handle))].sort((a, b) => a.localeCompare(b, 'en', {sensitivity: 'base'}));
  const topics = [...new Set(posts.map(post => post.topic))].sort();
  return `<h1>Posts from registered X accounts</h1>
    <p class="lede">Selected posts on Eritrea, regional affairs and policy. The summaries attribute claims to the account that made them. Previews connect to X when opened.</p>
    <p class="watch-checks">Posts from ${accounts.length} of ${registrySize} registered accounts · Newest first</p>
    <nav class="watch-links" aria-label="Watch navigation">${link('/watch/', 'Regional watch')}${link('/updates/', 'Policy updates')}${link('/watch/sources/#registered-account-groups', 'X account directory')}</nav>
    <section id="x-posts" data-watch-filter>
      <div class="watch-post-filters" data-watch-controls hidden>
        <label class="watch-field">Search posts<input type="search" data-watch-query aria-controls="post-results" placeholder="Search headlines, topics or handles" maxlength="160"></label>
        <label class="watch-field">Account<select data-watch-account aria-controls="post-results"><option value="">All accounts with posts</option>
          ${accounts.map(handle => `<option value="${esc(handle.toLowerCase())}">@${esc(handle)}</option>`).join('')}
        </select></label>
        <label class="watch-field">Topic<select data-watch-topic aria-controls="post-results"><option value="">All topics</option>
          ${topics.map(topic => `<option>${esc(topic)}</option>`).join('')}
        </select></label>
      </div>
      <p class="watch-filter-status" data-watch-result role="status" hidden></p>
      <div class="watch-post-list" id="post-results">${posts.map(post => postCard(post, link, true)).join('') || '<p>Selected posts will appear here after review.</p>'}</div>
    </section>`;
}

export function watchPostsWindow(posts, link) {
  if (!posts.length) return '';
  const recent = posts.slice(0, 3);
  return `<section class="watch-post-section" aria-labelledby="watch-x-heading">
    <header><h2 id="watch-x-heading">Recent posts from X sources</h2>${link('/watch/posts/', 'Browse all selected posts ↗')}</header>
    <div class="watch-post-list">${recent.map(post => postCard(post, link, false)).join('')}</div>
  </section>`;
}
```

## src/js/watch.js

```javascript
import {normalise} from './core.js';
import {makeXPostFrame} from './x-post-frame.js';

const params = new URLSearchParams(location.search);
for (const panel of document.querySelectorAll('[data-watch-filter]')) {
  const query = panel.querySelector('[data-watch-query]');
  const account = panel.querySelector('[data-watch-account]');
  const topic = panel.querySelector('[data-watch-topic]');
  const result = panel.querySelector('[data-watch-result]');
  const rows = [...panel.querySelectorAll('[data-watch-row]')].map(row => ({
    row,
    text: normalise(row.textContent),
  }));
  const noun = account ? 'post' : 'source';
  const accountFilter = params.get('account');
  if (account && [...account.options].some(option => option.value === accountFilter)) {
    account.value = accountFilter;
  }
  function filter() {
    const words = normalise(query.value).trim().split(/\s+/).filter(Boolean);
    let visible = 0;
    for (const {row, text} of rows) {
      const matches = words.every(word => text.includes(word))
        && (!account?.value || row.dataset.postAccount === account.value)
        && (!topic?.value || row.dataset.postTopic === topic.value);
      row.hidden = !matches;
      if (matches) visible++;
      else row.querySelector('[data-x-preview][open]')?.removeAttribute('open');
    }
    result.textContent = visible === 0 ? `No matching ${noun}s` : `${visible} ${noun}${visible === 1 ? '' : 's'}`;
  }
  query.addEventListener('input', filter);
  account?.addEventListener('change', filter);
  topic?.addEventListener('change', filter);
  (panel.querySelector('[data-watch-controls]') ?? query.closest('label')).hidden = false;
  result.hidden = false;
  filter();
}

for (const preview of document.querySelectorAll('[data-x-preview]')) {
  const summary = preview.querySelector('summary');
  const container = preview.querySelector('[data-x-frame]');
  // Only a visitor gesture starts a network request. The shared anchor and
  // print handlers can open details, so a toggle alone must never load X.
  summary.addEventListener('click', () => {
    if (preview.open) return;
    for (const other of document.querySelectorAll('[data-x-preview][open]')) other.open = false;
    const frame = makeXPostFrame(preview.dataset.xPost, preview.dataset.xHandle);
    if (!frame) return;
    frame.classList.add('watch-x-frame');
    container.replaceChildren(frame);
  });
  preview.addEventListener('toggle', () => {
    if (!preview.open) container.replaceChildren();
  });
  preview.hidden = false;
}
```

## src/js/x-post-frame.js

```javascript
export function makeXPostFrame(id, handle) {
  if (!/^[0-9]{15,22}$/.test(id) || !/^[a-z0-9_]{1,15}$/i.test(handle)) return null;
  const frame = document.createElement('iframe');
  frame.title = 'Post on X from @' + handle;
  frame.referrerPolicy = 'no-referrer';
  frame.src = 'https://platform.twitter.com/embed/Tweet.html?dnt=true&id=' + id;
  return frame;
}
```

## scripts/fetch_sources.py

```python
#!/usr/bin/env python3
"""Collect a bounded public feed and persist a resumable source checkpoint."""
from __future__ import annotations

import argparse
import asyncio
import fcntl
import hashlib
import json
import os
import random
import re
import signal
import tempfile
from collections import Counter
from contextlib import aclosing
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.parse import urljoin, urlsplit, urlunsplit
from urllib.robotparser import RobotFileParser

import httpx

ROOT = Path(__file__).resolve().parents[1]
USER_AGENT = "Eritrea2042SourceFeed/1.0 (+https://eritrea2042.marinespoon.chatgpt.site/watch/)"
MAX_FEED_BYTES = 499_999
MAX_HTML_BYTES = 2_000_000
MAX_ITEMS = 500
RETENTION = timedelta(days=14)
HANDLE = re.compile(r"[a-zA-Z0-9_]{1,15}\Z")
COOKIE = re.compile(r"[a-zA-Z0-9._~-]{12,1024}\Z")
TERMINAL = {"ok", "not-found", "protected"}


def now() -> datetime:
    return datetime.now(UTC)


def stamp(value: datetime) -> str:
    return value.astimezone(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")


def as_date(value: str | None) -> datetime | None:
    if not isinstance(value, str) or len(value) > 100:
        return None
    try:
        result = datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError:
        try:
            result = parsedate_to_datetime(value)
        except (ValueError, TypeError):
            return None
    return result.replace(tzinfo=result.tzinfo or UTC).astimezone(UTC)


def text(value: str | None, length: int = 500) -> str:
    clean = " ".join((value or "").split())
    return clean if len(clean) <= length else clean[:length - 1].rstrip() + "…"


def https_url(value: str | None, host: str | None = None) -> str | None:
    if not isinstance(value, str) or len(value) > 1000 or any(c.isspace() for c in value):
        return None
    try:
        parsed = urlsplit(value)
        if parsed.scheme == "https" and parsed.hostname and not parsed.username and not parsed.password \
                and parsed.port in (None, 443) and (host is None or parsed.hostname == host):
            return urlunsplit(parsed._replace(fragment=""))
    except ValueError:
        pass
    return None


def read_json(path: Path, default: dict | None = None) -> dict:
    try:
        result = json.loads(path.read_text(encoding="utf-8"))
    except FileNotFoundError:
        if default is None:
            raise
        return default
    if not isinstance(result, dict) or result.get("schemaVersion") != 1:
        raise ValueError(f"Unsupported schema for {path.name}")
    return result


def encode(value: dict) -> bytes:
    return (json.dumps(value, ensure_ascii=False, separators=(",", ":")) + "\n").encode()


def write_atomic(path: Path, value: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as out:
        stage = Path(out.name)
        out.write(encode(value))
    try:
        stage.replace(path)
    finally:
        stage.unlink(missing_ok=True)


def validate_catalog(catalog: dict) -> None:
    sources = catalog["sources"]
    category_ids = {row["id"] for row in catalog["categories"]}
    types = {row["id"] for row in catalog["sourceTypes"]}
    ids = {row["id"] for row in sources}
    if len(ids) != len(sources) or not category_ids or len(category_ids) != len(catalog['categories']) or types != {'official', 'independent', 'social', 'project'}:
        raise ValueError("Duplicate sources or invalid category schema")
    for source in sources:
        url = source["profileUrl"]
        if not https_url(url) or source["categoryId"] not in category_ids \
                or source["sourceType"] not in types or not isinstance(source["active"], bool):
            raise ValueError(f"Invalid source record {source['id']}")
        if source["platform"] == "x":
            handle = source["handle"]
            if not HANDLE.fullmatch(handle) or source["id"] != f"x:{handle.casefold()}" \
                    or url.casefold() != f"https://x.com/{handle.casefold()}":
                raise ValueError(f"Invalid X profile {source['id']}")
        elif source["platform"] == "web":
            if source.get("rssRegistry"):
                if not https_url(source["url"]):
                    raise ValueError(f"Invalid RSS endpoint {source['id']}")
                continue
            host = urlsplit(url).hostname
            if not source["listingUrls"] or not all(https_url(url, host) for url in source["listingUrls"]):
                raise ValueError(f"Invalid publisher URLs for {source['id']}")
            re.compile(source["articlePathPattern"])
        else:
            raise ValueError(f"Unknown platform for {source['id']}")
    remote = catalog.get("remoteFeedUrl")
    if remote is not None and not https_url(remote):
        raise ValueError("remoteFeedUrl must be a public HTTPS URL or null")


class SourceError(Exception):
    def __init__(self, code: str, *, delay: float = 0, halt_x: bool = False):
        super().__init__(code)
        self.code = code
        self.delay = delay
        self.halt_x = halt_x


@dataclass
class Result:
    status: str
    items: list[dict] = field(default_factory=list)
    attempted: bool = True
    delay: float = 0


class Requests:
    def __init__(self, concurrency: int, jitter_min: float, jitter_max: float):
        self.slots = asyncio.Semaphore(concurrency)
        self.jitter = (jitter_min, jitter_max)

    async def call(self, operation, *args):
        async with self.slots:
            await asyncio.sleep(random.uniform(*self.jitter))
            return await asyncio.wait_for(operation(*args), timeout=40)


def retry_delay(headers, attempt: int) -> float:
    delay = 3 * (2 ** attempt)
    header = headers.get("retry-after", "")
    if header.isdigit():
        return max(delay, float(header))
    date = as_date(header)
    return max(delay, (date - now()).total_seconds()) if date else delay


class Publishers:
    def __init__(self, requests: Requests, client: httpx.AsyncClient):
        self.requests = requests
        self.client = client

    async def response(self, url: str, host: str) -> tuple[int, dict, str]:
        for _ in range(4):
            if not https_url(url, host):
                raise SourceError("publisher-redirect-off-domain")
            async with self.client.stream("GET", url) as response:
                if response.is_redirect:
                    url = urljoin(url, response.headers.get("location", ""))
                    continue
                if response.status_code != 200:
                    return response.status_code, dict(response.headers), ""
                body = bytearray()
                async for chunk in response.aiter_bytes():
                    body.extend(chunk)
                    if len(body) > MAX_HTML_BYTES:
                        raise SourceError("publisher-response-too-large")
                return 200, dict(response.headers), body.decode(response.encoding or "utf-8", errors="replace")
        raise SourceError("publisher-redirect-limit")

    async def get(self, url: str, host: str, *, allow_missing: bool = False) -> str:
        for attempt in range(3):
            try:
                status, headers, body = await self.requests.call(self.response, url, host)
            except (TimeoutError, httpx.RequestError) as exc:
                if attempt == 2:
                    raise SourceError("publisher-network-error", delay=900) from exc
                await asyncio.sleep(3 * 2 ** attempt)
                continue
            if status == 200:
                return body
            if status == 404 and allow_missing:
                return ""
            if status in (403, 429) or 500 <= status <= 599:
                delay = retry_delay(headers, attempt)
                if delay <= 25 and attempt < 2:
                    await asyncio.sleep(delay)
                    continue
                raise SourceError(f"publisher-http-{status}", delay=max(delay, 900))
            raise SourceError(f"publisher-http-{status}", delay=900)
        raise SourceError("publisher-unavailable", delay=900)

    async def collect(self, source: dict) -> Result:
        host = urlsplit(source["profileUrl"]).hostname
        robots = RobotFileParser()
        policy = await self.get(f"https://{host}/robots.txt", host, allow_missing=True)
        robots.parse(policy.splitlines())
        pattern = re.compile(source["articlePathPattern"])
        candidates = {}
        listing_errors = []
        for listing_template in source["listingUrls"]:
            listing = listing_template.replace("{year}", str(now().year))
            if not robots.can_fetch(USER_AGENT, listing):
                listing_errors.append(SourceError("publisher-robots-denied", delay=86_400))
                continue
            try:
                page = await self.get(listing, host)
            except SourceError as error:
                listing_errors.append(error)
                if error.code.endswith(("-403", "-429")):
                    break
                continue
            found = listing_links(page, listing, host, pattern)
            for url, title in found[:8]:
                candidates.setdefault(url, title)
        if not candidates:
            if listing_errors:
                raise listing_errors[0]
            raise SourceError("publisher-listing-has-no-article-links", delay=3600)
        items = []
        article_errors = []
        dated = 0
        cutoff = now() - RETENTION
        for url, fallback_title in list(candidates.items())[:12]:
            # Dated URL paths can eliminate older articles without another request.
            date_hint = date_in_url(url)
            if date_hint and date_hint < cutoff:
                dated += 1
                continue
            if not robots.can_fetch(USER_AGENT, url):
                article_errors.append(SourceError("publisher-robots-denied", delay=86_400))
                continue
            try:
                page = await self.get(url, host)
            except SourceError as error:
                article_errors.append(error)
                if error.code.endswith(("-403", "-429")):
                    break
                continue
            item = parse_article(page, url, source, fallback_title, date_hint)
            if item:
                dated += 1
                items.append(item)
        if article_errors or listing_errors:
            error = (listing_errors + article_errors)[0]
            return Result(error.code, items, delay=error.delay)
        if not dated:
            raise SourceError("publisher-publication-date-unavailable", delay=3600)
        return Result("ok", items)


def listing_links(page: str, base: str, host: str, pattern: re.Pattern) -> list[tuple[str, str]]:
    from bs4 import BeautifulSoup
    doc = BeautifulSoup(page, "html.parser")
    content = doc.select_one("main, [role=main]") or doc
    links = {}
    for anchor in content.select("a[href]"):
        url = https_url(urljoin(base, anchor["href"]), host)
        if not url:
            continue
        parsed = urlsplit(url)
        if pattern.fullmatch(parsed.path):
            key = urlunsplit(parsed._replace(query=""))
            title = text(anchor.get_text(" ", strip=True), 200)
            if key not in links or not links[key]:
                links[key] = title
    return list(links.items())


def date_in_url(url: str) -> datetime | None:
    path = urlsplit(url).path
    match = re.search(r"/(20\d\d)/(\d{2})/(\d{2})/", path) or re.search(r"(20\d\d)(\d{2})(\d{2})", path)
    return as_date("-".join(match.groups())) if match else None


def parse_article(page: str, url: str, source: dict, fallback: str, date_hint: datetime | None) -> dict | None:
    from bs4 import BeautifulSoup
    doc = BeautifulSoup(page, "html.parser")

    def meta(*names):
        for name in names:
            tag = doc.find("meta", attrs={"property": name}) or doc.find("meta", attrs={"name": name})
            if tag and tag.get("content"):
                return tag["content"]
        return None

    heading = doc.select_one("main h1, article h1, h1")
    title = text(meta("og:title") or (heading.get_text(" ", strip=True) if heading else fallback), 200)
    time_tag = doc.select_one("main time[datetime], article time[datetime], time[datetime]")
    published = as_date(meta("article:published_time", "datePublished", "DC.date", "pubdate") or
                        (time_tag["datetime"] if time_tag else None))
    if not published:
        found = re.search(r'"datePublished"\s*:\s*"([^"]{1,80})"', page)
        published = as_date(found[1]) if found else date_hint
    if not title or not published:
        return None
    excerpt = text(meta("og:description", "description"), 360)
    image = https_url(urljoin(url, meta("og:image") or ""), urlsplit(url).hostname) if meta("og:image") else None
    item = {"id": "url:" + hashlib.sha256(url.encode()).hexdigest()[:24], "sourceId": source["id"],
            "url": url, "publishedAt": stamp(published), "title": title}
    if excerpt and excerpt != title:
        item["text"] = excerpt
    if image:
        item["imageUrl"] = image
    return item


class XTimeline:
    # A single authorized session. One lock per operation avoids a false
    # "no account" result when two calls try to use the same SDK queue.
    def __init__(self, requests: Requests):
        self.requests = requests
        self.profile_lock = asyncio.Lock()
        self.timeline_lock = asyncio.Lock()
        self.halt = None

    async def start(self, database: Path, token: str, csrf: str) -> None:
        from twscrape import API, set_log_level
        set_log_level("CRITICAL")
        self.api = API(str(database), debug=False, raise_when_no_account=True, wait_timeout=None)
        await self.api.pool.add_account_cookies("feed-session", f"auth_token={token}; ct0={csrf}")

    async def lock_delay(self, queue: str) -> float:
        account = await self.api.pool.get("feed-session")
        if not account.active:
            return 0
        locked = account.locks.get(queue)
        return max(0, (locked.replace(tzinfo=locked.tzinfo or UTC) - now()).total_seconds()) if locked else 0

    async def call(self, operation, lock: asyncio.Lock, queue: str, arg):
        from twscrape import AbortReqError, HttpError, NoAccountError, ParseError, XClIdParseError
        async with lock:
            if self.halt:
                raise self.halt
            for attempt in range(3):
                try:
                    return await self.requests.call(operation, arg)
                except NoAccountError as exc:
                    delay = await self.lock_delay(queue)
                    if 0 < delay <= 25 and attempt < 2:
                        await asyncio.sleep(max(delay, 3 * (2 ** attempt)) + 1)
                        continue
                    code = "x-rate-limited" if delay else "x-session-unavailable"
                    self.halt = SourceError(code, delay=max(delay, 900), halt_x=True)
                    raise self.halt from exc
                except AbortReqError as exc:
                    # The SDK reports an HTML access challenge as AbortReqError.
                    if any(str(status) in str(exc).split(" - ", 1)[0] for status in (403, 429)):
                        self.halt = SourceError("x-access-denied", delay=3600, halt_x=True)
                        raise self.halt from exc
                    raise SourceError("x-request-rejected", delay=900) from exc
                except XClIdParseError as exc:
                    self.halt = SourceError("x-session-protocol-changed", delay=3600, halt_x=True)
                    raise self.halt from exc
                except ParseError as exc:
                    raise SourceError("x-invalid-response", delay=900) from exc
                except (TimeoutError, HttpError) as exc:
                    if attempt == 2:
                        raise SourceError("x-network-error", delay=900) from exc
                    await asyncio.sleep(3 * 2 ** attempt)

    async def one_page(self, user_id: int) -> list:
        from twscrape.models import parse_tweets
        request = self.api.user_tweets_raw(user_id, limit=1, kv={"count": 8, "includePromotedContent": False})
        async with aclosing(request) as pages:
            response = await anext(pages, None)
            return list(parse_tweets(response, limit=8)) if response else []

    async def collect(self, source: dict) -> Result:
        if self.halt:
            return Result(self.halt.code, attempted=False, delay=self.halt.delay)
        user = await self.call(self.api.user_by_login, self.profile_lock, "UserByScreenName", source["handle"])
        if not user:
            return Result("not-found")
        if user.protected:
            return Result("protected")
        if user.username.casefold() != source["handle"].casefold():
            raise SourceError("x-handle-mismatch", delay=86_400)
        posts = await self.call(self.one_page, self.timeline_lock, "UserTweets", user.id)
        items = []
        for post in posts:
            if post.user.id != user.id or post.user.protected or post.retweetedTweetId:
                continue
            post_id = str(post.id)
            item = {"id": "x:" + post_id, "tweetId": post_id, "sourceId": source["id"],
                    "url": f"https://x.com/{source['handle']}/status/{post_id}",
                    "publishedAt": stamp(post.date), "text": text(post.rawContent)}
            if user.blue is True and user.blueType in {"Government", "Business"}:
                item["platformVerification"] = user.blueType
            photos = post.media.photos
            if photos and (image := https_url(photos[0].url, "pbs.twimg.com")):
                item["imageUrl"] = image
            elif post.media.videos and (image := https_url(post.media.videos[0].thumbnailUrl, "pbs.twimg.com")):
                item["imageUrl"] = image
            for link in post.links:
                if preview := https_url(link.url):
                    item["linkUrl"] = preview
                    break
            items.append(item)
        return Result("ok", items)


def choose_sources(catalog: dict, state: dict, full: bool, batch_size: int) -> list[dict]:
    active = [source for source in catalog["sources"] if source["active"] and not source.get("rssRegistry")]
    if full:
        key = hashlib.sha256(encode({"ids": [source["id"] for source in active],
                                     "revision": catalog["revision"]})).hexdigest()
        sweep = state.get("fullSweep") or {}
        if sweep.get("key") != key or sweep.get("finishedAt"):
            sweep = {"key": key, "startedAt": stamp(now()), "completed": []}
            state["fullSweep"] = sweep
        completed = set(sweep["completed"])
        return [source for source in active if source["id"] not in completed]
    x = [source for source in active if source["platform"] == "x"]
    if not x:
        return active
    web = [source for source in active if source["platform"] == "web"]
    pending = set(state.get("batchPending", []))
    resume = [source for source in x if source["id"] in pending]
    if resume:
        return web + resume
    cursor = state.get("cursor", 0) % len(x)
    count = min(len(x), batch_size)
    selected = (x + x)[cursor:cursor + count]
    state["cursor"] = (cursor + count) % len(x)
    state["batchPending"] = [source["id"] for source in selected]
    return web + selected


def compact(feed: dict, items, source_ids: set[str]) -> None:
    instant = now()
    cutoff = instant - RETENTION
    sorted_items = []
    for item in items:
        published = as_date(item.get("publishedAt"))
        if item.get("sourceId") in source_ids and published and cutoff <= published <= instant + timedelta(minutes=5):
            sorted_items.append((published, item))
    keys = set()
    feed["items"] = []
    size = len(encode(feed))
    for _, item in sorted(sorted_items, key=lambda row: row[0], reverse=True):
        if not item.get("id") or not https_url(item.get("url")):
            continue
        identity = {item["id"], item["url"]}
        if item.get("tweetId"):
            identity.add("tweet-id:" + item["tweetId"])
        if keys & identity:
            continue
        size += len(encode(item))
        if size > MAX_FEED_BYTES or len(feed["items"]) == MAX_ITEMS:
            break
        keys |= identity
        feed["items"].append(item)


async def collect_all(args, catalog: dict, state: dict, feed: dict) -> int:
    full = args.full or any(os.environ.get(flag) == "1" for flag in ("FORCE_FULL_SWEEP", "IGNORE_BATCH_CAP"))
    mode = "web_only" if args.web_only else "full_now" if full else "batch"
    if args.web_only:
        selected = [source for source in catalog["sources"] if source["platform"] == "web" and source["active"] and not source.get("rssRegistry")]
    else:
        selected = choose_sources(catalog, state, full, args.batch_size)
    sweep = state.get("fullSweep") if mode == "full_now" else None
    completed = set(sweep["completed"]) if sweep else set()
    previous = len(completed)
    pool = asyncio.Queue()
    for source in sorted(selected, key=lambda x: x["platform"] != "web"):
        pool.put_nowait(source)
    requests = Requests(args.max_concurrent, args.jitter_min, args.jitter_max)
    stop = asyncio.Event()
    loop = asyncio.get_running_loop()
    for sig in (signal.SIGINT, signal.SIGTERM):
        loop.add_signal_handler(sig, stop.set)
    timer = loop.call_later(args.max_minutes * 60, stop.set)
    flags = Counter()
    attempted = 0
    last_sync = feed.get("lastSyncedAt")
    old_items = {item["id"]: item for item in feed.get("items", [])}
    active_ids = {source["id"] for source in catalog["sources"] if source["active"]}
    run_time = stamp(now())
    token, csrf = (os.environ.pop(name, "").strip() for name in ("AUTH_TOKEN", "CT0"))

    def checkpoint() -> dict:
        coverage = {"mode": mode, "planned": len(selected) + previous, "selectedThisRun": len(selected),
                    "previouslyCompleted": previous, "attempted": attempted,
                    "succeeded": flags["ok"], "protectedOrMissing": flags["protected"] + flags["not-found"],
                    "pending": max(0, len(selected) + previous - (len(completed) if sweep else
                                                                   flags["ok"] + flags["protected"] + flags["not-found"])),
                    "outcomes": dict(flags)}
        feed.update(catalogRevision=catalog["revision"], lastSyncedAt=last_sync,
                    lastCheckedAt=run_time, coverage=coverage)
        compact(feed, old_items.values(), active_ids)
        if sweep:
            sweep["completed"] = sorted(completed)
            if coverage["pending"] == 0:
                sweep["finishedAt"] = stamp(now())
        state["lastRun"] = coverage
        write_atomic(args.data / "feed.json", feed)
        write_atomic(args.data / "state.json", state)
        return coverage

    async def process(source: dict, web: Publishers, x: XTimeline | None) -> Result:
        record = state["sources"].get(source["id"], {})
        retry_at = as_date(record.get("retryAt"))
        if retry_at and retry_at > now():
            return Result("deferred-backoff", attempted=False)
        if source["platform"] == "x":
            if not x:
                return Result("x-credentials-missing", attempted=False)
            pause = as_date(state.get("xRetryAt"))
            if pause and pause > now():
                return Result("x-service-backoff", attempted=False)
        try:
            return await (x.collect(source) if source["platform"] == "x" else web.collect(source))
        except SourceError as error:
            if error.halt_x and not (as_date(state.get("xRetryAt")) or datetime.min.replace(tzinfo=UTC)) > now():
                streak = min(int(state.get("xFailureCount", 0)) + 1, 6)
                state["xFailureCount"] = streak
                delay = min(error.delay * 2 ** (streak - 1), 86_400)
                state["xRetryAt"] = stamp(now() + timedelta(seconds=max(error.delay, delay)))
            return Result(error.code, delay=error.delay)
        except (httpx.HTTPError, TimeoutError, ValueError):
            # Publisher or SDK error bodies and cookies stay outside all logs.
            return Result("collector-input-error", delay=900)

    async def worker(web: Publishers, x: XTimeline | None) -> None:
        nonlocal last_sync, attempted
        while not stop.is_set():
            try:
                source = pool.get_nowait()
            except asyncio.QueueEmpty:
                return
            result = await process(source, web, x)
            flags[result.status] += 1
            attempted += int(result.attempted)
            identifier = source["id"]
            if result.attempted:
                timestamp = stamp(now())
                record = state["sources"].setdefault(identifier, {})
                record.update(lastAttemptAt=timestamp, status=result.status)
                if result.status == "ok":
                    record["lastSuccessAt"] = last_sync = timestamp
                    if source["platform"] == "x" and not x.halt:
                        state.pop("xFailureCount", None)
                        state.pop("xRetryAt", None)
                if result.delay:
                    record["retryAt"] = stamp(now() + timedelta(seconds=result.delay))
                else:
                    record.pop("retryAt", None)
                if result.status in {"protected", "not-found"}:
                    # The publisher's explicit visibility or handle change supersedes old copies.
                    for item_id in [key for key, item in old_items.items() if item["sourceId"] == identifier]:
                        old_items.pop(item_id)
            if sweep and result.status in TERMINAL:
                completed.add(identifier)
            if mode == "batch" and source["platform"] == "x":
                state["batchPending"] = [key for key in state["batchPending"] if key != identifier]
            for item in result.items:
                old_items[item["id"]] = item
            checkpoint()

    try:
        with tempfile.TemporaryDirectory(prefix="eritrea-x-") as directory:
            x = None
            if not args.web_only and COOKIE.fullmatch(token) and COOKIE.fullmatch(csrf):
                os.environ["TWS_HTTP_BACKEND"] = "httpx"
                x = XTimeline(requests)
                await x.start(Path(directory) / "session.db", token, csrf)
            async with httpx.AsyncClient(timeout=httpx.Timeout(14), headers={"user-agent": USER_AGENT}) as client:
                web = Publishers(requests, client)
                await asyncio.gather(*(worker(web, x) for _ in range(args.max_concurrent)))
    finally:
        timer.cancel()
        if pool.qsize():
            flags["checkpointed-unattempted"] += pool.qsize()
        report = checkpoint()
    print(json.dumps(report, ensure_ascii=False), flush=True)
    return 2 if report["pending"] else 0


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data", type=Path, default=ROOT / "data")
    parser.add_argument("--full", action="store_true", help="Sweep all active sources and resume unfinished full runs.")
    parser.add_argument("--web-only", action="store_true", help="Read the registered public publisher pages only.")
    parser.add_argument("--validate", action="store_true", help="Validate the local JSON without contacting publishers.")
    parser.add_argument("--batch-size", type=int, default=int(os.environ.get("BATCH_SIZE", 35)))
    parser.add_argument("--max-concurrent", type=int, default=int(os.environ.get("MAX_CONCURRENT", 3)))
    parser.add_argument("--jitter-min", type=float, default=float(os.environ.get("JITTER_MIN", 2.5)))
    parser.add_argument("--jitter-max", type=float, default=float(os.environ.get("JITTER_MAX", 6.5)))
    parser.add_argument("--max-minutes", type=float, default=float(os.environ.get("MAX_RUN_MINUTES", 100)))
    args = parser.parse_args()
    if not 1 <= args.max_concurrent <= 3 or args.batch_size < 1 or args.max_minutes <= 0 \
            or not 0 <= args.jitter_min <= args.jitter_max <= 60:
        parser.error("Check concurrency, batch size, time budget and jitter ranges.")
    catalog = read_json(args.data / "sources.json")
    validate_catalog(catalog)
    feed = read_json(args.data / "feed.json", {"schemaVersion": 1, "items": []})
    if args.validate:
        if len(encode(feed)) >= 500_000:
            raise ValueError("Feed exceeds 500 KB")
        print(f"Validated {len(catalog['sources'])} source records and {len(feed['items'])} feed items.")
        return 0
    directory = os.open(args.data, os.O_RDONLY)
    try:
        try:
            fcntl.flock(directory, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            parser.error("Another collector is writing this data directory.")
        state = read_json(args.data / "state.json", {"schemaVersion": 1, "cursor": 0, "sources": {}})
        feed = read_json(args.data / "feed.json", {"schemaVersion": 1, "items": []})
        return asyncio.run(collect_all(args, catalog, state, feed))
    finally:
        os.close(directory)


if __name__ == "__main__":
    raise SystemExit(main())
```

## .github/workflows/scrape.yml

```yaml
name: Eritrea 2042 source feed

on:
  schedule:
    - cron: '17 */6 * * *'
  workflow_dispatch:
    inputs:
      run_mode:
        description: Resumable full sweep or the next scheduled slice
        type: choice
        required: true
        default: full_now
        options: [full_now, batch]

concurrency:
  group: eritrea2042-static-writer
  cancel-in-progress: false

permissions:
  contents: read

jobs:
  ingest:
    if: github.event.repository.private == false && github.ref_name == github.event.repository.default_branch
    runs-on: ubuntu-latest
    timeout-minutes: 110
    permissions:
      contents: write
    outputs:
      pages: ${{ steps.stage.outputs.enabled }}
    env:
      BATCH_SIZE: '35'
      MAX_CONCURRENT: '3'
      JITTER_MIN: '2.5'
      JITTER_MAX: '6.5'
      MAX_RUN_MINUTES: '100'
      FORCE_FULL_SWEEP: ${{ (inputs.run_mode == 'full_now') && '1' || '0' }}
      IGNORE_BATCH_CAP: ${{ (inputs.run_mode == 'full_now') && '1' || '0' }}
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event.repository.default_branch }}
      - uses: actions/setup-python@v7
        with:
          python-version: '3.12'
      - name: Install and validate
        run: |
          python -m pip install --disable-pip-version-check -r requirements.txt
          python scripts/fetch_sources.py --validate
      - name: Collect public source records
        id: collect
        env:
          AUTH_TOKEN: ${{ secrets.AUTH_TOKEN }}
          CT0: ${{ secrets.CT0 }}
        run: |
          status=0
          python scripts/fetch_sources.py || status=$?
          echo "code=$status" >> "$GITHUB_OUTPUT"
          if [[ "$status" != 0 && "$status" != 2 ]]; then exit "$status"; fi
      - name: Refresh regional publisher feeds
        run: |
          node tools/collect-rss.mjs
          node --input-type=module -e "import {syncWatch} from './tools/sync-watch.mjs'; await syncWatch();"
      - name: Save feed and checkpoint
        if: ${{ !cancelled() && steps.collect.outcome != 'skipped' }}
        env:
          BRANCH: ${{ github.event.repository.default_branch }}
        run: |
          python scripts/fetch_sources.py --validate
          git config user.name 'github-actions[bot]'
          git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
          git add -- data/feed.json data/state.json data/rss-snapshot.json data/status.json data/sources.json
          if ! git diff --cached --quiet; then
            git commit -m 'Refresh source feed and checkpoint'
            git pull --rebase origin "$BRANCH"
            git push origin "HEAD:$BRANCH"
          fi
      - name: Report sweep coverage
        if: ${{ !cancelled() && steps.collect.outcome != 'skipped' }}
        env:
          COLLECTION_CODE: ${{ steps.collect.outputs.code }}
        run: |
          {
            echo '### Source coverage'
            echo '```json'
            jq '.coverage' data/feed.json
            echo '```'
          } >> "$GITHUB_STEP_SUMMARY"
          if [[ "$COLLECTION_CODE" == 2 ]]; then
            echo "::warning::Some sources remain pending. Review data/feed.json coverage and resume with full_now."
          fi
      - name: Stage optional feed-only Pages site
        id: stage
        if: vars.DEPLOY_FEED_PAGES == 'true'
        run: |
          mkdir -p "$RUNNER_TEMP/source-pages/data"
          cp regional-watch.html "$RUNNER_TEMP/source-pages/index.html"
          cp feed.js feed.css "$RUNNER_TEMP/source-pages/"
          cp data/sources.json data/feed.json "$RUNNER_TEMP/source-pages/data/"
          echo 'enabled=true' >> "$GITHUB_OUTPUT"
      - name: Upload Pages artifact
        if: steps.stage.outputs.enabled == 'true'
        uses: actions/upload-pages-artifact@v4
        with:
          path: ${{ runner.temp }}/source-pages
          retention-days: 1

  pages:
    needs: ingest
    if: needs.ingest.outputs.pages == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 10
    permissions:
      pages: write
      id-token: write
    environment:
      name: github-pages
      url: ${{ steps.publish.outputs.page_url }}
    steps:
      - name: Publish feed and JSON
        uses: actions/deploy-pages@v4
        id: publish
```

## feed.js

```javascript
const DAY = 86_400_000;

function element(tag, content, className) {
  const node = document.createElement(tag);
  if (content) node.textContent = content;
  if (className) node.className = className;
  return node;
}

function publicURL(value) {
  if (typeof value !== 'string' || value.length > 1000) return null;
  try {
    const url = new URL(value);
    return url.protocol === 'https:' && !url.username && !url.password && (!url.port || url.port === '443') ? url : null;
  } catch { return null; }
}

function anchor(url, text, className) {
  const link = element('a', text, className);
  link.href = url.href;
  link.target = '_blank';
  link.rel = 'noopener noreferrer';
  return link;
}

async function json(url, limit) {
  const response = await fetch(url, { cache: 'no-cache', credentials: 'omit', signal: AbortSignal.timeout(12_000) });
  if (!response.ok || Number(response.headers.get('content-length')) > limit) throw new Error('Data unavailable');
  const data = await response.text();
  if (new TextEncoder().encode(data).byteLength > limit) throw new Error('Data exceeds limit');
  const value = JSON.parse(data);
  if (value?.schemaVersion !== 1) throw new Error('Unknown data version');
  return value;
}

function itemURL(item, source) {
  const url = publicURL(item.url);
  if (!url) return null;
  if (source.platform === 'web') {
    return url.hostname === new URL(source.profileUrl).hostname ? url : null;
  }
  const postId = String(item.tweetId ?? '');
  return /^\d{1,24}$/.test(postId) && url.hostname === 'x.com'
    && url.pathname.toLowerCase() === '/' + source.handle.toLowerCase() + '/status/' + postId ? url : null;
}

function displayTime(value, timestamp = false) {
  const stamp = new Date(value).toISOString().replace(/\.\d+Z$/, 'Z');
  const time = element('time', timestamp ? stamp.slice(0, 16).replace('T', ' ') + ' UTC' : stamp.slice(0, 10));
  time.dateTime = timestamp ? stamp : stamp.slice(0, 10);
  return time;
}

function sourceBadge(source) {
  const kind = source.platform === 'x' ? 'social' : source.sourceType;
  const labels = {project:'Project source', social: 'Social source', independent: 'Independent source', official: 'Official source'};
  const badge = element('span', labels[kind], 'site-badge');
  badge.dataset.badge = kind;
  return badge;
}

function card(item, source, category, url) {
  const article = element('article', null, 'sf-card');
  const meta = element('p', null, 'sf-card-meta');
  meta.append(element('span', category, 'sf-tag'));
  meta.append(sourceBadge(source));
  const origin = element('p', null, 'sf-card-origin');
  const profile = publicURL(source.profileUrl);
  if (profile) origin.append(anchor(profile, source.handle ? '@' + source.handle : source.displayName), ' · ');
  origin.append(displayTime(item.publishedAt));
  article.append(meta, element('h3', item.title ? source.displayName + ' · ' + item.title : source.displayName), origin);
  if (item.text) article.append(element('p', item.text, 'sf-excerpt'));
  const image = publicURL(item.imageUrl);
  if (image && image.hostname === (source.platform === 'x' ? 'pbs.twimg.com' : profile?.hostname)) {
    const img = document.createElement('img');
    img.src = image.href;
    img.alt = '';
    img.loading = 'lazy';
    img.decoding = 'async';
    img.referrerPolicy = 'no-referrer';
    img.addEventListener('error', () => img.remove(), { once: true });
    article.append(img);
  }
  const link = publicURL(item.linkUrl);
  if (link && link.href !== url.href) article.append(anchor(link, 'Linked page · ' + link.hostname, 'sf-preview'));
  article.append(anchor(url, source.platform === 'x' ? 'View original on X ↗' : 'Read at the publisher ↗', 'sf-original'));
  return article;
}

async function mount(root) {
  const get = key => root.querySelector('[data-sf-' + key + ']');
  const [catalogResult, localResult] = await Promise.allSettled([
    json(root.dataset.catalog, 1_000_000),
    json(root.dataset.feed, 499_999),
  ]);
  if (catalogResult.status !== 'fulfilled' || !Array.isArray(catalogResult.value.sources)) {
    get('sync').textContent = 'Source catalog unavailable';
    get('loading').hidden = true;
    get('cards').setAttribute('aria-busy', 'false');
    get('status').textContent = 'Open the catalog directly or reload to try again.';
    return;
  }

  const catalog = catalogResult.value;
  const sources = new Map(catalog.sources.filter(source => source.active && publicURL(source.profileUrl)).map(source => [source.id, source]));
  const categories = new Map(catalog.categories.map(({ id, label }) => [id, label]));
  const directory = get('directory');
  const pills = get('pills');
  const input = get('query');
  const cards = get('cards');
  let activeCategory = '';
  let activeType = '';
  let limit = 18;
  let feed = localResult.status === 'fulfilled' ? localResult.value : null;
  if (feed?.catalogRevision !== catalog.revision) feed = null;

  const remote = publicURL(catalog.remoteFeedUrl);
  let remoteUnavailable = false;
  if (remote) {
    try {
      const refreshed = await json(remote.href, 499_999);
      if (refreshed.catalogRevision !== catalog.revision || !Array.isArray(refreshed.items)) throw new Error('Catalog mismatch');
      if ((refreshed.lastCheckedAt ?? '') >= (feed?.lastCheckedAt ?? '')) feed = refreshed;
    } catch { remoteUnavailable = true; }
  }

  const stamp = feed?.lastSyncedAt ? new Date(feed.lastSyncedAt) : null;
  const sync = get('sync');
  if (stamp && Number.isFinite(stamp.getTime())) {
    sync.replaceChildren('Snapshot synced ', displayTime(stamp, true));
    sync.dataset.stale = String(Date.now() - stamp.getTime() > 2 * DAY);
    if (sync.dataset.stale === 'true') sync.append(' · Stale');
  } else {
    sync.textContent = 'No successful sync recorded';
  }
  if (feed?.coverage?.mode === 'web_only') sync.append(' · Web publisher snapshot');
  if (feed?.coverage?.pending > 0) sync.append(' · Partial coverage');
  if (remoteUnavailable) sync.append(' · Remote feed unavailable');
  const allItems = (feed?.items ?? []).flatMap(item => {
    const source = sources.get(item.sourceId);
    const when = Date.parse(item.publishedAt);
    const url = source && Number.isFinite(when) && when >= Date.now() - 14 * DAY && itemURL(item, source);
    return url ? [{ item, source, url }] : [];
  });

  function matchesSource(source) {
    return (!activeCategory || source.categoryId === activeCategory) && (!activeType || source.sourceType === activeType);
  }

  function findText(...fields) {
    const query = input.value.toLowerCase().trim().replace(/^@/, '');
    return !query || fields.some(field => typeof field === 'string' && field.toLowerCase().includes(query));
  }

  function drawDirectory() {
    if (!directory.open) return;
    const categoriesOpen = new Set([...directory.querySelectorAll('details[open]')].map(entry => entry.dataset.category));
    const lists = [];
    let count = 0;
    for (const [id, label] of categories) {
      const matching = [...sources.values()].filter(source => source.categoryId === id && matchesSource(source) &&
        findText(source.handle, source.displayName, source.bio, source.listedCategory));
      if (!matching.length) continue;
      count += matching.length;
      const section = element('details');
      section.dataset.category = id;
      section.open = categoriesOpen.has(id) || Boolean(activeCategory || activeType || input.value.trim());
      const list = element('ul');
      list.tabIndex = 0;
      list.setAttribute('aria-label', label + ' source profiles');
      for (const source of matching) {
        const entry = element('li');
        const name = source.displayName + (source.handle ? ' · @' + source.handle : '');
        entry.append(anchor(publicURL(source.profileUrl), name));
        entry.append(' ', sourceBadge(source));
        if (source.bio) entry.append(element('p', source.bio));
        list.append(entry);
      }
      section.append(element('summary', label + ' · ' + matching.length), list);
      lists.push(section);
    }
    get('directory-count').textContent = 'Showing ' + count + ' of ' + sources.size + ' catalog entries';
    get('directory-body').replaceChildren(...(lists.length ? lists : [element('p', 'No source profiles match.')]));
  }

  function render() {
    const matches = allItems.filter(({ source, item }) => matchesSource(source) &&
      findText(source.handle, source.displayName, source.listedCategory, item.text, item.title));
    const batch = matches.slice(0, limit);
    cards.replaceChildren(...batch.map(({ item, source, url }) => card(item, source, categories.get(source.categoryId), url)));
    get('status').textContent = !feed ? 'The feed could not be loaded. Source profiles are available in the current catalog.' :
      !allItems.length ? 'No posts are available in the last 14 days.' :
      !matches.length ? 'No posts match these filters.' : 'Showing ' + batch.length + ' of ' + matches.length + ' posts';
    get('more').hidden = batch.length >= matches.length;
    drawDirectory();
  }

  function reset() { limit = 18; render(); }
  const types = get('types');
  function addChips(container, choices, select) {
    for (const [id, label] of choices) {
      const button = element('button', label);
      button.type = 'button';
      button.setAttribute('aria-pressed', String(!id));
      button.addEventListener('click', () => {
        select(id);
        for (const other of container.children) other.setAttribute('aria-pressed', String(other === button));
        reset();
      });
      container.append(button);
    }
  }
  addChips(pills, [['', 'All categories'], ...categories], value => { activeCategory = value; });
  addChips(types, [['', 'All source types'], ...catalog.sourceTypes.map(({id, label}) => [id, label])],
    value => { activeType = value; });
  get('count').textContent = [...sources.values()].filter(source => source.platform === 'x').length + ' X accounts · ' +
    [...sources.values()].filter(source => source.platform === 'web').length + ' web publishers';
  input.addEventListener('input', reset);
  get('reset').addEventListener('click', () => {
    input.value = activeCategory = activeType = '';
    for (const container of [pills, types]) {
      for (const button of container.children) button.setAttribute('aria-pressed', String(button === container.firstElementChild));
    }
    reset();
  });
  if (location.pathname.startsWith('/watch/sources/')) directory.open = true;
  directory.addEventListener('toggle', drawDirectory);
  get('more').addEventListener('click', () => {
    const index = cards.children.length;
    limit += 18;
    render();
    cards.children[index]?.querySelector('a')?.focus();
  });
  get('filters').hidden = directory.hidden = false;
  get('loading').hidden = true;
  cards.setAttribute('aria-busy', 'false');
  render();
}

for (const root of document.querySelectorAll('[data-source-feed]')) {
  const start = () => mount(root).catch(() => {
    root.querySelector('[data-sf-loading]').hidden = true;
    root.querySelector('[data-sf-cards]').setAttribute('aria-busy', 'false');
    root.querySelector('[data-sf-sync]').textContent = 'Source feed unavailable';
  });
  const folded = root.closest('details:not([open])');
  if (folded) {
    function startOnOpen() {
      if (!folded.open) return;
      folded.removeEventListener('toggle', startOnOpen);
      start();
    }
    folded.addEventListener('toggle', startOnOpen);
  } else start();
}
```

## public/watch/watch.css

```css
.project-scope{border:1px solid #d9dfd8;border-left:3px solid #a6854d;background:light-dark(#f3f5ef,#172720);padding:20px 24px;margin:26px auto;color:light-dark(#28463b,#e9f1eb);font:14px/1.7 system-ui;max-width:1180px}.project-scope strong{font-family:Georgia,serif;font-size:1.12rem}.project-scope p{margin:8px 0 0}.source-watch{color:light-dark(#173e34,#e9f1eb);line-height:1.65}.watch-page{padding-block:56px 64px}.watch-page h1{font:500 clamp(2.1rem,5vw,3.8rem)/1.12 Georgia,serif;max-width:25ch}.watch-page .lede{max-width:80ch}.watch-window{padding:28px;border:1px solid #d9dfd8;background:light-dark(#f7f8f3,#172720);margin-block:36px;border-radius:7px}.watch-window>header{display:flex;align-items:center;justify-content:space-between;gap:24px}.watch-window h2,.watch-page h2{font:500 clamp(1.45rem,2.5vw,2rem)/1.25 Georgia,serif;margin-block:8px 18px}.watch-intro{font-size:.92rem;max-width:85ch;color:light-dark(#5e6d68,#b9c9be)}.watch-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,300px),1fr));gap:18px}.watch-lanes{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:22px}.watch-lane{min-width:0}.watch-card{min-width:0;background:light-dark(#fff,#172720);border:1px solid #d9dfd8;border-top:3px solid #a6854d;border-radius:5px;padding:20px;margin:0 0 18px;font-size:.89rem}.watch-card :is(h2,h3){font:500 1.2rem/1.35 Georgia,serif;margin-block:14px;overflow-wrap:anywhere}.watch-card :is(h2,h3) a{text-decoration:none}.watch-attribution{font-size:.72rem;font-weight:650;color:light-dark(#53685e,#b9c9be);line-height:1.5;margin:0 0 12px}.watch-independent{border-top-color:#78898e}.watch-independent .watch-attribution{background:light-dark(#edf1f3,#20362c);padding:10px;margin:-3px -3px 12px}.watch-tags{display:flex;flex-wrap:wrap;gap:6px}.watch-tags span{font-size:.65rem;border:1px solid #d9dfd8;border-radius:4px;padding:2px 6px}.watch-date{font-size:.74rem;color:light-dark(#64756c,#b9c9be)}.watch-original{font-size:.8rem}.watch-refs{border-top:1px solid #d9dfd8;margin-top:18px;padding-top:12px;font-size:.8rem}.watch-refs summary{cursor:pointer}.watch-refs li{margin-block:8px}.independent-boundary{font-size:.76rem;line-height:1.55;color:light-dark(#5b6d73,#b9c9be);background:light-dark(#edf1f3,#20362c);border-left:3px solid #78898e;padding:12px;margin-bottom:18px}.watch-account-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:8px;margin-block:24px}.watch-account-grid .account-row{border:1px solid #d9dfd8;padding:12px;min-width:0}.watch-account-grid .account-row span{display:block;font-size:.7rem;margin-top:5px;color:light-dark(#526457,#b9c9be)}.watch-record{margin-top:28px;max-width:80ch}.watch-record dd{margin:0 0 14px;overflow-wrap:anywhere}.watch-record code{font-size:.7rem}.watch-footer{font-size:.8rem;padding-bottom:30px}.election-feature{margin:22px 0 32px;border:1px solid #d9dfd8;background:light-dark(#f2f4ee,#172720);padding:18px;border-radius:6px;display:grid;grid-template-columns:minmax(0,340px) minmax(220px,1fr);gap:24px;align-items:center}.election-feature img{display:block;width:100%;height:auto;border-radius:4px}.election-feature figcaption{font-size:.9rem;line-height:1.7;color:light-dark(#53675b,#b9c9be);max-width:45ch}.election-feature figcaption a{display:block;margin-top:14px}.shared-discussions{border:1px solid #d9dfd8;padding:24px;border-radius:6px;margin-block:24px;background:light-dark(#fbfcf8,#172720)}.shared-discussions h3{font-family:Georgia,serif;font-size:1.6rem}.shared-discussions p{font-size:.9rem;line-height:1.6}.giscus{min-height:40px}.analysis-download{display:block;background:light-dark(#f0f3ee,#20362c);border:1px solid #d9dfd8;border-left:3px solid #a6854d;padding:22px;margin:24px 0;text-decoration:none}.analysis-download strong{display:block;font:500 1.5rem Georgia,serif;margin-block:8px}.analysis-download span{font-size:.8rem;color:light-dark(#53675b,#b9c9be)}.source-watch a,.shared-discussions a{color:light-dark(#173e34,#e9f1eb);text-underline-offset:3px}.source-watch a:focus-visible,.source-watch summary:focus-visible{outline:3px solid #a6854d;outline-offset:4px}
@media(max-width:1000px){.watch-lanes{grid-template-columns:1fr 1fr}.watch-lane:first-child{grid-column:1/-1}.watch-lane:first-child{display:grid;grid-template-columns:1fr 1fr;gap:18px}.watch-lane:first-child h2{grid-column:1/-1}}
@media(max-width:620px){.watch-lanes,.watch-lane:first-child{display:block}.watch-window{padding:20px}.watch-window>header{display:block}.watch-card{padding:18px}.watch-page{padding-block:32px 48px}.election-feature{grid-template-columns:1fr;padding:14px}.election-feature>a{max-width:380px;margin:auto}.election-feature figcaption{max-width:none}.project-scope{margin-inline:16px;padding:18px}.watch-page h1{font-size:2.3rem}}

.watch-links {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-block: 22px;
}
.watch-links a {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  min-height: 40px;
  padding: 6px 13px;
  background: light-dark(#fff,#172720);
  border: 1px solid #cbd7cf;
  border-radius: 5px;
  font-size: .88rem;
  font-weight: 600;
  text-decoration: none;
}
.watch-links a:hover { background: light-dark(#eaf0e9,#20362c); text-decoration: underline; }
.watch-coverage {
  margin-block: 28px;
  border: 1px solid #d0dbd0;
  border-radius: 7px;
  background: light-dark(#f3f6f0,#172720);
  overflow: hidden;
}
.watch-metrics { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); }
.watch-metrics > div { padding: 16px 20px; }
.watch-metrics > div + div { border-inline-start: 1px solid #d0dbd0; }
.watch-metrics strong, .watch-field { font-size: .83rem; font-weight: 700; }
.watch-metrics p { margin: 4px 0 0; font-size: .82rem; }
.watch-metrics p + p, .watch-coverage-details, .watch-checks { color: light-dark(#495e54,#b9c9be); }
.watch-coverage-details {
  display: grid;
  gap: 6px;
  padding: 10px 20px;
  border-top: 1px solid #d0dbd0;
  font-size: .82rem;
}
.watch-coverage-links { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 20px; }
.watch-coverage-details summary { cursor: pointer; }
.watch-coverage-details p { margin: 6px 0; max-width: 90ch; }
.watch-checks { font-size: .84rem; }
.watch-field { display: grid; align-content: start; gap: 4px; }
.watch-field :is(input, select) {
  color: light-dark(#173e34,#e9f1eb);
  background: light-dark(#fff,#172720);
  border: 1px solid #adbdb1;
  border-radius: 5px;
  padding: 9px 12px;
  min-height: 42px;
  width: 100%;
  min-width: 0;
  font-family: inherit;
  font-size: .9rem;
  font-weight: 400;
  line-height: 1.4;
}
.watch-field :is(input, select):focus-visible { outline: 2px solid #896532; outline-offset: 3px; }
#source-access .watch-field { max-width: 28rem; margin-bottom: 14px; }
.watch-access-table { min-width: 46rem; }
.watch-access-table time { white-space: nowrap; }
.watch-access-detail { display: block; margin-top: 4px; color: light-dark(#495e54,#b9c9be); font-size: .79rem; }
.watch-state {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  color: light-dark(#384b45,#e9f1eb);
  background: light-dark(#eef0ed,#20362c);
  font-size: .77rem;
  font-weight: 650;
  white-space: nowrap;
}
.watch-state[data-state="ok"] { color: light-dark(#174e38,#e9f1eb); background: light-dark(#e3efe5,#20362c); }
.watch-state[data-state="backoff"] { color: light-dark(#634716,#e9f1eb); background: light-dark(#faefd6,#20362c); }
.watch-state[data-state="unavailable"] { color: light-dark(#7a312d,#e9f1eb); background: light-dark(#f8e7e4,#20362c); }
.watch-post-section { margin-block: 30px 36px; }
.watch-post-section > header {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 5px 20px;
  margin-bottom: 12px;
}
.watch-post-section > header h2 { margin: 0; }
.watch-post-section > header a { font-size: .86rem; }
.watch-post-list {
  display: grid;
  grid-template-columns: repeat(3,minmax(0,1fr));
  align-items: start;
  gap: 14px;
}
.watch-post {
  min-width: 0;
  padding: 17px;
  background: light-dark(#fff,#172720);
  border: 1px solid #d0dbd0;
  border-radius: 6px;
  font-size: .9rem;
  overflow-wrap: anywhere;
}
.watch-post-meta {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 4px 12px;
  font-size: .78rem;
  color: light-dark(#495e54,#b9c9be);
}
.watch-post-meta a { font-weight: 700; }
.watch-post-topic { margin: 10px 0 4px; color: light-dark(#495e54,#b9c9be); font-size: .77rem; }
.watch-post :is(h2,h3) { margin: 0; font: 500 1.22rem/1.32 Georgia,serif; }
.watch-post > p:not(.watch-post-topic) { margin-block: 9px 12px; }
.watch-post-preview { margin-top: 10px; border-top: 1px solid #d0dbd0; }
.watch-post-preview summary { padding: 8px 0; cursor: pointer; font-weight: 650; }
.watch-x-frame { display: block; width: 100%; height: 450px; border: 0; background: light-dark(#f3f6f0,#172720); }
.watch-post-filters {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr;
  gap: 12px;
  padding: 14px;
  background: light-dark(#f3f6f0,#172720);
  border: 1px solid #d0dbd0;
  border-radius: 6px;
}
.watch-field[hidden], .watch-post[hidden], .watch-post-filters[hidden] { display: none; }
.watch-filter-status { font-size: .82rem; color: light-dark(#495e54,#b9c9be); margin: 10px 0; }
.watch-account-grid .account-row { display: block; overflow-wrap: anywhere; }
.watch-account-posts { display: inline-block; margin-top: 6px; font-size: .78rem; }

@media (max-width: 900px) {
  .watch-post-list { grid-template-columns: repeat(2,minmax(0,1fr)); }
}
@media (max-width: 620px) {
  .watch-metrics, .watch-post-list, .watch-post-filters { grid-template-columns: 1fr; }
  .watch-metrics > div + div { border-inline-start: 0; border-top: 1px solid #d0dbd0; }
}
```

## monitoring/deploy-vercel.py

```python
"""Optional free-plan deploy hook. No hook is contacted unless explicitly enabled."""
import os
import urllib.parse
import urllib.request

if os.environ.get('DEPLOY_VERCEL') != 'true':
    raise SystemExit('Vercel deploy is disabled.')
hook = os.environ.get('VERCEL_DEPLOY_HOOK', '')
p = urllib.parse.urlsplit(hook)
if p.scheme != 'https' or p.hostname != 'api.vercel.com' or not p.path.startswith('/v1/integrations/deploy/') or p.username or p.password:
    raise SystemExit('A valid Vercel deploy hook must be configured as an Actions secret.')
try:
    with urllib.request.urlopen(urllib.request.Request(hook, method='POST', data=b''), timeout=20) as response:
        if response.status not in (200, 201, 202):
            raise RuntimeError('Deploy hook rejected')
    print('Vercel deployment requested. Inspect Vercel for its final result.')
except Exception:
    raise SystemExit('Vercel deployment request failed; no paid fallback was used.') from None
```
