Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): post release notes body in the Slack release announcement (#2935)
Andrew Mikofalvy3029da2f8164
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex 5498ae8d6..c16735d5f 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -529,6 +529,7 @@ jobs:if: success() && steps.channel.outputs.channel == 'latest' && github.event_name != 'workflow_dispatch'env:SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}RELEASE_TAG: ${{ github.event.client_payload.release_tag || inputs.release_tag }}VERSION: ${{ steps.channel.outputs.version }}run: |@@ -538,23 +539,25 @@ jobs:exit 0fiRELEASE_URL="https://github.com/${GITHUB_REPOSITORY}/releases/tag/${RELEASE_TAG}"- # Build the Block Kit payload with jq so $VERSION / $RELEASE_URL are- # JSON-escaped — a stray quote in a tag would otherwise corrupt the- # body. `text` is the notification/a11y fallback Slack recommends- # alongside blocks; the header is plain_text, the section mrkdwn.- payload="$(jq -n \- --arg version "$VERSION" \- --arg release_url "$RELEASE_URL" \- '{- text: ("OpenKnowledge \($version) released — " + $release_url),- blocks: [- { type: "header",- text: { type: "plain_text", text: "🎉 OpenKnowledge \($version) released", emoji: true } },- { type: "section",- text: { type: "mrkdwn",- text: ("*<\($release_url)|Release notes & downloads>*") } }- ]- }')"+ # Inline the notes so the channel reads what shipped without clicking+ # through. A failed fetch is not fatal: the builder degrades to the+ # header + link message on empty input.+ NOTES="$(gh release view "$RELEASE_TAG" --json body --jq '.body' 2>/dev/null || true)"+ # The builder emits the whole Block Kit payload as JSON (so $VERSION /+ # $RELEASE_URL are JSON-escaped — a stray quote in a tag would+ # otherwise corrupt the body), converts the notes from GitHub markdown+ # to Slack mrkdwn, and keeps every section under Slack's 3000-char cap.+ # `text` is the notification/a11y fallback Slack recommends alongside+ # blocks. Unit-tested in scripts/build-slack-release-payload.test.mjs.+ payload="$(printf '%s' "$NOTES" \+ | node scripts/build-slack-release-payload.mjs --version "$VERSION" --url "$RELEASE_URL" \+ || true)"+ # Keep the announcement best-effort: a builder failure warns rather+ # than failing a release that is already published.+ if [[ -z "$payload" ]]; then+ echo "::warning::Could not build the Slack payload for ${RELEASE_TAG} (release is published; notification is best-effort)."+ exit 0+ fi# The failing curl sits in an `if` condition, which `set -e` does# not treat as fatal — a Slack outage routes to the else/warning# and the step still exits 0.diff --git a/knip.config.ts b/knip.config.tsindex 296751a02..563d574d8 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -55,6 +55,7 @@ export default {'.{agents,codex}/skills/**': ['files'],'biome-plugins/__fixtures__/**': ['files'],'scripts/compute-next-beta.mjs': ['files'],+ 'scripts/build-slack-release-payload.mjs': ['files'],'scripts/assert-smoke-not-vacuous.mjs': ['files'],'scripts/assert-app-built.mjs': ['files'],'docs/src/lib/share-splash.ts': ['exports', 'types'],diff --git a/scripts/build-slack-release-payload.mjs b/scripts/build-slack-release-payload.mjsnew file mode 100644index 000000000..cdb34b8f6--- /dev/null+++ b/scripts/build-slack-release-payload.mjs@@ -0,0 +1,219 @@+#!/usr/bin/env node+/**+ * Build the Slack Block Kit payload announcing a stable release, with the+ * release notes inlined so the channel reads what shipped without clicking+ * through to GitHub.+ *+ * Two things make this more than a jq one-liner, which is why it lives in a+ * tested script rather than inline in the workflow:+ *+ * 1. Slack mrkdwn is not GitHub markdown. `### Patch Changes` renders as a+ * literal `###`, `**bold**` as literal asterisks, and `[text](url)` as+ * literal brackets. Release bodies are Changesets output, so they always+ * carry level headings and usually links/bold — posting them raw looks+ * broken.+ * 2. A section block's text caps at 3000 characters and release bodies run+ * past 6000 on a minor. Overflowing the cap is a hard 400 from Slack, so+ * the notes are truncated to a budget and split across sections at line+ * boundaries.+ *+ * Usage:+ * gh release view "$TAG" --json body --jq '.body' \+ * | node scripts/build-slack-release-payload.mjs --version 0.38.4 --url https://…+ *+ * Emits the payload JSON on stdout. Empty/missing notes on stdin degrade to+ * the header + link message this replaced, so a failed `gh release view` still+ * announces the release. Pure text transform; no network.+ */+import { pathToFileURL } from 'node:url';++// A section block's `text.text` caps at 3000 chars (Slack rejects the whole+// message otherwise). Chunk below the cap so a multi-byte tail can't straddle+// it.+const SECTION_LIMIT = 2900;++// Total notes budget across all sections. Matches the Discord announcement's+// limit so both channels show the same amount of a long release body; the+// remainder is a click away behind the link block.+const NOTES_LIMIT = 3500;++/** Slack requires these three escaped in mrkdwn text. */+function escapeSlackText(text) {+ return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+}++/**+ * Convert GitHub markdown to Slack mrkdwn.+ *+ * Runs line-by-line so fenced code blocks can be passed through untouched —+ * rewriting `*`/`[]` inside a fence would corrupt the sample it is quoting.+ *+ * @param {string} markdown Release body as authored by Changesets.+ * @returns {string} mrkdwn-formatted equivalent.+ */+export function githubMarkdownToSlackMrkdwn(markdown) {+ // Strip HTML comments first: the beta cadence embeds an internal+ // `<!-- ok-consumed-set: … -->` marker that must never reach the channel.+ const withoutComments = markdown.replace(/<!--[\s\S]*?-->/g, '');++ let inFence = false;+ const lines = withoutComments.split('\n').map((rawLine) => {+ // Escape before any conversion so a literal `<` in prose cannot be read as+ // the start of a Slack link, and so the `<url|label>` links built below+ // survive (escaping only touches & < >, never [ ] ( )).+ const line = escapeSlackText(rawLine);++ if (/^\s*```/.test(line)) {+ inFence = !inFence;+ return line;+ }+ if (inFence) return line;++ // Headings have no mrkdwn equivalent; bold carries the same visual weight.+ const heading = line.match(/^\s*#{1,6}\s+(.*?)\s*$/);+ if (heading) return heading[1] ? `*${heading[1]}*` : '';++ let out = line;++ // Bullets: mrkdwn has no list syntax, so render the glyph literally.+ // Changesets nests one level (two-space indent) for sub-points.+ const bullet = out.match(/^(\s*)[-*+]\s+(.*)$/);+ if (bullet) {+ const depth = Math.floor(bullet[1].length / 2);+ const glyph = depth === 0 ? '•' : '◦';+ out = `${' '.repeat(depth)}${glyph} ${bullet[2]}`;+ }++ // `[label](url)` -> `<url|label>`. Label excludes `]` and the URL excludes+ // `)` and whitespace so adjacent links on one line stay separate matches.+ out = out.replace(/\[([^\]]*)\]\(([^)\s]+)\)/g, (_m, label, url) =>+ label ? `<${url}|${label}>` : `<${url}>`,+ );++ // `**bold**` / `__bold__` -> `*bold*`. Single-asterisk emphasis is left+ // alone: Slack reads it as bold, which is a closer render than the literal+ // asterisks any rewrite would risk producing.+ out = out.replace(/\*\*(?=\S)([\s\S]*?\S)\*\*/g, '*$1*');+ out = out.replace(/__(?=\S)([\s\S]*?\S)__/g, '*$1*');++ return out;+ });++ return lines.join('\n').replace(/\n{3,}/g, '\n\n').trim();+}++/**+ * Truncate to `limit` characters on a line boundary, marking the cut.+ *+ * Cutting mid-line would risk splitting a `<url|label>` link into visible+ * syntax, so a too-long single line is dropped rather than sliced.+ *+ * @returns {string} Text at or under the limit, `…` appended when truncated.+ */+export function truncateOnLineBoundary(text, limit) {+ if (text.length <= limit) return text;+ const kept = [];+ let used = 0;+ for (const line of text.split('\n')) {+ // +1 for the newline that rejoins this line to the previous one.+ const cost = line.length + (kept.length === 0 ? 0 : 1);+ if (used + cost > limit) break;+ kept.push(line);+ used += cost;+ }+ return `${kept.join('\n').trimEnd()}\n…`;+}++/**+ * Split text into chunks that each fit a section block, preferring paragraph+ * then line boundaries so a chunk never starts mid-sentence.+ *+ * @returns {string[]} Chunks, each at or under `limit`.+ */+export function chunkForSections(text, limit = SECTION_LIMIT) {+ if (!text) return [];+ if (text.length <= limit) return [text];++ const chunks = [];+ let current = '';+ for (const line of text.split('\n')) {+ const candidate = current ? `${current}\n${line}` : line;+ if (candidate.length <= limit) {+ current = candidate;+ continue;+ }+ if (current) chunks.push(current);+ // A single line over the limit cannot be kept whole; hard-slice it so the+ // message still sends rather than 400s.+ if (line.length > limit) {+ let rest = line;+ while (rest.length > limit) {+ chunks.push(rest.slice(0, limit));+ rest = rest.slice(limit);+ }+ current = rest;+ } else {+ current = line;+ }+ }+ if (current) chunks.push(current);+ return chunks.filter((chunk) => chunk.trim() !== '');+}++/**+ * @param {{version: string, releaseUrl: string, notes?: string}} input+ * @returns {object} Slack incoming-webhook payload.+ */+export function buildSlackReleasePayload({ version, releaseUrl, notes = '' }) {+ const mrkdwn = truncateOnLineBoundary(githubMarkdownToSlackMrkdwn(notes ?? ''), NOTES_LIMIT);++ const blocks = [+ {+ type: 'header',+ text: { type: 'plain_text', text: `🎉 OpenKnowledge ${version} released`, emoji: true },+ },+ ...chunkForSections(mrkdwn).map((chunk) => ({+ type: 'section',+ text: { type: 'mrkdwn', text: chunk },+ })),+ {+ type: 'section',+ text: { type: 'mrkdwn', text: `*<${releaseUrl}|Release notes & downloads>*` },+ },+ ];++ return {+ // Notification/a11y fallback Slack recommends alongside blocks.+ text: `OpenKnowledge ${version} released — ${releaseUrl}`,+ blocks,+ };+}++function parseArgs(argv) {+ const args = { version: '', releaseUrl: '' };+ for (let i = 0; i < argv.length; i += 1) {+ if (argv[i] === '--version') args.version = argv[i + 1] ?? '';+ if (argv[i] === '--url') args.releaseUrl = argv[i + 1] ?? '';+ }+ return args;+}++function main() {+ const { version, releaseUrl } = parseArgs(process.argv.slice(2));+ if (!version || !releaseUrl) {+ process.stderr.write('usage: build-slack-release-payload.mjs --version <v> --url <url>\n');+ process.exitCode = 1;+ return;+ }+ const chunks = [];+ process.stdin.on('data', (c) => chunks.push(c));+ process.stdin.on('end', () => {+ const notes = Buffer.concat(chunks).toString('utf8');+ process.stdout.write(JSON.stringify(buildSlackReleasePayload({ version, releaseUrl, notes })));+ });+}++// Run main() only as a CLI, not when imported by the test file.+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main();+}diff --git a/scripts/build-slack-release-payload.test.mjs b/scripts/build-slack-release-payload.test.mjsnew file mode 100644index 000000000..a00a0ccb5--- /dev/null+++ b/scripts/build-slack-release-payload.test.mjs@@ -0,0 +1,210 @@+import { describe, expect, test } from 'vitest';+import {+ buildSlackReleasePayload,+ chunkForSections,+ githubMarkdownToSlackMrkdwn,+ truncateOnLineBoundary,+} from './build-slack-release-payload.mjs';++const RELEASE_URL = 'https://github.com/inkeep/open-knowledge/releases/tag/v0.38.4';++/** Slack rejects the message when any section's text exceeds this. */+const SLACK_SECTION_CAP = 3000;++function sectionTexts(payload) {+ return payload.blocks.filter((b) => b.type === 'section').map((b) => b.text.text);+}++describe('githubMarkdownToSlackMrkdwn', () => {+ test('converts Changesets level headings to bold (mrkdwn has no headings)', () => {+ expect(githubMarkdownToSlackMrkdwn('### Patch Changes')).toBe('*Patch Changes*');+ expect(githubMarkdownToSlackMrkdwn('## Minor Changes')).toBe('*Minor Changes*');+ });++ test('renders bullets as glyphs and indents the one nesting level Changesets emits', () => {+ const out = githubMarkdownToSlackMrkdwn('- top level\n - nested point');+ expect(out).toBe('• top level\n ◦ nested point');+ });++ test('rewrites inline links to Slack link syntax', () => {+ expect(githubMarkdownToSlackMrkdwn('see [the docs](https://example.com/x)')).toBe(+ 'see <https://example.com/x|the docs>',+ );+ });++ test('keeps two links on one line separate', () => {+ expect(githubMarkdownToSlackMrkdwn('[a](https://e.com/a) and [b](https://e.com/b)')).toBe(+ '<https://e.com/a|a> and <https://e.com/b|b>',+ );+ });++ test('converts double-asterisk and double-underscore bold to single-asterisk', () => {+ expect(githubMarkdownToSlackMrkdwn('**bold** and __also bold__')).toBe(+ '*bold* and *also bold*',+ );+ });++ test('escapes the three characters Slack reserves in mrkdwn', () => {+ expect(githubMarkdownToSlackMrkdwn('Y.Text<string> & Y.Map')).toBe(+ 'Y.Text<string> & Y.Map',+ );+ });++ test('strips the internal consumed-set marker so it never reaches the channel', () => {+ const out = githubMarkdownToSlackMrkdwn('- a change\n\n<!-- ok-consumed-set: ["x"] -->\n');+ expect(out).toBe('• a change');+ expect(out).not.toContain('ok-consumed-set');+ });++ test('passes fenced code through without list or bold rewriting', () => {+ const md = '```js\nconst a = **x**;\n- not a bullet\n```';+ const out = githubMarkdownToSlackMrkdwn(md);+ expect(out).toContain('const a = **x**;');+ expect(out).toContain('- not a bullet');+ expect(out).not.toContain('•');+ });++ test('preserves indented continuation paragraphs under a bullet', () => {+ const md = '- fix: tear down the sibling\n\n `ok start` spawns a detached process.';+ expect(githubMarkdownToSlackMrkdwn(md)).toBe(+ '• fix: tear down the sibling\n\n `ok start` spawns a detached process.',+ );+ });++ test('leaves backticked code spans intact', () => {+ expect(githubMarkdownToSlackMrkdwn('run `ok start` now')).toBe('run `ok start` now');+ });++ test('returns empty string for empty input', () => {+ expect(githubMarkdownToSlackMrkdwn('')).toBe('');+ });+});++describe('truncateOnLineBoundary', () => {+ test('returns text untouched when within the limit', () => {+ expect(truncateOnLineBoundary('short', 100)).toBe('short');+ });++ test('cuts on a line boundary and marks the truncation', () => {+ const out = truncateOnLineBoundary('aaaa\nbbbb\ncccc', 9);+ expect(out).toBe('aaaa\nbbbb\n…');+ });++ test('never emits more than the limit plus the marker', () => {+ const text = Array.from({ length: 400 }, (_, i) => `line ${i} of the release notes`).join('\n');+ const out = truncateOnLineBoundary(text, 500);+ expect(out.length).toBeLessThanOrEqual(500 + 2);+ expect(out.endsWith('…')).toBe(true);+ });+});++describe('chunkForSections', () => {+ test('returns a single chunk when the text fits', () => {+ expect(chunkForSections('short notes')).toEqual(['short notes']);+ });++ test('returns nothing for empty text', () => {+ expect(chunkForSections('')).toEqual([]);+ });++ test('splits on line boundaries with every chunk under the cap', () => {+ const text = Array.from({ length: 200 }, (_, i) => `• change number ${i}`).join('\n');+ const chunks = chunkForSections(text, 500);+ expect(chunks.length).toBeGreaterThan(1);+ for (const chunk of chunks) expect(chunk.length).toBeLessThanOrEqual(500);+ // No content is dropped by the split.+ expect(chunks.join('\n')).toBe(text);+ });++ test('hard-slices a single line longer than the limit rather than overflowing', () => {+ const chunks = chunkForSections('x'.repeat(1200), 500);+ for (const chunk of chunks) expect(chunk.length).toBeLessThanOrEqual(500);+ expect(chunks.join('')).toBe('x'.repeat(1200));+ });+});++describe('buildSlackReleasePayload', () => {+ test('includes the release notes body in the message', () => {+ const payload = buildSlackReleasePayload({+ version: '0.38.4',+ releaseUrl: RELEASE_URL,+ notes: '### Patch Changes\n\n- fix: tear down the `ok ui` sibling',+ });+ const texts = sectionTexts(payload);+ expect(texts.some((t) => t.includes('*Patch Changes*'))).toBe(true);+ expect(texts.some((t) => t.includes('• fix: tear down the `ok ui` sibling'))).toBe(true);+ });++ test('keeps the header and the trailing downloads link', () => {+ const payload = buildSlackReleasePayload({+ version: '0.38.4',+ releaseUrl: RELEASE_URL,+ notes: '- a change',+ });+ expect(payload.blocks[0]).toEqual({+ type: 'header',+ text: { type: 'plain_text', text: '🎉 OpenKnowledge 0.38.4 released', emoji: true },+ });+ expect(payload.blocks.at(-1).text.text).toBe(`*<${RELEASE_URL}|Release notes & downloads>*`);+ expect(payload.text).toBe(`OpenKnowledge 0.38.4 released — ${RELEASE_URL}`);+ });++ test('degrades to the header + link message when notes are unavailable', () => {+ // `gh release view` failing must not cost us the announcement.+ for (const notes of ['', undefined]) {+ const payload = buildSlackReleasePayload({ version: '0.38.4', releaseUrl: RELEASE_URL, notes });+ expect(payload.blocks).toHaveLength(2);+ expect(payload.blocks[0].type).toBe('header');+ expect(payload.blocks[1].text.text).toBe(`*<${RELEASE_URL}|Release notes & downloads>*`);+ }+ });++ test('keeps every section under the Slack cap for an oversized release body', () => {+ // Larger than any real body (a 0.38.0-scale minor is ~6.4k).+ const notes = `### Minor Changes\n\n${Array.from(+ { length: 120 },+ (_, i) => `- change ${i}: ${'detail '.repeat(20)}`,+ ).join('\n\n')}`;+ const payload = buildSlackReleasePayload({+ version: '0.39.0',+ releaseUrl: RELEASE_URL,+ notes,+ });+ for (const text of sectionTexts(payload)) {+ expect(text.length).toBeLessThanOrEqual(SLACK_SECTION_CAP);+ }+ expect(payload.blocks.length).toBeLessThanOrEqual(50);+ // Truncated bodies still point at the full notes.+ expect(payload.blocks.at(-1).text.text).toContain(RELEASE_URL);+ });++ test('produces a mrkdwn-clean message for a real release body', () => {+ const notes = [+ '### Patch Changes',+ '',+ '- fix: tear down the `ok ui` sibling when `ok start` exits via a signal',+ '',+ ' `ok start` spawns a detached `ok ui` process to serve the editor shell.',+ ' See [the runbook](https://example.com/runbook) for the **full** story.',+ ].join('\n');+ const payload = buildSlackReleasePayload({+ version: '0.38.4',+ releaseUrl: RELEASE_URL,+ notes,+ });+ const body = sectionTexts(payload).join('\n');+ expect(body).not.toMatch(/^#{1,6} /m);+ expect(body).not.toContain('**');+ expect(body).not.toMatch(/\[[^\]]*\]\([^)]*\)/);+ expect(body).toContain('<https://example.com/runbook|the runbook>');+ });++ test('payload is JSON-serializable with a quote-bearing version', () => {+ const payload = buildSlackReleasePayload({+ version: '0.38.4"; drop',+ releaseUrl: RELEASE_URL,+ notes: '- a "quoted" change',+ });+ expect(() => JSON.parse(JSON.stringify(payload))).not.toThrow();+ });+});