From 7fd47763db14fba778bb40785d8b5bd03dfc4750 Mon Sep 17 00:00:00 2001 From: Phil Leggetter Date: Fri, 6 Nov 2026 15:34:28 +0000 Subject: [PATCH 1/2] Reset issue triggers to declared defaults, not snapshot ids Closes the trigger half of #28 and fixes #117. The snapshot recorded trigger ids and only deleted, so it adopted a rewritten default as pristine, never recreated a deleted one, and in CI adopted whatever the last job left. All three happened to the delivery default alerting-001 is built around; since 19 August the scenario ran with no delivery trigger. DEFAULT_ISSUE_TRIGGERS lists the four triggers project creation makes, by content, muted. Every reset keeps the oldest trigger of each type and rewrites it to that content, creates any missing, and deletes the rest. A failed trigger reset fails the acquire, like the rest of the reset. The Outpost gateway guard now also checks the gateway key's live ids, because restored triggers get new ids a persisted snapshot lacks. Verified against evals-ci: the missing delivery default was created, a rewritten one was restored in place, and a second pass wrote nothing. This changes what alerting-001 starts from: an enabled, wildcard delivery trigger with no channel. Results either side are not comparable. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 40 +- README.md | 4 +- .../EVAL.ts | 9 + packages/hookdeck/src/index.ts | 3 + packages/hookdeck/src/project-source.ts | 197 ++++++++- packages/hookdeck/test/project-source.test.ts | 380 ++++++++++++------ 6 files changed, 481 insertions(+), 152 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 448da84..d65ca41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1274,28 +1274,39 @@ queue URL and leaves `credentials` empty. default issue triggers. The first acquire snapshots what the project contains, and every reset deletes only what a run added. +**Except issue triggers, which are declared, not captured.** A new project gets +exactly four — delivery, transformation, backpressure, request — and +`DEFAULT_ISSUE_TRIGGERS` lists them by content, read from the Event Gateway +implementation. Every reset keeps the oldest trigger of each type and rewrites it +to that content, creates any that are missing, and deletes every other trigger. + +A captured snapshot of ids failed on these both ways round, and both happened to +the delivery default that `alerting-001` is built around (#28, #117). A run +rewrote it on 7 August before the snapshot was taken, so the rewrite was kept as +pristine; it was deleted by hand on 19 August as an orphan, and an id-based reset +never recreates anything, so the scenario then ran with no delivery trigger at +all. In CI it is worse, because each fresh checkout takes a new snapshot and so +adopts whatever the last job left. + **Those defaults email the whole team, so reset mutes them.** Each default trigger carries an `email` channel, and the email channel has no recipients of its own: it goes to every member of the organization who has not turned alerts off, whenever the project's notification methods include email. Scenarios fail deliveries, requests and transformations on purpose, so from at least 21 August every run emailed the people on `evals-ci` about failures we had caused, and it surfaced -on 6 November only because they said so. `muteIssueTriggerNotifications` now sets -`channels: {}` on every issue trigger, on acquire and on release, and leaves -each one enabled and scoped as it was. +on 6 November only because they said so. The declared defaults carry +`channels: {}`, and `muteIssueTriggerNotifications` sets the same on every +trigger after each reset, which matters on release, where the reset is best +effort and can stop partway. -Three things to know before touching it: +What to know before touching it: -- **Every trigger, not only the snapshot's.** In CI each fresh checkout takes - its own snapshot, so a trigger leaked by a run that died before release can be - recorded as pristine and is then never deleted. Muting is the one part of - reset that still reaches it. - **It changes what `alerting-001` starts from.** No scorer reads issues, and - the agent's own work is never muted before it is scored: acquire mutes before - the agent runs, release mutes after scoring. But the agent now finds every - existing trigger at `channels: {}`, which is the silent state that scenario - fails an agent for leaving. A default delivery trigger can no longer be passed - by confirming it, and an agent copying its neighbours' shape fails the channel + the agent's own work is never reset before it is scored: acquire resets before + the agent runs, release after scoring. But the agent now finds an enabled, + wildcard delivery trigger at `channels: {}` — configured and silent, which is + the failure that scenario exists to catch. It cannot be passed by confirming + the trigger, and an agent copying its neighbours' shape fails the channel check. That is an instrument change, so results either side of it are not comparable for that scenario, and the next release notes say so. - **The cleaner switch is out of reach.** Email is only sent when the project's @@ -1309,6 +1320,9 @@ Three things to know before touching it: must call `muteIssueTriggerNotifications` before the first run, and the `ProjectSource` interface says so. If anyone creates an eval project by hand, mute it the same way, or the first run emails the team. +- **A failed trigger reset fails the acquire**, like the rest of the reset. + Nothing has been paid for yet, and `alerting-001` started without its default + would score as though it were valid. The Outpost project's gateway side is reset to empty, and that follows the same rule: pristine there *is* empty. Platform project creation gives an Outpost project no issue diff --git a/README.md b/README.md index 9489596..22a6440 100644 --- a/README.md +++ b/README.md @@ -227,7 +227,9 @@ against. See `.env.example`. **Reset is to pristine, not to empty.** A new Hookdeck project ships with default issue triggers. Deleting them would leave the project unlike any real customer's. The first acquire snapshots what the project contains and every reset deletes only what a -run added. +run added. Issue triggers are the exception: they are declared in code by content +(`DEFAULT_ISSUE_TRIGGERS`), so a reset also recreates a default a run deleted and +rewrites one a run changed, which a snapshot of ids cannot do. **Every reset turns issue trigger notifications off.** Those default triggers email every member of the organization, and scenarios fail deliveries, requests and transformations on diff --git a/evals/benchmark-alerting-001-delivery-alerts/EVAL.ts b/evals/benchmark-alerting-001-delivery-alerts/EVAL.ts index b1c3224..2e2a2a6 100644 --- a/evals/benchmark-alerting-001-delivery-alerts/EVAL.ts +++ b/evals/benchmark-alerting-001-delivery-alerts/EVAL.ts @@ -25,6 +25,15 @@ import type { * a no-op on an empty object, so nothing is ever sent. The console's own create form defaults to `email: {selected: * true}` for exactly this reason. * + * The agent starts from the delivery trigger a new project ships with, enabled + * and wildcard-scoped, but with `channels: {}`: the harness mutes every trigger + * so runs do not email the eval project's team (#116), and declares the defaults + * so a run cannot delete or rewrite this one for the next (#117). So the + * starting state is the third failure above, an alert that is configured and + * silent, and an agent that confirms the existing trigger without giving it a + * channel fails. Results from before 6 November started from a rewritten + * trigger (to 19 August) or from none at all, and are not comparable. + * * Scored on configuration rather than by causing a real alert, which is a * compromise worth naming. The honest test is to break the destination, send * traffic, and wait for an issue to appear, but that depends on the retry cycle diff --git a/packages/hookdeck/src/index.ts b/packages/hookdeck/src/index.ts index 4524637..ff18a89 100644 --- a/packages/hookdeck/src/index.ts +++ b/packages/hookdeck/src/index.ts @@ -10,10 +10,13 @@ export type { HookdeckClientOptions, } from './client.js'; export { + DEFAULT_ISSUE_TRIGGERS, FixedProjectSource, muteIssueTriggerNotifications, + resetIssueTriggersToDefaults, } from './project-source.js'; export type { + IssueTriggerChange, ProjectSource, LeasedProject, PristineSnapshot, diff --git a/packages/hookdeck/src/project-source.ts b/packages/hookdeck/src/project-source.ts index 8bdf2b3..7e9539f 100644 --- a/packages/hookdeck/src/project-source.ts +++ b/packages/hookdeck/src/project-source.ts @@ -75,11 +75,12 @@ export interface ProjectSource { * copying its neighbours' shape fails the channel check. Results either side of * this change are not comparable for that scenario. * - * Every trigger, not only the snapshot's. In CI the snapshot is taken by each - * fresh checkout, so a trigger leaked by a run that died before release can be - * recorded as pristine and then never deleted; muting it is the only reset that - * still reaches it. Every channel, not only email: a Slack or PagerDuty channel - * on an eval project would page a person for a failure we caused on purpose. + * `FixedProjectSource` gets this for free from `resetIssueTriggersToDefaults`, + * which leaves only the declared defaults and declares them muted, and still + * calls this afterwards: on release that reset is best effort, and this is the + * part worth having when it stops partway. Every trigger and every channel, not + * only email: a Slack or PagerDuty channel on an eval project would page a + * person for a failure we caused on purpose. * * Returns the ids it changed, so a caller can log them. */ @@ -119,6 +120,11 @@ export async function muteIssueTriggerNotifications( * * Recording IDs rather than a count means any future default resource type is * protected without a code change. + * + * **Except issue triggers, which are declared rather than captured.** See + * `DEFAULT_ISSUE_TRIGGERS`. Their ids are still recorded here, because the + * Outpost gateway reset uses every recorded id to tell the two projects apart, + * but the gateway project's reset no longer reads them. */ export interface PristineSnapshot { capturedAt: string; @@ -165,6 +171,146 @@ export const OUTPOST_GATEWAY_PRISTINE: PristineSnapshot = { ids: {}, }; +/** + * The issue triggers a new Event Gateway project ships with, by content. + * + * Read in the Event Gateway implementation, not inferred from the API: project + * creation adds exactly these four, in one transaction, with `channels: { email: + * {} }` and no name. Here they carry `channels: {}` instead, for the reason + * `muteIssueTriggerNotifications` gives. + * + * **Declared rather than captured, because a captured snapshot of triggers + * failed both ways round** (#28, #117). It records ids and only deletes, so: + * + * - a leftover present when a snapshot is taken is adopted as pristine, and in + * CI every job is a fresh checkout that takes a fresh snapshot; + * - a default a run rewrote keeps its id, so it is kept, rewritten; + * - a default a run deleted is never recreated. + * + * All three happened to the delivery default, which `alerting-001` is built + * around. An early run rewrote it on 7 August into a trigger scoped to a + * connection that was later deleted; it was deleted by hand on 19 August as an + * orphan; and from then on the scenario ran with no delivery trigger at all. + */ +export const DEFAULT_ISSUE_TRIGGERS: ReadonlyArray<{ + type: string; + configs: Record; +}> = [ + { + type: 'delivery', + configs: { strategy: 'first_attempt', connections: '*' }, + }, + { + type: 'transformation', + configs: { log_level: 'warn', transformations: '*' }, + }, + { + type: 'backpressure', + configs: { delay: 1000 * 60 * 10, destinations: '*' }, + }, + { + type: 'request', + configs: { + rejection_causes: '*', + excluded_rejection_causes: ['NO_CONNECTION', 'UNSUPPORTED_HTTP_METHOD'], + sources: '*', + }, + }, +]; + +export type IssueTriggerChange = + | { action: 'deleted'; id: string; type: string } + | { action: 'restored'; id: string; type: string } + | { action: 'created'; id: string; type: string }; + +/** + * Make the project's issue triggers exactly `DEFAULT_ISSUE_TRIGGERS`. + * + * One trigger is kept per default type, the oldest of that type, since that is + * the one project creation made; it is rewritten in place if a run changed its + * configs, channels, name or enabled state. A type with no trigger gets one. + * Everything else is deleted, whoever created it. + * + * Extras are deleted before anything is restored, so a name a leftover holds + * can never collide with the write that follows. Reports each change through + * `onChange` as it happens, so a reset that fails partway still leaves a record. + */ +export async function resetIssueTriggersToDefaults( + client: HookdeckClient, + onChange?: (change: IssueTriggerChange) => void +): Promise { + const existing = await client.list('issue-triggers'); + const kept = new Map(); + for (const declared of DEFAULT_ISSUE_TRIGGERS) { + const oldest = existing + .filter((t) => t.type === declared.type) + .sort((a, b) => + String(a.created_at ?? '').localeCompare(String(b.created_at ?? '')) + )[0]; + if (oldest) kept.set(declared.type, oldest); + } + const keepIds = new Set([...kept.values()].map((t) => t.id)); + + for (const trigger of existing) { + if (keepIds.has(trigger.id)) continue; + await client.delete('issue-triggers', trigger.id); + onChange?.({ + action: 'deleted', + id: trigger.id, + type: String(trigger.type), + }); + } + + for (const declared of DEFAULT_ISSUE_TRIGGERS) { + const current = kept.get(declared.type); + if (!current) { + const created = await client.request( + 'POST', + '/issue-triggers', + { type: declared.type, configs: declared.configs, channels: {} } + ); + onChange?.({ action: 'created', id: created.id, type: declared.type }); + continue; + } + if (matchesDeclared(current, declared.configs)) continue; + await client.request('PUT', `/issue-triggers/${current.id}`, { + configs: declared.configs, + channels: {}, + disabled_at: null, + name: null, + }); + onChange?.({ action: 'restored', id: current.id, type: declared.type }); + } +} + +function matchesDeclared( + trigger: HookdeckResource, + configs: Record +): boolean { + const channels = trigger.channels; + return ( + canonicalJson(trigger.configs) === canonicalJson(configs) && + !!channels && + typeof channels === 'object' && + Object.keys(channels).length === 0 && + !trigger.disabled_at && + !trigger.name + ); +} + +/** JSON with object keys sorted, so key order the API returns cannot differ. */ +function canonicalJson(value: unknown): string { + return JSON.stringify(value, (_key, v) => + v && typeof v === 'object' && !Array.isArray(v) + ? Object.fromEntries( + Object.entries(v as Record).sort(([a], [b]) => + a.localeCompare(b) + ) + ) + : v + ); +} + export interface FixedProjectSourceOptions { apiKey: string; projectId?: string; @@ -271,7 +417,7 @@ export class FixedProjectSource implements ProjectSource { async acquire(): Promise { const snapshot = await this.loadOrCaptureSnapshot(); - await this.resetToPristine(this.client, snapshot); + await this.resetGatewayProject(snapshot, 'acquire'); await this.muteNotifications('acquire'); // Before the seed, not only on release: a run that dies before release // must not hand its gateway resources in the Outpost project to the next @@ -301,7 +447,7 @@ export class FixedProjectSource implements ProjectSource { let snapshot: PristineSnapshot | undefined; try { snapshot = await this.loadOrCaptureSnapshot(); - await this.resetToPristine(this.client, snapshot); + await this.resetGatewayProject(snapshot, 'release'); } catch { // Swallowed deliberately: a failed release must not fail the run, and // the next acquire will clean up regardless. @@ -685,10 +831,12 @@ export class FixedProjectSource implements ProjectSource { private async resetToPristine( client: HookdeckClient, snapshot: PristineSnapshot, - onDelete?: (kind: ResourceKind, resource: HookdeckResource) => void + onDelete?: (kind: ResourceKind, resource: HookdeckResource) => void, + skip: readonly ResourceKind[] = [] ): Promise { // Connections reference sources and destinations, so they go first. for (const kind of RESOURCE_KINDS) { + if (skip.includes(kind)) continue; const keep = new Set(snapshot.ids[kind] ?? []); const existing: HookdeckResource[] = await client.list(kind); for (const resource of existing) { @@ -699,6 +847,32 @@ export class FixedProjectSource implements ProjectSource { } } + /** + * Reset the gateway project: everything but issue triggers to the snapshot, + * then issue triggers to `DEFAULT_ISSUE_TRIGGERS`. + * + * Triggers last, after the connections and transformations they may be scoped + * to are gone. Logs trigger changes on acquire only: release routinely undoes + * what the agent just did, which is the point of it, while a change found at + * acquire means a run died before releasing or something outside the harness + * changed the project. + */ + private async resetGatewayProject( + snapshot: PristineSnapshot, + when: 'acquire' | 'release' + ): Promise { + await this.resetToPristine(this.client, snapshot, undefined, [ + 'issue-triggers', + ]); + await resetIssueTriggersToDefaults(this.client, (change) => { + if (when !== 'acquire') return; + console.warn( + `issue triggers: ${change.action} ${change.type} trigger ${change.id} ` + + 'to match the defaults a new project ships with' + ); + }); + } + /** * Reset the Event Gateway side of the Outpost project to * `OUTPOST_GATEWAY_PRISTINE`, which is empty. @@ -720,7 +894,14 @@ export class FixedProjectSource implements ProjectSource { const client = this.outpostGatewayClient; if (!client) return; + // The snapshot's ids plus what the gateway key can see now. Issue triggers + // are recreated by the gateway reset, so their ids drift away from a + // persisted snapshot, and a guard built on the snapshot alone would weaken + // every time a default was restored. const gatewayIds = new Set(Object.values(gatewaySnapshot.ids).flat()); + for (const kind of RESOURCE_KINDS) { + for (const r of await this.client.list(kind)) gatewayIds.add(r.id); + } for (const kind of RESOURCE_KINDS) { const shared = (await client.list(kind)).filter((r) => gatewayIds.has(r.id) diff --git a/packages/hookdeck/test/project-source.test.ts b/packages/hookdeck/test/project-source.test.ts index 54a8180..f4a1d10 100644 --- a/packages/hookdeck/test/project-source.test.ts +++ b/packages/hookdeck/test/project-source.test.ts @@ -2,7 +2,13 @@ import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { FixedProjectSource, type PristineSnapshot } from '../src/index.js'; +import { + DEFAULT_ISSUE_TRIGGERS, + FixedProjectSource, + HookdeckClient, + muteIssueTriggerNotifications, + type PristineSnapshot, +} from '../src/index.js'; /** * A fake Hookdeck API. The provisioner only ever lists and deletes, so this @@ -53,11 +59,11 @@ describe('FixedProjectSource', () => { expect(snapshot.capturedAt).toBeTruthy(); }); - it('preserves the default issue triggers a new project ships with', async () => { - // The whole reason reset is to pristine rather than to empty: deleting the - // defaults would change what BM4 tests and drift the project irreversibly. + it('preserves what the project held when the snapshot was taken', async () => { + // The whole reason reset is to pristine rather than to empty. Issue + // triggers are declared rather than snapshotted; see the describe below. const { fetchImpl, deleted } = fakeApi({ - 'issue-triggers': ['it_default_1', 'it_default_2'], + sources: ['src_1', 'src_2'], }); vi.stubGlobal('fetch', fetchImpl); const snapshotPath = tempSnapshotPath(); @@ -69,32 +75,32 @@ describe('FixedProjectSource', () => { expect(deleted).toEqual([]); }); - it('deletes what a previous run added, keeping the defaults', async () => { + it('deletes what a previous run added, keeping what was there before', async () => { const { fetchImpl, deleted, state } = fakeApi({ - 'issue-triggers': ['it_default'], + sources: ['src_before'], }); vi.stubGlobal('fetch', fetchImpl); const snapshotPath = tempSnapshotPath(); const source = new FixedProjectSource({ apiKey: 'k', snapshotPath }); await source.acquire(); - // a run leaves resources behind, including an extra trigger - state.set('sources', new Set(['src_leftover'])); - state.get('issue-triggers')!.add('it_from_a_run'); + // a run leaves resources behind + state.get('sources')!.add('src_leftover'); + state.set('destinations', new Set(['des_leftover'])); await source.acquire(); expect(deleted).toEqual([ { kind: 'sources', id: 'src_leftover' }, - { kind: 'issue-triggers', id: 'it_from_a_run' }, + { kind: 'destinations', id: 'des_leftover' }, ]); - expect(state.get('issue-triggers')).toContain('it_default'); + expect(state.get('sources')).toContain('src_before'); }); it('self-heals after a run that crashed without releasing', async () => { // Reset keys off the snapshot, not a per-run timestamp, so leftovers from a // crashed run are cleaned by the next acquire rather than accumulating. - const { fetchImpl, state } = fakeApi({ 'issue-triggers': ['it_default'] }); + const { fetchImpl, state } = fakeApi(); vi.stubGlobal('fetch', fetchImpl); const snapshotPath = tempSnapshotPath(); const source = new FixedProjectSource({ apiKey: 'k', snapshotPath }); @@ -114,17 +120,17 @@ describe('FixedProjectSource', () => { snapshotPath, JSON.stringify({ capturedAt: '2026-08-07T00:00:00.000Z', - ids: { 'issue-triggers': ['it_default'] }, + ids: { sources: ['src_before'] }, }) ); const { fetchImpl, deleted } = fakeApi({ - 'issue-triggers': ['it_default', 'it_added_later'], + sources: ['src_before', 'src_added_later'], }); vi.stubGlobal('fetch', fetchImpl); await new FixedProjectSource({ apiKey: 'k', snapshotPath }).acquire(); - expect(deleted).toEqual([{ kind: 'issue-triggers', id: 'it_added_later' }]); + expect(deleted).toEqual([{ kind: 'sources', id: 'src_added_later' }]); }); it('returns a lease carrying acquiredAt, for scoping scorer queries', async () => { @@ -470,7 +476,7 @@ describe('FixedProjectSource Outpost project gateway reset', () => { // from August, plus issue triggers, which an Outpost project does not ship // with. A fresh snapshot path is a fresh CI checkout. const api = fakeTwoProjects({ - [GATEWAY_KEY]: { 'issue-triggers': ['it_default'] }, + [GATEWAY_KEY]: { sources: ['src_gateway'] }, [OUTPOST_KEY]: { connections: ['web_leftover'], sources: ['src_leftover'], @@ -486,9 +492,9 @@ describe('FixedProjectSource Outpost project gateway reset', () => { expect( api.deleted.filter((d) => d.key === OUTPOST_KEY).map((d) => d.kind) ).toEqual(['connections', 'sources', 'destinations', 'issue-triggers']); - // The gateway project keeps its defaults: the Outpost baseline is empty, + // The gateway project keeps its resources: the Outpost baseline is empty, // the gateway one is not. - expect(api.ids(GATEWAY_KEY, 'issue-triggers')).toEqual(['it_default']); + expect(api.ids(GATEWAY_KEY, 'sources')).toEqual(['src_gateway']); }); it('does not let a crashed attempt hand its edits to the next attempt', async () => { @@ -564,8 +570,8 @@ describe('FixedProjectSource Outpost project gateway reset', () => { // Two keys, one project. The Outpost baseline is "delete everything", which // would take the gateway project's default issue triggers with it. const api = fakeTwoProjects({ - [GATEWAY_KEY]: { 'issue-triggers': ['it_default'] }, - [OUTPOST_KEY]: { 'issue-triggers': ['it_default', 'it_other'] }, + [GATEWAY_KEY]: { sources: ['src_shared'] }, + [OUTPOST_KEY]: { sources: ['src_shared', 'src_other'] }, }); vi.stubGlobal('fetch', api.fetchImpl); const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); @@ -578,7 +584,7 @@ describe('FixedProjectSource Outpost project gateway reset', () => { it('does nothing extra when both keys are the same', async () => { const api = fakeTwoProjects({ - [GATEWAY_KEY]: { 'issue-triggers': ['it_default'] }, + [GATEWAY_KEY]: { sources: ['src_gateway'] }, }); vi.stubGlobal('fetch', api.fetchImpl); const s = new FixedProjectSource({ @@ -591,7 +597,7 @@ describe('FixedProjectSource Outpost project gateway reset', () => { await s.release(lease); expect(api.deleted).toEqual([]); - expect(api.ids(GATEWAY_KEY, 'issue-triggers')).toEqual(['it_default']); + expect(api.ids(GATEWAY_KEY, 'sources')).toEqual(['src_gateway']); }); it('touches no Outpost project when no Outpost key is configured', async () => { @@ -661,16 +667,41 @@ describe('FixedProjectSource Outpost project gateway reset', () => { }); /** - * A new project's default issue triggers email every member, and scenarios fail - * deliveries on purpose, so every run emailed the eval project's team. Reset has - * to leave every trigger notifying no one, whoever created it. + * Issue triggers are reset to the four a new project ships with, by content, + * and muted. A captured snapshot failed both ways round on these: it adopted a + * rewritten default as pristine (#28) and never recreated a deleted one (#117). + * And a new project's defaults email every member while scenarios fail + * deliveries on purpose, so every run emailed the team. */ -describe('FixedProjectSource issue trigger notifications', () => { +describe('FixedProjectSource issue triggers', () => { beforeEach(() => vi.restoreAllMocks()); - function fakeTriggers(triggers: Record>) { + type Trigger = Record; + + const declared = (type: string) => + DEFAULT_ISSUE_TRIGGERS.find((d) => d.type === type)!; + + /** A trigger exactly as the reset leaves it. */ + const pristine = (type: string, created_at = '2026-08-07T10:46:14.347Z') => ({ + type, + configs: declared(type).configs, + channels: {}, + disabled_at: null, + name: null, + created_at, + }); + + const allPristine = (): Record => ({ + it_delivery: pristine('delivery'), + it_transformation: pristine('transformation'), + it_backpressure: pristine('backpressure'), + it_request: pristine('request'), + }); + + function fakeTriggers(triggers: Record) { const state = new Map(Object.entries(triggers)); - const puts: Array<{ id: string; body: unknown }> = []; + const writes: Array<{ method: string; id?: string; body?: unknown }> = []; + let next = 0; const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit) => { const path = new URL(String(url)).pathname.replace(/^\/[^/]+/, ''); const method = init?.method ?? 'GET'; @@ -678,173 +709,262 @@ describe('FixedProjectSource issue trigger notifications', () => { if (kind !== 'issue-triggers') { return new Response(JSON.stringify({ models: [] }), { status: 200 }); } + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + if (method === 'POST') { + const newId = `it_new_${next++}`; + state.set(newId, { ...body, created_at: '2026-11-06T00:00:00.000Z' }); + writes.push({ method, body }); + return new Response(JSON.stringify({ id: newId, ...state.get(newId) })); + } if (method === 'PUT') { - const body = JSON.parse(String(init?.body)) as Record; - puts.push({ id, body }); state.set(id, { ...state.get(id), ...body }); - return new Response(JSON.stringify({ id, ...state.get(id) }), { - status: 200, - }); + writes.push({ method, id, body }); + return new Response(JSON.stringify({ id, ...state.get(id) })); } if (method === 'DELETE') { state.delete(id); + writes.push({ method, id }); return new Response('', { status: 200 }); } const models = [...state].map(([rid, t]) => ({ id: rid, ...t })); return new Response(JSON.stringify({ models }), { status: 200 }); }); - return { fetchImpl, state, puts }; + const byType = (type: string) => + [...state.values()].filter((t) => t.type === type); + return { fetchImpl, state, writes, byType }; } - it('clears the email channel on the default triggers at acquire, and keeps them', async () => { - const { fetchImpl, state, puts } = fakeTriggers({ - it_delivery: { type: 'delivery', channels: { email: {} } }, - it_request: { type: 'request', channels: { email: {} } }, + function source(snapshotPath = tempSnapshotPath()) { + return new FixedProjectSource({ apiKey: 'k', snapshotPath }); + } + + it('declares the four triggers project creation makes', () => { + expect(DEFAULT_ISSUE_TRIGGERS.map((d) => d.type).sort()).toEqual([ + 'backpressure', + 'delivery', + 'request', + 'transformation', + ]); + expect(declared('delivery').configs).toEqual({ + strategy: 'first_attempt', + connections: '*', }); - vi.stubGlobal('fetch', fetchImpl); + }); + + it('writes nothing when the triggers already match the defaults', async () => { + const api = fakeTriggers(allPristine()); + vi.stubGlobal('fetch', api.fetchImpl); + + const s = source(); + await s.release(await s.acquire()); + + expect(api.writes).toEqual([]); + }); + + it('recreates a default a run deleted, muted', async () => { + // The state evals-ci was in from 19 August: no delivery trigger at all. + const { it_delivery: _gone, ...rest } = allPristine(); + const api = fakeTriggers(rest); + vi.stubGlobal('fetch', api.fetchImpl); vi.spyOn(console, 'warn').mockImplementation(() => {}); - await new FixedProjectSource({ - apiKey: 'k', - snapshotPath: tempSnapshotPath(), - }).acquire(); + await source().acquire(); - expect(puts).toEqual([ - { id: 'it_delivery', body: { channels: {} } }, - { id: 'it_request', body: { channels: {} } }, + expect(api.writes).toEqual([ + { + method: 'POST', + body: { + type: 'delivery', + configs: declared('delivery').configs, + channels: {}, + }, + }, ]); - expect([...state.keys()]).toEqual(['it_delivery', 'it_request']); - expect(state.get('it_delivery')?.type).toBe('delivery'); }); - it('leaves an already muted trigger alone', async () => { - const { fetchImpl, puts } = fakeTriggers({ - it_quiet: { type: 'delivery', channels: {} }, + it('rewrites a default a run changed, in place', async () => { + // The state evals-ci was in from 7 August: the delivery default renamed, + // switched to final_attempt and scoped to one connection. + const api = fakeTriggers({ + ...allPristine(), + it_delivery: { + ...pristine('delivery'), + name: 'fulfilment-delivery-failures', + configs: { strategy: 'final_attempt', connections: ['web_gone'] }, + channels: { email: {} }, + }, }); - vi.stubGlobal('fetch', fetchImpl); + vi.stubGlobal('fetch', api.fetchImpl); + vi.spyOn(console, 'warn').mockImplementation(() => {}); - await new FixedProjectSource({ - apiKey: 'k', - snapshotPath: tempSnapshotPath(), - }).acquire(); + await source().acquire(); - expect(puts).toEqual([]); + expect(api.writes).toEqual([ + { + method: 'PUT', + id: 'it_delivery', + body: { + configs: declared('delivery').configs, + channels: {}, + disabled_at: null, + name: null, + }, + }, + ]); }); - it('mutes a trigger with null or missing channels, which still emails', async () => { - // The notification service emails the team when a trigger has no channels - // at all, so null is not the same as {}. - const { fetchImpl, puts } = fakeTriggers({ - it_null: { type: 'request', channels: null }, - it_missing: { type: 'backpressure' }, + it('re-enables a default a run disabled', async () => { + const api = fakeTriggers({ + ...allPristine(), + it_request: { + ...pristine('request'), + disabled_at: '2026-11-06T00:00:00Z', + }, }); - vi.stubGlobal('fetch', fetchImpl); + vi.stubGlobal('fetch', api.fetchImpl); vi.spyOn(console, 'warn').mockImplementation(() => {}); - await new FixedProjectSource({ - apiKey: 'k', - snapshotPath: tempSnapshotPath(), - }).acquire(); + await source().acquire(); - expect(puts).toEqual([ - { id: 'it_null', body: { channels: {} } }, - { id: 'it_missing', body: { channels: {} } }, - ]); + expect(api.state.get('it_request')?.disabled_at).toBeNull(); }); - it('still mutes on release when the reset throws', async () => { - const { fetchImpl, state, puts } = fakeTriggers({ - it_default: { type: 'delivery', channels: {} }, - }); - vi.stubGlobal('fetch', fetchImpl); - const source = new FixedProjectSource({ - apiKey: 'k', - snapshotPath: tempSnapshotPath(), + it('deletes a trigger a run added, keeping the oldest of its type', async () => { + const api = fakeTriggers({ + ...allPristine(), + it_agent: { + ...pristine('delivery', '2026-11-06T09:00:00.000Z'), + channels: { email: {} }, + }, }); - const lease = await source.acquire(); - state.set('it_default', { type: 'delivery', channels: { email: {} } }); - vi.stubGlobal( - 'fetch', - vi.fn(async (url: string | URL, init?: RequestInit) => - new URL(String(url)).pathname.includes('/connections') - ? new Response('boom', { status: 500 }) - : fetchImpl(url, init) - ) - ); + vi.stubGlobal('fetch', api.fetchImpl); + vi.spyOn(console, 'warn').mockImplementation(() => {}); - await source.release(lease); + await source().acquire(); - expect(puts).toEqual([{ id: 'it_default', body: { channels: {} } }]); + expect(api.writes).toEqual([{ method: 'DELETE', id: 'it_agent' }]); + expect(api.byType('delivery')).toHaveLength(1); }); - it('mutes a trigger recorded in the snapshot that a run gave a channel', async () => { - // In CI each checkout captures its own snapshot, so a trigger leaked by a - // run that died is recorded as pristine and never deleted. Muting is the - // only part of reset that still reaches it. + it('deletes a leftover even when a fresh snapshot recorded it as pristine', async () => { + // In CI every job captures its own snapshot, so a leftover is in it. const snapshotPath = tempSnapshotPath(); writeFileSync( snapshotPath, JSON.stringify({ capturedAt: '2026-11-06T00:00:00.000Z', - ids: { 'issue-triggers': ['it_leaked'] }, + ids: { + 'issue-triggers': [...Object.keys(allPristine()), 'it_leaked'], + }, }) ); - const { fetchImpl, puts } = fakeTriggers({ + const api = fakeTriggers({ + ...allPristine(), it_leaked: { - type: 'delivery', + ...pristine('delivery', '2026-08-20T00:00:00.000Z'), channels: { email: {}, slack: { channel_name: '#ops' } }, }, }); - vi.stubGlobal('fetch', fetchImpl); + vi.stubGlobal('fetch', api.fetchImpl); vi.spyOn(console, 'warn').mockImplementation(() => {}); - await new FixedProjectSource({ apiKey: 'k', snapshotPath }).acquire(); + await source(snapshotPath).acquire(); - expect(puts).toEqual([{ id: 'it_leaked', body: { channels: {} } }]); + expect(api.state.has('it_leaked')).toBe(false); }); - it('mutes a channel added during the lease on release', async () => { - const { fetchImpl, state, puts } = fakeTriggers({ - it_default: { type: 'delivery', channels: {} }, + it('mutes the defaults, including null or missing channels, which still email', async () => { + const api = fakeTriggers({ + it_delivery: { ...pristine('delivery'), channels: { email: {} } }, + it_transformation: { ...pristine('transformation'), channels: null }, + it_backpressure: (({ channels: _c, ...t }) => t)( + pristine('backpressure') + ), + it_request: pristine('request'), }); - vi.stubGlobal('fetch', fetchImpl); - const source = new FixedProjectSource({ - apiKey: 'k', - snapshotPath: tempSnapshotPath(), + vi.stubGlobal('fetch', api.fetchImpl); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await source().acquire(); + + for (const id of ['it_delivery', 'it_transformation', 'it_backpressure']) { + expect(api.state.get(id)?.channels).toEqual({}); + } + expect(api.writes.map((w) => w.id)).toEqual([ + 'it_delivery', + 'it_transformation', + 'it_backpressure', + ]); + }); + + it('restores on release what the agent did to a default, after it was scored', async () => { + // alerting-001: the agent gives the muted delivery default a channel. + const api = fakeTriggers(allPristine()); + vi.stubGlobal('fetch', api.fetchImpl); + const s = source(); + const lease = await s.acquire(); + api.state.set('it_delivery', { + ...pristine('delivery'), + channels: { email: {} }, }); - const lease = await source.acquire(); - // an agent repairs the default and gives it email, which alerting-001 scores - state.set('it_default', { type: 'delivery', channels: { email: {} } }); - await source.release(lease); + await s.release(lease); - expect(puts).toEqual([{ id: 'it_default', body: { channels: {} } }]); + expect(api.state.get('it_delivery')?.channels).toEqual({}); }); - it('does not fail an acquire when muting fails', async () => { - const { fetchImpl } = fakeTriggers({ - it_default: { type: 'delivery', channels: { email: {} } }, + it('still mutes on release when the reset throws', async () => { + const api = fakeTriggers(allPristine()); + vi.stubGlobal('fetch', api.fetchImpl); + const s = source(); + const lease = await s.acquire(); + api.state.set('it_delivery', { + ...pristine('delivery'), + channels: { email: {} }, }); vi.stubGlobal( 'fetch', vi.fn(async (url: string | URL, init?: RequestInit) => - init?.method === 'PUT' + new URL(String(url)).pathname.includes('/connections') ? new Response('boom', { status: 500 }) - : fetchImpl(url, init) + : api.fetchImpl(url, init) ) ); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - await expect( - new FixedProjectSource({ - apiKey: 'k', - snapshotPath: tempSnapshotPath(), - }).acquire() - ).resolves.toBeDefined(); - expect(warn).toHaveBeenCalledWith( - expect.stringContaining( - 'could not clear notification channels on acquire' + await s.release(lease); + + expect(api.state.get('it_delivery')?.channels).toEqual({}); + }); + + it('fails the acquire when the triggers cannot be reset', async () => { + // Before the agent runs nothing has been paid for, and alerting-001 started + // without its default would score as though it were valid. + const { it_delivery: _gone, ...rest } = allPristine(); + const api = fakeTriggers(rest); + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string | URL, init?: RequestInit) => + init?.method === 'POST' + ? new Response('boom', { status: 500 }) + : api.fetchImpl(url, init) ) ); + + await expect(source().acquire()).rejects.toThrow(/500/); + }); + + it('muteIssueTriggerNotifications skips only an empty object', async () => { + const api = fakeTriggers({ + it_quiet: pristine('delivery'), + it_null: { ...pristine('request'), channels: null }, + it_loud: { ...pristine('backpressure'), channels: { email: {} } }, + }); + vi.stubGlobal('fetch', api.fetchImpl); + + const muted = await muteIssueTriggerNotifications( + new HookdeckClient({ apiKey: 'k' }) + ); + + expect(muted).toEqual(['it_null', 'it_loud']); }); }); From df5c4de7209b19d62dfe69f63c729384cad487c0 Mon Sep 17 00:00:00 2001 From: Phil Leggetter Date: Fri, 6 Nov 2026 15:40:59 +0000 Subject: [PATCH 2/2] Test the oldest-wins sort, and warn on undeclared trigger types From review of #118. The API lists triggers newest first and every fixture listed the oldest first, so removing the sort passed every test; a fixture now lists them newest first, and fails without it. A trigger type DEFAULT_ISSUE_TRIGGERS does not declare is most likely a new default, which an id snapshot would have kept; the reset now warns when it deletes one. The Outpost guard's live-id path gets a test, and its warning and AGENTS.md say "snapshot or live state". README no longer says triggers stay as they were. Timestamps compare with < rather than localeCompare. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- README.md | 5 +- packages/hookdeck/src/project-source.ts | 29 +++++-- packages/hookdeck/test/project-source.test.ts | 79 ++++++++++++++++++- 4 files changed, 104 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d65ca41..52531a5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1163,8 +1163,8 @@ connections instead of changing the Outpost destination's topics. The filter carried into the cell's next two attempts, because nothing reset that side. `FixedProjectSource` now deletes every gateway resource in the Outpost project on every acquire, for every scenario, before the seed, and again on release. It -refuses if the Outpost key can see anything in the gateway project's snapshot, -because that means both keys reach one project. So `OUTPOST_API_KEY` must +refuses if the Outpost key can see anything in the gateway project's snapshot +or live state, because that means both keys reach one project. So `OUTPOST_API_KEY` must belong to a dedicated project, and a gateway API error on that key now fails the acquire of every cell, Event Gateway scenarios included. diff --git a/README.md b/README.md index 22a6440..2f8d473 100644 --- a/README.md +++ b/README.md @@ -234,8 +234,9 @@ rewrites one a run changed, which a snapshot of ids cannot do. **Every reset turns issue trigger notifications off.** Those default triggers email every member of the organization, and scenarios fail deliveries, requests and transformations on purpose, so left alone they email the team about failures a run caused deliberately. -Each acquire and release sets `channels: {}` on every issue trigger in the project. The -triggers stay enabled and scoped as they were, so issues still open; nobody is told. +Each acquire and release resets the project to the four default triggers, enabled and +wildcard-scoped as a new project has them, but with `channels: {}`, so issues still open +and nobody is told. Anything that creates or hands out a project calls `muteIssueTriggerNotifications`. **Scope scorer queries to `ctx.acquiredAt`.** Events and requests cannot be deleted diff --git a/packages/hookdeck/src/project-source.ts b/packages/hookdeck/src/project-source.ts index 7e9539f..efd9c79 100644 --- a/packages/hookdeck/src/project-source.ts +++ b/packages/hookdeck/src/project-source.ts @@ -124,7 +124,9 @@ export async function muteIssueTriggerNotifications( * **Except issue triggers, which are declared rather than captured.** See * `DEFAULT_ISSUE_TRIGGERS`. Their ids are still recorded here, because the * Outpost gateway reset uses every recorded id to tell the two projects apart, - * but the gateway project's reset no longer reads them. + * but the gateway project's reset no longer reads them. So a new default + * *trigger* type is not protected without a code change: the reset deletes it + * and warns, naming `DEFAULT_ISSUE_TRIGGERS` as where to add it. */ export interface PristineSnapshot { capturedAt: string; @@ -242,17 +244,32 @@ export async function resetIssueTriggersToDefaults( const existing = await client.list('issue-triggers'); const kept = new Map(); for (const declared of DEFAULT_ISSUE_TRIGGERS) { + // The API lists newest first, so this sort is load-bearing: without it the + // reset keeps the trigger a run just made and deletes the default. const oldest = existing .filter((t) => t.type === declared.type) - .sort((a, b) => - String(a.created_at ?? '').localeCompare(String(b.created_at ?? '')) - )[0]; + .sort((a, b) => { + const x = String(a.created_at ?? ''); + const y = String(b.created_at ?? ''); + return x < y ? -1 : x > y ? 1 : 0; + })[0]; if (oldest) kept.set(declared.type, oldest); } const keepIds = new Set([...kept.values()].map((t) => t.id)); + const declaredTypes = new Set(DEFAULT_ISSUE_TRIGGERS.map((d) => d.type)); for (const trigger of existing) { if (keepIds.has(trigger.id)) continue; + if (!declaredTypes.has(String(trigger.type))) { + // Every run makes delivery triggers, and none makes another type, so an + // unknown type is most likely a default Hookdeck has started shipping. + // An id snapshot would have kept it; a declared list deletes it, so say + // so loudly rather than let it vanish as an ordinary leftover. + console.warn( + `issue triggers: deleting ${trigger.id}, of type ${String(trigger.type)}, which ` + + 'DEFAULT_ISSUE_TRIGGERS does not declare. If new projects now ship with it, add it there.' + ); + } await client.delete('issue-triggers', trigger.id); onChange?.({ action: 'deleted', @@ -909,8 +926,8 @@ export class FixedProjectSource implements ProjectSource { if (shared.length > 0) { console.warn( `outpost project gateway reset: skipped, because OUTPOST_API_KEY can see ${kind} ` + - `${shared.map((r) => r.id).join(', ')} from the gateway project's pristine ` + - 'snapshot. The two keys appear to belong to one project, and resetting it ' + + `${shared.map((r) => r.id).join(', ')} from the gateway project's snapshot ` + + 'or live state. The two keys appear to belong to one project, and resetting it ' + "to the Outpost baseline would delete that project's defaults." ); return; diff --git a/packages/hookdeck/test/project-source.test.ts b/packages/hookdeck/test/project-source.test.ts index f4a1d10..7c46557 100644 --- a/packages/hookdeck/test/project-source.test.ts +++ b/packages/hookdeck/test/project-source.test.ts @@ -408,7 +408,12 @@ describe('FixedProjectSource Outpost project gateway reset', () => { const GATEWAY_KEY = 'gateway-key'; const OUTPOST_KEY = 'outpost-key'; - function fakeTwoProjects(projects: Record>) { + function fakeTwoProjects( + projects: Record>, + /** Keys that reach another key's project: two keys, one project. */ + aliases: Record = {} + ) { + let created = 0; const state = new Map>>(); for (const [key, kinds] of Object.entries(projects)) { const byKind = new Map>(); @@ -429,12 +434,20 @@ describe('FixedProjectSource Outpost project gateway reset', () => { } return new Response(JSON.stringify({ models: [] }), { status: 200 }); } - const key = String( + const bearer = String( (init?.headers as Record | undefined)?.Authorization ).replace(/^Bearer /, ''); + const key = aliases[bearer] ?? bearer; const project = state.get(key) ?? new Map>(); state.set(key, project); const [, kind, id] = u.pathname.replace(/^\/[^/]+/, '').split('/'); + if (init?.method === 'POST') { + const newId = `${kind}_created_${created++}`; + const ids = project.get(kind) ?? new Set(); + project.set(kind, ids); + ids.add(newId); + return new Response(JSON.stringify({ id: newId }), { status: 200 }); + } if ((init?.method ?? 'GET') === 'DELETE') { project.get(kind)?.delete(id); deleted.push({ key, kind, id }); @@ -582,6 +595,27 @@ describe('FixedProjectSource Outpost project gateway reset', () => { expect(warn.mock.calls.flat().join('\n')).toContain('skipped'); }); + it('still refuses when the only shared resources are triggers the reset just recreated', async () => { + // Restored triggers get ids a persisted snapshot does not have, so a guard + // reading the snapshot alone would see nothing shared and delete them. + const snapshotPath = tempSnapshotPath(); + writeFileSync( + snapshotPath, + JSON.stringify({ capturedAt: '2026-08-07T00:00:00.000Z', ids: {} }) + ); + const api = fakeTwoProjects( + { [GATEWAY_KEY]: {} }, + { [OUTPOST_KEY]: GATEWAY_KEY } + ); + vi.stubGlobal('fetch', api.fetchImpl); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await source(snapshotPath).acquire(); + + expect(warn.mock.calls.flat().join('\n')).toContain('skipped'); + expect(api.ids(GATEWAY_KEY, 'issue-triggers')).toHaveLength(4); + }); + it('does nothing extra when both keys are the same', async () => { const api = fakeTwoProjects({ [GATEWAY_KEY]: { sources: ['src_gateway'] }, @@ -596,7 +630,9 @@ describe('FixedProjectSource Outpost project gateway reset', () => { const lease = await s.acquire(); await s.release(lease); - expect(api.deleted).toEqual([]); + // Issue triggers are reset to declared defaults on every lease, which this + // fake cannot type; that has its own suite below. + expect(api.deleted.filter((d) => d.kind !== 'issue-triggers')).toEqual([]); expect(api.ids(GATEWAY_KEY, 'sources')).toEqual(['src_gateway']); }); @@ -846,6 +882,43 @@ describe('FixedProjectSource issue triggers', () => { expect(api.byType('delivery')).toHaveLength(1); }); + it('keeps the oldest when the API lists newest first, as it does', async () => { + const { it_delivery, ...rest } = allPristine(); + const api = fakeTriggers({ + it_agent: { + ...pristine('delivery', '2026-11-06T09:00:00.000Z'), + channels: { email: {} }, + }, + it_delivery, + ...rest, + }); + vi.stubGlobal('fetch', api.fetchImpl); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await source().acquire(); + + expect(api.state.has('it_delivery')).toBe(true); + expect(api.state.has('it_agent')).toBe(false); + }); + + it('warns when it deletes a trigger type it does not declare', async () => { + // Most likely a default Hookdeck has started shipping, which an id + // snapshot would have kept. + const api = fakeTriggers({ + ...allPristine(), + it_future: { type: 'something_new', channels: {}, created_at: 'x' }, + }); + vi.stubGlobal('fetch', api.fetchImpl); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await source().acquire(); + + expect(api.state.has('it_future')).toBe(false); + expect(warn.mock.calls.flat().join('\n')).toContain( + 'of type something_new, which DEFAULT_ISSUE_TRIGGERS does not declare' + ); + }); + it('deletes a leftover even when a fresh snapshot recorded it as pristine', async () => { // In CI every job captures its own snapshot, so a leftover is in it. const snapshotPath = tempSnapshotPath();