Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/GITHUB_RELEASE_WEBHOOK_PLAN.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# GitHub Release Webhook Plan

The dated phase records below describe the configuration deployed at each
milestone. For the current Mail/cleanup/reconciliation schedules, use
[Worker operations](../worker/README.md) and
[`worker/wrangler.jsonc`](../worker/wrangler.jsonc).

## Status

**Stage:** Phase E activated and first real stable publish observed
Expand Down Expand Up @@ -57,7 +62,7 @@ webhook, redelivery, recon, and rollback.
- Gates: `npm run check`, `npm test` (108 + 1 D1), `npm run build` on
`origin/main` before deploy.
- Secret: `GITHUB_WEBHOOK_SECRET` installed via Wrangler (not in git/Actions).
- Deploy: Worker version `52d03e76-b69a-42c8-9d63-bcb6316e33f3` on
- Deploy (2026-07-29 configuration): Worker version `52d03e76-b69a-42c8-9d63-bcb6316e33f3` on
`pegma.dev/api/*` with crons `* * * * *` and `0 */6 * * *`.
- Smoke: operator signed `ping` → 204; unsigned POST → 401; health
`githubReleases.ingestionConfigured=true`; `GET /api/releases` schema
Expand Down
11 changes: 8 additions & 3 deletions docs/SUPPORT_COMPOSITION.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,8 @@ Durable rate-limit policies (separate from Identity):
- `pegma.admin.role.mutate` (assign / revoke, 30/h per operator)
- `pegma.admin.principal.lookup` (directory lookups, 120/h per operator)

All four are swept by the same scheduled maintenance run.
All four are swept by the same rotating cleanup schedule, one policy per
invocation.

## Site pages

Expand All @@ -198,8 +199,12 @@ All four are swept by the same scheduled maintenance run.

Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
## Maintenance and health

Minute cron runs Support Desk queue repair and inactive projection sweep with
independent cursors, plus Support Desk rate-limit sweeps. Mail send for support
The separate cleanup cron (`1-59 * * * *`) runs one rotating task per
invocation, including Support Desk queue repair, inactive projection sweep,
and each Support/Admin rate-limit policy. Each task runs every 14–15 minutes,
with independent queue cursors and no writes for unchanged bookmarks.
Identity Mail send/reconciliation keeps its own one-minute invocation.
Mail send for support
notifications is deferred (templates are defined; create/reply/staff reply omit
notification for this host surface).

Expand Down
6 changes: 6 additions & 0 deletions docs/securityscan.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
Point-in-time security review per the `security-scan` skill. Date: 2026-07-29.
Read-only review; this report is the only file created.

Schedule descriptions below record the configuration reviewed on that date.
For the current Mail and rotating cleanup schedule, see
[Worker maintenance](../worker/README.md#identity-composition) and
[`worker/wrangler.jsonc`](../worker/wrangler.jsonc). This note does not update
or rerun the historical security assessment.

## Phase 0 — Recon

### Stack
Expand Down
43 changes: 36 additions & 7 deletions worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,31 @@ Passkey removal stays disabled until an email-code recovery implementation is
live. This deliberately avoids a last-factor lockout in the passkey-only
configuration.

The one-minute Cron trigger advances independently persisted cursors for
challenge, email-operation, Mail send, Mail reconciliation, and terminal
retention scans. It also purges expired Sessions and sweeps all four durable
rate-limit policies. Replaying a cursor after a crash is safe because claims
and deletions are conditional. Dead-letter and terminal-unknown Mail remains
The one-minute Cron trigger runs Mail send and reconciliation only. A separate
`1-59 * * * *` trigger runs one cleanup lane per invocation: challenge cleanup,
email-operation repair, Mail retention, expired Sessions, each of the four
Identity rate-limit policies, Support queue repair/inactive sweep, and each of
the four Support/Admin rate-limit policies. The 14 lanes rotate using the
scheduled UTC time, including across hour boundaries, so each runs every
14–15 minutes. This gives cleanup its own invocation CPU budget instead of
combining every task under the Workers Free 10 ms limit. Authentication and
rate-limit checks still enforce expiry on access; cleanup only reclaims or
repairs stored data.

Each run reads its cursor record once, merges successful lane results into a
single conditional update, and skips unchanged cursors (including empty
pages). Identity and Support retain independent collections and bookmarks.
The D1 adapter retries conditional updates up to three times, re-reading the
current record before merging the changed fields, including when Mail and
cleanup invocations overlap. Cursor-save failures are logged as
`identity.maintenance_failed` or `support.maintenance_failed` with task
`cursors`; the next invocation replays the page from its prior bookmark.
These bookmarks optimize scans rather than commit domain work: Mail leases,
provider idempotency keys, receipts, and conditional cleanup writes remain
durable independently of the cursor save.
Routine per-lane success logs are omitted; invocation logs and error/terminal
Mail logs remain enabled. Replaying a cursor after a crash is safe because
claims and deletions are conditional. Dead-letter and terminal-unknown Mail remains
in D1 for operator inspection until explicitly acknowledged. Email delivery
must remain disabled until the host also has an authenticated, audited
operator acknowledgement workflow; this Worker intentionally exposes no
Expand All @@ -179,7 +199,7 @@ via AccessContext defaults (not a paid entitlement). Categories:
marker: `[PEG-…]`. Tracking pages: `/feedback` and `/feedback/{ticketId}`.

Create and reply use durable rate limits `pegma.support.ticket.create` and
`pegma.support.ticket.reply`. Minute maintenance runs queue repair and
`pegma.support.ticket.reply`. Rotating cleanup runs queue repair and
inactive projection sweep with independent cursors. Notifications on
create/reply are omitted in this slice; Pegma templates are composed for a
later mail activation. Health lists Support Desk package detail without
Expand Down Expand Up @@ -240,11 +260,20 @@ webhook secret in the same maintenance window.
`GITHUB_ALLOWED_REPOSITORY_IDS` (comma-separated numeric IDs). Names are display
data only; IDs are the allowlist authority.

**Schedules:** `* * * * *` runs Identity maintenance only. `0 */6 * * *` runs
**Schedules:** `* * * * *` runs Identity Mail send/reconciliation.
`1-59 * * * *` runs one rotating Identity or Support cleanup lane.
`0 */6 * * *` runs
GitHub release reconciliation only (public `/repos/{owner}/{repo}/releases/latest`
with conditional ETags, bounded timeouts/bodies). Reconciliation is also the
initial backfill path; it never fabricates `@pegma/webhooks` receipt rows.

After deploying maintenance changes, check invocation CPU times and outcomes
for both mail and cleanup triggers in Workers Observability. Local D1 tests
verify cursor writes and dispatch, but do not enforce Cloudflare's production
CPU limit. A busy mail page or large cleanup page can still require smaller
pages or Workers Paid; reducing cron frequency alone does not raise the
per-invocation allowance.

**Organization webhook (Phase E):** create one org webhook subscribed only to
`release` events, payload URL `https://pegma.dev/api/webhooks/github/releases`,
content type `application/json`, secret matching the Worker secret. Verify
Expand Down
160 changes: 160 additions & 0 deletions worker/src/identity-maintenance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,166 @@ function fixture() {
}

describe('Identity maintenance', () => {
it('does no bookmark I/O or failure logging when only disabled mail tasks are selected', async () => {
const value = fixture();
const collection = vi.spyOn(value.runtime.store, 'collection');
await runIdentityMaintenance(
{ ...value.runtime, mailWorker: null },
value.logger,
{
tasks: ['mail_send', 'mail_reconcile', 'mail_retention'],
},
);
expect(collection).not.toHaveBeenCalled();
expect(value.logger.log).not.toHaveBeenCalled();
expect(value.sendPage).not.toHaveBeenCalled();
expect(value.reconciliationPage).not.toHaveBeenCalled();
expect(value.mailSweep).not.toHaveBeenCalled();
});

it('logs an invalid limiter selection instead of silently skipping cleanup', async () => {
const value = fixture();
await runIdentityMaintenance(value.runtime, value.logger, {
tasks: ['rate_limits'],
limiterIndex: 1,
});
expect(value.limiterSweep).not.toHaveBeenCalled();
expect(value.logger.log).toHaveBeenCalledExactlyOnceWith(
'error',
'identity.maintenance_failed',
{ task: 'rate_limits', error: 'RangeError' },
);
});

it('identifies cursor-save failures and replays from the prior durable bookmark', async () => {
const value = fixture();
const collection = value.runtime.store.collection;
let fail = true;
vi.spyOn(value.runtime.store, 'collection').mockImplementation(
(definition) => {
const target = collection(definition);
return {
...target,
update: (...args) => {
if (fail)
return Promise.reject(new Error('cursor write unavailable'));
return target.update(...args);
},
};
},
);
await runIdentityMaintenance(value.runtime, value.logger, {
tasks: ['mail_send'],
});
expect(value.logger.log).toHaveBeenCalledWith(
'error',
'identity.maintenance_failed',
{ task: 'cursors', error: 'Error' },
);
fail = false;
await runIdentityMaintenance(value.runtime, value.logger, {
tasks: ['mail_send'],
});
expect(value.sendPage).toHaveBeenNthCalledWith(2, { limit: 5 });
await runIdentityMaintenance(value.runtime, value.logger, {
tasks: ['mail_send'],
});
expect(value.sendPage).toHaveBeenNthCalledWith(3, {
limit: 5,
cursor: 'send-next',
});
});

it('still runs cursor-independent hygiene if the bookmark read fails', async () => {
const value = fixture();
const collection = value.runtime.store.collection;
vi.spyOn(value.runtime.store, 'collection').mockImplementation(
(definition) => {
const target = collection(definition);
return definition.name === 'pegma-dev-maintenance'
? {
...target,
get: async () => {
throw new Error('bookmark unavailable');
},
}
: target;
},
);
await runIdentityMaintenance(value.runtime, value.logger);
expect(value.limiterSweep).toHaveBeenCalledTimes(1);
expect(value.purgeExpired).toHaveBeenCalledTimes(1);
expect(value.challengeSweep).not.toHaveBeenCalled();
expect(value.logger.log).toHaveBeenCalledWith(
'error',
'identity.maintenance_failed',
{ task: 'challenges', error: 'Error' },
);
});

it('runs only mail on the minute path and does not write idle cursors', async () => {
const value = fixture();
value.sendPage.mockResolvedValue({
examined: 0,
results: [],
nextCursor: null,
});
value.reconciliationPage.mockResolvedValue({
examined: 0,
results: [],
nextCursor: null,
});
const collection = value.runtime.store.collection;
const writes = vi.fn();
const reads = vi.fn();
vi.spyOn(value.runtime.store, 'collection').mockImplementation(
(definition) => {
const target = collection(definition);
return {
...target,
get: (...args) => {
reads();
return target.get(...args);
},
update: (...args) => {
writes();
return target.update(...args);
},
};
},
);

await runIdentityMaintenance(value.runtime, value.logger, {
tasks: ['mail_send', 'mail_reconcile'],
});

expect(reads).toHaveBeenCalledTimes(1);
expect(writes).not.toHaveBeenCalled();
expect(value.sendPage).toHaveBeenCalledTimes(1);
expect(value.reconciliationPage).toHaveBeenCalledTimes(1);
expect(value.challengeSweep).not.toHaveBeenCalled();
expect(value.operationSweep).not.toHaveBeenCalled();
expect(value.mailSweep).not.toHaveBeenCalled();
expect(value.limiterSweep).not.toHaveBeenCalled();
expect(value.purgeExpired).not.toHaveBeenCalled();
expect(value.logger.log).not.toHaveBeenCalled();
});

it('sweeps just the selected rate-limit policy', async () => {
const value = fixture();
const other = {
...value.runtime.limiters[0]!,
sweep: vi.fn(async () => ({ scanned: 0, deleted: 0 })),
};
await runIdentityMaintenance(
{ ...value.runtime, limiters: [...value.runtime.limiters, other] },
value.logger,
{ tasks: ['rate_limits'], limiterIndex: 1 },
);
expect(value.limiterSweep).not.toHaveBeenCalled();
expect(other.sweep).toHaveBeenCalledTimes(1);
});

it('persists independent cursors and runs every hygiene lane', async () => {
const value = fixture();

Expand Down
Loading
Loading