From cc9d0e34b9280b05fa4428d59c8dc16311091758 Mon Sep 17 00:00:00 2001 From: Agando Date: Tue, 27 Oct 2026 17:42:46 +0100 Subject: fix(docs): apply the GLM-5.3 review to the changelog pipeline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Verdict was APPROVE WITH CHANGES: 21 findings, 17 fixed, 3 refuted with the command that killed them, 1 kept with the audit that justifies it. The reviewer's best find was a design bug of mine, not a typo. - The age guard was unfixable by --fix and fired on a quiet week. check_changelog() regenerated only on a version mismatch, then returned from the version-match branch before the age check could act, so a page older than the threshold stayed red forever with the false diagnosis "the daily job is not running". Now --fix always regenerates (0.84 s) and age is read from a new `checked` stamp separate from `generated` (content-change time), which also stops a daily 65 KB rewrite of an unchanged page. Proved: seeded 641 h -> FAIL + "run maintain --fix to refresh" -> --fix -> PASS. - Atomic writes everywhere (temp + os.replace): nginx serves these files off disk, so an in-place truncate could hand a visitor half a page. - The JSON island now escapes " would have closed it early and truncated the page). Proved by injecting exactly that subject: island still parses, no stray script tag, payload survives as data. - Sibling drift is checked, not assumed: changelog.json's currentVersion is compared with LATEST_VER. Seeded v4.6.100 -> FAIL "feed drifted", --fix repairs. - Build tags are audited under --deep: 67 tags, each must be reachable from HEAD and name the version its commit tree carries. Proved by tampering (v9.9.9 on the root commit -> FAIL) and by deleting it (-> PASS). - Feed: ids no longer hardcode 2026 or contain spaces, entries carry a , timestamps are real iso-strict commit times instead of a fake T00:00:00Z on a local date, and summaries are truncated before escaping so no "&l" tail. 0 ids with spaces, 0 broken entity tails. - write_md refuses to overwrite a CHANGELOG.md that lost its markers; run() gained a 300 s timeout (a hung git used to block the whole 07:15 job); jumpToHash no longer stacks hint paragraphs; dead fields removed (KIND_ORDER, order, currentSynthesized, sourcesRead — each appeared exactly once in the page, i.e. only in the island the generator wrote). - HTML nits: guide.html footer separator, empty "fixed in" line suppressed, help.html version bumped off v4.5.22. Header stat relabelled "Commits behind it" (it read "Bug records on disk" while counting commits — my own defect, not the reviewer's). - Refuted: merge commits (repo has 0: `git log --merges | wc -l`), first-version board links (the 2 multi-version notes both name the fixing build first), sources disclosure (the page already renders those module paths). maintain --deep: node tests 20/20, changelog current, age 0.0h, 67 tags verified, result OK. Mobile: ALL VIEWPORTS OK. --- scripts/build-changelog.py | 92 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 64 insertions(+), 28 deletions(-) (limited to 'scripts/build-changelog.py') diff --git a/scripts/build-changelog.py b/scripts/build-changelog.py index ac4e8c1..1b00a5e 100644 --- a/scripts/build-changelog.py +++ b/scripts/build-changelog.py @@ -43,24 +43,25 @@ KIND = OrderedDict([ ('test', 'review'), ('refactor', 'project'), ('docs', 'docs'), ('style', 'project'), ('chore', 'project'), ('build', 'project'), ('ci', 'project'), ]) -KIND_ORDER = ['current', 'release', 'fix', 'review', 'docs', 'project', 'bug'] MAX_ITEMS = 14 # per release; the rest is counted, not hidden def git(*args): + # encoding is pinned: the cron runs with an unset locale and commit subjects carry non-ASCII + # (em dashes, ellipses). Without it a decode error would kill every 07:15 regeneration. return subprocess.run(['git', '-C', ROOT] + list(args), - capture_output=True, text=True, check=True).stdout + capture_output=True, text=True, encoding='utf-8', check=True).stdout def commits(): """Oldest first: [{sha, date, subject, files:[...]}]""" - raw = git('log', '--reverse', '--date=short', - '--format=%x01%H%x01%ad%x01%s', '--name-only', '--', APP_REL) + raw = git('log', '--reverse', '--date=iso-strict', + '--format=%x01%H%x01%aI%x01%s', '--name-only', '--', APP_REL) out, cur = [], None for line in raw.split('\n'): if line.startswith('\x01'): - _, sha, date, subject = line.split('\x01', 3) - cur = {'sha': sha, 'date': date, 'subject': subject, 'files': []} + _, sha, iso, subject = line.split('\x01', 3) + cur = {'sha': sha, 'iso': iso, 'date': iso[:10], 'subject': subject, 'files': []} out.append(cur) elif line.strip() and cur is not None: cur['files'].append(line.strip()) @@ -182,6 +183,7 @@ def build(): 'kind': kind, 'version': ver, 'date': group[-1]['date'], + 'updated': group[-1]['iso'], 'title': '%s — %d commit%s' % (ver, len(group), '' if len(group) == 1 else 's'), 'items': items, 'note': 'Touches ' + ', '.join('%s (%d)' % (a, n) for a, n in areas.most_common(4)) @@ -208,15 +210,20 @@ def build(): 'commit shows one line even if it changed ten files; run ' '`git show ` for the change itself.'}) + now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') + prev = existing_island() + # `generated` is the last time the CONTENT changed; `checked` is the last time this ran. Two + # fields because one cannot serve both: a daily rewrite would churn 65 KB of git for nothing, + # while a content-only stamp cannot tell a live cron from a dead one. + content_same = bool(prev) and prev.get('entries') == entries page = { - 'generated': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), + 'generated': (prev or {}).get('generated', now) if content_same else now, + 'checked': now, 'currentVersion': ver_now, - 'currentSynthesized': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), 'stats': { 'entries': len(entries), 'versions': '%s – %s' % (first_known, ver_now), 'records': len(rows), - 'sourcesRead': 1, }, 'gaps': gaps, 'entries': entries, @@ -233,10 +240,29 @@ GAP_INTRO = ('This page is generated from the repository\'s own history for ' 'the shape of a squash-merged change.') +def write_atomic(path, text): + """Temp + rename: nginx serves these files straight off disk, so an in-place truncate can + hand a visitor a half-written page (or leave one after a crash).""" + tmp = path + '.tmp' + with open(tmp, 'w', encoding='utf-8') as fh: + fh.write(text) + os.replace(tmp, path) + + +def existing_island(): + try: + with open(PAGE, encoding='utf-8') as fh: + return json.loads(fh.read().split('id="changelog-data">')[1].split('')[0]) + except Exception: + return None + + def write_page(page): with open(PAGE, encoding='utf-8') as fh: doc = fh.read() - island = json.dumps(page, ensure_ascii=False, indent=2) + # json.dumps leaves " would end the island + # early and truncate the page. Escape it; JSON.parse reads "<\/" back as ")[\s\S]*?()', lambda m: m.group(1) + '\n' + island + '\n' + m.group(2), doc, count=1) assert n == 1, 'changelog JSON island not found - page layout changed' @@ -245,14 +271,12 @@ def write_page(page): new = re.sub(r'(
[\s\S]*?

[^<]*

\s*

)[\s\S]*?(

)', lambda m: m.group(1) + GAP_INTRO + m.group(2), new, count=1) new = re.sub(r'()[^<]*()', lambda m: m.group(1) + html.escape(page['currentVersion']) + m.group(2), new, count=1) - with open(PAGE, 'w', encoding='utf-8') as fh: - fh.write(new) + write_atomic(PAGE, new) return len(new) def write_md(page, rows): """App-side Keep-a-Changelog history; generated region is delimited.""" - order = {'release': 0, 'fix': 1, 'review': 2, 'docs': 3, 'project': 4, 'bug': 5} out = ['# newOS4 changelog', '', 'Generated from git history by `scripts/build-changelog.py` — do not edit by hand ' 'between the markers.', '', '', ''] @@ -267,12 +291,16 @@ def write_md(page, rows): out.extend(['', '']) body = '\n'.join(out) if os.path.exists(MD): - old = open(MD, encoding='utf-8').read() + with open(MD, encoding='utf-8') as fh: + old = fh.read() m = re.search(r'[\s\S]*?\n?', old) - if m: - body = old[:m.start()] + body + old[m.end():] - with open(MD, 'w', encoding='utf-8') as fh: - fh.write(body) + if not m: + # Refuse rather than replace: without the markers the file may hold prose that a + # hand-edit added, and silently dropping it is worse than failing loudly. + raise SystemExit('CHANGELOG.md exists but has no generated:start/end markers - ' + 'refusing to overwrite it') + body = old[:m.start()] + body + old[m.end():] + write_atomic(MD, body) return len(body) @@ -283,20 +311,30 @@ def write_feed(page): pretending to a time of day. Item markup is stripped: a feed reader gets text, not HTML. """ base = os.path.dirname(PAGE) - with open(os.path.join(base, 'changelog.json'), 'w', encoding='utf-8') as fh: - json.dump(page, fh, ensure_ascii=False, indent=1) + write_atomic(os.path.join(base, 'changelog.json'), + json.dumps(page, ensure_ascii=False, indent=1)) entries = [] for e in page['entries']: title = '%s — %s' % (e['version'], e['date']) - body = ' '.join(re.sub(r'<[^>]+>', ' ', i).strip() for i in e['items']) + body = re.sub(r'\s+', ' ', ' '.join(re.sub(r'<[^>]+>', ' ', i).strip() + for i in e['items'])).strip() + # Truncate the PLAIN text, then escape: slicing an escaped string can cut "<" in half + # and leave garbage at the tail of every long summary. + if len(body) > 900: + body = body[:900].rsplit(' ', 1)[0] + ' …' + # A tag: URI cannot contain spaces ("before v4.6.10") and must not hardcode the year. + year = (e['date'] or '')[:4] or '2026' + slug = re.sub(r'[^A-Za-z0-9._-]+', '-', e['version']) + anchor = re.sub(r'[^a-z0-9]+', '-', e['version'].lower()) entries.append( ' \n' ' %s\n' - ' tag:webx11.duckdns.org,2026:%s\n' - ' %sT00:00:00Z\n' + ' tag:webx11.duckdns.org,%s:%s\n' + ' \n' + ' %s\n' ' %s\n' - ' ' % (html.escape(title), html.escape(e['version']), - e['date'], html.escape(re.sub(r'\s+', ' ', body)[:900])) + ' ' % (html.escape(title), year, slug, anchor, + e.get('updated') or (e['date'] + 'T00:00:00Z'), html.escape(body)) ) feed = ('\n' '\n' @@ -304,9 +342,7 @@ def write_feed(page): ' tag:webx11.duckdns.org,2026:changelog\n' ' %s\n WebX11\n%s\n\n' % (page['generated'], '\n'.join(entries))) - path = os.path.join(base, 'feed.xml') - with open(path, 'w', encoding='utf-8') as fh: - fh.write(feed) + write_atomic(os.path.join(base, 'feed.xml'), feed) return len(feed) -- cgit v1.2.3