aemerson-commits/shareable-skills/worker-build
Claude Code and agent skill by aemerson-commits/shareable-skills
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
Factory for building Cloudflare Workers — email reporters, cron jobs, API monitors. Parallel agents: scaffold, admin UI, secrets config, deploy + verify.
Install
npx vskill@latest install aemerson-commits/shareable-skills/worker-buildSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as aemerson-commits/shareable-skills/worker-build.
Worker Build — Cloudflare Worker Factory
Templated pipeline for building new Cloudflare Workers. Most workers follow the same pattern: cron-triggered, email delivery, KV recipient lists, admin UI in a settings panel, Bearer token auth on HTTP endpoints.
Arguments
- First argument (required): Worker name (e.g., "inventory-report", "shipping-alert")
--type=email|monitor|sync(default: email)email: Cron-triggered email report (JWT email delivery, recipients, admin UI)monitor: API polling + alert on change (KV state tracking, threshold alerts)sync: Data synchronization (source → KV/D1, reconciliation)--cron=<schedule>(e.g., "0 12 MON-FRI" for 8am ET weekdays during EDT)
Phase 0: Scope (Main Agent)
- Verify worker name is unique: check
workers/directory - Determine type and cron schedule
- Read existing worker of same type for reference pattern
Phase 1: Parallel Build (3 Agents, model: "sonnet")
Pattern: Fan-Out/Fan-In. All use isolation: "worktree".
Agent: Worker Scaffold (worktree)
Create the worker directory and core files:
`workers/{name}/wrangler.toml`:
`workers/{name}/package.json`:
`workers/{name}/src/index.js`: Must include:
- Bearer token auth (timing-safe HMAC via
crypto.subtle) for all HTTP endpoints scheduled(event, env, ctx)handler for cronfetch(request, env, ctx)handler with/run,/preview,/statusendpoints- Email JWT flow (RS256) for email type
- KV recipient list read (
{name}-recipientskey) - HTML email builder with
escapeHtml()for any user data - Worker alert integration (KV success/error tracking)
- Error handling with try/catch on cron, report errors to KV
Timezone rules for M-F cron workers:
- Cron schedules in
wrangler.tomlare UTC:"0 12 * * MON-FRI"= 8am EDT / 7am EST - DST: EDT (Mar-Nov) uses
0 12, EST (Nov-Mar) uses0 13. Pick one based on current date or accept the shift. - If the worker code checks "is today a weekday?" (e.g. for weekend-skip logic), MUST use local day, not UTC:
```js // CORRECT — local day handles Fri evening without silently skipping as "weekend" const localDay = new Date().toLocaleDateString('en-US', { timeZone: 'America/New_York', weekday: 'short' }) const isWeekend = localDay === 'Sat' || localDay === 'Sun'
// WRONG — at Fri 8pm ET = Sat 00:00 UTC, this flips to weekend and masks Friday failures const utcDay = new Date().getUTCDay() const isWeekend = utcDay === 0 || utcDay === 6 ```
- Never use `.split('T')[0]` to extract a day from an ISO string when comparing to a local
todayStr. Z-suffixed times yield the UTC day, not the local day. Use local components instead:${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}.
Agent: Admin UI Builder (worktree)
Add recipient management to admin settings:
- Create admin endpoint — KV-backed CRUD for email recipients (copy pattern from existing recipient endpoints)
- Add to settings UI: new section with recipient list + add/remove UI
- Add worker to worker health monitoring array
Agent: Deploy Config (worktree)
Prepare deployment:
- Document required secrets (list them, don't set them)
- Add to cron monitoring if cron-triggered
Phase 2: Integration (Main Agent)
- Merge all 3 worktrees
- Verify no import conflicts
- Build admin project (admin UI changes)
- Generate the secrets setup commands:
``bash npx wrangler secret put EMAIL_SERVICE_ACCOUNT --name={name} npx wrangler secret put EMAIL_PRIVATE_KEY --name={name} npx wrangler secret put EMAIL_SENDER --name={name} npx wrangler secret put WORKER_AUTH_TOKEN --name={name} # CRITICAL: secret put creates a deployment with stale code — MUST redeploy after npx wrangler deploy ``
Phase 3: Verification (2 Agents, model: "opus")
Agent: Code Reviewer
- Verify Bearer auth on ALL HTTP endpoints (timing-safe HMAC, not string comparison)
- Verify email JWT flow matches shared pattern
- Verify error responses don't leak
err.message - Verify cron handler has try/catch with error logging
- Verify
escapeHtml()on all user data in HTML email
Agent: Build Verifier
- Build admin project (lint + build)
- Verify wrangler.toml has correct KV binding ID
- Verify package.json is minimal (no unnecessary deps)
Phase 4: Report
Syntax-check before commit/deploy
Chain node --check before any commit or deploy of worker source:
Catches syntax errors that would otherwise fail silently post-deploy (worker stays on last good build, but the next cron fails).
Email HTML iteration pattern (shared)
Email-reporter workers expose /run?preview=1 (or similar) that returns the rendered HTML without sending. Iteration loop:
Faster than sending test emails and digging through the inbox.
Cron Trigger Verification (MANDATORY after any wrangler deploy or redeploy)
CAVEAT: Numeric DOW is silently broken — the PUT [] / PUT [{cron}] heal is INSUFFICIENTSymptom: A cron with any numeric day-of-week — range (1-5) or single day (1,2) — can appear correctly registered inGET /schedules(right cron string, freshmodified_on) yet silently never fire. The wipe-then-readdPUT [] / PUT [{cron}]cycle described below advancesmodified_onbut does NOT restart the trigger. The worker stays dead.Root cause: CF's cron dispatcher silently discards numeric DOW at the internal scheduling layer. Only a syntactically-different cron string causes the dispatcher to re-parse and clear the stuck state.The only confirmed heal: change the literal cron string to use named days —MON-FRIinstead of1-5,MONinstead of1,TUEinstead of2— then run the wipe-then-readd cycle with the renamed string.Exception: workers that branch onevent.cronstring-equality must keep the numeric literal that matches their code. Fix the equality branch in source first, then rewrite the cron string.Rule for new workers: never use numeric DOW. Always writeMON-FRI,MON,TUE, etc.
Wrangler's `Deployed {name} triggers` output lies. The message prints regardless of whether CF actually advanced the trigger registration. Silent cron failures are a real recurring pattern — triggers appear registered but never fire because wrangler no-ops when the cron string matches what CF already has stored.
The Cloudflare API is the source of truth. After every wrangler deploy of a cron worker:
GOTCHA: Wrangler OAuth token expires ~2h. Mid-session deploys may fail with AuthenticationError [code: 10000] if the token aged out. If you see this error, run npx wrangler login to refresh — the token location varies by OS (check wrangler's config directory). Do not retry the deploy until re-authenticated.
Getting a CF API token for direct schedule calls
When the environment CF_API_TOKEN is unavailable or rejected, extract wrangler's OAuth token:
Expires ~2h. On AuthenticationError [code: 10000], run wrangler login to refresh.
Verify two things:
- Schedules match wrangler.toml exactly.
modified_on>= deploy time. Ifmodified_onis older than the deploy, the trigger did NOT re-register — wrangler silently no-op'd because the cron string matched the current CF state. This is a landmine: an already-broken trigger (stuck non-firing) stays broken through redeploys.
Remedy when `modified_on` is stale: force re-registration with a wipe-then-readd PUT cycle (plain redeploy won't work):
After the PUT, modified_on and created_on both advance to the current time. This is the only way to heal a silently-stuck trigger registration.
Trigger re-registration is required whenever:
- You ran
wrangler secret putwithout a follow-up redeploy (known footgun) - You commented out
[triggers]and redeployed (wrangler does NOT unregister; need PUT[]) - A cron monitoring alert fires for a worker whose
wrangler deployjust ran "successfully"
Post-deploy verification: after PUT, the definitive evidence the trigger fires is a fresh success KV entry on the next scheduled run. Don't assume success from wrangler output alone.
Bug-Class Sweep
After fixing a bug in one worker, grep workers/*/ for the same pattern class before committing — workers copy-paste shared logic and bugs propagate silently.
Common classes to sweep:
| Class | What to grep | ||
|---|---|---|---|
| Em-dash in email subjects | `grep -rn "—\ | –" workers/*/src/` (non-ASCII dashes) | |
| TTL math | grep for the specific constant or formula you just fixed | ||
btoa() newline handling | grep -rn "btoa" workers/*/src/ | ||
trackSuccess params | grep -rn "trackSuccess" workers/*/src/ — verify all call sites pass the same shape | ||
| Bearer auth pattern | grep -rn "Authorization" workers/*/src/ — timing-safe HMAC everywhere |
Also check any shared utility module imported by most workers — a bug there propagates to all of them simultaneously.
Fix all affected workers in one pass, in the same commit. Don't defer to follow-up commits — they consistently don't happen.
A Worker Deploy IS a Production Release
Unlike paired dev/prod Pages-style projects, an edge worker is typically a single deployment: wrangler deploy (or equivalent) from any branch and any working tree puts that code straight into production. Two consequences:
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 90 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/worker-build/SKILL.md
Popularity
- Repository stars
- 1
- 7-day trend score
- 3
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/aemerson-commits/shareable-skills/worker-build)