diff --git a/.github/workflows/weekly-social.yml b/.github/workflows/weekly-social.yml index c41ed178..2b1edb6c 100644 --- a/.github/workflows/weekly-social.yml +++ b/.github/workflows/weekly-social.yml @@ -49,6 +49,7 @@ jobs: # Persist before sending. An uncertain send keeps its claim and cannot # be retried automatically, including after a cancelled runner. - name: Claim destination and week + id: claim if: steps.prepare.outputs.eligible == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: @@ -60,6 +61,7 @@ jobs: if: steps.prepare.outputs.eligible == 'true' run: pnpm exec tsx scripts/weekly-social.ts publish ${{ matrix.destination }} env: + SKILLD_WEEKLY_CLAIM_ARTIFACT_ID: ${{ steps.claim.outputs.artifact-id }} GH_TOKEN: ${{ github.token }} SKILLD_WEEKLY_X_API_KEY: ${{ matrix.destination == 'x' && secrets.SKILLD_WEEKLY_X_API_KEY || '' }} SKILLD_WEEKLY_X_API_SECRET: ${{ matrix.destination == 'x' && secrets.SKILLD_WEEKLY_X_API_SECRET || '' }} diff --git a/scripts/lib/weekly-social.ts b/scripts/lib/weekly-social.ts index 0cbc92ec..622582da 100644 --- a/scripts/lib/weekly-social.ts +++ b/scripts/lib/weekly-social.ts @@ -28,12 +28,14 @@ const detailSchema = z.object({ export const socialSkillSchema = feedRow.extend({ evidence: evidenceSchema, sourceUrl: detailSchema.shape.sourceUrl, runCommand: detailSchema.shape.runCommand }) export type SocialSkill = z.infer -export function assertWeeklyClaim(value: unknown, runId: string): void { - const claims = z.object({ - total_count: z.number().int().nonnegative(), - artifacts: z.array(z.object({ workflow_run: z.object({ id: z.number().int() }) })), +export function assertWeeklyClaim(value: unknown, expected: { artifactId: string, name: string, runId: string }): void { + const claim = z.object({ + id: z.number().int().positive(), + name: z.string(), + expired: z.boolean(), + workflow_run: z.object({ id: z.number().int() }), }).parse(value) - if (claims.total_count !== 1 || claims.artifacts.length !== 1 || String(claims.artifacts[0]?.workflow_run.id) !== runId) + if (String(claim.id) !== expected.artifactId || claim.name !== expected.name || claim.expired || String(claim.workflow_run.id) !== expected.runId) throw new Error('This run does not own the weekly claim') } diff --git a/scripts/weekly-social.ts b/scripts/weekly-social.ts index 75dd6304..04ff0592 100644 --- a/scripts/weekly-social.ts +++ b/scripts/weekly-social.ts @@ -4,10 +4,11 @@ import { z } from 'zod' import { assertWeeklyClaim, buildWeeklySocial, loadWeeklySocial, parseSocialDestination, publishWeeklySocial, socialSkillSchema, verifySocialDestination, weekOf } from './lib/weekly-social' /** GitHub's artifact service persists the claim before any public send. */ -async function weeklyClaims(name: string): Promise { +async function weeklyClaims(query: { name: string } | { artifactId: string }): Promise { const repository = z.string().regex(/^[\w.-]+\/[\w.-]+$/).parse(process.env.GITHUB_REPOSITORY) const token = z.string().min(1).parse(process.env.GH_TOKEN) - const response = await fetch(`https://api.github.com/repos/${repository}/actions/artifacts?name=${encodeURIComponent(name)}&per_page=100`, { + const path = 'artifactId' in query ? `/${query.artifactId}` : `?name=${encodeURIComponent(query.name)}&per_page=100` + const response = await fetch(`https://api.github.com/repos/${repository}/actions/artifacts${path}`, { headers: { 'authorization': `Bearer ${token}`, 'accept': 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }, redirect: 'error', signal: AbortSignal.timeout(30_000), @@ -37,7 +38,14 @@ async function run() { const saved = z.object({ week: z.string(), computedAt: z.number(), skills: z.array(socialSkillSchema) }).parse(JSON.parse(await readFile(path, 'utf8'))) if (saved.week !== weekOf(now) || now.getTime() / 1000 - saved.computedAt > 3600) throw new Error('Prepare a fresh weekly post before publishing') - assertWeeklyClaim(await weeklyClaims(`skilld-weekly-${destinationName}-${saved.week}`), z.string().regex(/^\d+$/).parse(process.env.GITHUB_RUN_ID)) + // The prepare lookup can remain cached for 60 seconds after upload. + // Read the uploaded artifact directly instead of repeating that list request. + const artifactId = z.string().regex(/^\d+$/).parse(process.env.SKILLD_WEEKLY_CLAIM_ARTIFACT_ID) + assertWeeklyClaim(await weeklyClaims({ artifactId }), { + artifactId, + name: `skilld-weekly-${destinationName}-${saved.week}`, + runId: z.string().regex(/^\d+$/).parse(process.env.GITHUB_RUN_ID), + }) const result = await publishWeeklySocial(parseSocialDestination(destinationName, process.env), buildWeeklySocial(saved.skills, now)) console.log(JSON.stringify(result)) await writeFile(join(directory, 'receipt.json'), `${JSON.stringify(result, null, 2)}\n`) @@ -56,7 +64,7 @@ async function run() { await appendFile(process.env.GITHUB_STEP_SUMMARY, `### ${destinationName}: ${post.week}\n\n\`\`\`json\n${preview}\n\`\`\`\n`) let eligible = post._tag === 'ready' && publishing - if (eligible && z.object({ total_count: z.number().int().nonnegative() }).parse(await weeklyClaims(claim)).total_count > 0) { + if (eligible && z.object({ total_count: z.number().int().nonnegative() }).parse(await weeklyClaims({ name: claim })).total_count > 0) { eligible = false console.log('This destination already has a weekly delivery claim. Inspect its previous run before retrying.') } diff --git a/test/unit/weekly-social.test.ts b/test/unit/weekly-social.test.ts index d8e8fe18..a45a03f9 100644 --- a/test/unit/weekly-social.test.ts +++ b/test/unit/weekly-social.test.ts @@ -101,6 +101,8 @@ describe('weekly social posts', () => { describe('posting identity', () => { const credentials = { consumerKey: 'key', consumerSecret: 'secret', accessToken: 'token', accessSecret: 'token-secret' } + const claim = { id: 14861832971, name: 'skilld-weekly-discord-2026-11-23', expired: false, workflow_run: { id: 45264333491 } } + const expectedClaim = { artifactId: String(claim.id), name: claim.name, runId: String(claim.workflow_run.id) } it('signs the RFC 5849 reference request', () => { const header = oauthHeader('GET', 'http://photos.example.net/photos?file=vacation.jpg&size=original', { consumerKey: 'dpf43f3p2l4k3l03', @@ -122,10 +124,11 @@ describe('posting identity', () => { await expect(verifySocialDestination({ _tag: 'discord', webhookUrl: 'https://discord.com/api/webhooks/1/token', channelId: '2' }, fetchImpl)).rejects.toThrow('Discord webhook belongs to another server or channel') }) - it('publishes to the checked Discord channel and returns its confirmed message ID', async () => { + it('publishes with the uploaded claim and returns the checked Discord channel message ID', async () => { const fetchImpl = vi.fn() .mockResolvedValueOnce(Response.json({ guild_id: '931135234261532713', channel_id: '2' })) .mockResolvedValueOnce(Response.json({ id: '123' })) + assertWeeklyClaim(claim, expectedClaim) const result = await publishWeeklySocial({ _tag: 'discord', webhookUrl: 'https://discord.com/api/webhooks/1/token', channelId: '2' }, buildWeeklySocial([skill], now), fetchImpl) expect(result).toEqual({ _tag: 'sent', id: '123' }) expect(fetchImpl.mock.calls[1]?.[0]).toBe('https://discord.com/api/webhooks/1/token?wait=true') @@ -140,9 +143,12 @@ describe('posting identity', () => { expect(fetchImpl).toHaveBeenCalledTimes(2) }) - it('requires a persisted claim owned by this run before sending', () => { - expect(() => assertWeeklyClaim({ total_count: 0, artifacts: [] }, '42')).toThrow('This run does not own the weekly claim') - expect(() => assertWeeklyClaim({ total_count: 1, artifacts: [{ workflow_run: { id: 41 } }] }, '42')).toThrow('This run does not own the weekly claim') - assertWeeklyClaim({ total_count: 1, artifacts: [{ workflow_run: { id: 42 } }] }, '42') + it.each([ + { ...claim, id: 14861832972 }, + { ...claim, name: 'skilld-weekly-x-2026-11-23' }, + { ...claim, expired: true }, + { ...claim, workflow_run: { id: 45264333490 } }, + ])('rejects a claim that does not match the upload, week, destination, or run: %j', (artifact) => { + expect(() => assertWeeklyClaim(artifact, expectedClaim)).toThrow('This run does not own the weekly claim') }) })