Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

feat: generate and deliver contributor cards for merged PRs

Yunyue Licf2fa9597b36
diff --git a/.github/workflows/contributor-cards.yml b/.github/workflows/contributor-cards.yml
new file mode 100644
index 00000000..51a07f59
--- /dev/null
+++ b/.github/workflows/contributor-cards.yml
@@ -0,0 +1,104 @@
+name: Contributor cards
+
+on:
+ pull_request:
+ paths:
+ - 'tools/contributor-cards/**'
+ - '.github/workflows/contributor-cards.yml'
+ push:
+ branches: [main]
+ paths:
+ - 'tools/contributor-cards/**'
+ - '.github/workflows/contributor-cards.yml'
+ pull_request_target:
+ types: [closed]
+ branches: [main]
+ workflow_dispatch:
+ inputs:
+ pr:
+ description: 'Merged pull request number'
+ required: true
+ type: string
+ publish:
+ description: 'Publish the card and post or update its thank-you reply'
+ type: boolean
+ default: false
+
+permissions:
+ contents: read
+
+jobs:
+ check:
+ if: github.event_name == 'pull_request' || github.event_name == 'push'
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@v5
+ with:
+ node-version: 22
+ - uses: browser-actions/setup-chrome@v2
+ id: chrome
+ with:
+ chrome-version: stable
+ install-dependencies: true
+ - name: Install Chinese fallback font
+ run: sudo apt-get update && sudo apt-get install --no-install-recommends -y fonts-noto-cjk
+ - name: Verify records, publication retries and real card layout
+ env:
+ ARCHIFY_CHROME: ${{ steps.chrome.outputs.chrome-path }}
+ ARCHIFY_CHROME_NO_SANDBOX: '1'
+ run: node --test tools/contributor-cards/test/*.test.mjs
+
+ card:
+ if: >-
+ github.repository == 'tt-a1i/archify' &&
+ (github.event_name == 'workflow_dispatch' ||
+ (github.event_name == 'pull_request_target' &&
+ github.event.pull_request.merged == true &&
+ github.event.pull_request.user.type == 'User'))
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ concurrency:
+ group: contributor-card-${{ github.event.pull_request.number || inputs.pr }}
+ cancel-in-progress: false
+ permissions:
+ contents: write
+ pull-requests: write
+ steps:
+ # Privileged runs use only the default branch, never PR head/merge refs.
+ - uses: actions/checkout@v5
+ with:
+ ref: ${{ github.event.repository.default_branch }}
+ persist-credentials: false
+ - uses: actions/setup-node@v5
+ with:
+ node-version: 22
+ - uses: browser-actions/setup-chrome@v2
+ id: chrome
+ with:
+ chrome-version: stable
+ install-dependencies: true
+ - name: Install Chinese fallback font
+ run: sudo apt-get update && sudo apt-get install --no-install-recommends -y fonts-noto-cjk
+ - name: Render card and optionally publish
+ env:
+ GH_TOKEN: ${{ github.token }}
+ CARD_PR: ${{ github.event.pull_request.number || inputs.pr }}
+ CARD_PUBLISH: ${{ github.event_name == 'pull_request_target' || inputs.publish }}
+ ARCHIFY_CHROME: ${{ steps.chrome.outputs.chrome-path }}
+ ARCHIFY_CHROME_NO_SANDBOX: '1'
+ shell: bash
+ run: |
+ args=(--out "$RUNNER_TEMP/contributor-card")
+ if [[ "$CARD_PUBLISH" == 'true' ]]; then args+=(--publish); fi
+ node tools/contributor-cards/cli.mjs "${args[@]}"
+ - name: Keep downloadable card and rendering evidence
+ uses: actions/upload-artifact@v4
+ with:
+ name: contributor-card-${{ github.event.pull_request.number || inputs.pr }}
+ path: ${{ runner.temp }}/contributor-card/
+ retention-days: 7
+ if-no-files-found: error
diff --git a/tools/contributor-cards/README.md b/tools/contributor-cards/README.md
new file mode 100644
index 00000000..3d7d8c68
--- /dev/null
+++ b/tools/contributor-cards/README.md
@@ -0,0 +1,50 @@
+# Contributor cards
+
+Generate Archify's paper-map contribution card from an actual merged GitHub PR. The repository author, title, PR number, UTC merge date and merge commit come from the GitHub API. The card says **Merged**, not **Verified**. Closed but unmerged PRs, bot authors and PRs targeting a non-default branch are rejected.
+
+## Generate a preview
+
+Use Node 22 or newer, Chrome and either an authenticated `gh` session or `GH_TOKEN`:
+
+```sh
+node tools/contributor-cards/cli.mjs --pr 394 --out /tmp/archify-card
+```
+
+An optional `--repo owner/repository` selects another repository. On Linux, install `fonts-noto-cjk` for Chinese titles; on macOS the template uses PingFang SC. `ARCHIFY_CHROME` can select a Chrome executable. Preview mode never writes to GitHub.
+
+The output includes the 1000 × 1500 PNG, a portable HTML document with embedded map/fonts, original metadata with a PNG digest, a browser layout receipt, and the proposed reply. Full PR titles remain in metadata and the HTML title attribute. Font size is reduced within a readable range; exceptionally long titles end with an explicit ellipsis. Usernames are fitted without truncation. Middle-dot text separators are not used.
+
+## Publish and reply
+
+```sh
+node tools/contributor-cards/cli.mjs --pr 394 --out /tmp/archify-card --publish
+```
+
+This is an explicit external write. It atomically adds the PNG and source record to the dedicated `contributor-cards` branch, verifies that the public image is readable, and posts a thank-you reply on that PR. Only public repositories are supported for publication. It does not create a Release, tag, Pages deployment or commit on main.
+
+Each PR has one filename and one comment marker. Unchanged images do not create new commits. A repeated run reuses or updates the authenticated publisher's existing reply. It does not edit comments owned by another user. Consequently, use the workflow consistently for production; publishing locally as a person and later as the Actions bot creates separately owned replies. Existing images remain available through commit-pinned links. A failed comment request can be recovered by rerunning. Ref updates are fast-forward only, and conflicts retry against the latest tree without dropping other PR cards.
+
+## GitHub workflow
+
+[Contributor cards](../../.github/workflows/contributor-cards.yml) provides:
+
+- Automatic publication after a human-authored PR merges into `main` in `tt-a1i/archify`.
+- **Run workflow** with a merged PR number for preview or backfill. **Publish** defaults to false; enable it to post/update the reply.
+- A downloadable workflow artifact retained for seven days; published PNGs live in the data branch independently of that retention.
+- Scoped unit/browser checks when this tool or its workflow changes.
+
+Privileged runs explicitly check out the default branch, never the PR head or merge ref. PR text is read as JSON, validated and HTML-escaped; it is never interpolated into shell commands or JavaScript. Exported HTML has a restrictive content policy, and Chrome blocks network requests during rendering. Checkout does not persist credentials. Job permissions are limited to repository content and PR comments. Per-PR concurrency prevents duplicate replies; publication handles races between different PRs.
+
+To stop automatic replies, disable this workflow in Actions. Historical PRs are not automatically backfilled. Re-enable and use a manual run to recover a failed card. No separate API key, paid image generation or external publishing service is needed for each card.
+
+## Validation
+
+```sh
+node --test tools/contributor-cards/test/*.test.mjs
+```
+
+Chrome is required; browser acceptance fails rather than silently skipping when unavailable. Coverage includes unmerged/wrong-repository/bot inputs, HTML injection, long handles, long unbroken/Chinese titles, duplicate runs, ref races, failed comments, forged comment markers, and public-image availability. Linux CI installs the Chinese fallback font explicitly. Visual review still checks the real PNG; layout metrics alone are not an aesthetic verdict.
+
+## Assets and design
+
+The map is the user-directed ChatGPT Web Pro image from the contributor-card exploration on 2026-09-03. It is reused unchanged; no new model call occurs during generation. Manrope and Barlow Condensed are bundled from the Google Fonts repository under their included SIL Open Font License files. The design retains the approved paper palette, map position and sentence-case typography. These are repository/community assets, outside the packaged Archify skill and its diagram design system.
diff --git a/tools/contributor-cards/assets/PROVENANCE.md b/tools/contributor-cards/assets/PROVENANCE.md
new file mode 100644
index 00000000..90f74a68
--- /dev/null
+++ b/tools/contributor-cards/assets/PROVENANCE.md
@@ -0,0 +1,8 @@
+# Contributor-card assets
+
+- `map.png`: unchanged `docs/assets/contributor-card-concepts/pro-field-map-visual.png`, generated in the user's ChatGPT Web Pro session on 2026-09-03 as part of this Archify design task. SHA-256 recorded below. No text is generated in the image; contribution information is rendered from API data.
+- `fonts/Manrope-Variable.ttf`: https://github.com/google/fonts/tree/main/ofl/manrope, downloaded 2026-09-14. License: `fonts/Manrope-OFL.txt`.
+- `fonts/BarlowCondensed-SemiBold.ttf`: https://github.com/google/fonts/tree/main/ofl/barlowcondensed, downloaded 2026-09-14. License: `fonts/BarlowCondensed-OFL.txt`.
+
+Fonts and map are embedded in the generated HTML. CJK glyphs use the documented platform fallback.
+c38797cd8f6fcb4e618e0c3c0695240a16def4e9221cae1901fd1741e125c8f4 tools/contributor-cards/assets/map.png
diff --git a/tools/contributor-cards/assets/fonts/BarlowCondensed-OFL.txt b/tools/contributor-cards/assets/fonts/BarlowCondensed-OFL.txt
new file mode 100644
index 00000000..11f25280
--- /dev/null
+++ b/tools/contributor-cards/assets/fonts/BarlowCondensed-OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/tools/contributor-cards/assets/fonts/BarlowCondensed-SemiBold.ttf b/tools/contributor-cards/assets/fonts/BarlowCondensed-SemiBold.ttf
new file mode 100644
index 00000000..9df66576
Binary files /dev/null and b/tools/contributor-cards/assets/fonts/BarlowCondensed-SemiBold.ttf differ
diff --git a/tools/contributor-cards/assets/fonts/Manrope-OFL.txt b/tools/contributor-cards/assets/fonts/Manrope-OFL.txt
new file mode 100644
index 00000000..b13cba53
--- /dev/null
+++ b/tools/contributor-cards/assets/fonts/Manrope-OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2018 The Manrope Project Authors (https://github.com/sharanda/manrope)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/tools/contributor-cards/assets/fonts/Manrope-Variable.ttf b/tools/contributor-cards/assets/fonts/Manrope-Variable.ttf
new file mode 100644
index 00000000..23dcf5e0
Binary files /dev/null and b/tools/contributor-cards/assets/fonts/Manrope-Variable.ttf differ
diff --git a/tools/contributor-cards/assets/map.png b/tools/contributor-cards/assets/map.png
new file mode 100644
index 00000000..d845fcb9
Binary files /dev/null and b/tools/contributor-cards/assets/map.png differ
diff --git a/tools/contributor-cards/card.mjs b/tools/contributor-cards/card.mjs
new file mode 100644
index 00000000..baf5ad8a
--- /dev/null
+++ b/tools/contributor-cards/card.mjs
@@ -0,0 +1,106 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { createHash } from 'node:crypto';
+import { ChromeVisualBrowser, findChrome } from '../../archify/bin/visual-check.mjs';
+
+const root = path.dirname(fileURLToPath(import.meta.url));
+export const DATA_BRANCH = 'contributor-cards';
+export const templateVersion = 1;
+export function validRepository(value) {
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(value || '') || value.includes('..')) throw new Error('Expected owner/repository.');
+ return value;
+}
+export function prNumber(value) {
+ if (!/^[1-9]\d{0,9}$/.test(String(value))) throw new Error('Expected a positive PR number.');
+ return Number(value);
+}
+export function recordFromPull(pull, repository) {
+ validRepository(repository);
+ const number = prNumber(pull.number);
+ if (pull.base?.repo?.full_name?.toLowerCase() !== repository.toLowerCase()) throw new Error('PR belongs to a different repository.');
+ if (pull.merged !== true || !pull.merged_at || !Number.isFinite(Date.parse(pull.merged_at))) throw new Error('Only merged pull requests receive contribution cards.');
+ if (!/^[a-f0-9]{40}$/.test(pull.merge_commit_sha || '')) throw new Error('Missing merge commit.');
+ if (pull.user?.type !== 'User' || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(pull.user.login || '')) throw new Error('A human GitHub author is required.');
+ if (typeof pull.title !== 'string' || !pull.title.trim() || pull.title.length > 512) throw new Error('Invalid PR title.');
+ return {
+ templateVersion, repository, number, author: pull.user.login,
+ title: pull.title, mergedAt: pull.merged_at, mergeCommit: pull.merge_commit_sha,
+ url: `https://github.com/${repository}/pull/${number}`,
+ };
+}
+export function escapeHtml(value) {
+ return String(value).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+}
+export async function cardHtml(record) {
+ const data = {
+ AUTHOR: record.author, NUMBER: record.number, REPOSITORY: record.repository,
+ TITLE: record.title.replace(/[\u0000-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069·•]/g, ' ').replace(/\s+/g, ' ').trim(),
+ DATE: record.mergedAt.slice(0, 10), SHORT_SHA: record.mergeCommit.slice(0, 7),
+ };
+ let html = (await fs.readFile(path.join(root, 'template.html'), 'utf8'))
+ .replace(/\{\{([A-Z_]+)\}\}/g, (_, key) => {
+ if (!(key in data)) throw new Error(`Unknown template field: ${key}`);
+ return escapeHtml(data[key]);
+ });
+ for (const [name, mime] of [['map.png', 'image/png'], ['fonts/Manrope-Variable.ttf', 'font/ttf'], ['fonts/BarlowCondensed-SemiBold.ttf', 'font/ttf']]) {
+ const bytes = await fs.readFile(path.join(root, 'assets', name));
+ html = html.replace(`./assets/${name}`, `data:${mime};base64,${bytes.toString('base64')}`);
+ }
+ return html.replace('<meta charset="utf-8">', '<meta charset="utf-8">\n <meta http-equiv="Content-Security-Policy" content="default-src \'none\'; img-src data:; font-src data:; style-src \'unsafe-inline\'; base-uri \'none\'">');
+}
+export async function renderCard(record, outputDirectory, { chrome = findChrome() } = {}) {
+ if (!chrome) throw new Error('Chrome is required. Set ARCHIFY_CHROME to its executable.');
+ await fs.mkdir(outputDirectory, { recursive: true });
+ const stem = path.resolve(outputDirectory, `pr-${record.number}`);
+ const html = await cardHtml(record);
+ await fs.writeFile(`${stem}.html`, html);
+ const browser = new ChromeVisualBrowser(chrome);
+ let receipt;
+ try {
+ const session = await browser.sessionPromise;
+ const send = (method, params = {}) => browser.cdp.send(method, params, session, 30000);
+ await send('Network.enable');
+ await send('Network.setBlockedURLs', { urls: ['http://*', 'https://*'] });
+ await send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1500, deviceScaleFactor: 1, mobile: false });
+ const loaded = browser.cdp.waitFor('Page.loadEventFired', session);
+ const navigation = await send('Page.navigate', { url: pathToFileURL(`${stem}.html`).href });
+ if (navigation.errorText) throw new Error(navigation.errorText);
+ await loaded;
+ const metrics = await send('Runtime.evaluate', { awaitPromise: true, returnByValue: true, expression: `(async () => {
+ await document.fonts.ready;
+ await Promise.all([...document.images].map(i => i.decode()));
+ const overflow = e => e.scrollWidth > e.clientWidth + 1 || e.scrollHeight > e.clientHeight + 1;
+ for (const e of document.querySelectorAll('[data-fit-min]')) {
+ let size = parseFloat(getComputedStyle(e).fontSize);
+ while (overflow(e) && size > Number(e.dataset.fitMin)) {
+ size -= 1; e.style.fontSize = size + 'px';
+ }
+ if (overflow(e) && e.dataset.ellipsis === 'true') {
+ e.dataset.truncated = 'true';
+ const parts = [...new Intl.Segmenter('en', {granularity:'grapheme'}).segment(e.textContent)].map(p => p.segment);
+ while (parts.length && overflow(e)) { parts.pop(); e.textContent = parts.join('').trimEnd() + '…'; }
+ }
+ if (overflow(e)) throw new Error('Text exceeds supported layout: ' + e.className + ' ' + [e.clientWidth,e.scrollWidth,e.clientHeight,e.scrollHeight]);
+ }
+ await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
+ const selectors = ['.handle','.role','.moment','.datum','.datum-value','.series','.record'];
+ const clipped = [...document.querySelectorAll(selectors.join(','))].filter(overflow).map(e => e.className);
+ const fonts = [...document.fonts].map(f => ({family:f.family,status:f.status}));
+ if (fonts.some(f => f.status !== 'loaded')) throw new Error('A bundled font did not load');
+ if (clipped.length) throw new Error('Clipped elements: ' + clipped.join(', '));
+ if (document.querySelector('.moment').getBoundingClientRect().bottom + 20 > document.querySelector('footer').getBoundingClientRect().top) throw new Error('Message overlaps the contribution record');
+ return {width:1000,height:1500,fonts,clipped,text:document.body.innerText,
+ fitted:[...document.querySelectorAll('[data-fit-min]')].map(e=>({text:e.innerText,fontSize:getComputedStyle(e).fontSize,truncated:e.dataset.truncated === 'true'}))};
+ })()` });
+ if (metrics.exceptionDetails) throw new Error(metrics.exceptionDetails.exception?.description || metrics.exceptionDetails.text);
+ receipt = metrics.result.value;
+ const screenshot = await send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false });
+ const png = Buffer.from(screenshot.data, 'base64');
+ if (png.readUInt32BE(16) !== 1000 || png.readUInt32BE(20) !== 1500) throw new Error('Wrong export size');
+ await fs.writeFile(`${stem}.png`, png);
+ await fs.writeFile(`${stem}.json`, JSON.stringify({ ...record, pngSha256: createHash('sha256').update(png).digest('hex') }, null, 2) + '\n');
+ await fs.writeFile(`${stem}.check.json`, JSON.stringify(receipt, null, 2) + '\n');
+ } finally { await browser.close(); }
+ return { stem, receipt };
+}
diff --git a/tools/contributor-cards/cli.mjs b/tools/contributor-cards/cli.mjs
new file mode 100644
index 00000000..834e516e
--- /dev/null
+++ b/tools/contributor-cards/cli.mjs
@@ -0,0 +1,44 @@
+#!/usr/bin/env node
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { prNumber, validRepository, recordFromPull, renderCard } from './card.mjs';
+import { githubClient, publishCard, commentBody } from './github.mjs';
+
+try {
+ const args = process.argv.slice(2);
+ const options = { repo: process.env.GITHUB_REPOSITORY || 'tt-a1i/archify', out: 'artifacts/contributor-cards' };
+ for (let i = 0; i < args.length; i++) {
+ const key = args[i];
+ if (key === '--publish') options.publish = true;
+ else if (['--repo', '--pr', '--out'].includes(key) && args[i + 1] && !args[i + 1].startsWith('--')) options[key.slice(2)] = args[++i];
+ else throw new Error('Usage: node tools/contributor-cards/cli.mjs --pr NUMBER [--repo OWNER/REPO] [--out DIRECTORY] [--publish]');
+ }
+ const repository = validRepository(options.repo);
+ const number = prNumber(options.pr || process.env.CARD_PR);
+ const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN || execFileSync('gh', ['auth', 'token'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ const api = githubClient(token, repository);
+ const repo = await api(`/repos/${repository}`);
+ const pull = await api(`/repos/${repository}/pulls/${number}`);
+ if (pull.base?.ref !== repo.default_branch) throw new Error('Only PRs merged into the default branch receive cards.');
+ const record = recordFromPull(pull, repository);
+ if (options.publish && repo.private) throw new Error('Public image publication is supported only for public repositories.');
+ const { stem } = await renderCard(record, options.out);
+ await fs.writeFile(`${stem}.comment.md`, commentBody(record, `https://raw.githubusercontent.com/${repository}/contributor-cards/cards/pr-${number}.png`) + '\n');
+ console.log(`Rendered ${stem}.png for @${record.author}, merged ${record.mergedAt}.`);
+ if (options.publish) {
+ // workflow tokens act as github-actions[bot]; local gh tokens act as the authenticated user.
+ const commenter = process.env.GITHUB_ACTIONS === 'true' ? 'github-actions[bot]' : (await api('/user')).login;
+ // Recheck live state after rendering before any external writes.
+ const fresh = recordFromPull(await api(`/repos/${repository}/pulls/${number}`), repository);
+ if (JSON.stringify(fresh) !== JSON.stringify(record)) throw new Error('PR metadata changed during rendering. Run again.');
+ const result = await publishCard(api, record, await fs.readFile(`${stem}.png`), { commenter });
+ await fs.writeFile(`${stem}.publication.json`, JSON.stringify(result, null, 2) + '\n');
+ console.log(JSON.stringify(result));
+ if (process.env.GITHUB_STEP_SUMMARY) await fs.appendFile(process.env.GITHUB_STEP_SUMMARY, `Contribution card for [PR #${number}](${record.url})\n\n![Card](${result.imageUrl})\n\n[Thank-you reply](${result.commentUrl})\n`);
+ }
+ if (process.env.GITHUB_OUTPUT) await fs.appendFile(process.env.GITHUB_OUTPUT, `card_directory=${path.resolve(options.out)}\n`);
+} catch (error) {
+ console.error(error.message);
+ process.exitCode = 1;
+}
diff --git a/tools/contributor-cards/examples/README.md b/tools/contributor-cards/examples/README.md
new file mode 100644
index 00000000..08a90a88
--- /dev/null
+++ b/tools/contributor-cards/examples/README.md
@@ -0,0 +1,9 @@
+# Real PR example
+
+This is a snapshot of merged PR [#394](https://github.com/tt-a1i/archify/pull/394), generated on 2026-09-14 from GitHub API metadata using the contributor-card CLI. The image was visually checked at 1000 × 1500. It is an example output, not an instruction to send a reply or reissue a card. The adjacent JSON preserves source metadata and PNG SHA-256.
+
+Regenerate with:
+
+```sh
+node tools/contributor-cards/cli.mjs --pr 394 --out /tmp/archify-card
+```
diff --git a/tools/contributor-cards/examples/pr-394.json b/tools/contributor-cards/examples/pr-394.json
new file mode 100644
index 00000000..2f958d51
--- /dev/null
+++ b/tools/contributor-cards/examples/pr-394.json
@@ -0,0 +1,11 @@
+{
+ "templateVersion": 1,
+ "repository": "tt-a1i/archify",
+ "number": 394,
+ "author": "tt-a1i",
+ "title": "chore(review): reduce repeated CodeRabbit evidence requests",
+ "mergedAt": "2026-09-12T02:23:34Z",
+ "mergeCommit": "6db72a9aea3d0f67a6a034e41f8a5491476a11c1",
+ "url": "https://github.com/tt-a1i/archify/pull/394",
+ "pngSha256": "8a37e5f6c9324af6b7db793a91f83f9e7bf6460b82ca5756b2ab113a14372d96"
+}
diff --git a/tools/contributor-cards/examples/pr-394.png b/tools/contributor-cards/examples/pr-394.png
new file mode 100644
index 00000000..cd4a6bbe
Binary files /dev/null and b/tools/contributor-cards/examples/pr-394.png differ
diff --git a/tools/contributor-cards/github.mjs b/tools/contributor-cards/github.mjs
new file mode 100644
index 00000000..4dd41bfa
--- /dev/null
+++ b/tools/contributor-cards/github.mjs
@@ -0,0 +1,85 @@
+import { createHash } from 'node:crypto';
+import { DATA_BRANCH, validRepository } from './card.mjs';
+
+export function githubClient(token, repository) {
+ validRepository(repository);
+ if (!token) throw new Error('GH_TOKEN or GITHUB_TOKEN is required.');
+ return async (route, { method = 'GET', body, allow404 = false } = {}) => {
+ if (!route.startsWith('/') || route.startsWith('//')) throw new Error('Invalid GitHub route');
+ const response = await fetch(`https://api.github.com${route}`, {
+ method, headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(30000),
+ });
+ if (allow404 && response.status === 404) return null;
+ if (!response.ok) throw new Error(`GitHub ${method} ${route.split('?')[0]} failed (${response.status})`);
+ return response.status === 204 ? null : response.json();
+ };
+}
+const blobSha = bytes => createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
+export function commentBody(record, imageUrl) {
+ return `<!-- archify-contributor-card:pr-${record.number} -->\nThanks @${record.author} for contributing to Archify! Your work is now part of the project.\n\n![Archify contribution card for ${record.author}](${imageUrl})\n\n[Download your card](${imageUrl})\n\n[View contribution](${record.url})`;
+}
+export async function publishCard(api, record, png, { commenter = 'github-actions[bot]', verifyImage = verifyPublicImage } = {}) {
+ const repository = validRepository(record.repository);
+ const base = `/repos/${repository}`;
+ if (!png.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])) || png.readUInt32BE(16) !== 1000 || png.readUInt32BE(20) !== 1500) throw new Error('Expected a 1000 x 1500 PNG');
+ const files = [
+ { path: `cards/pr-${record.number}.png`, bytes: png },
+ { path: `cards/pr-${record.number}.json`, bytes: Buffer.from(JSON.stringify(record, null, 2) + '\n') },
+ ];
+ let publishedCommit;
+ // Ref updates are fast-forward only. Rebuild from the latest tree if a different PR wins a race.
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const ref = await api(`${base}/git/ref/heads/${DATA_BRANCH}`, { allow404: true });
+ const commit = ref ? await api(`${base}/git/commits/${ref.object.sha}`) : null;
+ const tree = commit ? await api(`${base}/git/trees/${commit.tree.sha}?recursive=1`) : { tree: [] };
+ if (tree.truncated) throw new Error('Card data tree exceeds the supported size');
+ const unchanged = files.every(f => tree.tree.some(e => e.path === f.path && e.sha === blobSha(f.bytes)));
+ if (unchanged) { publishedCommit = ref.object.sha; break; }
+ const entries = [];
+ for (const file of files) {
+ const blob = await api(`${base}/git/blobs`, { method: 'POST', body: { encoding: 'base64', content: file.bytes.toString('base64') } });
+ entries.push({ path: file.path, mode: '100644', type: 'blob', sha: blob.sha });
+ }
+ const newTree = await api(`${base}/git/trees`, { method: 'POST', body: { ...(commit ? { base_tree: commit.tree.sha } : {}), tree: entries } });
+ const next = await api(`${base}/git/commits`, { method: 'POST', body: { message: `Add contribution card for PR #${record.number}`, tree: newTree.sha, parents: ref ? [ref.object.sha] : [] } });
+ try {
+ await api(`${base}/git/${ref ? 'refs/heads/' + DATA_BRANCH : 'refs'}`, { method: ref ? 'PATCH' : 'POST', body: ref ? { sha: next.sha, force: false } : { ref: `refs/heads/${DATA_BRANCH}`, sha: next.sha } });
+ publishedCommit = next.sha;
+ break;
+ } catch (error) {
+ if (attempt === 2 || !/\((409|422)\)/.test(error.message)) throw error;
+ }
+ }
+ // Point at the PNG blob's latest commit, so unrelated card additions do not churn old comments.
+ const history = await api(`${base}/commits?sha=${DATA_BRANCH}&path=cards/pr-${record.number}.png&per_page=1`);
+ const imageCommit = history[0]?.sha || publishedCommit;
+ const imageUrl = `https://raw.githubusercontent.com/${repository}/${imageCommit}/cards/pr-${record.number}.png`;
+ await verifyImage(imageUrl, png);
+ const body = commentBody(record, imageUrl);
+ const marker = `<!-- archify-contributor-card:pr-${record.number} -->`;
+ let existing;
+ for (let page = 1; ; page++) {
+ const comments = await api(`${base}/issues/${record.number}/comments?per_page=100&page=${page}`);
+ existing = comments.find(c => c.user?.login === commenter && c.body?.startsWith(marker));
+ if (existing || comments.length < 100) break;
+ }
+ let comment;
+ if (existing?.body === body) comment = existing;
+ else if (existing) comment = await api(`${base}/issues/comments/${existing.id}`, { method: 'PATCH', body: { body } });
+ else comment = await api(`${base}/issues/${record.number}/comments`, { method: 'POST', body: { body } });
+ return { imageUrl, commentUrl: comment.html_url, commit: publishedCommit, changedComment: existing?.body !== body };
+}
+
+async function verifyPublicImage(url, png) {
+ const expected = createHash('sha256').update(png).digest('hex');
+ for (let attempt = 0; attempt < 6; attempt++) {
+ const response = await fetch(url, { signal: AbortSignal.timeout(10000) });
+ if (response.ok) {
+ const bytes = Buffer.from(await response.arrayBuffer());
+ if (createHash('sha256').update(bytes).digest('hex') === expected) return;
+ }
+ if (attempt < 5) await new Promise(resolve => setTimeout(resolve, 2000));
+ }
+ throw new Error('Published PNG is not publicly readable yet; no comment was sent. Retry the workflow.');
+}
diff --git a/tools/contributor-cards/template.html b/tools/contributor-cards/template.html
new file mode 100644
index 00000000..0ac678c8
--- /dev/null
+++ b/tools/contributor-cards/template.html
@@ -0,0 +1,306 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Archify Contributor Field Note</title>
+ <style>
+ @font-face {
+ font-family: "Barlow Condensed";
+ src: url("./assets/fonts/BarlowCondensed-SemiBold.ttf") format("truetype");
+ font-style: normal;
+ font-weight: 600;
+ font-display: block;
+ }
+
+ @font-face {
+ font-family: "Manrope";
+ src: url("./assets/fonts/Manrope-Variable.ttf") format("truetype");
+ font-weight: 200 800;
+ font-style: normal;
+ font-display: block;
+ }
+
+ :root {
+ --paper: #f1eee7;
+ --ink: #101922;
+ --muted: #5f686e;
+ --hairline: rgba(16, 25, 34, 0.22);
+ --cyan: #009fc1;
+ --gold: #b98232;
+ }
+
+ * { box-sizing: border-box; }
+
+ html,
+ body {
+ width: 1000px;
+ height: 1500px;
+ margin: 0;
+ overflow: hidden;
+ background: var(--paper);
+ }
+
+ body {
+ color: var(--ink);
+ font-family: "Manrope", "Noto Sans CJK SC", "PingFang SC", sans-serif;
+ font-variant-numeric: tabular-nums lining-nums;
+ }
+
+ ::selection {
+ color: var(--paper);
+ background: var(--cyan);
+ }
+
+ .card {
+ position: relative;
+ width: 1000px;
+ height: 1500px;
+ isolation: isolate;
+ overflow: hidden;
+ background: var(--paper);
+ }
+
+ .art {
+ position: absolute;
+ z-index: -2;
+ left: 0;
+ top: 36px;
+ width: 1000px;
+ height: auto;
+ display: block;
+ mix-blend-mode: multiply;
+ mask-image: linear-gradient(to bottom, transparent, #000 80px, #000 calc(100% - 240px), transparent);
+ }
+
+ .paper-wash {
+ position: absolute;
+ z-index: -1;
+ inset: 0;
+ pointer-events: none;
+ background:
+ linear-gradient(180deg, rgba(241, 238, 231, 0.96) 0, rgba(241, 238, 231, 0.36) 25%, transparent 39%),
+ linear-gradient(0deg, rgba(241, 238, 231, 0.98) 0, rgba(241, 238, 231, 0.60) 21%, transparent 36%);
+ }
+
+ .rail {
+ position: absolute;
+ top: 54px;
+ bottom: 48px;
+ left: 52px;
+ width: 1px;
+ background: var(--hairline);
+ }
+
+ .rail::before,
+ .rail::after {
+ content: "";
+ position: absolute;
+ left: -4px;
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ background: var(--ink);
+ }
+
+ .rail::before { top: 0; }
+ .rail::after { bottom: 0; }
+
+ header {
+ position: absolute;
+ top: 54px;
+ left: 82px;
+ right: 62px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ min-height: 58px;
+ border-bottom: 1px solid var(--hairline);
+ }
+
+ .brand {
+ display: flex; align-items: center; gap: 14px;
+ font-size: 22px; font-weight: 750; letter-spacing: 0.10em; text-transform: uppercase;
+ }
+
+ .brand-mark {
+ width: 38px;
+ height: 38px;
+ color: var(--cyan);
+ }
+
+ .series {
+ display: grid; gap: 5px; text-align: right; color: var(--muted);
+ font-size: 12px; font-weight: 500; letter-spacing: 0.04em;
+ }
+
+ .identity {
+ position: absolute;
+ top: 151px;
+ left: 82px;
+ right: 62px;
+ }
+
+ .handle {
+ margin: 0; white-space: nowrap; font-size: 50px; font-weight: 650;
+ line-height: 1.3; letter-spacing: -0.035em;
+ }
+
+ .role {
+ margin-top: 16px; color: var(--muted);
+ font-size: 18px; font-weight: 450; line-height: 1.4; letter-spacing: 0;
+ }
+
+
+ .moment {
+ position: absolute; left: 82px; top: 1018px; width: 640px;
+ }
+
+ .moment h1 {
+ max-width: 640px; margin: 0; font-family: "Barlow Condensed", sans-serif;
+ font-size: 82px; font-weight: 600; line-height: 0.98; letter-spacing: -0.015em;
+ }
+
+ .moment p {
+ margin: 26px 0 0; color: var(--muted); font-size: 18px;
+ font-weight: 450; line-height: 1.6;
+ }
+
+ .locator {
+ position: absolute;
+ right: 63px;
+ top: 1034px;
+ width: 146px;
+ height: 146px;
+ display: grid;
+ place-items: center;
+ }
+
+ .locator::before,
+ .locator::after {
+ content: "";
+ position: absolute;
+ border-radius: 50%;
+ border: 1px solid rgba(185, 130, 50, 0.55);
+ }
+
+ .locator::before { inset: 24px; }
+ .locator::after { inset: 42px; }
+
+ .locator span {
+ width: 13px;
+ height: 13px;
+ border-radius: 50%;
+ background: var(--gold);
+ box-shadow: 0 7px 18px rgba(94, 56, 12, 0.24);
+ }
+
+ .locator i,
+ .locator b {
+ position: absolute;
+ display: block;
+ background: rgba(185, 130, 50, 0.5);
+ }
+
+ .locator i { width: 112px; height: 1px; }
+ .locator b { width: 1px; height: 112px; }
+
+ footer {
+ position: absolute; left: 82px; right: 62px; bottom: 64px;
+ display: grid; grid-template-columns: 160px minmax(0, 1fr) 174px;
+ border-top: 1px solid var(--hairline); border-bottom: 1px solid var(--hairline);
+ }
+
+ .datum {
+ height: 136px; padding: 18px 20px 18px 0;
+ }
+
+ .datum + .datum {
+ padding-left: 26px; border-left: 1px solid var(--hairline);
+ }
+
+ .datum-label {
+ display: block; margin-bottom: 10px; color: var(--muted);
+ font-size: 12px; font-weight: 500; letter-spacing: 0.025em;
+ }
+
+ .datum:nth-child(2) .datum-value {
+ height: 82px; font-size: 18px; font-weight: 550; overflow-wrap: anywhere;
+ }
+ .merge-date { display: block; margin-top: 10px; color: var(--muted); font-size: 12px; font-weight: 450; }
+ .datum-value {
+ display: block; font-size: 18px; font-weight: 650;
+ line-height: 1.35; letter-spacing: -0.02em;
+ }
+
+ .verified {
+ display: block; color: var(--ink); font-size: 16px;
+ }
+
+
+ .record {
+ position: absolute; left: 82px; right: 62px; bottom: 28px;
+ display: flex; justify-content: space-between; color: var(--muted);
+ font-size: 11px; font-weight: 450; letter-spacing: 0.02em;
+ }
+ </style>
+</head>
+<body>
+ <!--
+ THESIS: One precise correction becomes the keepsake; refuse the metric-heavy achievement poster.
+ OWN-WORLD: Mineral paper, ink geometry, verified cyan, and one warm calibration point.
+ STORY: Recognize the contributor, see where the map changed, then verify the merged record.
+ FIRST VIEWPORT: Identity above a full-width tactile map; the contribution statement and proof sit below it.
+ FORM: User-pinned Pro field-map direction, narrow artifact extension, seed pro-field-map-v1.
+ Data comes from a merged pull request. Merged status is not a separate verification claim.
+ -->
+ <main class="card" aria-label="Archify contributor field note for {{AUTHOR}}">
+ <img class="art" src="./assets/map.png" alt="Folded engineering map with a verified cyan route and a gold correction point">
+ <div class="paper-wash" aria-hidden="true"></div>
+ <div class="rail" aria-hidden="true"></div>
+
+ <header>
+ <div class="brand">
+ <svg class="brand-mark" viewBox="0 0 48 48" aria-hidden="true">
+ <path d="M24 3.8 42 14.1v19.8L24 44.2 6 33.9V14.1L24 3.8Z" fill="none" stroke="currentColor" stroke-width="2.6"/>
+ <path d="m6.8 14.6 17.2 10 17.2-10M24 24.6v18.3" fill="none" stroke="currentColor" stroke-width="2.6"/>
+ <path d="m14.2 29.3 9.8 5.6 9.8-5.6" fill="none" stroke="currentColor" stroke-width="2.6"/>
+ </svg>
+ <span>Archify</span>
+ </div>
+ <div class="series"><span>Contributor field note</span><span>PR {{NUMBER}}</span></div>
+ </header>
+
+ <section class="identity" aria-label="Contributor identity">
+ <p class="handle" data-fit-min="30">@{{AUTHOR}}</p>
+ <div class="role">System cartographer</div>
+ </section>
+
+ <section class="moment" aria-label="Contribution message">
+ <h1>The map<br>changed here.</h1>
+ <p>You made the system easier to see.<br>This revision is now part of Archify.</p>
+ </section>
+
+ <div class="locator" aria-hidden="true">
+ <i></i><b></b><span></span>
+ </div>
+
+ <footer aria-label="Merged contribution record">
+ <div class="datum">
+ <span class="datum-label">Contribution</span>
+ <span class="datum-value">PR #{{NUMBER}}</span>
+ </div>
+ <div class="datum">
+ <span class="datum-label">Change</span>
+ <span class="datum-value" data-fit-min="14" data-ellipsis="true" title="{{TITLE}}">{{TITLE}}</span>
+ </div>
+ <div class="datum">
+ <span class="datum-label">Status</span>
+ <span class="datum-value verified">Merged<span class="merge-date">{{DATE}} UTC</span></span>
+ </div>
+ </footer>
+
+ <div class="record"><span>github.com/{{REPOSITORY}}</span><span>{{SHORT_SHA}}</span></div>
+ </main>
+</body>
+</html>
diff --git a/tools/contributor-cards/test/card.test.mjs b/tools/contributor-cards/test/card.test.mjs
new file mode 100644
index 00000000..50c03536
--- /dev/null
+++ b/tools/contributor-cards/test/card.test.mjs
@@ -0,0 +1,54 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { recordFromPull, cardHtml, renderCard, prNumber, validRepository } from '../card.mjs';
+export const pull = {
+ number: 394, title: 'chore(review): reduce repeated CodeRabbit evidence requests',
+ merged: true, merged_at: '2026-09-12T02:23:34Z', merge_commit_sha: '6db72a9aea3d0f67a6a034e41f8a5491476a11c1',
+ user: { login: 'tt-a1i', type: 'User' }, base: { repo: { full_name: 'tt-a1i/archify' } },
+};
+
+test('only authentic merged records are accepted; metadata is not inferred from example text', () => {
+ assert.equal(recordFromPull(pull, 'tt-a1i/archify').author, 'tt-a1i');
+ for (const patch of [{merged:false},{merged_at:null},{merge_commit_sha:'bad'},{user:{login:'bot[bot]',type:'Bot'}},{user:{login:'../bad',type:'User'}},{title:''},{base:{repo:{full_name:'someone/else'}}}]) {
+ assert.throws(() => recordFromPull({...pull,...patch}, 'tt-a1i/archify'));
+ }
+ for (const value of ['0','-1','1; echo bad','1/2','01','1\n']) assert.throws(()=>prNumber(value));
+ for (const value of ['../repo','https://github.com/x/y','x/y/z']) assert.throws(()=>validRepository(value));
+});
+
+test('untrusted PR text is escaped, assets are embedded, and no false verified status is emitted', async () => {
+ const record = recordFromPull({...pull,title:'修复 · <img src=x onerror="alert(1)"> {{AUTHOR}}'}, 'tt-a1i/archify');
+ const html = await cardHtml(record);
+ assert.ok(html.includes('&lt;img src=x onerror=&quot;alert(1)&quot;&gt; {{AUTHOR}}'));
+ assert.ok(!html.includes('<img src=x'));
+ assert.ok(!html.includes('·'));
+ assert.ok(!html.includes('Merged and verified'));
+ assert.ok(!html.includes('Sample record'));
+ assert.ok(!html.includes('./assets/'));
+ assert.ok(html.includes('Content-Security-Policy'));
+ assert.ok(html.includes('2026-09-12 UTC'));
+});
+
+test('real browser fits long GitHub usernames, long unbroken titles and Chinese descriptions', {timeout:90000}, async () => {
+ const output = await fs.mkdtemp(path.join(os.tmpdir(),'archify-card-test-'));
+ try {
+ for (const [number, login, title] of [
+ [394,'tt-a1i',pull.title],
+ [395,'a'.repeat(39),'W'.repeat(256)],
+ [396,'contributor','修复复杂架构图中的边界重叠问题,并改善中文说明和长标题在贡献卡上的排版效果。'.repeat(3)],
+ [397,'contributor','<script>document.body.remove()</script> & safe text'],
+ ]) {
+ const record=recordFromPull({...pull,number,title,user:{type:'User',login}},'tt-a1i/archify');
+ const result=await renderCard(record,output);
+ assert.deepEqual(result.receipt.clipped,[]);
+ assert.ok(result.receipt.text.includes('@'+login));
+ assert.ok(result.receipt.text.includes('Merged'));
+ const png=await fs.readFile(result.stem+'.png');
+ assert.equal(png.readUInt32BE(16),1000);
+ assert.equal(png.readUInt32BE(20),1500);
+ }
+ } finally { await fs.rm(output,{recursive:true,force:true}); }
+});
diff --git a/tools/contributor-cards/test/github.test.mjs b/tools/contributor-cards/test/github.test.mjs
new file mode 100644
index 00000000..50284df1
--- /dev/null
+++ b/tools/contributor-cards/test/github.test.mjs
@@ -0,0 +1,80 @@
+import {test} from 'node:test';
+import assert from 'node:assert/strict';
+import {createHash} from 'node:crypto';
+import {publishCard, commentBody} from '../github.mjs';
+const record={repository:'tt-a1i/archify',number:394,author:'tt-a1i',title:'A contribution',mergedAt:'2026-09-12T02:23:34Z',mergeCommit:'a'.repeat(40),url:'https://github.com/tt-a1i/archify/pull/394',templateVersion:1};
+const png=Buffer.alloc(24);Buffer.from([137,80,78,71,13,10,26,10]).copy(png);png.writeUInt32BE(1000,16);png.writeUInt32BE(1500,20);
+function mock({failComment=false,conflict=false}={}) {
+ const state={ref:null,tree:[],blobs:new Map(),comments:[],updates:0,posts:0,refWrites:0,commits:0};
+ const api=async(route,{method='GET',body}={})=>{
+ const short=route.replace('/repos/tt-a1i/archify','');
+ if(short==='/git/ref/heads/contributor-cards') return state.ref?{object:{sha:state.ref}}:null;
+ if(short.startsWith('/git/commits/') && method==='GET') return {tree:{sha:'tree'}};
+ if(short.startsWith('/git/trees/') && method==='GET') return {tree:state.tree};
+ if(short==='/git/blobs') {const b=Buffer.from(body.content,'base64');const sha=createHash('sha1').update(`blob ${b.length}\0`).update(b).digest('hex');state.blobs.set(sha,b);return {sha};}
+ if(short==='/git/trees') {state.nextTree=body.tree;return {sha:'nextTree'};}
+ if(short==='/git/commits') {state.commits++;return {sha:String(state.commits).padStart(40,'a')};}
+ if(short==='/git/refs'||short==='/git/refs/heads/contributor-cards') {
+ if(conflict){conflict=false;state.ref='other';state.tree=[{path:'cards/pr-1.png',sha:'other'}];throw new Error('GitHub PATCH ref failed (422)');}
+ assert.notEqual(body.force,true);state.refWrites++;state.ref=body.sha;
+ state.tree=[...state.tree.filter(e=>!state.nextTree.some(n=>n.path===e.path)),...state.nextTree];return {object:{sha:state.ref}};
+ }
+ if(short.startsWith('/commits?')) return [{sha:state.ref}];
+ if(short.startsWith('/issues/394/comments?')) return state.comments;
+ if(short==='/issues/394/comments') {
+ if(failComment){failComment=false;throw new Error('temporary comment failure');}
+ state.posts++;const comment={id:state.posts,user:{login:'github-actions[bot]'},body:body.body,html_url:'https://github.com/tt-a1i/archify/pull/394#issuecomment-1'};state.comments.push(comment);return comment;
+ }
+ if(short.startsWith('/issues/comments/')) {state.updates++;Object.assign(state.comments.find(c=>c.id===Number(short.split('/').at(-1))),body);return state.comments.find(c=>c.id===Number(short.split('/').at(-1)));}
+ throw new Error('Unexpected API '+method+' '+short);
+ };
+ return {api,state};
+}
+const options={verifyImage:async()=>{}};
+test('reruns do not duplicate comments or commit identical content',async()=>{
+ const {api,state}=mock();
+ await publishCard(api,record,png,options);
+ await publishCard(api,record,png,options);
+ assert.equal(state.posts,1);assert.equal(state.updates,0);assert.equal(state.refWrites,1);
+});
+test('retry after a comment failure reuses the existing image',async()=>{
+ const {api,state}=mock({failComment:true});
+ await assert.rejects(publishCard(api,record,png,options),/temporary comment/);
+ await publishCard(api,record,png,options);
+ assert.equal(state.posts,1);assert.equal(state.refWrites,1);
+});
+test('concurrent branch updates preserve another PR card and never force-push',async()=>{
+ const {api,state}=mock({conflict:true});
+ await publishCard(api,record,png,options);
+ assert.ok(state.tree.some(e=>e.path==='cards/pr-1.png'));
+ assert.equal(state.posts,1);
+});
+test('a user spoofing the marker cannot become the bot-owned reply',async()=>{
+ const {api,state}=mock();
+ state.comments.push({id:99,user:{login:'attacker'},body:commentBody(record,'fake')});
+ await publishCard(api,record,png,options);
+ assert.equal(state.updates,0);assert.equal(state.posts,1);assert.equal(state.comments[0].id,99);
+});
+test('unavailable public image prevents sending the reply',async()=>{
+ const {api,state}=mock();
+ await assert.rejects(publishCard(api,record,png,{verifyImage:async()=>{throw new Error('not available');}}));
+ assert.equal(state.posts,0);
+});
+test('updated image updates the existing bot reply',async()=>{
+ const {api,state}=mock();
+ await publishCard(api,record,png,options);
+ const changed=Buffer.concat([png,Buffer.from('new render')]);
+ await publishCard(api,record,changed,options);
+ assert.equal(state.posts,1);assert.equal(state.updates,1);
+});
+test('finds the existing bot reply beyond the first comment page',async()=>{
+ const {api,state}=mock();
+ await publishCard(api,record,png,options);
+ const wrapped=async(route,args)=>{
+ if(route.includes('/comments?') && route.endsWith('page=1')) return Array.from({length:100},(_,id)=>({id,user:{login:'someone'},body:'Discussion'}));
+ if(route.includes('/comments?') && route.endsWith('page=2')) return state.comments;
+ return api(route,args);
+ };
+ await publishCard(wrapped,record,png,options);
+ assert.equal(state.posts,1);assert.equal(state.updates,0);
+});
diff --git a/tools/contributor-cards/test/workflow.test.mjs b/tools/contributor-cards/test/workflow.test.mjs
new file mode 100644
index 00000000..d57ed45a
--- /dev/null
+++ b/tools/contributor-cards/test/workflow.test.mjs
@@ -0,0 +1,15 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+const workflow = await fs.readFile(new URL('../../../.github/workflows/contributor-cards.yml', import.meta.url), 'utf8');
+// Security contract checks guard future edits to the privileged event path.
+test('privileged automation reads the default branch and does not interpolate PR text into shell', () => {
+ assert.match(workflow, /pull_request_target:\s+types: \[closed\]/);
+ assert.match(workflow, /github\.event\.pull_request\.merged == true/);
+ assert.match(workflow, /ref: \$\{\{ github\.event\.repository\.default_branch \}\}/);
+ assert.doesNotMatch(workflow, /pull_request\.head|refs\/pull|pull_request\.merge_commit_sha/);
+ assert.doesNotMatch(workflow, /\$\{\{[^}]*\.(title|body|login)[^}]*\}\}/);
+ assert.match(workflow, /persist-credentials: false/);
+ assert.match(workflow, /group: contributor-card-\$\{\{ github\.event\.pull_request\.number \|\| inputs\.pr \}\}/);
+ assert.match(workflow, /cancel-in-progress: false/);
+});