Opengrep: a grep that understands code, and why it matters more when agents write the code
20 min read
This repository's AGENTS.md has a rule: never put user input inside a data-* expression, because the browser decodes HTML escaping before Datastar evaluates the expression. The result would be XSS.
The agents that write code in this repository read that file at the start of every task, and they mostly follow it. "Mostly" is the problem. An agent that follows the rule 99 times out of 100 and edits hundreds of files a day produces a new hole every week, and the person who has to find it is a reviewer reading a two-thousand-line diff as the fortieth file of the day.
The article on the map of software bugs ended by saying that rules which live only in documents get forgotten, while rules in a linter are checked on every commit, including the ones an AI wrote. This article expands on that sentence with one tool that makes turning a written rule into an enforced rule very cheap: Opengrep (and Semgrep, where it came from).
The first half covers the basics: what the tool is and how to write rules. The second half explains why it becomes more valuable when agents write most of the code. Every rule in this article has been run with Opengrep 1.26.0 and passes opengrep test.
The basics: what is static analysis?
Static analysis means checking code without running it. A compiler that reports a type mismatch is doing static analysis, and so is a linter. Tools in this family differ in how deeply they understand code and in how hard it is to add a new rule.
| Tool | How much it understands | Adding a rule |
|---|---|---|
grep / regex |
Nothing; it sees characters | Very easy |
| Typical linters (go vet, staticcheck, ESLint) | Syntax and types | Write a program, such as an analyzer with go/analysis |
| Opengrep / Semgrep | Syntax, imports, data flow within a file | A short YAML rule with patterns that look like code |
| CodeQL | Turns code into a database; deep cross-file analysis | Write queries in QL, a language that takes a while to learn |
The clearest example is in this repository. The architecture test has this line to stop code in internal/core from reading the clock:
var hiddenInputs = regexp.MustCompile(`\btime\.(Now|Since|Until|Sleep|After|Tick|NewTimer|NewTicker)\(`)
It works, but a regex doesn't know it is reading Go. It flags comments and strings that contain time.Now(), and it misses code that imports the package under another name:
import t "time"
func IsExpired(deadline t.Time) bool {
return t.Now().After(deadline) // the regex doesn't see this
}
Doing it properly means writing an analyzer that parses Go and follows imports. That is dozens of lines, and most people won't do it, because it isn't worth it for one rule.
Opengrep sits between the two. It parses code into a syntax tree like a linter, but you write the rule as example code, the way you would with grep.
Where Semgrep and Opengrep came from
It started as sgrep, which Yoann Padioleau wrote at Facebook around 2009 as part of pfff, a set of program analysis tools. (Padioleau had earlier worked on Coccinelle, a pattern-based tool for transforming C code that the Linux kernel uses.) By his account, when he left Facebook in 2014 more than 200 sgrep rules ran on every pull request.
In 2019 Padioleau joined r2c, which forked sgrep and kept developing it, renaming it Semgrep in 2020. The company later renamed itself Semgrep Inc. after the product.
In December 2024 Semgrep renamed its open source edition to Semgrep Community Edition and moved the rules it maintains to the Semgrep Rules License, which restricts some commercial uses. The engine stayed LGPL 2.1. Some features moved to the paid edition.
In January 2025 a group of at least ten security companies, led by Aikido, Endor Labs, Jit, Orca Security and others, announced a fork of Semgrep CE 1.100.0 called Opengrep, under LGPL 2.1. Their stated reason was to keep a fully open engine. Semgrep replied that the rules license changed because some companies had been redistributing the rules repository against the existing terms. There are two sides to this, and if you want to judge for yourself, read both (links at the end).
What a rule author needs to know is that the rule syntax is the same. The rules in this article work with both tools. I use Opengrep because it is fully open source and has cross-function taint analysis within a single file (the --taint-intrafile flag), which is a paid feature in Semgrep. Semgrep has its own strengths, including cross-file analysis in Semgrep Pro and a platform for managing scan results across an organization.
A first rule
This repository manages tools with mise, so installing is:
mise use [email protected]
You can also download a binary from the Releases page of Opengrep on GitHub.
Back to the bug that opened the article on the map of software bugs:
if user.role == "admin" or "editor":
This condition is always true, because "editor" is a non-empty string. A rule that catches it looks like this:
rules:
- id: or-with-constant-string
languages: [python]
severity: ERROR
message: >-
`$X == $A or "$B"` is always true, because a non-empty string is truthy.
Write `$X in ($A, "$B")` instead.
pattern: $X == $A or "$B"
fix: $X in ($A, "$B")
The important line is pattern, which is ordinary Python with the variable parts replaced by metavariables that start with $. Running opengrep scan --config admin.yaml . gives:
❯❯❱ or-with-constant-string
`user.role == "admin" or "editor"` is always true, because a non-empty string is truthy.
Write `user.role in ("admin", "editor")` instead.
3┆ if user.role == "admin" or "editor":
The message fills in the real values of $X, $A and $B, so the reader (or the agent) gets advice that applies to that exact line. With fix, opengrep scan --autofix rewrites the code itself.
The pattern language
The whole syntax is a handful of pieces:
$Xmatches any expression. If the same name appears twice, both places must hold the same value....means "anything, any number of times". It works in arguments (http.Get(...)) and between statements."$B"matches a string literal and binds its contents to$B.patternsis AND: every condition must hold.pattern-eitheris OR.pattern-notandpattern-not-insideremove the correct cases.pattern-insidelimits the context, for example to functions that take afiber.Ctx.metavariable-regexchecks the value of a metavariable with a regex.focus-metavariablesays which part of the match to report.
Here is an example that combines several of them: an HTTP response body that is never closed, from group 4 of the bug map.
rules:
- id: http-body-not-closed
languages: [go]
severity: WARNING
message: >-
The body of `$RESP` is never closed, so every call leaks a connection.
Add `defer $RESP.Body.Close()` right after the error check.
patterns:
- pattern: $RESP, $ERR := http.Get(...)
- pattern-not-inside: |
$RESP, $ERR := http.Get(...)
...
defer $RESP.Body.Close()
In plain words: "find calls to http.Get that are not followed by defer ....Body.Close() on the same variable, however many lines apart." The ... between the two statements is what a regex can't do, because Opengrep knows it is skipping statements, not characters.
It understands code, not characters
Back to the rule against reading the clock. As an Opengrep rule:
rules:
- id: core-reads-clock
languages: [go]
severity: ERROR
paths:
include: ["internal/core/**"]
message: >-
Core code must not read the clock (FCIS rule in AGENTS.md).
Add a `now time.Time` parameter and let the shell pass `time.Now()`.
pattern-either:
- pattern: time.Now()
- pattern: time.Since(...)
- pattern: time.Until(...)
- pattern: time.Sleep(...)
This rule catches t.Now() in a file that does import t "time", because Opengrep follows imports. It doesn't flag comments or strings containing time.Now(), because those aren't function calls. It also ignores whitespace, line breaks and extra parentheses. foo(1, 2) and
foo(
1,
2,
)
are the same thing to it.
I added the paths line after running the rule against this repository. The first version didn't have it, and it flagged two places in internal/shell/web/respond.go, where the shell is allowed to call time.Now(). Rules are like code: try them on the real thing before you trust them.
Taint mode: following the data
A plain pattern answers "is there code that looks like this?" But many bugs are about data flowing from one place to another, not about the shape of a single line. User input reaching a SQL query is the classic case.
Taint mode lets you declare three things:
- sources: where dangerous data comes from
- sinks: places where that data causes harm
- sanitizers: what makes the data safe
Opengrep then follows the data for you, through assignments, string concatenation and closures.
Here is an example from this repository's rules. Fiber reuses its buffers, so a string returned by c.Params() can change after the handler returns. Before using it in a goroutine, you must copy it with strings.Clone.
func (s *Server) Bad(c fiber.Ctx) error {
slug := c.Params("slug")
key := "post:" + slug
go func() {
s.warm(key) // may already hold another request's slug
}()
return nil
}
grep can't find this bug, because the line that reads the value and the line that uses it are in different places, and the value changes variable name on the way. A taint rule can:
rules:
- id: fiber-ctx-value-escapes
languages: [go]
severity: ERROR
message: >-
A string from fiber.Ctx is used inside a goroutine. Fiber reuses its
buffers, so the value can change after the handler returns.
Copy it first with strings.Clone (see AGENTS.md, "Fiber v3").
mode: taint
pattern-sources:
- patterns:
- pattern-inside: |
func ($R $T) $F($C fiber.Ctx) error { ... }
- pattern-either:
- pattern: $C.Params(...)
- pattern: $C.Query(...)
- pattern: $C.Body()
pattern-sanitizers:
- pattern: strings.Clone(...)
pattern-sinks:
- patterns:
- pattern-inside: go func(...) { ... }(...)
- pattern: $FN(..., $ARG, ...)
- focus-metavariable: $ARG
It catches s.warm(key) above, even though key is derived from slug. It doesn't fire when you write slug := strings.Clone(c.Params("slug")), or when slug is used normally inside the handler.
I didn't get this rule right the first time either. The first version used a bare $FN(...) as the sink and matched nothing at all. It only worked once focus-metavariable pointed at the argument. That is why the next section matters.
Rules have tests too
A rule without tests fails silently: it reports nothing, and you conclude the code is clean. So Opengrep has tests built in. Write an example file with the same name as the rule file, and annotate the lines that should and shouldn't match:
def can_delete(user, post):
# ruleid: or-with-constant-string
if user.role == "admin" or "editor":
return True
# ok: or-with-constant-string
if user.role == "admin" or user.role == "editor":
return True
# ok: or-with-constant-string
if user.role in ("admin", "editor"):
return True
return False
opengrep test rules/
1/1: ✓ All tests passed
1/1: ✓ All fix tests passed
If a rule has a fix, add an admin.fixed.py with the expected output, and opengrep test checks the autofix as well.
Why it is so much more powerful when agents write the code
Everything above has been true since 2020. Several things change once most of the code is no longer written by people.
1. The bottleneck moves from writing to reading
An agent writes hundreds of lines in a few minutes. People still read at the same speed, and read less carefully as they tire. If every check has to pass through human eyes, people are the bottleneck, and an overflowing bottleneck turns into approving without reading.
The job of static analysis now is to take the checks that need no judgment away from people, so they can spend their attention on what tools can't check: the design, and what users actually need.
2. AGENTS.md is a request; a linter rule is a requirement
AGENTS.md is advice that the model reads and then decides how far to follow. It has an effect, but a probabilistic one. The longer the context and the more complex the task, the less weight line 80 carries.
An Opengrep rule has no probability. Code that matches is flagged every time. Compare the rules in this repository's AGENTS.md with the tools that can enforce them:
| Rule in AGENTS.md | Enforced by |
|---|---|
| Core must not import I/O packages | depguard and the architecture test (already in place) |
Core must not call time.Now() |
the regex in the architecture test (already in place), or core-reads-clock above, which follows imports |
Values from fiber.Ctx must be copied before use in a goroutine |
fiber-ctx-value-escapes (taint) |
No user values inside data-* expressions |
a regex rule on .mustache files (see below) |
| Every Redis key needs a TTL | $R.Set($CTX, $K, $V, 0) |
Log with slog, no string concatenation |
slog.$LEVEL($MSG + $X, ...) |
Money is never float64 |
a struct field pattern with metavariable-regex on the field name |
Every line in this table is a rule the agent can no longer forget, because it no longer depends on the agent's memory.
3. Agent mistakes repeat as patterns
People make mistakes at random: tired today, forgot to close a file today. Models make mistakes in patterns, because they learned from the same code and get similar prompts. If a model likes writing InsecureSkipVerify: true to get a test passing in one file, it will do the same in other files.
Mistakes that repeat as patterns are exactly what a pattern matcher is best at. Here are rules I call "agent hygiene", which catch what agents often leave behind when they want work to look finished:
rules:
- id: tls-verify-disabled
languages: [go]
severity: ERROR
message: >-
TLS certificate checks are turned off. If a test needs a self-signed
certificate, use httptest.NewTLSServer and its Client() instead.
pattern: "tls.Config{..., InsecureSkipVerify: true, ...}"
- id: placeholder-implementation
languages: [go]
severity: ERROR
message: >-
This looks like a stub left behind: panic("$MSG").
Implement it, or return an error that says what is missing.
patterns:
- pattern: panic("$MSG")
- metavariable-regex:
metavariable: $MSG
regex: (?i)^(todo|fixme|not implemented|unimplemented|implement)
- id: empty-error-branch
languages: [go]
severity: ERROR
message: >-
`$ERR` is checked and then ignored. Return it wrapped with context:
fmt.Errorf("doing x: %w", $ERR).
pattern: |
if $ERR != nil {
}
All three are shortcuts that turn the build green and make tests pass without solving the problem. A reviewer may miss panic("TODO: implement refund") in the middle of a diff. Opengrep sees it every time.
4. The same result every time
Having another LLM review the code is useful. It finds problems nobody has written a rule for. But it is probabilistic, like the model that wrote the code. Two runs can give different opinions, and it can miss something it caught before.
Opengrep is the opposite: same input, same output. Scanning this whole repository (about 6,000 lines of Go plus templates) with the rules in this article takes about 1.4 seconds, costs no tokens, and doesn't get tired at file forty.
So the two don't compete; they work in sequence. An LLM reviewer (or a person) discovers a new kind of problem, and Opengrep locks that kind out so it doesn't come back.
5. Writing a rule now costs almost nothing
This is the biggest change. Teams used to have only a few custom lint rules, because writing them took time: learning the syntax, trial and error, and someone to maintain them. Most cases ended with "we'll be careful", and then it happened again.
Opengrep rules look like code and come with a built-in test system, two things agents are good at. When you find a bug you never want to see again, the work is one instruction:
Write an Opengrep rule that catches this pattern, with a test file that has both
ruleid:andok:cases. Makeopengrep testpass, then run the rule on the whole repository and report everything it finds.
The agent writes the rule, writes the test, runs it, fixes the rule until it passes, and runs it on the real code. What's left for a person is reading a fifteen-line rule and a list of findings, which is much faster than reviewing every future file that might repeat the mistake.
opengrep test matters here because it lets you check the agent's work without taking its word for it. The Fiber rule above is a good example: the first version looked right and matched nothing. The test said so immediately.
6. The message is a prompt
When an agent breaks a rule, what it sees is the rule's message. So write the message for whoever has to fix the code, not just for whoever needs to know something is wrong.
- Say why it is wrong. An agent that understands the reason fixes the problem instead of dodging the pattern.
- Say how to fix it, specifically, and use metavariables to fill in the real names.
- Point to the documentation, such as
see AGENTS.md, "Fiber v3", so the agent can read further.
A good message lets the agent fix the problem in one pass without a person getting involved.
7. Put it inside the agent's loop
Checking rules in CI is good, but by the time CI reports, the agent has moved on. The faster the feedback, the cheaper the fix. The best place is right after the agent edits a file.
Claude Code has hooks that run a command after each tool call. If the command exits with code 2, its stderr is sent back to the agent. Configure it in .claude/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": ".claude/hooks/opengrep.sh" }
]
}
]
}
}
The script reads the path of the edited file from the JSON on stdin and scans just that file:
#!/usr/bin/env bash
file=$(jq -r '.tool_input.file_path // empty')
[ -n "$file" ] || exit 0
if ! out=$(opengrep scan --config .opengrep --error --quiet "$file" 2>&1); then
echo "$out" >&2
exit 2
fi
--error makes Opengrep exit non-zero when it finds something. Now whenever the agent writes panic("TODO: ..."), it sees the rule's message a second later and fixes it before moving to another file. Most other agent tools have a similar mechanism.
Then put a full-repository scan in mise run check and in CI as the last gate. If an older repository has many existing findings, --baseline-commit reports only problems introduced after a given commit, so you can adopt a new rule right away without first fixing everything old.
Trying it on this repository
I ran every rule in this article against this repository to see what it finds in real code. The Go rules found nothing (once the clock rule had its paths). The first version of the template rule,
pattern-regex: data-[\w:.-]+="[^"]*\{\{
flagged three places: {{SearchURL}} on the search page, {{Action}} in the contact form, and {{Paths.Contact}} in a content partial. All three are paths the server builds, not user input, so none is a vulnerability.
This is a limit worth knowing up front. The rule in AGENTS.md is about "user input", and a regex can't know which values come from users. You have to settle on a convention first. I chose this one: view-model fields that hold server-built paths end in URL, content files use {{Paths.X}}, and the rule exempts both:
rules:
- id: user-value-in-datastar-expression
languages: [regex]
severity: ERROR
paths:
include: ["*.mustache"]
message: >-
A Mustache value is placed inside a data-* expression. The browser decodes
HTML escaping before Datastar evaluates it, so a user value here is an XSS.
Put the value in value="{{...}}" and use data-bind (AGENTS.md, "Datastar").
Server-built paths are allowed: name the view-model field ...URL, or use
{{Paths.X}} in content files.
patterns:
- pattern-regex: data-[\w:.-]+="[^"]*\{\{\{?\w+(\.\w+)*\}?\}\}
- pattern-not-regex: data-[\w:.-]+="[^"]*\{\{(\w+URL|Paths\.\w+)\}\}
This version still flagged {{Action}}, so I renamed that field to ActionURL to fit the convention, and the next scan came back clean. Choosing the convention belongs to a person, not the tool, and it is the kind of decision you make once.
The Go and template rules in this article now live in this repository's .opengrep/ directory, each with a test fixture of the same name, and mise run check runs both opengrep test and a full scan every time.
Limits
Opengrep doesn't solve everything, and knowing what it can't do matters as much as knowing what it can.
- It mostly looks at one file at a time. Opengrep's taint analysis follows data across functions within one file. If data flows across files or packages, it won't see it. CodeQL or Semgrep Pro go further there.
- It matches patterns, not intent. If code is written to look different, the rule won't see it. An agent that keeps getting flagged may take that route. A message that explains the reason helps, but doesn't guarantee anything.
- Exceptions can be abused. A
// nosemgrepcomment silences a finding on that line. You need it for false positives, but agents can write it too. Require every exception to carry a reason, and make any diff that addsnosemgrepsomething a person always reviews. - False positives destroy trust. A rule that fires wrongly gets ignored or turned off, by people and agents alike. A few precise rules beat many noisy ones.
- It doesn't know what you should build. Group 12 of the bug map, requirements and design, is beyond any rule. Type systems and tests are as necessary as ever. Opengrep fills the gap between them; it doesn't replace them.
Where to start
- Read AGENTS.md (or your team's convention document) line by line and ask which lines can be checked from the shape of the code. Those lines are your first rules.
- Add "agent hygiene" rules for what agents tend to leave behind: stubs, swallowed errors, disabled security checks and skipped tests.
- Make it a team rule that a problem found in review a second time becomes a rule, written by the agent along with its tests.
- Run a new rule on the whole repository before enforcing it. Read every finding and adjust the rule until there are no false positives.
- Run it in three places: a hook after the agent edits a file,
checkon your machine, and CI. - If you use someone else's ready-made ruleset, read its license first. Ruleset licensing is the very issue that caused this fork.
When agents write code faster than we can read it, the most valuable thing isn't reading faster. It is having less to read. Every time we turn a lesson into a rule, we never have to teach it again, to people or to agents.
References
- Opengrep: source code, releases and documentation
- Semgrep rule syntax: the rule syntax reference, which also applies to Opengrep
- Semgrep: a static analysis journey: Yoann Padioleau on the path from Coccinelle and sgrep at Facebook to Semgrep
- Launching Opengrep: why we forked Semgrep: the Opengrep side
- Compare Semgrep to Opengrep: the Semgrep side
- Opengrep SAST after one year: what Opengrep added in its first year, including cross-function taint analysis
- Claude Code hooks: documentation for the hooks used in the example