operational-gotchas
Skill2 starsChanged 8 months agoMITView on GitHub
Twilio development skill: operational-gotchas
- Reads credentials
In this repository66 other files it gives its agents.
- adversarial-reviewSkill
- agent-connectSkill
- agent-teams-guideSkill
- agent-testingSkill
- android-sdkSkill
- brainstormSkill
- branded-callingSkill
- callbacksSkill
- compliance-regulatorySkill
- conferenceSkill
- context-engineeringSkill
- context-hubSkill
- conversational-intelligenceSkill
- conversation-relay-referenceSkill
- conversation-relaySkill
- conversationrelaySkill
- conversations-v2Skill
- customer-memorySkill
- deepgramSkill
- deep-validationSkill
- elastic-sip-trunkingSkill
- env-doctorSkill
- event-streamsSkill
- getting-startedSkill
- hooks-referenceSkill
- iamSkill
- ios-sdkSkill
- ivr-crawlerSkill
- ivr-migratorSkill
- lookupSkill
- media-streamsSkill
- memory-systemsSkill
- messaging-services-referenceSkill
- messaging-servicesSkill
- messagingSkill
- multi-agent-patternsSkill
- paymentsSkill
- paySkill
- phone-numbersSkill
- proxySkill
- real-time-transcriptionSkill
- recordingsSkill
- segmentSkill
- sendgrid-emailSkill
- sip-byocSkill
- sipSkill
- sync-referenceSkill
- syncSkill
- taskrouter-referenceSkill
- taskrouterSkill
- tdd-workflowSkill
- tool-boundariesSkill
- twilio-cliSkill
- twilio-invariantsSkill
- verify-referenceSkill
- verifySkill
- video-patternsSkill
- videoSkill
- voice-insightsSkill
- voice-referenceSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 160
Detection: Use validate_environment() MCP tool at session start.
- Very specific: line 162
Prevention: After switching accounts (twilio profiles:use), re-run npm run setup or ./scripts/bootstrap.sh to re-provision resources.
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Operational Gotchas
Cross-cutting gotchas discovered through real debugging sessions. Domain-specific gotchas live in their respective CLAUDE.md files; these are the ones that span multiple domains or have no single home.
SIP Connectivity Taxonomy
- SIP Interface ≠ Elastic SIP Trunking — These are distinct products. SIP Interface (also called SIP Domains, Programmable SIP) connects SIP infrastructure to Programmable Voice with full TwiML/API access. Elastic SIP Trunking is a pure PSTN conduit that bypasses PV entirely. BYOC is a type of SIP Interface for non-ported carrier numbers. The decision is: need TwiML? → SIP Interface. Just need cheap PSTN pipe? → Elastic SIP Trunking.
- IP ACLs and Credential Lists are account-level resources — They are NOT subresources of trunks or domains. They can be shared between SIP Domains and SIP Trunks. Up to 1000 of each per account.
- SIP Registration is SIP Interface only — Elastic SIP Trunking is INVITE-only. No registration required or supported. SIP Registration is for PV SIP use cases (agent desk phones, softphone apps).
- Phone number can only be trunk OR PV, not both — Assigning a number to a SIP trunk removes its voice webhook. They are mutually exclusive on a per-number basis. SIP Interface and Elastic SIP Trunking can coexist on the same account for different numbers.
CLI Profile and .env Independence
- CLI profile and
.envare independent auth sources — The Twilio CLI profile can point to the main account while.envhas a subaccount SID, or vice versa. They do not share state. Always check both before operations:twilio profiles:listfor CLI context, and.envcontents for SDK/serverless context. Deploying with one profile while.envtargets a different account causes silent misrouting.
Testing
- Coverage summary JSON is cached —
pre-bash-validate.shreadscoverage/coverage-summary.jsonand considers it fresh if newer thanpackage.json. After adding test files, must regenerate:npx jest --coverage --coverageReporters=json-summary. jest.doMockfor Runtime.getFunctions() — Callback handlers useRuntime.getFunctions()at require-time. Usejest.doMock(path, factory)+jest.resetModules()inbeforeEach(), notjest.mock()(which hoists before variable assignments).toContainEqualfor asymmetric matchers in arrays —toContain(expect.stringContaining())uses===reference equality. UsetoContainEqual()for deep equality with asymmetric matchers.- Newman E2E needs local server —
npm run test:e2ehitslocalhost:3000. Startnpm start(twilio-run) first. Use--timeout-request 5000to avoid hangs. <Start><Recording>hangs twilio-run locally — Functions usingtwiml.start().recording()hang indefinitely on the local dev server and never return a response. Affected: ivr-welcome, notification-outbound, outbound-customer-leg, sales-dialer-prospect, call-tracking-inbound, contact-center-welcome. Works fine deployed. E2E tests exclude these for local runs; usenpm run test:e2e:deployedfor full coverage.
Serverless Runtime
- Twilio Functions have no built-in scheduler — Functions are stateless HTTP handlers triggered by webhooks or direct HTTP calls. They cannot run on a cron/timer. For scheduled execution, use an external cron service (GitHub Actions, EasyCron, AWS EventBridge) that calls the Function's HTTP endpoint. Studio Flows with scheduled triggers are an alternative within the Twilio ecosystem. Do not use
setInterval()or cron libraries inside a Function — they won't persist between invocations. .protected.jsdoesn't work with external cron callers — Protected functions validate Twilio request signatures, which external cron services cannot provide. For cron-triggered functions, use a public.jsendpoint with a shared-secret query parameter checked in the handler.
Deployment
services.jsononly supports single-level directory names: Usingvoice/orangeas a directory entry fails because the deploy script can't create nested symlinks. Use flat names likeorange→ ``.- Twilio Serverless env var context limit is 3583 bytes: The deploy script auto-filters to only vars referenced via
context.VAR_NAMEin each service's functions. To fix an already over-limit service: delete the service and re-deploy fresh —--override-existing-projectchecks the EXISTING service's context first and rejects before applying the new deploy. - macOS
grep -R --includedoes NOT follow symlinks: The deploy build dir uses symlinks to source directories.grep -Rsilently returns empty results. Usefind -L ... -exec grepinstead. - CLI
--valueflag double-escapes JSON strings —twilio api:...:variables:create --value '{"k":"v"}'stores escaped JSON. Use.envfile + redeploy instead for JSON env vars. - Inbound leg CallSid differs from outbound API call SID — When initiating outbound to a tracking number, the function sees a different CallSid (inbound child). Sync docs keyed by inbound SID, recordings on outbound SID.
- TwiML App voice URL drifts after redeployment — The Serverless Toolkit can change the deployment domain between deploys (e.g.
prototype-2504-dev.twil.io→prototype-1483-dev.twil.io). The TwiML App SID (TWILIO_VOICE_SDK_APP_SID) stores an absolute voice URL that does NOT auto-update when the domain changes. This causes Voice SDK error 21005 (HTTP connection failure) because the TwiML App points to the old dead domain. After everytwilio serverless:deploy, verify and update the TwiML App's voice URL to match the new domain.
Verify API
- Verify Service FriendlyName rejects names with 5+ total digits (error 60200) —
POST /v2/Servicesreturns "Invalid parameter" if the FriendlyName contains 5 or more digit characters total, even non-consecutive (e.g.test-20260307-abchas 8 digits). Convert numeric identifiers to alpha-only hash:echo "$TS" | md5 | tr '0-9' 'g-p' | head -c 8.
Voice Call Routing
- REST API
Twimlparameter for inline TwiML —POST .../Calls.jsonaccepts aTwimlparameter with inline TwiML instead of requiring aUrlwebhook. Useful for provisioning tests and one-off calls. CLI equivalent:twilio api:core:calls:create --twiml '<Response><Say>Hello</Say></Response>'. - Empty
voiceUrlon a Twilio number causes silent instant call failure — Whenmake_calltargets a Twilio number that has no voice webhook configured (voiceUrl: ""), the call fails instantly withduration: 0. Twilio produces ZERO diagnostics: no debugger alerts, no call notifications, no error codes, no Voice Insights errors. The only symptom isstatus: failedwith start_time === end_time. This wastes enormous debugging time because it looks identical to auth failures, regional routing issues, or account-level blocks. Always verify destination number webhooks before troubleshooting call failures. Uselist_phone_numbersand check that every number involved in testing has a non-emptyvoiceUrl.
ConversationRelay & Voice Intelligence
record: trueon make_call is ignored with ConversationRelay — REST API recording param silently produces no recording when TwiML handler uses<Connect><ConversationRelay>. Always use<Start><Recording>in TwiML before ConversationRelay.- Agent-to-agent ConversationRelay setup is not optional — It produces the multi-turn transcripts needed to validate topic keywords and conversation quality. Using a generic IVR handler produces meaningless transcripts.
- Language Operators run automatically on VI transcripts — Conversation Summary and Sentiment Analysis produce results without explicit invocation if configured as default operators on the Intelligence service.
Voice SDK / WebRTC
- Voice SDK 2.x has no CDN — Must serve
node_modules/@twilio/voice-sdk/dist/twilio.min.jsfrom own Express server. The 1.x CDN was deprecated April 2025. - SDK 2.x API changes from 1.x —
device.register()required (no auto-register), events are'registered'/'unregistered'(not'ready'/'offline'),device.connect({ params: { To } })returns Promise. Twilio.Responseis serverless-runtime-only — Not in npmtwiliopackage. Tests need MockResponse class.jwt.AccessTokenIS in npm package.- TwiML App SID (
APxxx) stored asTWILIO_VOICE_SDK_APP_SIDin.envand serverless env vars. - Playwright + Chromium handles WebRTC — Use
--use-fake-device-for-media-stream+--use-fake-ui-for-media-stream. Server-side validation covers what browser-side can't. - CRITICAL: Voice SDK
connectedfires at A-leg, not B-leg bridge —device.connect()reportsconnectedwhen the browser connects to Twilio's WebRTC gateway, BEFORE the TwiML App dials the B-leg and it answers. A test completing in <2s for an outbound PSTN call is a false positive — real bridged calls take 3-5s minimum. Always sanity-check test durations against real-world call setup latency. - Never report Twilio E2E test results without checking timing — Green tests with suspiciously fast durations are likely testing signaling only, not actual media/audio bridging. Verify call duration via REST API or add explicit post-bridge waits + duration assertions.
Regional API & Authentication
- Regional URL requires edge location —
api.{edge}.{region}.twilio.com(e.g.api.sydney.au1.twilio.com). Omitting the edge (e.g.api.au1.twilio.com) resolves to US infrastructure where regional API keys return 401. - API key auth cannot fetch
/Accounts/{SID}.json— The account fetch endpoint requires auth token auth specifically. API keys work for all other endpoints. UseIncomingPhoneNumbers.json?PageSize=1as a lightweight auth validation endpoint when using API keys. - Auth token rotation invalidates ALL API keys — When the auth token is rotated/expired, every API key created under it dies. Regional and US keys all fail simultaneously. Only recovery: fresh auth token from Console → create new keys.
- Twilio Node SDK regional constructor —
Twilio(apiKeySid, apiKeySecret, { accountSid, region: 'au1', edge: 'sydney' })for API key auth.Twilio(accountSid, authToken, { region, edge })for auth token auth. The MCP server'screateTwilioMcpServer()supports both viaTWILIO_API_KEY/TWILIO_API_SECRET/TWILIO_REGION/TWILIO_EDGEenv vars. - Twilio Node SDK auto-reads
TWILIO_REGIONandTWILIO_EDGEfrom env — The SDK reads these env vars automatically even when not passed in the constructor options. Setting them in.envsilently routes ALL API calls to regional infrastructure (api.{edge}.{region}.twilio.com). If those calls use a US1 auth token, every request returns 401. Symptoms: cascading auth failures across unrelated tests with no obvious cause. Fix: comment out or unsetTWILIO_REGION/TWILIO_EDGEwhen not actively testing regional endpoints.
Claude Code & MCP
- MCP server requires Claude Code restart after env changes — The MCP server is a separate process that inherits the shell environment at launch. Mid-session changes to
.envor exported variables do NOT propagate. Must quit and restart Claude Code entirely. .mcp.jsonenv block augments, doesn't replace parent env — The MCP server subprocess inherits ALL env vars from the parent Claude Code process. Theenvblock in.mcp.jsonadds or overrides individual vars but does not isolate the process. To prevent inheritedTWILIO_REGION/TWILIO_EDGEfrom contaminating the MCP server, explicitly set them to empty strings in.mcp.json.source .envdoes not undo commented-out vars — Shell variables persist in memory after commenting out lines in.env. Must explicitlyunset TWILIO_REGION TWILIO_EDGEetc. before re-sourcing. This interacts badly with MCP (which also needs a restart to pick up the unset).- dotenv
{ override: true }is project-wide policy — Allrequire('dotenv').config()calls in this project use{ override: true }so.envvalues always win over inherited shell vars. The shipped.envrcprovides the same isolation for shell scripts via explicitunsetbefore loading. New users with pre-existing Twilio env vars (from.zshrc, other projects, or Twilio CLI) would otherwise hit silent auth failures. Run./scripts/env-doctor.shto diagnose conflicts.
Hooks & Documentation Flywheel
- Hooks receive tool input on stdin as JSON, not env vars —
CLAUDE_TOOL_INPUT_FILE_PATH,CLAUDE_TOOL_INPUT_COMMAND,CLAUDE_TOOL_INPUT_CONTENTdon't exist. Parse stdin withjq:FILE_PATH="$(cat | jq -r '.tool_input.file_path // empty')". All 4 hooks (pre-bash-validate, pre-write-validate, post-write, post-bash) were silently broken until fixed. - Flywheel must exclude its own output files — Editing
pending-actions.jsontriggers post-write, which tracks it in.session-files, which the next flywheel run picks up, generating infinite recursive suggestions. Filter outpending-actions.json,.session-files,.session-start,.last-doc-checkfrom the file collection. - Pending actions auto-clear only works for concrete paths — Entries with vague targets ("Relevant CLAUDE.md") or gitignored paths (
todo.md) never match staged files and accumulate forever. Always use specific file paths in suggestions. - Flywheel has 4 sources — git status (uncommitted), recent commits (since session start), session-tracked files (.session-files), validation failure patterns (pattern-db.json). Source 3 was broken until the stdin fix.
- Meta-mode hook blocks writes outside project root —
pre-write-validate.shprefix-stripsPROJECT_ROOT/fromFILE_PATH. When path is outside the project (e.g.,~/plans/), the strip is a no-op, leaving an absolute path that matches no allowed patterns. Fixed: wrapped case block inif [[ "$RELATIVE_PATH" != "$FILE_PATH" ]].
Hooks & Worktrees
- Merge conflicts in hook scripts create a deadlock — If both
pre-bash-validate.shandpre-write-validate.shhave conflict markers simultaneously, ALL Claude Code tools (Bash, Edit, Write) are blocked because the hooks themselves fail to parse. The only escape is the user running a manual command via!orgit checkout --theirs/--ours. Prevention: when merging branches that touch hook scripts, resolve hook conflicts first. Hooks resolve from the main repo path even when working in a worktree. - Worktree cleanup race with background agents — Background agents can remove the worktree directory while the main session is still using it. Recovery:
git fsck --unreachable --no-reflogsto find dangling commits, recreate branch from tip, merge. - CC settings.json hook type names are schema-validated at edit time only — The settings.json schema rejects unknown hook type names when the Edit tool writes to it. An invalid type name (e.g.,
PermissionDeniedinstead ofPermissionRequest) is silently ignored at runtime — schema validation during editing is your only safety net.
Twilio API Quirks
- Geographic Permissions API booleans must be strings —
client.voice.v1.dialingPermissions.bulkCountryUpdates.create()accepts a JSON string of update objects where boolean values must be"true"/"false"(strings), not actual booleans. Passing native booleans silently fails. - GitHub branch protection requires prior CI runs — The "Add checks" search in GitHub rulesets only shows status checks that have previously run against the default branch via a PR. If you've only pushed directly to main, the check names won't appear. Push via PR first, then add the check.
Sierra Stack (Pre-GA)
- IP-based auth restrictions on pre-GA APIs — Conversations v2, Customer Memory, and CI v3 APIs reject requests from cloud VM IPs (DigitalOcean, AWS, etc.) with 401 "invalid username". Same credentials work from local machines. Pre-GA demos must run from a trusted/registered IP. (Discovered 2026-04-03)
- ENVIRONMENT=dev routes to non-existent regional endpoints — TAC SDK reads
ENVIRONMENTenv var and constructs URLs likeconversations.dev-us1.twilio.com. These don't resolve →ENOTFOUND→ "fetch failed". Always useENVIRONMENT=prodor omit (defaults to prod). (Discovered 2026-04-03) - CI v3 operator PUT creates an inactive version with no activation API — Updating a pre-GA operator via PUT creates a new version but does not activate it. The operator silently stops producing results. No REST API to activate a version. Must delete and POST to recreate. (Discovered 2026-04-03)
- CI v3 API response shapes differ from v2 and from docs — List endpoints return
items[]notoperatorResults[]orconversations[]. Operator results useresult.labelnotoutput.label. Dates aredateCreatednotcreatedAt. Channels arechannels[]array notchannelstring. Pagination usesmeta.nextTokennotnextPageUrl. Operator results don't includedisplayName— onlyoperator.id; resolve names via separateGET /v3/ControlPlane/Operators. (Discovered 2026-04-06)
ngrok
- Dead ngrok tunnel returns 404 HTML, not connection refused — When an ngrok tunnel is offline, requests to the domain return HTTP 404 with an ngrok-branded HTML error page.
curl -s -o /dev/null -w "%{http_code}"shows 404, which looks identical to a missing route on your server. Always check the response body or verify viacurl -s https://DOMAIN/health | head -1to distinguish ngrok error page from your server's 404. localhost:4040/api/tunnelscan show tunnel as "active" when forwarding is dead — The ngrok agent API reports tunnel entries that are no longer forwarding traffic. The only reliable check is an end-to-end request through the tunnel to your server's health endpoint.- Twilio produces ZERO diagnostics when callback URLs are unreachable —
<Start><Recording>,<Start><Transcription>,<Start><Stream>, and ConversationRelay WebSocket connections all fail silently when the target URL/domain is unreachable. No debugger alerts, no call notifications, no error events. The call continues but no data flows. When ConversationRelay + Real-Time Transcription + Media Streams all fail simultaneously, suspect ngrok/infrastructure before platform. (Discovered 2026-04-06)
Cross-Account SID Mismatch
Scenario: Deploy to a new subaccount but env vars (TWILIO_TASKROUTER_WORKSPACE_SID, TWILIO_SYNC_SERVICE_SID, TWILIO_VERIFY_SERVICE_SID) still reference the old account. Resources return 404.
Detection: Use validate_environment() MCP tool at session start. It verifies all SID env vars resolve against the current account.
Prevention: After switching accounts (twilio profiles:use), re-run npm run setup or ./scripts/bootstrap.sh to re-provision resources. The MCP server inherits env at launch, not runtime — restart Claude Code after .env changes.
Gotcha: CLI profile and .env are independent. twilio profiles:list shows one account; .env may point to another. Always check both.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

