The Analogy: The Watch Room, the Running Card, and the Box Alarm
In a traditional fire department, the busiest desk in the station is the watch room. It does not fight fires. When an alarm comes in from a street box, the watch officer's job is purely to decide who rolls out the door, and they do not decide it by judgment in the moment. They pull a running card: a pre-printed assignment, filed by box number, that names exactly which companies respond to an alarm at that location. The card was written in advance, in a quiet office, by people who studied the district. The watch officer reads it and dispatches. That is the entire job -- match the alarm to a card, and send whoever the card names.
A running card is keyed to two things at once: the box number, which fixes the location, and the alarm level, which says how serious the call is. A first-alarm card for a downtown box might send two engines and a ladder; a second-alarm card for the same box adds a rescue company and a battalion chief. Critically, the card does not spell out every hose movement. It names standard assignments -- "Engine 12, standard pre-connect" -- packages of equipment and procedure that were defined once and are reused on every card that references them. Nobody re-describes how Engine 12 lays a supply line each time. The card just names the package, and the package carries the detail.
The matching is exact and layered, and every layer must agree before a card sends its companies. The box has to fall in the card's district. The alarm level has to be one the card is written for -- a card for structure fires does not respond to a medical call at the same box. Some cards narrow further, covering only certain streets within a box's area and explicitly excluding others. Only when the location, the level, and the street all line up does that card commit its apparatus. Get any one wrong and the card stays in the file while some other card, or no card, answers the call.
The failure that empties a station for nothing is a running card written too broadly. A card whose district was transcribed as "any box beginning with 4" will roll the whole first-due assignment to a burning wastebasket in a town three districts over, because a box number there happened to begin with 4. A card with a sloppy street rule matches addresses on cross streets it was never meant to cover. Nothing mechanical failed. The trucks started, the crews suited up, the response was flawless -- against the wrong alarm. The apparatus that a real fire needed is now committed miles away, because the card matched something it should never have matched. In automation the running card is the workflow's trigger block, and a trigger that matches more than you intended is the most common and most expensive mistake there is.
Syntax or Core Structure
A GitHub Actions workflow is a YAML file in .github/workflows. It has three moving parts: the on block, which is the running card -- the events and filters that decide whether the workflow fires at all; one or more jobs, each of which runs on a fresh virtual machine; and within each job a list of steps. A step is one of two kinds. A run step executes shell commands. A uses step pulls in a pre-packaged action -- the standard assignment, reusable and versioned by a ref like @v4 -- and never re-describes what that action does internally.
name: CI
on:
push:
branches: [main, 'release/*']
paths: ['src/**', 'package.json']
pull_request:
types: [opened, synchronize]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci
- run: npm test
The on block is not documentation; it is an executable rule, and you can implement the exact rule GitHub applies. A push fires the workflow only if its branch matches one of the branches globs and one of its changed files matches a paths glob. A pull_request fires only if its activity type is in types. Here is that rule as a small reference matcher, run against six events:
import re
def glob_to_regex(pat):
out = ['^']; i = 0
while i < len(pat):
c = pat[i]
if c == '*':
if i + 1 < len(pat) and pat[i+1] == '*':
out.append('.*'); i += 2; continue
out.append('[^/]*'); i += 1; continue
out.append(re.escape(c)); i += 1
out.append('$'); return ''.join(out)
def ref_match(pat, s):
return re.match(glob_to_regex(pat), s) is not None
def matches(spec, ev):
name = ev['event']
if name not in spec:
return (False, 'event not triggered')
rule = spec[name] or {}
if 'branches' in rule:
if not any(ref_match(p, ev['ref']) for p in rule['branches']):
return (False, 'branch not listed')
if 'paths' in rule:
if not any(any(ref_match(p, f) for p in rule['paths']) for f in ev.get('files', [])):
return (False, 'no path matched')
if 'types' in rule:
if ev.get('type') not in rule['types']:
return (False, 'type not listed')
return (True, 'run')
spec = {
'push': {'branches': ['main', 'release/*'], 'paths': ['src/**', 'package.json']},
'pull_request': {'types': ['opened', 'synchronize']},
}
events = [
{'event': 'push', 'ref': 'main', 'files': ['src/app.js']},
{'event': 'push', 'ref': 'main', 'files': ['docs/readme.md']},
{'event': 'push', 'ref': 'release/1.2', 'files': ['src/app.js']},
{'event': 'push', 'ref': 'feature/x', 'files': ['src/app.js']},
{'event': 'pull_request', 'ref': '-', 'type': 'opened'},
{'event': 'pull_request', 'ref': '-', 'type': 'closed'},
]
print('%-14s %-14s %-16s %-4s %s' % ('EVENT','REF','DETAIL','RUN','WHY'))
run = skip = 0
for ev in events:
ok, why = matches(spec, ev)
detail = ev.get('type', ','.join(ev.get('files', []))) or '-'
print('%-14s %-14s %-16s %-4s %s' % (ev['event'], ev['ref'], detail, 'yes' if ok else 'no', why))
run += 1 if ok else 0
skip += 0 if ok else 1
print('run=%d skip=%d' % (run, skip))
Output:
EVENT REF DETAIL RUN WHY
push main src/app.js yes run
push main docs/readme.md no no path matched
push release/1.2 src/app.js yes run
push feature/x src/app.js no branch not listed
pull_request - opened yes run
pull_request - closed no type not listed
run=3 skip=3
Three events fire and three are filtered out, and the reason column is the whole point: a push to main that only touched docs is skipped because no changed file matched paths, while a push to feature/x is skipped one layer earlier because its branch was never listed. The workflow's YAML did not "almost run" in either case; the running card simply did not match.
Technical Depth: What Fires, What Runs, and the Glob That Betrays You
Not every event honors every filter
The branches, paths, and types filters are not universal. Each event type accepts only the filters that make sense for it, and applying one an event ignores does not error -- it silently has no effect, which is worse. A push and a pull_request carry a ref and a file list, so they honor branches and paths. Only events that have activity variants honor types. Time-based and manual events carry no ref at all, so a branches filter on them is dead text.
| Event | branches / paths | types | Typical use |
|---|---|---|---|
push | honored | ignored | run CI on commits to tracked branches |
pull_request | honored | honored (opened, synchronize, closed) | gate merges |
schedule | ignored | ignored | nightly jobs on a cron |
workflow_dispatch | ignored | ignored | manual, button-triggered runs |
run and uses are the two kinds of step
Every step is either a run (shell you wrote) or a uses (an action someone packaged). The distinction matters for supply-chain safety: a uses line pulls third-party code into your pipeline, pinned by a ref you chose. Counting them is the first thing a workflow audit does.
steps = [
{'uses': 'actions/checkout@v4'},
{'uses': 'actions/setup-node@v4', 'with': {'node-version': '20'}},
{'run': 'npm ci'},
{'run': 'npm test'},
]
uses = sum(1 for s in steps if 'uses' in s)
runs = sum(1 for s in steps if 'run' in s)
print('steps=%d uses=%d run=%d' % (len(steps), uses, runs))
for s in steps:
kind = 'uses' if 'uses' in s else 'run'
print(' %-4s %s' % (kind, s.get('uses', s.get('run'))))
Output:
steps=4 uses=2 run=2
uses actions/checkout@v4
uses actions/setup-node@v4
run npm ci
run npm test
Two of these four steps run code from another repository. That is normal and useful, but it is exactly the count a security review wants, because each uses at a mutable ref like @v4 is code that can change under you between runs.
The glob that does not cross a slash
The single most misunderstood rule in the whole trigger system is what * means in a branch pattern. In GitHub's filter syntax * matches any run of characters except /, and ** is the one that crosses slashes. This is not how the shell's fnmatch behaves, and reaching for fnmatch to test a pattern gives an answer that is wrong in precisely the case people most often hit: a nested branch name.
import re, fnmatch
pat = 'release/*'
for ref in ['release/1.2', 'release/hotfix/urgent', 'feature/x']:
naive = fnmatch.fnmatch(ref, pat)
correct = ref_match(pat, ref)
print('%-22s fnmatch=%-3s documented=%-3s' % (ref, 'yes' if naive else 'no', 'yes' if correct else 'no'))
Output:
release/1.2 fnmatch=yes documented=yes
release/hotfix/urgent fnmatch=yes documented=no
feature/x fnmatch=no documented=no
For release/1.2 and feature/x the two agree. For release/hotfix/urgent they part ways: fnmatch says the pattern matches because its * happily swallows the second slash, but GitHub's release/* stops at the first slash and does not match a two-level name. The workflow will not fire for that push, no matter what fnmatch believes. Anyone who validates their triggers with the shell's globbing will be certain a pipeline runs when it does not.
Real World Example: A Preflight That Trusts the Wrong Globber
Waiting for a forge to tell you whether a push triggered your pipeline is slow: you push, you switch to the browser, you find out. So it is natural to write a small preflight that answers the question locally before you push. The one below transcribes the branch and path lists from a real ci.yml and reports whether a given push would fire it. It is the kind of five-minute helper that gets shared around a team and quietly trusted.
#!/usr/bin/env python3
# would-run.py <ref> [changed-file ...]
# Preflight: will pushing <ref> with these files trigger our CI workflow?
# The branch and path lists are transcribed from .github/workflows/ci.yml.
import sys, fnmatch
BRANCHES = ['main', 'release/*']
PATHS = ['src/**', 'package.json']
def any_match(patterns, value):
return any(fnmatch.fnmatch(value, p) for p in patterns)
def main(argv):
if len(argv) < 2:
print('usage: would-run.py <ref> [changed-file ...]')
return 2
ref = argv[1]
files = argv[2:]
branch_ok = any_match(BRANCHES, ref)
path_ok = any(any_match(PATHS, f) for f in files)
print('ref=%s files=%d' % (ref, len(files)))
print('branch-match=%s path-match=%s' % ('yes' if branch_ok else 'no', 'yes' if path_ok else 'no'))
if branch_ok and path_ok:
print('verdict=would-run')
return 0
print('verdict=skipped')
return 1
sys.exit(main(sys.argv))
Run it against three branch names, each touching src/app.js:
for args in "release/1.2 src/app.js" "release/hotfix/urgent src/app.js" "feature/x src/app.js"; do
echo "$ would-run.py $args"
py would-run.py $args
echo "exit=$?"
done
Output:
$ would-run.py release/1.2 src/app.js
ref=release/1.2 files=1
branch-match=yes path-match=yes
verdict=would-run
exit=0
$ would-run.py release/hotfix/urgent src/app.js
ref=release/hotfix/urgent files=1
branch-match=yes path-match=yes
verdict=would-run
exit=0
$ would-run.py feature/x src/app.js
ref=feature/x files=1
branch-match=no path-match=yes
verdict=skipped
exit=1
The first and third answers are correct. A push to release/1.2 touching src does fire the workflow, and a push to feature/x does not, because that branch is not listed. The tool cleanly separates the two reasons a push can be skipped -- wrong branch or wrong path -- and returns a shell exit code, so it drops neatly into a pre-push hook. On the branches a team actually uses day to day, it is right.
The middle answer is wrong, and it is wrong in the way that costs a debugging afternoon. The tool reports would-run for a push to release/hotfix/urgent, but that push does not trigger the workflow at all, because GitHub's release/* does not cross the second slash. A developer trusts the green would-run, pushes, and waits for a pipeline that never starts -- and the failure is silent, because a workflow that does not trigger produces no run, no log, and no error. The tool's own technical-depth table already proved this: for release/hotfix/urgent the documented rule is no while fnmatch is yes.
The design flaw is the choice of fnmatch for any_match. The shell's globber treats * as matching across slashes, so it accepts nested branch names that GitHub's segment-aware * rejects, and every over-broad verdict flows from that one import. Swapping fnmatch.fnmatch for the ref_match shown earlier fixes it. Two smaller gaps sit beside it and would each mislead in their own scenario: the tool understands only branches and paths, so a workflow using branches-ignore or paths-ignore is judged by rules it does not implement; and the branch and path lists are transcribed by hand from ci.yml, so the day someone edits the workflow and forgets the preflight, the tool answers confidently from a stale copy of the running card.
Common Mistakes
- Using
fnmatchor shell globbing to test branch patterns. GitHub's*stops at a slash; the shell's does not. A pattern likerelease/*tested withfnmatchwill claim to matchrelease/a/b, which the real trigger rejects. The two globbers agree on flat names and diverge on nested ones.
- Putting
typeson an event that has none. Apushhas no activity types, sotypes: [opened]underpushis not an error and not a filter -- it is ignored, and the workflow fires on every push while you believe it is scoped.
- Believing
branchesandpathsare OR. They are AND. A push must match a branch pattern and touch a matching path. A branch push that changed onlydocsis skipped even though the branch matched, and readers of the YAML routinely expect the opposite.
- Filtering
scheduleorworkflow_dispatchby branch. These events carry no ref, so abranchesfilter on them matches nothing meaningful and is silently dead. A scheduled job does not run "on main"; it runs on the default branch's workflow file regardless.
- Pinning actions to a mutable tag and calling it stable.
uses: some/action@v4follows whereverv4is moved, which can be new code tomorrow. It reads like a version lock but it is a moving reference; only a full commit SHA is immutable.
- Confusing
pathswithpaths-ignore. They are opposites, and using the wrong one inverts the whole filter:pathsmeans "run only when these change",paths-ignoremeans "run except when only these change". A workflow that should skip doc-only pushes needspaths-ignore, notpaths.
- Assuming a push to a matching branch always runs. The path filter can still exclude it, the workflow file must exist on the branch being pushed, and a
paths-ignorecan veto it. "The branch matched" is one layer of three, not the verdict.
- Expecting
pull_requestto run with the PR's code and secrets. For pull requests from forks,pull_requestruns with a read-only token and no secrets by design. Workflows that assume full credentials on fork PRs fail in ways that look like flaky auth.
- Leaving
on: pushwith no filters on a busy repo. An unfiltered push trigger fires on every commit to every branch, burning runner minutes on work-in-progress branches nobody is watching. It is the running card written as "any box, any alarm".
Best Practices
- Scope
on: pushto the branches and paths that actually need CI. An unfiltered trigger is the default that quietly costs the most.
- Test branch and path patterns with a segment-aware matcher, never the shell's globber. If you must check locally, implement the
*-stops-at-slash rule rather than trustingfnmatch.
- Pin third-party actions to a full commit SHA for anything that touches secrets or deploys. Use a tag only where a surprise upgrade would be harmless.
- Keep
branchesandpathsfilters in oneonblock per event and read them as AND, so the intent is visible in one place rather than scattered.
- Prefer
paths-ignorefor "skip doc-only changes" andpathsfor "only these areas", and never mix the two on one event where their meanings collide.
- Give
pull_requestexplicittypes. The default set includessynchronize, which fires on every push to the PR branch; name the types you actually want.
- Set an explicit
permissionsblock so the job's token grants only what it needs, rather than inheriting the repository's broad default.
- Treat the workflow file as code under review: a change to the
onblock changes what fires, and it deserves the same scrutiny as a change to the branch protection rules it enforces.
Practice Exercises
- Prove the slash rule. Implement the segment-aware
glob_to_regexfrom this lesson and testrelease/*andrelease/**againstrelease/1.2andrelease/hotfix/urgent. Report which of the four combinations match, and explain in one sentence why only**crosses the slash.
- Fix the preflight. Take
would-run.py, replacefnmatchwith the segment-aware matcher, and rerun it against the three branches from the example. Confirmrelease/hotfix/urgentnow reportsskipped, and add handling for abranches-ignorelist so a workflow using it is judged correctly.
- Audit the steps. Given a workflow's job, write a check that counts
usesversusrunsteps and flags everyusespinned to a tag rather than a 40-character SHA. Run it on the example job and report the counts and which lines it flags.
- Trace an AND failure. Write out an
on: pushblock with both abranchesand apathsfilter, then list four pushes: matching both, matching only the branch, matching only the path, and matching neither. State which single one fires and connect each skip to the exact filter that vetoed it.