From 4abc5e119836707374918391d10ff00bed8b24e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 1 Oct 2026 04:35:24 +0000 Subject: [PATCH 1/7] feat: label-consolidation - Add rate-limited label write queue Add scripts/automation/includes/label-write-queue.js for spec 008 task T062a (FR-023 point 6; research R21). Every label write in Stages 3 to 5 goes through one queue: one write at a time, at least one second apart, a pause and retry on rate limits, and a RunPausedError when a write stays limited so the run can stop and resume. githubWrite wraps the existing githubApiRequest. Thirteen unit tests use a fake clock. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011cim45iF9naViRzx5vUysK --- .../__tests__/label-write-queue.test.js | 201 ++++++++++++++++++ .../automation/includes/label-write-queue.js | 195 +++++++++++++++++ 2 files changed, 396 insertions(+) create mode 100644 scripts/automation/__tests__/label-write-queue.test.js create mode 100644 scripts/automation/includes/label-write-queue.js diff --git a/scripts/automation/__tests__/label-write-queue.test.js b/scripts/automation/__tests__/label-write-queue.test.js new file mode 100644 index 0000000000..34138b57fc --- /dev/null +++ b/scripts/automation/__tests__/label-write-queue.test.js @@ -0,0 +1,201 @@ +/** + * Tests for the label consolidation write queue (spec 008, T062a; FR-023 point 6). + */ + +import { + createWriteQueue, + githubWrite, + rateLimitDelayMs, + RateLimitError, + RunPausedError, +} from '../includes/label-write-queue.js'; + +/** + * Builds a fake clock whose sleep advances time instantly. + * @returns {{ now: () => number, sleep: (ms: number) => Promise, sleeps: number[] }} + */ +function fakeClock() { + let time = 0; + const sleeps = []; + return { + now: () => time, + sleep: async (ms) => { + sleeps.push(ms); + time += ms; + }, + sleeps, + }; +} + +/** + * Builds a headers object like fetch's Headers. + * @param {Record} values - Header values by lower-case name + * @returns {{ get: (name: string) => string | null }} + */ +function headers(values) { + return { get: (name) => (name in values ? values[name] : null) }; +} + +describe('label-write-queue', () => { + describe('createWriteQueue', () => { + test('runs writes one at a time, in order', async () => { + const clock = fakeClock(); + const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep }); + const events = []; + const write = (name) => async () => { + events.push(`start ${name}`); + await clock.sleep(10); + events.push(`end ${name}`); + return name; + }; + + const results = await Promise.all([ + queue.run(write('a')), + queue.run(write('b')), + queue.run(write('c')), + ]); + + expect(results).toEqual(['a', 'b', 'c']); + expect(events).toEqual(['start a', 'end a', 'start b', 'end b', 'start c', 'end c']); + }); + + test('starts writes at least one second apart', async () => { + const clock = fakeClock(); + const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep }); + const starts = []; + const write = () => async () => { + starts.push(clock.now()); + }; + + await Promise.all([queue.run(write()), queue.run(write()), queue.run(write())]); + + expect(starts).toEqual([0, 1000, 2000]); + }); + + test('pauses for the rate-limit delay, then retries the same write', async () => { + const clock = fakeClock(); + const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep }); + let calls = 0; + + const result = await queue.run(async () => { + calls++; + if (calls === 1) { + throw new RateLimitError('secondary rate limit', 30000); + } + return 'done'; + }); + + expect(result).toBe('done'); + expect(calls).toBe(2); + expect(clock.sleeps).toContain(30000); + expect(queue.stats()).toEqual({ writes: 1, pauses: 1 }); + }); + + test('stops the run with RunPausedError when a write stays rate-limited', async () => { + const clock = fakeClock(); + const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep, maxPauses: 2 }); + let calls = 0; + + await expect( + queue.run(async () => { + calls++; + throw new RateLimitError('rate limit', 5000); + }) + ).rejects.toBeInstanceOf(RunPausedError); + expect(calls).toBe(3); + }); + + test('does not retry other errors, and keeps running later writes', async () => { + const clock = fakeClock(); + const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep }); + let calls = 0; + + const failed = queue.run(async () => { + calls++; + throw new Error('422 Validation Failed'); + }); + const next = queue.run(async () => 'next'); + + await expect(failed).rejects.toThrow('422 Validation Failed'); + await expect(next).resolves.toBe('next'); + expect(calls).toBe(1); + }); + }); + + describe('rateLimitDelayMs', () => { + test('uses Retry-After seconds first', () => { + expect( + rateLimitDelayMs(headers({ 'retry-after': '12', 'x-ratelimit-reset': '999' }), 0) + ).toBe(12000); + }); + + test('falls back to x-ratelimit-reset as a Unix time', () => { + expect(rateLimitDelayMs(headers({ 'x-ratelimit-reset': '100' }), 40000)).toBe(60000); + }); + + test('never returns a negative delay', () => { + expect(rateLimitDelayMs(headers({ 'x-ratelimit-reset': '10' }), 50000)).toBe(0); + }); + + test('returns null without rate-limit headers', () => { + expect(rateLimitDelayMs(headers({}), 0)).toBeNull(); + }); + }); + + describe('githubWrite', () => { + test('refuses read requests', () => { + const queue = createWriteQueue(); + expect(() => githubWrite(queue, 'GET', '/repos/o/r/labels')).toThrow( + 'mutating requests only' + ); + }); + + test('sends the write uncached through the queue', async () => { + const clock = fakeClock(); + const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep }); + const request = jest.fn().mockResolvedValue({ name: 'aiops:agents' }); + + const result = await githubWrite( + queue, + 'PATCH', + '/repos/o/r/labels/ai-ops:agents', + { new_name: 'aiops:agents' }, + { token: 'test' }, + request + ); + + expect(result).toEqual({ name: 'aiops:agents' }); + expect(request).toHaveBeenCalledWith( + 'PATCH', + '/repos/o/r/labels/ai-ops:agents', + { new_name: 'aiops:agents' }, + { token: 'test', useCache: false } + ); + }); + + test('turns a GitHub rate-limit error into a pause and retry', async () => { + const clock = fakeClock(); + const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep }); + const request = jest + .fn() + .mockRejectedValueOnce(new Error('GitHub API error: 403 API rate limit exceeded')) + .mockResolvedValueOnce(null); + + await expect( + githubWrite(queue, 'DELETE', '/repos/o/r/labels/old', null, { token: 'test' }, request) + ).resolves.toBeNull(); + expect(request).toHaveBeenCalledTimes(2); + expect(queue.stats().pauses).toBe(1); + }); + + test('passes other GitHub errors straight through', async () => { + const queue = createWriteQueue({ sleep: async () => {} }); + const request = jest.fn().mockRejectedValue(new Error('GitHub API error: 404 Not Found')); + + await expect( + githubWrite(queue, 'DELETE', '/repos/o/r/labels/missing', null, { token: 'test' }, request) + ).rejects.toThrow('404 Not Found'); + expect(request).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/scripts/automation/includes/label-write-queue.js b/scripts/automation/includes/label-write-queue.js new file mode 100644 index 0000000000..2283f0687e --- /dev/null +++ b/scripts/automation/includes/label-write-queue.js @@ -0,0 +1,195 @@ +/** + * Serialised, rate-limited queue for the label consolidation writes + * (spec 008, FR-023 point 6; research R21). + * + * Every mutating GitHub or Linear call in Stages 3 to 5 goes through one + * queue so that: + * - writes run one at a time, at least `minIntervalMs` apart; + * - a rate-limited write pauses until the limit resets, then is retried; + * - a write that stays rate-limited stops the run with a `RunPausedError`, + * so the caller can record progress and resume later (FR-023 point 1). + * + * GitHub writes can use `githubWrite`, which wraps `githubApiRequest` from + * `github-api-optimized.js`. Linear writes pass their own function to `run` + * and throw a `RateLimitError` when Linear reports a rate or complexity limit. + */ + +import { githubApiRequest } from './github-api-optimized.js'; + +const DEFAULT_MIN_INTERVAL_MS = 1000; +const DEFAULT_MAX_PAUSES = 3; +const DEFAULT_PAUSE_MS = 60000; + +/** + * A write was refused because of a rate or complexity limit. + */ +export class RateLimitError extends Error { + /** + * @param {string} message - What was limited + * @param {number} [retryAfterMs] - How long to wait before retrying + */ + constructor(message, retryAfterMs = DEFAULT_PAUSE_MS) { + super(message); + this.name = 'RateLimitError'; + this.retryAfterMs = retryAfterMs; + } +} + +/** + * The run stopped because a write stayed rate-limited after every pause. + * The caller records the step reached and resumes the run later. + */ +export class RunPausedError extends Error { + /** + * @param {string} message - Why the run paused + * @param {Error} cause - The last rate-limit error + */ + constructor(message, cause) { + super(message); + this.name = 'RunPausedError'; + this.cause = cause; + } +} + +/** + * Works out how long to wait from GitHub rate-limit headers. + * `Retry-After` is in seconds; `x-ratelimit-reset` is a Unix time in seconds. + * @param {{ get: (name: string) => string | null }} headers - Response headers + * @param {number} [nowMs] - Current time in milliseconds + * @returns {number | null} Milliseconds to wait, or null when no header applies + */ +export function rateLimitDelayMs(headers, nowMs = Date.now()) { + const retryAfter = headers.get('retry-after'); + if (retryAfter !== null && retryAfter !== '') { + const seconds = Number(retryAfter); + if (Number.isFinite(seconds)) { + return Math.max(seconds * 1000, 0); + } + } + const reset = headers.get('x-ratelimit-reset'); + if (reset !== null && reset !== '') { + const resetSeconds = Number(reset); + if (Number.isFinite(resetSeconds)) { + return Math.max(resetSeconds * 1000 - nowMs, 0); + } + } + return null; +} + +/** + * Default sleep used between writes and during pauses. + * @param {number} ms - Milliseconds to wait + * @returns {Promise} + */ +function defaultSleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * Creates a write queue. + * @param {object} [options] + * @param {number} [options.minIntervalMs=1000] - Minimum gap between writes + * @param {number} [options.maxPauses=3] - Rate-limit pauses allowed per write + * @param {() => number} [options.now] - Clock, for tests + * @param {(ms: number) => Promise} [options.sleep] - Sleep, for tests + * @returns {{ run: (write: () => Promise) => Promise, stats: () => object }} + */ +export function createWriteQueue(options = {}) { + const { + minIntervalMs = DEFAULT_MIN_INTERVAL_MS, + maxPauses = DEFAULT_MAX_PAUSES, + now = Date.now, + sleep = defaultSleep, + } = options; + + let tail = Promise.resolve(); + let lastStartedAt = null; + let writes = 0; + let pauses = 0; + + /** + * Runs one write, waiting for the gap and pausing on rate limits. + * @param {() => Promise} write - The mutating call + * @returns {Promise} The write's result + */ + async function execute(write) { + for (let attempt = 0; ; attempt++) { + if (lastStartedAt !== null) { + const wait = lastStartedAt + minIntervalMs - now(); + if (wait > 0) { + await sleep(wait); + } + } + lastStartedAt = now(); + try { + const result = await write(); + writes++; + return result; + } catch (error) { + if (!(error instanceof RateLimitError)) { + throw error; + } + if (attempt >= maxPauses) { + throw new RunPausedError( + `Write still rate-limited after ${maxPauses} pauses; stop and resume later`, + error + ); + } + pauses++; + await sleep(Math.max(error.retryAfterMs, minIntervalMs)); + } + } + } + + return { + run(write) { + const result = tail.then(() => execute(write)); + // Keep the chain going after a failure; the caller still sees the error. + tail = result.catch(() => {}); + return result; + }, + stats() { + return { writes, pauses }; + }, + }; +} + +/** + * Sends a GitHub write through the queue. A rate-limit failure from + * `githubApiRequest` (after its own retries) becomes a `RateLimitError`, so + * the queue pauses the run instead of failing it. + * @param {ReturnType} queue - The shared queue + * @param {string} method - POST, PATCH, PUT or DELETE + * @param {string} path - API path, for example `/repos/o/r/labels` + * @param {object | null} [body] - Request body + * @param {object} [options] - Passed to `githubApiRequest` + * @param {Function} [request] - Request function, for tests + * @returns {Promise} The API response + */ +export function githubWrite( + queue, + method, + path, + body = null, + options = {}, + request = githubApiRequest +) { + if (method === 'GET' || method === 'HEAD') { + throw new Error('githubWrite is for mutating requests only'); + } + return queue.run(async () => { + try { + return await request(method, path, body, { ...options, useCache: false }); + } catch (error) { + if ( + /GitHub API error: (403|429)\b/.test(error.message) && + /rate limit/i.test(error.message) + ) { + throw new RateLimitError(error.message); + } + throw error; + } + }); +} + +export default { createWriteQueue, githubWrite, rateLimitDelayMs, RateLimitError, RunPausedError }; From 60a4bf7d488bf626c17db85e10642e2cfacaa02e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 1 Oct 2026 04:35:58 +0000 Subject: [PATCH 2/7] docs: label-consolidation - Add changelog entry for the write queue Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011cim45iF9naViRzx5vUysK --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96fb6b7cdd..8a449d6828 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Label Write Queue** — Label consolidation writes now go through one queue that spaces them one second apart and pauses on GitHub or Linear rate limits, so a long run can stop and resume safely. (#3704) - **Footer Shape Signal** — `npm run validate:footers:shape` reports files holding two or more footer-shaped blocks the wording-based deduper cannot see. Advisory only: never edits a file, never fails a build. (#3682) - **CI and Changelog Agent Specs** — Added the CI failure remediation spec (017) and changelog agent quality spec (016), and updated the agent consolidation spec (014) tasks. (#3500) - **Code Graphs for OpenCode** — OpenCode can use locally built graft and graphify code graphs to locate code before searching files. The graphs are not committed. (#3569) From da27d0f51a0f960fb0bbb733a74b5e27c25ff98e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 1 Oct 2026 13:32:58 +0000 Subject: [PATCH 3/7] fix: label-consolidation - Honour Retry-After on the final rate-limited write githubApiRequest threw its final error without the response headers, so githubWrite always paused for the 60-second default even when GitHub asked for longer (FR-023 point 6). Keep the headers on the error and use rateLimitDelayMs for the pause, falling back to the default when no header applies. Adds a test for a 120-second Retry-After. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011cim45iF9naViRzx5vUysK --- .../automation/__tests__/label-write-queue.test.js | 12 ++++++++++++ scripts/automation/includes/github-api-optimized.js | 5 ++++- scripts/automation/includes/label-write-queue.js | 3 ++- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/scripts/automation/__tests__/label-write-queue.test.js b/scripts/automation/__tests__/label-write-queue.test.js index 34138b57fc..d5c6cb9a1e 100644 --- a/scripts/automation/__tests__/label-write-queue.test.js +++ b/scripts/automation/__tests__/label-write-queue.test.js @@ -188,6 +188,18 @@ describe('label-write-queue', () => { expect(queue.stats().pauses).toBe(1); }); + test('pauses for the delay in the final rate-limit response headers', async () => { + const clock = fakeClock(); + const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep }); + const limited = new Error('GitHub API error: 429 You have exceeded a secondary rate limit'); + limited.headers = headers({ 'retry-after': '120' }); + const request = jest.fn().mockRejectedValueOnce(limited).mockResolvedValueOnce(null); + + await githubWrite(queue, 'DELETE', '/repos/o/r/labels/old', null, { token: 'test' }, request); + + expect(clock.sleeps).toContain(120000); + }); + test('passes other GitHub errors straight through', async () => { const queue = createWriteQueue({ sleep: async () => {} }); const request = jest.fn().mockRejectedValue(new Error('GitHub API error: 404 Not Found')); diff --git a/scripts/automation/includes/github-api-optimized.js b/scripts/automation/includes/github-api-optimized.js index 20afba3f1a..9826160693 100644 --- a/scripts/automation/includes/github-api-optimized.js +++ b/scripts/automation/includes/github-api-optimized.js @@ -170,7 +170,10 @@ export async function githubApiRequest( ); continue; } - throw new Error(errorMessage); + const error = new Error(errorMessage); + // Keep the headers so callers can honour Retry-After on the final failure. + error.headers = response.headers; + throw error; } // Handle 204 No Content (no response body) diff --git a/scripts/automation/includes/label-write-queue.js b/scripts/automation/includes/label-write-queue.js index 2283f0687e..f59bec998f 100644 --- a/scripts/automation/includes/label-write-queue.js +++ b/scripts/automation/includes/label-write-queue.js @@ -185,7 +185,8 @@ export function githubWrite( /GitHub API error: (403|429)\b/.test(error.message) && /rate limit/i.test(error.message) ) { - throw new RateLimitError(error.message); + const retryAfterMs = error.headers ? rateLimitDelayMs(error.headers) : null; + throw new RateLimitError(error.message, retryAfterMs ?? DEFAULT_PAUSE_MS); } throw error; } From e1e931a173927c10ff3ee661cb4db4d80a31c015 Mon Sep 17 00:00:00 2001 From: Chris Vancoillie Date: Sat, 3 Oct 2026 16:33:16 +0200 Subject: [PATCH 4/7] Keep a paused write queue paused and classify GitHub rate limits by status --- .../__tests__/label-write-queue.test.js | 46 +++++++++++++++++++ .../includes/github-api-optimized.js | 1 + .../automation/includes/label-write-queue.js | 35 ++++++++++++-- 3 files changed, 77 insertions(+), 5 deletions(-) diff --git a/scripts/automation/__tests__/label-write-queue.test.js b/scripts/automation/__tests__/label-write-queue.test.js index d5c6cb9a1e..19a7cded5d 100644 --- a/scripts/automation/__tests__/label-write-queue.test.js +++ b/scripts/automation/__tests__/label-write-queue.test.js @@ -105,6 +105,21 @@ describe('label-write-queue', () => { expect(calls).toBe(3); }); + test('once paused, later queued writes never start', async () => { + const clock = fakeClock(); + const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep, maxPauses: 0 }); + const later = jest.fn().mockResolvedValue('later'); + + const first = queue.run(async () => { + throw new RateLimitError('rate limit', 5000); + }); + const second = queue.run(later); + + await expect(first).rejects.toBeInstanceOf(RunPausedError); + await expect(second).rejects.toBeInstanceOf(RunPausedError); + expect(later).not.toHaveBeenCalled(); + }); + test('does not retry other errors, and keeps running later writes', async () => { const clock = fakeClock(); const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep }); @@ -200,6 +215,37 @@ describe('label-write-queue', () => { expect(clock.sleeps).toContain(120000); }); + test.each([ + ['a 429 with an unrelated message', 429, 'Too Many Requests', {}], + ['a 403 with no quota left', 403, 'Forbidden', { 'x-ratelimit-remaining': '0' }], + ['a 403 with Retry-After', 403, 'Forbidden', { 'retry-after': '5' }], + ])('pauses on %s', async (_name, status, message, headerValues) => { + const clock = fakeClock(); + const queue = createWriteQueue({ now: clock.now, sleep: clock.sleep }); + const limited = new Error(`GitHub API error: ${status} ${message}`); + limited.status = status; + limited.headers = headers(headerValues); + const request = jest.fn().mockRejectedValueOnce(limited).mockResolvedValueOnce(null); + + await expect( + githubWrite(queue, 'DELETE', '/repos/o/r/labels/old', null, { token: 'test' }, request) + ).resolves.toBeNull(); + expect(queue.stats().pauses).toBe(1); + }); + + test('does not pause on a 403 permission error with quota left', async () => { + const queue = createWriteQueue({ sleep: async () => {} }); + const denied = new Error('GitHub API error: 403 Resource not accessible by integration'); + denied.status = 403; + denied.headers = headers({ 'x-ratelimit-remaining': '4999' }); + const request = jest.fn().mockRejectedValue(denied); + + await expect( + githubWrite(queue, 'DELETE', '/repos/o/r/labels/old', null, { token: 'test' }, request) + ).rejects.toThrow('403'); + expect(request).toHaveBeenCalledTimes(1); + }); + test('passes other GitHub errors straight through', async () => { const queue = createWriteQueue({ sleep: async () => {} }); const request = jest.fn().mockRejectedValue(new Error('GitHub API error: 404 Not Found')); diff --git a/scripts/automation/includes/github-api-optimized.js b/scripts/automation/includes/github-api-optimized.js index 9826160693..b190585c56 100644 --- a/scripts/automation/includes/github-api-optimized.js +++ b/scripts/automation/includes/github-api-optimized.js @@ -173,6 +173,7 @@ export async function githubApiRequest( const error = new Error(errorMessage); // Keep the headers so callers can honour Retry-After on the final failure. error.headers = response.headers; + error.status = response.status; throw error; } diff --git a/scripts/automation/includes/label-write-queue.js b/scripts/automation/includes/label-write-queue.js index f59bec998f..a06fb0e1ac 100644 --- a/scripts/automation/includes/label-write-queue.js +++ b/scripts/automation/includes/label-write-queue.js @@ -106,6 +106,7 @@ export function createWriteQueue(options = {}) { let lastStartedAt = null; let writes = 0; let pauses = 0; + let pausedError = null; /** * Runs one write, waiting for the gap and pausing on rate limits. @@ -113,6 +114,10 @@ export function createWriteQueue(options = {}) { * @returns {Promise} The write's result */ async function execute(write) { + // A paused run stays paused: later queued writes must not start. + if (pausedError) { + throw pausedError; + } for (let attempt = 0; ; attempt++) { if (lastStartedAt !== null) { const wait = lastStartedAt + minIntervalMs - now(); @@ -130,10 +135,11 @@ export function createWriteQueue(options = {}) { throw error; } if (attempt >= maxPauses) { - throw new RunPausedError( + pausedError = new RunPausedError( `Write still rate-limited after ${maxPauses} pauses; stop and resume later`, error ); + throw pausedError; } pauses++; await sleep(Math.max(error.retryAfterMs, minIntervalMs)); @@ -154,6 +160,28 @@ export function createWriteQueue(options = {}) { }; } +/** + * Tells whether a GitHub API error is a rate limit. A 429 always is; a 403 is + * one when no quota remains (`x-ratelimit-remaining: 0`), when GitHub sends + * `Retry-After` (secondary limit), or when the message says so. + * @param {Error & { status?: number, headers?: { get: (name: string) => string | null } }} error + * @returns {boolean} + */ +function isGithubRateLimit(error) { + const status = error.status ?? Number(/GitHub API error: (\d{3})\b/.exec(error.message)?.[1]); + if (status === 429) { + return true; + } + if (status !== 403) { + return false; + } + return ( + error.headers?.get('x-ratelimit-remaining') === '0' || + Boolean(error.headers?.get('retry-after')) || + /rate limit/i.test(error.message) + ); +} + /** * Sends a GitHub write through the queue. A rate-limit failure from * `githubApiRequest` (after its own retries) becomes a `RateLimitError`, so @@ -181,10 +209,7 @@ export function githubWrite( try { return await request(method, path, body, { ...options, useCache: false }); } catch (error) { - if ( - /GitHub API error: (403|429)\b/.test(error.message) && - /rate limit/i.test(error.message) - ) { + if (isGithubRateLimit(error)) { const retryAfterMs = error.headers ? rateLimitDelayMs(error.headers) : null; throw new RateLimitError(error.message, retryAfterMs ?? DEFAULT_PAUSE_MS); } From 9eddf92f8e6100ee36e65276f0b2e9e12d1ce391 Mon Sep 17 00:00:00 2001 From: Chris Vancoillie Date: Sat, 3 Oct 2026 16:43:59 +0200 Subject: [PATCH 5/7] Allow-list githubWrite verbs, test error propagation, drop unrelated changelog entries --- CHANGELOG.md | 3 - .../github-api-optimized-errors.test.js | 60 +++++++++++++++++++ .../__tests__/label-write-queue.test.js | 25 ++++++-- .../automation/includes/label-write-queue.js | 8 ++- 4 files changed, 85 insertions(+), 11 deletions(-) create mode 100644 scripts/automation/__tests__/github-api-optimized-errors.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index e848d1e297..25ecf83dcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,9 +29,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - **Label Write Queue** — Label consolidation writes now go through one queue that spaces them one second apart and pauses on GitHub or Linear rate limits, so a long run can stop and resume safely. (#3704) -- **Governance Audit Phase 0-2 Infrastructure** — Added audit rule loader, violation tracker and report generator scripts with governance rules, plus Spec 006 design docs. (#3367) -- **Governance audit report ids are unique and self-consistent** — Fixed duplicate violation ids and recommendation references that no longer resolved, plus Spec 006 count and enforcement wording. (#3367) -- **Governance audit reports now render in a stable order** — Fixed report output changing with the order findings arrived, so two runs of the same audit are comparable. (#3367) - **Weekly Label Drift Check** — A scheduled workflow compares every org repository and Linear label against labels.yml and updates one drift report issue; read-only, never writes labels. (#3754) - **Badge Links Stop Breaking On Spaces** — The generator percent-encodes labels, so a multi-word badge resolves instead of ending at the first space. A check reports the 76,594 broken ones, with a fix mode. (#3702) - **Badge Check Handles Titled and Nested Examples** — A badge carrying a quoted title is no longer reported or rewritten, and a badge inside a nested code fence is left alone. (#3702) diff --git a/scripts/automation/__tests__/github-api-optimized-errors.test.js b/scripts/automation/__tests__/github-api-optimized-errors.test.js new file mode 100644 index 0000000000..2e914c0478 --- /dev/null +++ b/scripts/automation/__tests__/github-api-optimized-errors.test.js @@ -0,0 +1,60 @@ +/** + * Tests that githubApiRequest keeps the status and headers on a final failure, + * which the label write queue relies on to classify rate limits (spec 008, T062a). + */ + +import { githubApiRequest } from '../includes/github-api-optimized.js'; + +describe('githubApiRequest final errors', () => { + const realFetch = global.fetch; + + afterEach(() => { + global.fetch = realFetch; + }); + + /** + * Replaces fetch with one response. + * @param {number} status - HTTP status + * @param {Record} headerValues - Response headers + * @param {object} body - JSON error body + */ + function respondWith(status, headerValues, body) { + global.fetch = jest.fn().mockResolvedValue({ + ok: false, + status, + statusText: 'error', + headers: { get: (name) => (name in headerValues ? headerValues[name] : null) }, + text: async () => JSON.stringify(body), + }); + } + + test('keeps the status and headers on a 403 with quota left', async () => { + respondWith( + 403, + { 'x-ratelimit-remaining': '4999', 'retry-after': '7' }, + { message: 'Resource not accessible by integration' } + ); + + const error = await githubApiRequest('DELETE', '/repos/o/r/labels/x', null, { + token: 'test', + useCache: false, + }).catch((caught) => caught); + + expect(error.message).toBe('GitHub API error: 403 Resource not accessible by integration'); + expect(error.status).toBe(403); + expect(error.headers.get('retry-after')).toBe('7'); + expect(error.headers.get('x-ratelimit-remaining')).toBe('4999'); + }); + + test('keeps the status on a 404', async () => { + respondWith(404, {}, { message: 'Not Found' }); + + const error = await githubApiRequest('DELETE', '/repos/o/r/labels/x', null, { + token: 'test', + useCache: false, + }).catch((caught) => caught); + + expect(error.status).toBe(404); + expect(error.headers).toBeDefined(); + }); +}); diff --git a/scripts/automation/__tests__/label-write-queue.test.js b/scripts/automation/__tests__/label-write-queue.test.js index 19a7cded5d..c0304897ea 100644 --- a/scripts/automation/__tests__/label-write-queue.test.js +++ b/scripts/automation/__tests__/label-write-queue.test.js @@ -158,11 +158,26 @@ describe('label-write-queue', () => { }); describe('githubWrite', () => { - test('refuses read requests', () => { - const queue = createWriteQueue(); - expect(() => githubWrite(queue, 'GET', '/repos/o/r/labels')).toThrow( - 'mutating requests only' - ); + test.each(['GET', 'get', 'HEAD', 'OPTIONS', 'TRACE', 'FETCH', ''])( + 'refuses %p, which is not a write verb', + (method) => { + const queue = createWriteQueue(); + expect(() => githubWrite(queue, method, '/repos/o/r/labels')).toThrow( + 'mutating requests only' + ); + } + ); + + test('normalises a lower-case write verb', async () => { + const queue = createWriteQueue({ sleep: async () => {} }); + const request = jest.fn().mockResolvedValue(null); + + await githubWrite(queue, 'delete', '/repos/o/r/labels/old', null, { token: 'test' }, request); + + expect(request).toHaveBeenCalledWith('DELETE', '/repos/o/r/labels/old', null, { + token: 'test', + useCache: false, + }); }); test('sends the write uncached through the queue', async () => { diff --git a/scripts/automation/includes/label-write-queue.js b/scripts/automation/includes/label-write-queue.js index a06fb0e1ac..22476741f7 100644 --- a/scripts/automation/includes/label-write-queue.js +++ b/scripts/automation/includes/label-write-queue.js @@ -19,6 +19,7 @@ import { githubApiRequest } from './github-api-optimized.js'; const DEFAULT_MIN_INTERVAL_MS = 1000; const DEFAULT_MAX_PAUSES = 3; const DEFAULT_PAUSE_MS = 60000; +const WRITE_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE']); /** * A write was refused because of a rate or complexity limit. @@ -202,12 +203,13 @@ export function githubWrite( options = {}, request = githubApiRequest ) { - if (method === 'GET' || method === 'HEAD') { - throw new Error('githubWrite is for mutating requests only'); + const verb = String(method).toUpperCase(); + if (!WRITE_METHODS.has(verb)) { + throw new Error('githubWrite is for mutating requests only (POST, PATCH, PUT or DELETE)'); } return queue.run(async () => { try { - return await request(method, path, body, { ...options, useCache: false }); + return await request(verb, path, body, { ...options, useCache: false }); } catch (error) { if (isGithubRateLimit(error)) { const retryAfterMs = error.headers ? rateLimitDelayMs(error.headers) : null; From d99fd9025ef6c621841fe7e1163301a62d589435 Mon Sep 17 00:00:00 2001 From: Chris Vancoillie Date: Sat, 3 Oct 2026 17:34:40 +0200 Subject: [PATCH 6/7] Parse HTTP-date Retry-After values in the label write queue --- .../__tests__/label-write-queue.test.js | 23 +++++++++++++++++++ .../automation/includes/label-write-queue.js | 7 +++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/scripts/automation/__tests__/label-write-queue.test.js b/scripts/automation/__tests__/label-write-queue.test.js index c0304897ea..31ea16e41b 100644 --- a/scripts/automation/__tests__/label-write-queue.test.js +++ b/scripts/automation/__tests__/label-write-queue.test.js @@ -152,6 +152,29 @@ describe('label-write-queue', () => { expect(rateLimitDelayMs(headers({ 'x-ratelimit-reset': '10' }), 50000)).toBe(0); }); + test('reads an HTTP-date Retry-After as the time until that date', () => { + const now = Date.parse('Sat, 03 Oct 2026 12:00:00 GMT'); + expect( + rateLimitDelayMs(headers({ 'retry-after': 'Sat, 03 Oct 2026 12:05:00 GMT' }), now) + ).toBe(300000); + }); + + test('an HTTP-date Retry-After in the past waits no time and beats the reset header', () => { + const now = Date.parse('Sat, 03 Oct 2026 12:00:00 GMT'); + expect( + rateLimitDelayMs( + headers({ 'retry-after': 'Sat, 03 Oct 2026 11:59:00 GMT', 'x-ratelimit-reset': '9999999999' }), + now + ) + ).toBe(0); + }); + + test('falls through to the reset header when Retry-After is neither seconds nor a date', () => { + expect( + rateLimitDelayMs(headers({ 'retry-after': 'soon', 'x-ratelimit-reset': '100' }), 40000) + ).toBe(60000); + }); + test('returns null without rate-limit headers', () => { expect(rateLimitDelayMs(headers({}), 0)).toBeNull(); }); diff --git a/scripts/automation/includes/label-write-queue.js b/scripts/automation/includes/label-write-queue.js index 22476741f7..763f36cbfd 100644 --- a/scripts/automation/includes/label-write-queue.js +++ b/scripts/automation/includes/label-write-queue.js @@ -54,7 +54,7 @@ export class RunPausedError extends Error { /** * Works out how long to wait from GitHub rate-limit headers. - * `Retry-After` is in seconds; `x-ratelimit-reset` is a Unix time in seconds. + * `Retry-After` is in seconds or an HTTP date; `x-ratelimit-reset` is a Unix time in seconds. * @param {{ get: (name: string) => string | null }} headers - Response headers * @param {number} [nowMs] - Current time in milliseconds * @returns {number | null} Milliseconds to wait, or null when no header applies @@ -66,6 +66,11 @@ export function rateLimitDelayMs(headers, nowMs = Date.now()) { if (Number.isFinite(seconds)) { return Math.max(seconds * 1000, 0); } + // `Retry-After` may also be an HTTP date (RFC 9110). + const date = Date.parse(retryAfter); + if (Number.isFinite(date)) { + return Math.max(date - nowMs, 0); + } } const reset = headers.get('x-ratelimit-reset'); if (reset !== null && reset !== '') { From df21e5338e3a4c120445e12d73e980d059ad20ba Mon Sep 17 00:00:00 2001 From: Chris Vancoillie Date: Sat, 3 Oct 2026 18:41:36 +0200 Subject: [PATCH 7/7] Describe the label write queue as added, not yet in use --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25ecf83dcc..0cecc5f794 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **Label Write Queue** — Label consolidation writes now go through one queue that spaces them one second apart and pauses on GitHub or Linear rate limits, so a long run can stop and resume safely. (#3704) +- **Label Write Queue** — Added a queue that spaces label writes one second apart and pauses on GitHub or Linear rate limits. Nothing calls it yet; later consolidation stages will. (#3704) - **Weekly Label Drift Check** — A scheduled workflow compares every org repository and Linear label against labels.yml and updates one drift report issue; read-only, never writes labels. (#3754) - **Badge Links Stop Breaking On Spaces** — The generator percent-encodes labels, so a multi-word badge resolves instead of ending at the first space. A check reports the 76,594 broken ones, with a fix mode. (#3702) - **Badge Check Handles Titled and Nested Examples** — A badge carrying a quoted title is no longer reported or rewritten, and a badge inside a nested code fence is left alone. (#3702)