:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ci): consolidate PR bot comments (#70670)
Paul D'Ambra42a825495fe3
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 0bde0e202b90..09c33587ed8a 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -12,7 +12,7 @@# - action paths: ./.depot/actions/... instead of ./.github/actions/... (pnpm-install# and setup-sqlx-cli are byte-equivalent mirrors of the canonical composites)# - permissions: pull-requests:read (no comment/auto-commit side effects)-# - Stripped side effects: artifact uploads, PR comment posters, snapshot+# - Stripped side effects: artifact uploads, CI report section posters, snapshot# auto-commit (handle-snapshots), posthog-github-action telemetry,# --store-durations write, test-selection verdict, Trunk flaky-test quarantine# gate (canonical runs per-shard analytics-uploader steps that post to thediff --git a/.github/actions/commit-snapshots/action.yml b/.github/actions/commit-snapshots/action.ymlindex dda8509736f9..76b5ddc58725 100644--- a/.github/actions/commit-snapshots/action.yml+++ b/.github/actions/commit-snapshots/action.yml@@ -1,5 +1,5 @@name: Commit Aggregated Snapshots-description: Applies snapshot patches, counts changes, commits, and posts PR comment+description: Applies snapshot patches, counts changes, commits, and updates the CI reportinputs:workflow-type:@@ -103,22 +103,23 @@ runs:fiecho "::endgroup::"- - name: Post skip comment+ - name: Post skipped snapshot update to CI reportif: steps.verify.outputs.branch-advanced == 'true'shell: bashenv:- GH_TOKEN: ${{ inputs.github-token }}+ GITHUB_TOKEN: ${{ github.token }}TESTED_SHA: ${{ inputs.commit-sha }}CURRENT_SHA: ${{ steps.verify.outputs.current-sha }}- PR_NUMBER: ${{ inputs.pr-number }}+ WORKFLOW_TYPE: ${{ inputs.workflow-type }}+ REPOSITORY: ${{ inputs.repository }}run: |- gh pr comment $PR_NUMBER --body "⏭️ Skipped snapshot commit because branch advanced to \`${CURRENT_SHA:0:7}\` while workflow was testing \`${TESTED_SHA:0:7}\`.-- The new commit will trigger its own snapshot update workflow.-- **If you expected this workflow to succeed:** This can happen due to concurrent commits. To get a fresh workflow run, either:- - Merge master into your branch, or- - Push an empty commit: \`git commit --allow-empty -m 'trigger CI' && git push\`"+ node .github/scripts/post-snapshot-section.mjs \+ "$WORKFLOW_TYPE" \+ "skip" \+ '{}' \+ "$REPOSITORY" \+ "$TESTED_SHA" \+ "$CURRENT_SHA"- name: Count changes and disable auto-mergeid: commitdiff --git a/.github/scripts/comment-pr-preview.js b/.github/scripts/comment-pr-preview.jsdeleted file mode 100755index 7dc18b360095..000000000000--- a/.github/scripts/comment-pr-preview.js+++ /dev/null@@ -1,65 +0,0 @@-#!/usr/bin/env node--// Post Vercel-style preview comment on PR-// Requires: github, context from actions/github-script-// Args: prNumber, triggerStatus, deploymentUrl, deploymentId--module.exports = async ({ github, context, prNumber, triggerStatus, deploymentUrl, deploymentId }) => {- const commentHash = `[docs-preview]: #docs-preview-${prNumber}`-- // Delete old preview comments by finding our hash- const comments = await github.rest.issues.listComments({- owner: context.repo.owner,- repo: context.repo.repo,- issue_number: prNumber,- })-- for (const comment of comments.data) {- if (comment.user.login === 'github-actions[bot]' && comment.body.includes('[docs-preview]:')) {- await github.rest.issues.deleteComment({- owner: context.repo.owner,- repo: context.repo.repo,- comment_id: comment.id,- })- }- }-- // Format timestamp like Vercel (UTC)- const now = new Date()- const timestamp = now.toLocaleString('en-US', {- month: 'short',- day: 'numeric',- year: 'numeric',- hour: 'numeric',- minute: '2-digit',- hour12: true,- timeZone: 'UTC',- })-- let message = ''-- if (triggerStatus === 'success') {- const previewUrl = deploymentUrl || 'https://posthog.com'- const inspectorUrl = deploymentId- ? `https://vercel.com/post-hog/posthog/${deploymentId}`- : 'https://vercel.com/post-hog/posthog'-- message =- `${commentHash}\nDocs from this PR will be published at posthog.com\n\n` +- `| Project | Deployment | Preview | Updated (UTC) |\n` +- `| :--- | :----- | :------ | :------ |\n` +- `| [posthog.com](${inspectorUrl}) | 🤷 Unknown | [Preview](${previewUrl}) | ${timestamp} |\n\n` +- `*Preview will be ready in ~10 minutes. Click Preview link above to access docs at \`/handbook/engineering/\`*`- } else {- message =- `${commentHash}\n⚠️ **Docs Preview Build Failed**\n\n` +- `Preview build could not be triggered. Check the [GitHub Action logs](https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}) for details.`- }-- await github.rest.issues.createComment({- issue_number: prNumber,- owner: context.repo.owner,- repo: context.repo.repo,- body: message,- })-}diff --git a/.github/scripts/post-ci-sections.test.mjs b/.github/scripts/post-ci-sections.test.mjsnew file mode 100644index 000000000000..765dce9a6655--- /dev/null+++ b/.github/scripts/post-ci-sections.test.mjs@@ -0,0 +1,65 @@+import assert from 'node:assert/strict'+import { describe, it } from 'node:test'++import { buildDocsPreviewSection } from './post-docs-preview-section.mjs'+import { buildHobbySection } from './post-hobby-section.mjs'++const commonHobby = {+ previewMode: true,+ sha: '1234567890abcdef',+ runNumber: '42',+ runUrl: 'https://github.com/PostHog/posthog/actions/runs/42',+}++describe('CI report section builders', () => {+ it('renders a docs preview link after a successful trigger', () => {+ const section = buildDocsPreviewSection({+ triggerStatus: 'success',+ deploymentUrl: 'https://preview.example.com',+ deploymentId: 'deployment-123',+ runUrl: 'https://github.com/PostHog/posthog/actions/runs/42',+ now: new Date('2026-07-14T10:00:00Z'),+ })+ assert.equal(section.status, 'info')+ assert.match(section.body, /https:\/\/preview\.example\.com/)+ assert.match(section.body, /Jul 14, 2026/)+ })++ it('links to workflow logs when the docs preview trigger fails', () => {+ const section = buildDocsPreviewSection({+ triggerStatus: 'failure',+ runUrl: 'https://github.com/PostHog/posthog/actions/runs/42',+ })+ assert.equal(section.status, 'fail')+ assert.match(section.body, /actions\/runs\/42/)+ })++ it('moves a hobby preview through setup, ready, and failed states', () => {+ const initial = buildHobbySection({ state: 'initial', ...commonHobby })+ const ready = buildHobbySection({+ state: 'final',+ ...commonHobby,+ files: {+ testExitCode: '0',+ dropletInfo: 'URL: https://hobby.example.com\nSSH: ssh [email protected]\nDroplet IP: 127.0.0.1\n',+ output: 'created',+ },+ })+ const failed = buildHobbySection({+ state: 'final',+ ...commonHobby,+ files: {+ testExitCode: '1',+ dropletInfo: 'URL: https://hobby.example.com\n',+ cloudInitLogs: 'line 1\nline 2',+ output: 'created',+ },+ })++ assert.equal(initial.status, 'info')+ assert.equal(ready.status, 'ok')+ assert.match(ready.body, /https:\/\/hobby\.example\.com/)+ assert.equal(failed.status, 'fail')+ assert.match(failed.body, /line 2/)+ })+})diff --git a/.github/scripts/post-django-migration-section.mjs b/.github/scripts/post-django-migration-section.mjsnew file mode 100644index 000000000000..1b8df26f9bf6--- /dev/null+++ b/.github/scripts/post-django-migration-section.mjs@@ -0,0 +1,30 @@+#!/usr/bin/env node+import fs from 'node:fs'++import { clearSectionIfPresent, postSection } from '../../frontend/bin/ci-report/update-ci-report.mjs'++const CONFIG = {+ sql: {+ id: 'django-migration-sql',+ legacyPrefixes: ['## Migration SQL Changes'],+ },+ risk: {+ id: 'django-migration-risk',+ legacyPrefixes: ['## 🔍 Migration Risk Analysis'],+ },+}++const [kind, mode, status, summary, bodyPath] = process.argv.slice(2)+const config = CONFIG[kind]+if (!config || !['post', 'clear'].includes(mode) || !summary || !bodyPath) {+ console.error('Usage: post-django-migration-section.mjs <sql|risk> <post|clear> <status> <summary> <body path>')+ process.exit(1)+}++const body = fs.readFileSync(bodyPath, 'utf8').trim()+const options = { legacyPrefixes: config.legacyPrefixes }+if (mode === 'clear') {+ await clearSectionIfPresent({ id: config.id, summary, body }, options)+} else {+ await postSection({ id: config.id, status, summary, body }, options)+}diff --git a/.github/scripts/post-docs-preview-section.mjs b/.github/scripts/post-docs-preview-section.mjsnew file mode 100644index 000000000000..985f1dae0b47--- /dev/null+++ b/.github/scripts/post-docs-preview-section.mjs@@ -0,0 +1,57 @@+#!/usr/bin/env node+import { pathToFileURL } from 'node:url'++import { postSection } from '../../frontend/bin/ci-report/update-ci-report.mjs'++export function buildDocsPreviewSection({ triggerStatus, deploymentUrl, deploymentId, runUrl, now = new Date() }) {+ if (triggerStatus !== 'success') {+ return {+ status: 'fail',+ summary: 'preview build failed to start',+ body: `The docs preview build could not be triggered. [View the workflow logs](${runUrl}) for details.`,+ }+ }++ const previewUrl = deploymentUrl || 'https://posthog.com'+ const inspectorUrl = deploymentId+ ? `https://vercel.com/post-hog/posthog/${deploymentId}`+ : 'https://vercel.com/post-hog/posthog'+ const timestamp = now.toLocaleString('en-US', {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ hour: 'numeric',+ minute: '2-digit',+ hour12: true,+ timeZone: 'UTC',+ })++ return {+ status: 'info',+ summary: 'preview build triggered',+ body: [+ 'Docs from this PR will be published at posthog.com.',+ '',+ '| Project | Preview | Updated (UTC) |',+ '| :--- | :--- | :--- |',+ `| [posthog.com](${inspectorUrl}) | [Open preview](${previewUrl}) | ${timestamp} |`,+ '',+ 'The preview should be ready in about 10 minutes. Open the preview at `/handbook/engineering/`.',+ ].join('\n'),+ }+}++async function main() {+ const repositoryUrl = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`+ const section = buildDocsPreviewSection({+ triggerStatus: process.env.TRIGGER_STATUS,+ deploymentUrl: process.env.DEPLOYMENT_URL,+ deploymentId: process.env.DEPLOYMENT_ID,+ runUrl: `${repositoryUrl}/actions/runs/${process.env.GITHUB_RUN_ID}`,+ })+ await postSection({ id: 'docs-preview', ...section }, { legacyPrefixes: ['[docs-preview]:'] })+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ await main()+}diff --git a/.github/scripts/post-hobby-section.mjs b/.github/scripts/post-hobby-section.mjsnew file mode 100644index 000000000000..7440760977f8--- /dev/null+++ b/.github/scripts/post-hobby-section.mjs@@ -0,0 +1,160 @@+#!/usr/bin/env node+import fs from 'node:fs'+import { pathToFileURL } from 'node:url'++import { postSection } from '../../frontend/bin/ci-report/update-ci-report.mjs'++function readFile(path, fallback = '') {+ try {+ return fs.readFileSync(path, 'utf8')+ } catch {+ return fallback+ }+}++function dropletDetails(dropletInfo) {+ return {+ instanceUrl: dropletInfo.match(/URL: (.*)/)?.[1] ?? '',+ sshCommand: dropletInfo.match(/SSH: (.*)/)?.[1] ?? '',+ dropletIp: dropletInfo.match(/Droplet IP: (.*)/)?.[1] ?? '',+ }+}++export function buildHobbySection({ state, previewMode, sha, runNumber, runUrl, buildConclusion, files = {} }) {+ const commit = sha.slice(0, 7)+ const metadata = `**Commit:** \`${commit}\` \n**Workflow run:** [#${runNumber}](${runUrl})`+ const mode = previewMode ? 'Preview (persistent)' : 'Smoke test (ephemeral)'++ if (state === 'initial') {+ return {+ status: 'info',+ summary: 'setting up preview instance',+ body: `Setting up a persistent preview instance. This takes about 30 minutes.\n\n${metadata}`,+ }+ }+ if (state === 'build-failed') {+ return {+ status: 'fail',+ summary: 'Docker image build failed',+ body: [+ `The Docker image build did not complete successfully (status: ${buildConclusion || 'unknown'}).`,+ '',+ `[View the workflow logs](${runUrl}), fix the build error, and push a new commit to retry.`,+ '',+ metadata,+ ].join('\n'),+ }+ }+ if (state === 'image-ready') {+ return {+ status: 'info',+ summary: 'Docker image ready, creating instance',+ body: `The Docker image is ready. The preview instance is being created.\n\n${metadata}`,+ }+ }++ const dropletInfo = files.dropletInfo ?? ''+ const { instanceUrl, sshCommand, dropletIp } = dropletDetails(dropletInfo)+ if (state === 'instance-created') {+ return {+ status: 'info',+ summary: instanceUrl ? `running smoke tests at ${instanceUrl}` : 'instance created, running smoke tests',+ body: [+ 'The preview instance is ready and smoke tests are running.',+ instanceUrl ? `\n**URL:** ${instanceUrl}` : '',+ '',+ metadata,+ ].join('\n'),+ }+ }++ if (state !== 'final') {+ throw new Error(`Unknown hobby section state: ${state}`)+ }++ const testPassed = files.testExitCode === '0'+ const instanceCreated = dropletInfo.length > 0+ let status = 'ok'+ let summary = previewMode ? 'preview deployment ready' : 'smoke test passed'+ let errorSection = ''+ if (!instanceCreated) {+ status = 'fail'+ summary = 'instance creation failed'+ errorSection = `### Deployment error++The instance could not be created. [View the workflow logs](${runUrl}) for the failing step.`+ } else if (!testPassed) {+ status = 'fail'+ summary = 'smoke tests failed'+ const recentLogs = (files.cloudInitLogs || 'Could not fetch cloud-init logs')+ .trim()+ .split('\n')+ .slice(-30)+ .join('\n')+ errorSection = `### Test failure++The deployment was created but health checks failed.++${instanceUrl ? `- Try accessing manually: ${instanceUrl}\n` : ''}${sshCommand ? `- SSH to debug: \`${sshCommand}\`` : ''}++<details>+<summary>Recent cloud-init logs</summary>++\`\`\`+${recentLogs}+\`\`\`+</details>`+ }++ const access = [+ instanceUrl ? `**URL:** ${instanceUrl}` : '',+ sshCommand ? `**SSH:** \`${sshCommand}\`` : '',+ dropletIp ? `**IP:** \`${dropletIp}\`` : '',+ ].filter(Boolean)+ const details =+ dropletInfo && testPassed+ ? `<details>\n<summary>Full instance details</summary>\n\n\`\`\`\n${dropletInfo.trim()}\n\`\`\`\n</details>`+ : ''+ const output = files.output || 'Could not read hobby-ci output'+ const sections = []+ if (access.length > 0) {+ sections.push(access.join('\n'))+ }+ sections.push(`**Mode:** ${mode}\n${metadata}`)+ if (errorSection) {+ sections.push(errorSection)+ }+ if (details) {+ sections.push(details)+ }+ sections.push(`<details>\n<summary>Deployment output</summary>\n\n\`\`\`\n${output.trim()}\n\`\`\`\n</details>`)+ return {+ status,+ summary,+ body: sections.join('\n\n'),+ }+}++async function main() {+ const [state] = process.argv.slice(2)+ const repositoryUrl = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`+ const section = buildHobbySection({+ state,+ previewMode: process.env.PREVIEW_MODE === 'true',+ sha: process.env.GITHUB_SHA || '',+ runNumber: process.env.GITHUB_RUN_NUMBER || '',+ runUrl: `${repositoryUrl}/actions/runs/${process.env.GITHUB_RUN_ID}`,+ buildConclusion: process.env.BUILD_CONCLUSION,+ files: {+ dropletInfo: readFile('/tmp/droplet_info.txt'),+ cloudInitLogs: readFile('/tmp/cloud-init-output.log'),+ output: readFile('/tmp/hobby-ci-output.txt', 'Could not read hobby-ci output'),+ testExitCode: process.env.TEST_EXIT_CODE,+ },+ })+ await postSection({ id: 'hobby-deploy', ...section }, { legacyPrefixes: ['<!-- hobby-ci-comment -->'] })+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ await main()+}diff --git a/.github/scripts/post-snapshot-section.mjs b/.github/scripts/post-snapshot-section.mjsindex cc57d9934a9f..f3f54a998123 100644--- a/.github/scripts/post-snapshot-section.mjs+++ b/.github/scripts/post-snapshot-section.mjs@@ -3,26 +3,13 @@ import { postSection } from '../../frontend/bin/ci-report/update-ci-report.mjs'const [workflowType, mode, changesJson, repo, commitSha, snapshotSha] = process.argv.slice(2)-if (process.argv.length !== 7 && process.argv.length !== 8) {+if (process.argv.length !== 8) {console.error(- 'Usage: post-snapshot-section.mjs <workflow_type> <mode> <changes_json> <repo> <commit_sha> [snapshot_sha]'+ 'Usage: post-snapshot-section.mjs <workflow_type> <mode> <changes_json> <repo> <commit_sha> <snapshot_sha>')process.exit(0)}-if (mode !== 'update') {- console.error(`Unknown mode: ${mode} — skipping snapshot section.`)- process.exit(0)-}--const changes = JSON.parse(changesJson)-const { total, added, modified, deleted } = changes--if (total === 0) {- console.info('No snapshot changes — nothing to post.')- process.exit(0)-}-const CONFIGS = {storybook: {id: 'storybook-snapshots',@@ -78,6 +65,36 @@ if (!config) {process.exit(0)}+if (mode === 'skip') {+ const currentShort = snapshotSha.slice(0, 7)+ const testedShort = commitSha.slice(0, 7)+ await postSection(+ {+ id: config.id,+ status: 'info',+ summary: `skipped stale run for ${testedShort}`,+ body: `Skipped the snapshot commit because the branch advanced to \`${currentShort}\` while the workflow was testing \`${testedShort}\`.++The new commit will trigger its own snapshot update workflow. If a fresh run does not start, merge master or push an empty commit.`,+ },+ { legacyPrefixes: ['⏭️ Skipped snapshot commit because branch advanced'] }+ )+ process.exit(0)+}++if (mode !== 'update') {+ console.error(`Unknown mode: ${mode} — skipping snapshot section.`)+ process.exit(0)+}++const changes = JSON.parse(changesJson)+const { total, added, modified, deleted } = changes++if (total === 0) {+ console.info('No snapshot changes — nothing to post.')+ process.exit(0)+}+const body = `### ${config.headerPrefix}: ${config.label} ${config.type} updated**Changes:** ${total} snapshots (${modified} modified, ${added} added, ${deleted} deleted)diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 695e7ad49c37..9421e10f3885 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -1090,7 +1090,7 @@ jobs:# (otherwise-empty) check suite rather than floating under a random# run in the crowded github-actions suite. The job's GITHUB_TOKEN# therefore no longer needs checks:write. pull-requests:write is still- # required for the migration SQL comment steps below.+ # required for the migration sections in the CI report.permissions:contents: readpull-requests: write@@ -1258,16 +1258,28 @@ jobs:run: |UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev- - name: Check migrations and post SQL comment+ - name: Check migrations and post SQL to CI reportif: github.event_name == 'pull_request' && needs.changes.outputs.migrations == 'true'env:GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}CHANGED_FILES: ${{ needs.changes.outputs.migrations_files }}BASE_SHA: ${{ github.event.pull_request.base.sha }}run: |+ # The PR checkout above uses the PR branch, which on unrebased PRs+ # predates this script — skip the CI report section rather than fail.+ post_migration_section() {+ if [ -f .github/scripts/post-django-migration-section.mjs ]; then+ node .github/scripts/post-django-migration-section.mjs "$@"+ else+ echo "Skipping Django migration section — script not present on this checkout"+ fi+ }+# If no migration files changed, exitif [ -z "$CHANGED_FILES" ]; thenecho "No migration files changed"+ echo "No new Django migrations need SQL review." > /tmp/django-migration-sql.md+ post_migration_section sql clear ok "no new migrations" /tmp/django-migration-sql.mdexit 0fi@@ -1279,8 +1291,9 @@ jobs:fi# Initialize comment body for SQL changes- COMMENT_BODY="## Migration SQL Changes\n\nHey 👋, we've detected some migrations on this PR. Here's the SQL output for each migration, make sure they make sense:\n\n"+ COMMENT_BODY="We've detected new migrations on this PR. Review the SQL output for each migration:\n\n"HAS_NEW_MIGRATIONS=false+ MIGRATION_COUNT=0# Process each changed migration file (excluding Rust migrations)for file in $CHANGED_FILES; do@@ -1306,35 +1319,22 @@ jobs:fiHAS_NEW_MIGRATIONS=true+ MIGRATION_COUNT=$((MIGRATION_COUNT + 1))echo "Checking migration $migration_number for app $app_name"# Get SQL outputSQL_OUTPUT=$(python manage.py sqlmigrate $app_name $migration_number)# Add to comment body- COMMENT_BODY+="#### [\`$file\`](https:\/\/github.com\/${{ github.repository }}\/blob\/${{ github.sha }}\/$file)\n\`\`\`sql\n$SQL_OUTPUT\n\`\`\`\n\n"+ COMMENT_BODY+="#### [\`$file\`](https://github.com/${{ github.repository }}/blob/${{ github.sha }}/$file)\n\`\`\`sql\n$SQL_OUTPUT\n\`\`\`\n\n"fidone- # Get existing comments (needed for both update and cleanup)- COMMENTS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \- -H "Accept: application/vnd.github.v3+json" \- "https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments")-- # Extract comment ID if exists- SQL_COMMENT_ID=$(echo "$COMMENTS" | jq -r '.[] | select(.body | startswith("## Migration SQL Changes")) | .id' | head -1)-- # If no new migrations, clean up any stale comment and exitif [ "$HAS_NEW_MIGRATIONS" = false ]; then- echo "No new migrations to show (all changed files already exist on base branch)"- if [ -n "$SQL_COMMENT_ID" ]; then- echo "Deleting stale SQL comment $SQL_COMMENT_ID"- curl -X DELETE \- -H "Authorization: token $GITHUB_TOKEN" \- -H "Accept: application/vnd.github.v3+json" \- "https://api.github.com/repos/${{ github.repository }}/issues/comments/$SQL_COMMENT_ID"- fi- exit 0+ echo "No new migrations to show (all changed files already exist on base branch)"+ echo "No new Django migrations need SQL review." > /tmp/django-migration-sql.md+ post_migration_section sql clear ok "no new migrations" /tmp/django-migration-sql.md+ exit 0fi# Add timestamp and commit SHA to SQL changes@@ -1345,27 +1345,15 @@ jobs:# Convert \n into actual newlinesCOMMENT_BODY=$(printf '%b' "$COMMENT_BODY")- COMMENT_BODY_JSON=$(jq -n --arg body "$COMMENT_BODY" '{body: $body}')-- if [ -n "$SQL_COMMENT_ID" ]; then- # Update existing comment- echo "Updating existing SQL comment $SQL_COMMENT_ID"- curl -X PATCH \- -H "Authorization: token $GITHUB_TOKEN" \- -H "Accept: application/vnd.github.v3+json" \- "https://api.github.com/repos/${{ github.repository }}/issues/comments/$SQL_COMMENT_ID" \- -d "$COMMENT_BODY_JSON"+ printf '%s' "$COMMENT_BODY" > /tmp/django-migration-sql.md+ if [ "$MIGRATION_COUNT" -eq 1 ]; then+ MIGRATION_SUMMARY="1 new migration to review"else- # Post new SQL comment to PR- echo "Posting new SQL comment to PR"- curl -X POST \- -H "Authorization: token $GITHUB_TOKEN" \- -H "Accept: application/vnd.github.v3+json" \- "https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" \- -d "$COMMENT_BODY_JSON"+ MIGRATION_SUMMARY="$MIGRATION_COUNT new migrations to review"fi+ post_migration_section sql post warn "$MIGRATION_SUMMARY" /tmp/django-migration-sql.md- - name: Run migration risk analysis and post comment+ - name: Run migration risk analysis and update CI reportif: github.event_name == 'pull_request'# Step timeout: an analyzer hang fails THIS step (a failure, which# !cancelled() still publishes as a definitive verdict) instead of@@ -1376,6 +1364,16 @@ jobs:env:GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: |+ # The PR checkout above uses the PR branch, which on unrebased PRs+ # predates this script — skip the CI report section rather than fail.+ post_migration_section() {+ if [ -f .github/scripts/post-django-migration-section.mjs ]; then+ node .github/scripts/post-django-migration-section.mjs "$@"+ else+ echo "Skipping Django migration section — script not present on this checkout"+ fi+ }+# Get risk analysis for all unapplied migrations (including third-party).# --output-json gives downstream consumers (the check-run step# below, and any other tool) a stable structured shape to read.@@ -1389,49 +1387,25 @@ jobs:echo "$RISK_ANALYSIS" > migration_analysis.mdfi- # Get existing comments- COMMENTS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \- -H "Accept: application/vnd.github.v3+json" \- "https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments")-- # Extract comment ID if exists- COMMENT_ID=$(echo "$COMMENTS" | jq -r '.[] | select(.body | startswith("## 🔍 Migration Risk Analysis")) | .id' | head -1)-if [ -n "$RISK_ANALYSIS" ] && echo "$RISK_ANALYSIS" | grep -q "Summary:"; then# Add timestamp and commit SHA to analysisTIMESTAMP=$(date -u '+%Y-%m-%d %H:%M UTC')COMMIT_SHA="${{ github.event.pull_request.head.sha }}"COMMIT_SHORT="${COMMIT_SHA:0:7}"- RISK_COMMENT="## 🔍 Migration Risk Analysis\n\nWe've analyzed your migrations for potential risks.\n\n$RISK_ANALYSIS\n\n*Last updated: $TIMESTAMP ([${COMMIT_SHORT}](https://github.com/${{ github.repository }}/commit/${COMMIT_SHA}))*"+ RISK_COMMENT="We've analyzed your migrations for potential risks.\n\n$RISK_ANALYSIS\n\n*Last updated: $TIMESTAMP ([${COMMIT_SHORT}](https://github.com/${{ github.repository }}/commit/${COMMIT_SHA}))*"RISK_COMMENT=$(printf '%b' "$RISK_COMMENT")- RISK_COMMENT_JSON=$(jq -n --arg body "$RISK_COMMENT" '{body: $body}')-- if [ -n "$COMMENT_ID" ]; then- # Update existing comment- echo "Updating existing risk analysis comment $COMMENT_ID"- curl -X PATCH \- -H "Authorization: token $GITHUB_TOKEN" \- -H "Accept: application/vnd.github.v3+json" \- "https://api.github.com/repos/${{ github.repository }}/issues/comments/$COMMENT_ID" \- -d "$RISK_COMMENT_JSON"+ printf '%s' "$RISK_COMMENT" > /tmp/django-migration-risk.md+ if [ $EXIT_CODE -ne 0 ]; then+ post_migration_section risk post fail "blocked migration detected" /tmp/django-migration-risk.mdelse- # Create new comment if none exists- echo "Posting new risk analysis comment to PR"- curl -X POST \- -H "Authorization: token $GITHUB_TOKEN" \- -H "Accept: application/vnd.github.v3+json" \- "https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" \- -d "$RISK_COMMENT_JSON"+ post_migration_section risk post ok "migration analysis complete" /tmp/django-migration-risk.mdfi- elif [ -n "$COMMENT_ID" ]; then- # No migrations to analyze but comment exists - delete it- echo "Deleting risk analysis comment (no migrations to analyze)"- curl -X DELETE \- -H "Authorization: token $GITHUB_TOKEN" \- -H "Accept: application/vnd.github.v3+json" \- "https://api.github.com/repos/${{ github.repository }}/issues/comments/$COMMENT_ID"+ elif [ $EXIT_CODE -ne 0 ]; then+ echo "Migration risk analysis failed. Check the workflow logs for details." > /tmp/django-migration-risk.md+ post_migration_section risk post fail "migration analysis failed" /tmp/django-migration-risk.mdelse- echo "No migrations to analyze and no existing comment"+ echo "No Django migrations need risk analysis." > /tmp/django-migration-risk.md+ post_migration_section risk clear ok "no migrations to analyze" /tmp/django-migration-risk.mdfi# Fail the job if there were blocked migrations@@ -1555,10 +1529,10 @@ jobs:MARKER="<!-- stamphog:v1 ${ANALYZED_PATHS} -->"# Truncate the human report to fit the check-run output- # limit (~64KB); the full markdown is also posted as a PR- # comment for humans. The marker stays at the top so it's+ # limit (~64KB); the full markdown is also posted in the CI+ # report for humans. The marker stays at the top so it's# never lost to truncation.- REPORT_BODY=$(head -c 59000 migration_analysis.md 2>/dev/null || echo "See PR comment")+ REPORT_BODY=$(head -c 59000 migration_analysis.md 2>/dev/null || echo "See the CI report")SUMMARY=$(printf '%s\n%s' "$MARKER" "$REPORT_BODY")jq -n \@@ -1665,7 +1639,7 @@ jobs:# `settings.CLOUD_DEPLOYMENT` (e.g. cloud-only Kafka tables). Render the SQL each# environment will execute so reviewers can spot per-env divergence and verify gated# branches don't sneak in ON CLUSTER or other forbidden patterns. We render once per- # environment and reuse the output both for the Actions log groups and the PR comment+ # environment and reuse the output both for the Actions log groups and the CI report# (environment -> node type(s) -> SQL). Environments that render identically are# grouped together; if all environments match, the environment level is collapsed.id: render_ch_sqldiff --git a/.github/workflows/ci-hobby.yml b/.github/workflows/ci-hobby.ymlindex e17b6ddc5189..f978e71f73fe 100644--- a/.github/workflows/ci-hobby.yml+++ b/.github/workflows/ci-hobby.yml@@ -102,7 +102,6 @@ jobs:if: github.event_name == 'pull_request' && needs.changes.outputs.should_run == 'true'outputs:preview-mode: ${{ steps.check-preview.outputs.preview }}- comment-id: ${{ steps.post-comment.outputs.comment-id }}deployment-id: ${{ steps.create-deployment.outputs.deployment-id }}conclusion: ${{ steps.wait-for-image.outputs.conclusion }}steps:@@ -141,69 +140,18 @@ jobs:console.log('Defaulting to smoke test mode');fs.appendFileSync(process.env.GITHUB_OUTPUT, 'preview=false\n');}- - name: Post initial PR comment- id: post-comment+ - name: Check out CI report scripts+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ sparse-checkout: |+ .github+ frontend/bin/ci-report+ - name: Post initial hobby preview statusif: steps.check-preview.outputs.preview == 'true'- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0env:+ GITHUB_TOKEN: ${{ github.token }}PREVIEW_MODE: ${{ steps.check-preview.outputs.preview }}- with:- script: |- const commentMarker = '<!-- hobby-ci-comment -->';- const previewMode = process.env.PREVIEW_MODE === 'true';-- // Find existing comment to update (in case of workflow retry)- const { data: comments } = await github.rest.issues.listComments({- owner: context.repo.owner,- repo: context.repo.repo,- issue_number: context.issue.number,- });-- const existingComment = comments.find(c => c.body.includes(commentMarker));-- const initialBody = `${commentMarker}- ## 🦔 Preview instance-- ${previewMode ? '🔄 **Preview mode** - Reusing or creating persistent droplet' : '🧪 **Smoke test mode** - Creating ephemeral droplet'}-- ⏳ Setting up instance... (this takes ~30 minutes)-- **Commit:** \`${context.sha.substring(0, 7)}\`- **Workflow run:** [#${context.runNumber}](${context.payload.repository.html_url}/actions/runs/${context.runId})- `;-- let commentId;- if (existingComment) {- // Update existing comment- await github.rest.issues.updateComment({- owner: context.repo.owner,- repo: context.repo.repo,- comment_id: existingComment.id,- body: initialBody,- });- commentId = existingComment.id;- console.log(`Updated existing comment ${commentId}`);- } else {- // Create new comment- const { data: newComment } = await github.rest.issues.createComment({- owner: context.repo.owner,- repo: context.repo.repo,- issue_number: context.issue.number,- body: initialBody,- });- commentId = newComment.id;- console.log(`Created new comment ${commentId}`);- }-- // Save comment ID for later update- const fs = require('fs');- const path = require('path');- const outputFile = path.join(process.env.RUNNER_TEMP, 'hobby-comment-id.txt');- fs.writeFileSync(outputFile, commentId.toString());-- // Also set as step output for the changes job to pick up- const output = `comment-id=${commentId}`;- fs.appendFileSync(process.env.GITHUB_OUTPUT, `${output}\n`);+ run: node .github/scripts/post-hobby-section.mjs initial- name: Create GitHub deploymentid: create-deploymentif: steps.check-preview.outputs.preview == 'true'@@ -239,10 +187,6 @@ jobs:});fs.appendFileSync(process.env.GITHUB_OUTPUT, `deployment-id=${deployment.id}\n`);- - name: Check out .github for local actions- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- with:- sparse-checkout: .github- name: Wait for container image build to completeuses: ./.github/actions/wait-for-checkid: wait-for-image@@ -252,41 +196,13 @@ jobs:ref: ${{ github.event.pull_request.head.sha }}timeoutSeconds: '3600'intervalSeconds: '30'- - name: Update comment - Docker build failed+ - name: Post Docker build failure to CI reportif: always() && steps.check-preview.outputs.preview == 'true' && steps.wait-for-image.outputs.conclusion != 'success'- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0env:- COMMENT_ID: ${{ steps.post-comment.outputs.comment-id }}+ GITHUB_TOKEN: ${{ github.token }}+ PREVIEW_MODE: ${{ steps.check-preview.outputs.preview }}BUILD_CONCLUSION: ${{ steps.wait-for-image.outputs.conclusion }}- with:- script: |- const commentMarker = '<!-- hobby-ci-comment -->';- const commentId = process.env.COMMENT_ID;- const buildConclusion = process.env.BUILD_CONCLUSION;-- const errorBody = `${commentMarker}- ## 🦔 Preview instance-- ❌ **Docker image build failed**-- The Docker image build did not complete successfully (status: ${buildConclusion}).-- **What to do:**- - Check the [Docker build workflow](${context.payload.repository.html_url}/actions/runs/${context.runId})- - Look for build errors in the container image build step- - Fix any Dockerfile syntax errors or dependency issues- - Push a new commit to retry-- **Commit:** \`${context.sha.substring(0, 7)}\`- **Workflow run:** [#${context.runNumber}](${context.payload.repository.html_url}/actions/runs/${context.runId})- `;-- await github.rest.issues.updateComment({- owner: context.repo.owner,- repo: context.repo.repo,- comment_id: parseInt(commentId),- body: errorBody,- });+ run: node .github/scripts/post-hobby-section.mjs build-failed- name: Check Docker image build resultenv:BUILD_CONCLUSION: ${{ steps.wait-for-image.outputs.conclusion }}@@ -299,35 +215,12 @@ jobs:echo "Docker image build failed with conclusion: $conclusion"exit 1fi- - name: Update comment - Docker image ready+ - name: Post Docker image ready status to CI reportif: steps.check-preview.outputs.preview == 'true' && steps.wait-for-image.outputs.conclusion == 'success'- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0env:- COMMENT_ID: ${{ steps.post-comment.outputs.comment-id }}+ GITHUB_TOKEN: ${{ github.token }}PREVIEW_MODE: ${{ steps.check-preview.outputs.preview }}- with:- script: |- const commentMarker = '<!-- hobby-ci-comment -->';- const commentId = process.env.COMMENT_ID;- const previewMode = process.env.PREVIEW_MODE === 'true';-- const updatedBody = `${commentMarker}- ## 🦔 Preview instance-- ${previewMode ? '🔄 **Preview mode** - Reusing or creating persistent droplet' : '🧪 **Smoke test mode** - Creating ephemeral droplet'}-- ✅ Docker image ready, creating instance...-- **Commit:** \`${context.sha.substring(0, 7)}\`- **Workflow run:** [#${context.runNumber}](${context.payload.repository.html_url}/actions/runs/${context.runId})- `;-- await github.rest.issues.updateComment({- owner: context.repo.owner,- repo: context.repo.repo,- comment_id: parseInt(commentId),- body: updatedBody,- });+ run: node .github/scripts/post-hobby-section.mjs image-readyhobby-test:runs-on: ubuntu-24.04@@ -351,7 +244,6 @@ jobs:- name: Set environment variables from previous jobrun: |echo "PREVIEW_MODE=${{ github.event_name == 'pull_request' && needs.wait-for-docker-image.outputs.preview-mode || 'false' }}" >> $GITHUB_ENV- echo "HOBBY_COMMENT_ID=${{ needs.wait-for-docker-image.outputs.comment-id }}" >> $GITHUB_ENVecho "HOBBY_DEPLOYMENT_ID=${{ needs.wait-for-docker-image.outputs.deployment-id }}" >> $GITHUB_ENV- name: Setup DO Hobby Instancerun: uv run bin/hobby-ci.py create "$BRANCH_NAME" "${{ github.run_id }}-${{ github.run_attempt }}" "${{ github.sha }}" "${{ github.event.pull_request.number || 'unknown' }}" 2>&1 | tee /tmp/hobby-ci-output.txt@@ -360,45 +252,11 @@ jobs:DIGITALOCEAN_TOKEN: ${{ secrets.DIGITAL_OCEAN_HOBBY_TOKEN }}DIGITALOCEAN_SSH_PRIVATE_KEY: ${{ secrets.DO_DEPLOY_SSH_PRIVATE_KEY }}INSTALLER_CHANGED: ${{ needs.changes.outputs.installer_changed || 'false' }}- - name: Update comment - Instance created- if: env.PREVIEW_MODE == 'true' && env.HOBBY_COMMENT_ID- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0- with:- script: |- const fs = require('fs');- const commentMarker = '<!-- hobby-ci-comment -->';- const commentId = process.env.HOBBY_COMMENT_ID;- const previewMode = process.env.PREVIEW_MODE === 'true';-- const dropletInfo = fs.existsSync('/tmp/droplet_info.txt')- ? fs.readFileSync('/tmp/droplet_info.txt', 'utf8')- : '';-- // Parse droplet info for quick access- let instanceUrl = '';- if (dropletInfo) {- const urlMatch = dropletInfo.match(/URL: (.*)/);- if (urlMatch) instanceUrl = urlMatch[1];- }-- const updatedBody = `${commentMarker}- ## 🦔 Preview instance-- ${previewMode ? '🔄 **Preview mode** - Reusing or creating persistent droplet' : '🧪 **Smoke test mode** - Creating ephemeral droplet'}-- ✅ Instance created, running smoke tests...- ${instanceUrl ? `\n🌐 **URL:** ${instanceUrl}` : ''}-- **Commit:** \`${context.sha.substring(0, 7)}\`- **Workflow run:** [#${context.runNumber}](${context.payload.repository.html_url}/actions/runs/${context.runId})- `;-- await github.rest.issues.updateComment({- owner: context.repo.owner,- repo: context.repo.repo,- comment_id: parseInt(commentId),- body: updatedBody,- });+ - name: Post instance created status to CI report+ if: env.PREVIEW_MODE == 'true'+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: node .github/scripts/post-hobby-section.mjs instance-created- name: Update GitHub deployment - instance createdif: env.PREVIEW_MODE == 'true' && env.HOBBY_DEPLOYMENT_IDuses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0@@ -472,134 +330,11 @@ jobs:env:DIGITALOCEAN_TOKEN: ${{ secrets.DIGITAL_OCEAN_HOBBY_TOKEN }}DIGITALOCEAN_SSH_PRIVATE_KEY: ${{ secrets.DO_DEPLOY_SSH_PRIVATE_KEY }}- - name: Update PR comment with final status- if: always() && env.PREVIEW_MODE == 'true' && env.HOBBY_COMMENT_ID- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0- with:- script: |- const fs = require('fs');- const commentMarker = '<!-- hobby-ci-comment -->';- const commentId = process.env.HOBBY_COMMENT_ID;- const previewMode = process.env.PREVIEW_MODE === 'true';- const testExitCode = process.env.TEST_EXIT_CODE;-- let output = '';- try {- output = fs.readFileSync('/tmp/hobby-ci-output.txt', 'utf8');- } catch (error) {- output = 'Could not read hobby-ci output';- }-- const dropletInfo = fs.existsSync('/tmp/droplet_info.txt')- ? fs.readFileSync('/tmp/droplet_info.txt', 'utf8')- : '';-- // Parse droplet info for nice display- let instanceUrl = '';- let sshCommand = '';- let dropletIp = '';- if (dropletInfo) {- const urlMatch = dropletInfo.match(/URL: (.*)/);- const sshMatch = dropletInfo.match(/SSH: (.*)/);- const ipMatch = dropletInfo.match(/Droplet IP: (.*)/);- if (urlMatch) instanceUrl = urlMatch[1];- if (sshMatch) sshCommand = sshMatch[1];- if (ipMatch) dropletIp = ipMatch[1];- }-- // Determine status- const testPassed = testExitCode === '0';- const instanceCreated = dropletInfo !== '';-- let statusEmoji = '✅';- let statusText = previewMode ? 'Preview deployment ready' : 'Smoke test passed';- let errorSection = '';-- if (!instanceCreated) {- statusEmoji = '❌';- statusText = 'Instance creation failed';- errorSection = `- ### ❌ Deployment Error-- The instance could not be created. Check the deployment output below for details.-- **Troubleshooting:**- - Check if DigitalOcean API is accessible- - Verify DIGITALOCEAN_TOKEN secret is valid- - Review cloud-init logs in the workflow artifacts-- **Workflow logs:** [View full logs](${context.payload.repository.html_url}/actions/runs/${context.runId})- `;- } else if (!testPassed) {- statusEmoji = '❌';- statusText = 'Smoke tests failed';-- // Get last 30 lines of cloud-init logs if available- let recentLogs = '';- try {- const cloudInitLogs = fs.readFileSync('/tmp/cloud-init-output.log', 'utf8');- const logLines = cloudInitLogs.trim().split('\n');- recentLogs = logLines.slice(-30).join('\n');- } catch (e) {- recentLogs = 'Could not fetch cloud-init logs';- }-- errorSection = `- ### ❌ Test Failure-- The deployment was created but health checks failed.-- **Quick diagnostics:**- ${instanceUrl ? `- Try accessing manually: ${instanceUrl}` : ''}- ${sshCommand ? `- SSH to debug: \`${sshCommand}\`\n Then run: \`tail -f /var/log/cloud-init-output.log\`\n And: \`docker-compose logs\`` : ''}-- <details>- <summary>Recent cloud-init logs (last 30 lines)</summary>-- \`\`\`- ${recentLogs}- \`\`\`- </details>-- **Common issues:**- - Container failed to start (check docker-compose logs)- - Database migration issues (check postgres/clickhouse logs)- - Out of memory (instance needs 4GB+)-- **Full logs:** Check workflow artifacts or [view logs](${context.payload.repository.html_url}/actions/runs/${context.runId})- `;- }-- const commentBody = `${commentMarker}- ## 🦔 Preview instance-- ${statusEmoji} **${statusText}**-- ${instanceUrl ? `### 🌐 Access the instance\n**URL:** ${instanceUrl}\n` : ''}- ${sshCommand ? `**SSH:** \`${sshCommand}\`\n` : ''}- ${dropletIp ? `**IP:** \`${dropletIp}\`\n` : ''}-- **Mode:** ${previewMode ? '🔄 Preview (persistent)' : '🧪 Smoke test (ephemeral)'}- **Commit:** \`${context.sha.substring(0, 7)}\`- **Workflow run:** [#${context.runNumber}](${context.payload.repository.html_url}/actions/runs/${context.runId})- ${errorSection}- ${dropletInfo && testPassed ? '\n<details>\n<summary>Full instance details</summary>\n\n```\n' + dropletInfo + '```\n</details>\n' : ''}-- <details>- <summary>Deployment output</summary>-- \`\`\`- ${output}- \`\`\`- </details>- `;-- await github.rest.issues.updateComment({- owner: context.repo.owner,- repo: context.repo.repo,- comment_id: parseInt(commentId),- body: commentBody,- });+ - name: Post final hobby preview status to CI report+ if: always() && env.PREVIEW_MODE == 'true'+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: node .github/scripts/post-hobby-section.mjs final- name: Update GitHub deployment statusif: always() && env.PREVIEW_MODE == 'true' && env.HOBBY_DEPLOYMENT_IDuses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex 39ae54f558e6..492ee10abc13 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -62,3 +62,6 @@ jobs:- name: PR title labeler tests (Node)run: node --test .github/scripts/label-pr-from-title.test.js++ - name: CI report section tests (Node)+ run: node --test .github/scripts/post-ci-sections.test.mjsdiff --git a/.github/workflows/docs-preview-trigger.yml b/.github/workflows/docs-preview-trigger.ymlindex 27a3dca458b5..3939b115b72b 100644--- a/.github/workflows/docs-preview-trigger.yml+++ b/.github/workflows/docs-preview-trigger.yml@@ -72,22 +72,11 @@ jobs:VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}run: .github/scripts/trigger-vercel-preview.sh "$BRANCH_NAME"- - name: Comment on PR+ - name: Post docs preview to CI reportif: github.event_name == 'pull_request'- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0env:+ GITHUB_TOKEN: ${{ github.token }}TRIGGER_STATUS: ${{ steps.trigger-build.outputs.trigger_status }}DEPLOYMENT_URL: ${{ steps.trigger-build.outputs.deployment_url }}DEPLOYMENT_ID: ${{ steps.trigger-build.outputs.deployment_id }}- PR_NUMBER: ${{ github.event.pull_request.number }}- with:- script: |- const commentFn = require('./.github/scripts/comment-pr-preview.js');- await commentFn({- github,- context,- prNumber: parseInt(process.env.PR_NUMBER, 10),- triggerStatus: process.env.TRIGGER_STATUS,- deploymentUrl: process.env.DEPLOYMENT_URL,- deploymentId: process.env.DEPLOYMENT_ID- });+ run: node .github/scripts/post-docs-preview-section.mjsdiff --git a/frontend/bin/ci-report/delete-legacy-comments.mjs b/frontend/bin/ci-report/delete-legacy-comments.mjsindex 68405e1f9ee5..3433e246f6e8 100644--- a/frontend/bin/ci-report/delete-legacy-comments.mjs+++ b/frontend/bin/ci-report/delete-legacy-comments.mjs@@ -17,6 +17,10 @@ const LEGACY_MARKERS = ['### 📄 Generated Docs Update Required','### 📦 Surveys SDK Version Check Reminder','<!-- hobby-smoke-test -->',+ '<!-- hobby-ci-comment -->',+ '[docs-preview]:',+ '## Migration SQL Changes',+ '## 🔍 Migration Risk Analysis',]const context = resolvePrContext('cleanup')diff --git a/frontend/bin/ci-report/format.mjs b/frontend/bin/ci-report/format.mjsindex 9a576c1bc303..fb4e11df7b37 100644--- a/frontend/bin/ci-report/format.mjs+++ b/frontend/bin/ci-report/format.mjs@@ -30,9 +30,9 @@ export function formatDelta(bytes, baselineBytes, { noBaseline } = {}) {}// One total compared against the base branch: the body line, header summary, and status-// for a size section, with the missing-baseline presentation handled once — growth warns,-// shrink/flat is ok, and no baseline is informational rather than a bogus "new" delta.-export function totalComparison(bytes, baselineBytes) {+// for a size section, with the missing-baseline presentation handled once. Growth at or+// above the configured threshold warns, shrink/flat is ok, and no baseline is informational.+export function totalComparison(bytes, baselineBytes, { warningThresholdPercent = 0 } = {}) {if (baselineBytes === null || baselineBytes === undefined) {return {status: 'info',@@ -40,8 +40,9 @@ export function totalComparison(bytes, baselineBytes) {totalLine: `**Total:** ${formatBytes(bytes)} _(no base branch measurement to compare against yet)_`,}}+ const growthPercent = baselineBytes === 0 ? Infinity : ((bytes - baselineBytes) / baselineBytes) * 100return {- status: bytes > baselineBytes ? 'warn' : 'ok',+ status: growthPercent >= warningThresholdPercent && bytes > baselineBytes ? 'warn' : 'ok',summary: formatDelta(bytes, baselineBytes),totalLine: `**Total:** ${formatBytes(bytes)} · ${formatDelta(bytes, baselineBytes)}`,}diff --git a/frontend/bin/ci-report/format.test.ts b/frontend/bin/ci-report/format.test.tsnew file mode 100644index 000000000000..8a38bb48eab0--- /dev/null+++ b/frontend/bin/ci-report/format.test.ts@@ -0,0 +1,16 @@+import { totalComparison } from './format.mjs'++describe('ci-report formatting', () => {+ it('warns on any growth by default', () => {+ expect(totalComparison(1001, 1000).status).toBe('warn')+ })++ it.each([+ [1019, 'ok'],+ [1020, 'warn'],+ [1021, 'warn'],+ [999, 'ok'],+ ])('sets status for %i bytes with a 2%% warning floor', (bytes: number, expectedStatus: string) => {+ expect(totalComparison(bytes, 1000, { warningThresholdPercent: 2 }).status).toBe(expectedStatus)+ })+})diff --git a/frontend/bin/ci-report/update-ci-report.mjs b/frontend/bin/ci-report/update-ci-report.mjsindex 3e1fc2d31f69..70e1626f5953 100644--- a/frontend/bin/ci-report/update-ci-report.mjs+++ b/frontend/bin/ci-report/update-ci-report.mjs@@ -25,12 +25,15 @@ export const SECTIONS = [{ id: 'backend-coverage', title: 'Backend coverage' },{ id: 'mcp-snapshots', title: 'MCP snapshots' },{ id: 'ai-evals', title: 'AI evals' },+ { id: 'django-migration-sql', title: 'Django migration SQL' },+ { id: 'django-migration-risk', title: 'Django migration risk' },{ id: 'ch-migration-sql', title: 'ClickHouse migration SQL' },{ id: 'hogql-parser-py', title: 'hogql-parser version' },{ id: 'hogql-parser-npm', title: '@posthog/hogql-parser version' },{ id: 'hogql-parser-rs', title: 'hogql-parser-rs version' },{ id: 'generated-docs', title: 'Generated docs' },- { id: 'hobby-deploy', title: 'Hobby deploy smoke test' },+ { id: 'docs-preview', title: 'Docs preview' },+ { id: 'hobby-deploy', title: 'Hobby preview' },{ id: 'survey-sdk', title: 'Survey SDK reminder' },]@@ -202,6 +205,26 @@ export function isReportComment(comment) {return comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(MARKER)}+export async function deleteLegacyComments(prefixes, context = resolvePrContext('legacy comment cleanup')) {+ if (!context || prefixes.length === 0) {+ return+ }+ const { token, repo, prNumber } = context+ try {+ const stale = (await listPrComments(context)).filter(+ (comment) =>+ comment.user?.login === 'github-actions[bot]' &&+ prefixes.some((prefix) => comment.body?.startsWith(prefix))+ )+ for (const comment of stale) {+ await gh(token, `/repos/${repo}/issues/comments/${comment.id}`, { method: 'DELETE' })+ console.info(`Deleted legacy CI comment ${comment.id} on PR #${prNumber}.`)+ }+ } catch (err) {+ console.warn(`Could not clean up legacy CI comments (read-only token on fork PRs?): ${err.message}`)+ }+}+// A concurrent healer racing us can delete the comment between our read and our write —// that surfaces as a 404 and is retryable. (A concurrent PATCH never 404s; the verify// pass catches it.) Anything else (403 on a fork's read-only token, 5xx) is not worth@@ -213,11 +236,17 @@ function isWriteConflict(err) {// Mark a section resolved (status ok), but only when the report already carries it —// a check whose condition passes on every PR must not add a section saying so, while// a warning that was real on one push must not linger after a later push fixes it.-export async function clearSectionIfPresent({ id, summary, body }) {+/**+ * @param {{ id: string, summary: string, body: string }} section+ * @param {{ legacyPrefixes?: string[] }} options+ */+export async function clearSectionIfPresent({ id, summary, body }, options = {}) {+ const { legacyPrefixes = [] } = optionsconst context = resolvePrContext(`clearing "${id}"`)if (!context) {return}+ await deleteLegacyComments(legacyPrefixes, context)let reportCommenttry {reportComment = (await listPrComments(context)).find(isReportComment)@@ -243,7 +272,12 @@ export async function clearSectionIfPresent({ id, summary, body }) {// to CREATE the comment can leave duplicates — every attempt merges all report// comments' sections into the oldest and deletes the rest, writing the merged content// BEFORE deleting so a cancelled job never loses sections that lived only in a duplicate.-export async function postSection({ id, status, summary, body }, { maxAttempts = 3, retryDelayMs = 1000 } = {}) {+/**+ * @param {{ id: string, status: string, summary: string, body: string }} section+ * @param {{ maxAttempts?: number, retryDelayMs?: number, legacyPrefixes?: string[] }} options+ */+export async function postSection({ id, status, summary, body }, options = {}) {+ const { maxAttempts = 3, retryDelayMs = 1000, legacyPrefixes = [] } = optionsconst context = resolvePrContext('comment')if (!context) {return@@ -321,6 +355,7 @@ export async function postSection({ id, status, summary, body }, { maxAttempts =console.warn(`CI report still has ${after.length - 1} duplicate comment(s) on PR #${prNumber}.`)}console.info(`Wrote CI report section "${id}" on PR #${prNumber} (attempt ${attempt}).`)+ await deleteLegacyComments(legacyPrefixes, context)return}} catch (err) {diff --git a/frontend/bin/ci-report/update-ci-report.test.ts b/frontend/bin/ci-report/update-ci-report.test.tsindex b39abe13662c..b524d679b1a6 100644--- a/frontend/bin/ci-report/update-ci-report.test.ts+++ b/frontend/bin/ci-report/update-ci-report.test.ts@@ -2,7 +2,15 @@ import fs from 'node:fs'import os from 'node:os'import path from 'node:path'-import { MARKER, parseSections, postSection, renderComment, STATUS_EMOJI, upsertSection } from './update-ci-report.mjs'+import {+ clearSectionIfPresent,+ MARKER,+ parseSections,+ postSection,+ renderComment,+ STATUS_EMOJI,+ upsertSection,+} from './update-ci-report.mjs'type SectionEntry = { status: string; summary: string; inner: string }type SectionState = Map<string, SectionEntry>@@ -300,6 +308,29 @@ describe('ci-report section helper', () => {expect([...sections.keys()]).toEqual(['bundle-size', 'eager-graph'])})+ it('removes a legacy bot comment only after its replacement section lands', async () => {+ const legacy = '<!-- old-check -->\nOld standalone result'+ const github = fakeGitHub([{ body: legacy }, { body: legacy, author: 'some-human' }])+ await postSection(+ { id: 'bundle-size', status: 'ok', summary: 'migrated', body: 'BUNDLE' },+ { ...opts, legacyPrefixes: ['<!-- old-check -->'] }+ )+ expect(github.comments).toHaveLength(2)+ expect(github.comments.some((comment) => comment.author === 'some-human' && comment.body === legacy)).toBe(+ true+ )+ expect(github.comments.some((comment) => parseSections(comment.body).has('bundle-size'))).toBe(true)+ })++ it('removes a resolved legacy comment even when no report section exists yet', async () => {+ const github = fakeGitHub([{ body: '## Old result\nNo longer relevant' }])+ await clearSectionIfPresent(+ { id: 'bundle-size', summary: 'resolved', body: 'Nothing to report.' },+ { legacyPrefixes: ['## Old result'] }+ )+ expect(github.comments).toHaveLength(0)+ })+it('retries when a concurrent writer clobbers the section, keeping both', async () => {// The other writer read the comment before our PATCH landed and wrote after// it — its render is missing our section. The verify pass must catch thatdiff --git a/frontend/bin/post-dist-size-comment.mjs b/frontend/bin/post-dist-size-comment.mjsindex 95e856509095..741caa711127 100644--- a/frontend/bin/post-dist-size-comment.mjs+++ b/frontend/bin/post-dist-size-comment.mjs@@ -8,6 +8,7 @@ import { postSection } from './ci-report/update-ci-report.mjs'const __dirname = path.dirname(fileURLToPath(import.meta.url))const frontendDir = path.resolve(__dirname, '..')+const WARNING_THRESHOLD_PERCENT = 2// The workflow measures `du -sb frontend/dist` after the PR build and after the base// build, writing each into these files. They are untracked, so both survive the@@ -31,7 +32,7 @@ if (baseBytes === null) {console.warn('No base dist size measurement found — the section will not show a vs-base delta.')}-const total = totalComparison(prBytes, baseBytes)+const total = totalComparison(prBytes, baseBytes, { warningThresholdPercent: WARNING_THRESHOLD_PERCENT })const body = ['Total size of the built `frontend/dist` folder (all assets), compared against the base branch.','',