Instructions for coding agents (Hermes, Claude Code, Codex, opencode) that
want to use this repo to improve the security of regex-based code. Read
docs/ only as needed — this file is the decision tree.
Use it when the code you are working on (or reviewing) has regexes on security boundaries:
- input validators / whitelists / deny-lists (usernames, actors, IP-shaped gates, allowed-charset checks)
- sanitizers / escapers (JSON escaping, shell quoting, audit-line shaping)
- parsers with regex fallbacks (sed/awk capture groups, classifier patterns)
- anything where the question is "is there ANY string that, after this regex runs, violates the boundary?"
Do NOT use Z3 for:
- ReDoS / catastrophic backtracking — that is complexity analysis of the
matching engine, not language membership. Use
recheck,safe-regex2, orvuln-regex-detector(seedocs/REDOS.md). - Lookaheads / lookbehinds / backreferences as written — not expressible
in Z3's regular-language theory. Rewrite to string ops, or route JS patterns
through Z3-Noodler's
re.from_ecma2020(docs/BACKENDS.md). Variable-width lookbehinds ((?<=^)underre.MULTILINE) get the IndexOf/SubString/CharAt rewrite indocs/LOOKBEHIND_REWRITE.md. - Dynamic compiles (
re.compilewith interpolated values) — cannot be proven as written. Classify the site (constant / escaped / raw-config) and prove the right thing perdocs/DYNAMIC.md; an unescaped config-supplied pattern is a finding, not a proof. - Cosmetic/internal patterns with no untrusted input — skip them; low value.
Find every regex on the boundary. Classify by input trust:
untrusted-input > config > internal. Only boundary regexes get properties.
Record each with: file:line, the pattern, what input feeds it, and the
property you actually care about (for example, "no ; can reach the shell",
"the capture never truncates an escaped quote").
From scripts/z3-property-template.py, the canonical shapes:
| Shape | Question | Encoding | Expect |
|---|---|---|---|
| 1. Alphabet disjointness | "accepted strings contain no char X" | single-char InRe(c, class) ∧ c == bad |
instant, no length bound — prefer this |
| 2. Whitelist exclusion | "a whitelisted string (len-bounded) contains no X" | InRe(s, wl) ∧ len(s) ∈ [a,b] → ¬Contains(s, X) |
length bound is load-bearing (≤16 instant, ≤64 times out) |
| 3. Counterexample finder | "is there a value where capture ≠ true value?" | string ops: IndexOf/SubString |
SAT + witness = the bug repro — cheapest, most valuable |
| 4. Per-token image | "escape output has no raw control chars" | one token per tiny solver query | monolithic image-regex TIMEOUTs — decompose |
5. Rule diff (rule_diff) |
"does R2 accept anything R1 misses?" | InRe(s, R2) ∧ Not(InRe(s, R1)) (no regex Complement) |
SAT = gap; UNSAT = no gap in bound; TIMEOUT ≠ pass |
Shape-5 registry/kind/family/mutation-guard contract:
docs/examples/shape5-rule_diff.md.
Dialect/call_kind/fold tables: docs/SEMANTICS.md.
The traps cost real debugging time. Minimum set:
Complement()is language complement, not char-class negation.Star(Complement(Re('"')))≠[^\"]*. UseRange/Unionor string ops.- Never set
smt.string_solver=z3str3for regex work — it returnsunknowninstantly onInRe. Defaultseqbackend is the one that solves. - Mirror the real code exactly: deny-lists verbatim, length checks, char classes. "root" matches the username regex; only the deny-list excludes it.
- State input-domain assumptions as constraints + comments (for example, POSIX shell strings cannot contain NUL).
re.replace_re/str.replace_allare unsupported — model with string ops.
A Z3 model is a mirror; SAT means "the mirror says there's a counterexample". Before reporting it:
- Run the real implementation on the witness (real
sed, real JS, real Pythonre) and confirm behavior matches the model byte-for-byte. - If the target runs BusyBox (OpenWrt), verify under
busybox sedtoo — pinbusyboxin CI for device fidelity. - Presence-gates use whole-word grep (
grep -wc) — substring matches lie ("sed" matches "passed"). See TRAPS.md #12. - Enumerate refuted reviewer/model claims in your report — a digest that
says what was checked and what was disproven is what makes a proof
trustworthy. This includes your own claims: read the surrounding code
before filing a finding (the pilot flagged an interpolated regex as
un-escaped when
re.escapewas already two lines above).
- Ship as a runnable script + CI job (
pip install z3-solver; TIMEOUT (unknown) = hard failure / not proven, never a silent skip). - Add mutation guards: a tagged property that weakens the regex and
asserts the result flips UNSAT→SAT. A harness that can't fail proves
nothing. Run them in
--all, always. The harness enforces coverage: every family with a security property must have at least one mutation guard (check_mutation_coverage()warns and exits non-zero otherwise). - Add differential fuzz for transformation properties: random inputs →
mirror accept/reject vs real implementation accept/reject must agree.
Mutation guards prove the mirror is sensitive; differential fuzz proves
mirror ≡ real code.
scripts/differential-fuzz.pyimplements this: give it a Z3 mirror expression + a real command (grep -qE,sed,busybox, …) and it fuzzes exhaustive short strings, random strings, and dangerous-char mutations, failing on any disagreement. The mirror is a Z3 expression, not a pattern string —z3.Re("...")is a literal match. - Ground-truth every SAT witness in code, not just in prose: give each
counterexample-finding property a
ground_truth=callback that runs the real implementation on the witness, and run the harness with--require-ground-truth. An unverified (or non-reproducing) witness is a hard failure — an unverified counterexample is never reported as a vulnerability. (The P3 sed-capture and P4-NUL properties ship real replay callbacks.) - Tag every property with
kind=:property(invariant must hold),counterexample_finder(SAT is the finding),mutation_guard(SAT proves sensitivity),bug_demo(SAT demonstrates a known bug),rule_diff(shape-5 gap query). Thekindfield is what makesexpect_unsat=Falseunambiguous and lets the coverage check reason about the registry. Scanner NDJSON also uses finding kindsredos,usage_mismatch,intent_mismatch,triage— seedocs/REPORTING.md. - Pin
z3-solver==5.0.0— theRe()/regex API changed across 4.x/5.x. The harness refuses to run (exit 3) on any non-5.0.x solver. - Machine-readable output (NDJSON contract — must match CLI help):
z3-verify.py --jsonemits one NDJSON object per property (schema_version, result, witness, ground-truth, domain, wall_ms,engine_versions,not_proven). Same facts as the human report — the two reports can never disagree. Partial streams remain valid if a later property fails. Mutually exclusive with--json-legacy.--json-legacyemits a single JSON array of the same records (one-release compat). Mutually exclusive with--json. - Triage / batch reports:
properties/triage/<repo>.ndjsonandproperties/generated/<repo>.ndjson(+*_batch.md). Field contracts:docs/REPORTING.md. Deterministic sort byregex_id. - Disclosure: security-tool findings are
private_first— seeSECURITY.md.
For each property report: the pattern (file:line), the property, the declared domain (what exactly was proven — a length bound means "proven up to this length", not "inputs are this length"), result (UNSAT=holds / SAT=witness / TIMEOUT=not proven / hard fail), ground-truth evidence, and engine versions.
Prefer alphabet-level, length-independent proofs wherever the property allows: they cover ALL strings with no bound at all. Use length bounds only for genuinely length-sensitive properties, and document the declared domain in the harness output so a reader knows exactly what was proven.
scripts/z3-property-template.py— runnable shapes 1–5 (incl. complement-free shape-5rule_diff) PASS against a pinned z3-solverdocs/examples/shape5-rule_diff.md— shape-5kind/family/mutation guardsscripts/rule-diff-pilot.py— Phase 3 gitleaks encodable-subset shape-5 pilot (independent-spec R1, admitted_pairs≥20, timeout gate)python -m regexproof.batch— Phase 5 batch (inventory, triage NDJSON, intent-vs-actual, scanner NDJSON/MD, ReDoS join optional, PR dry-run / disclosure gate)scripts/z3-verify.py --all— harness skeleton run: P1 injection chars, P2 actor whitelist, P3 sed-capture counterexample (SAT + witness), P4 per-token escape image + the NUL-passthrough bug demo, and theP1-mutated-starmutation guardproperties/usrmanage-p1-p6.md— full property suite (username validator, actor whitelist, sed-fallback truncation, JSON escaper image, audit-line integrity, password policy) with encoded forms and spike timingsproperties/fwlive-classifier.md— classifier regex inventory incl. theNETFILTER_KV_GLUElookahead blocker and the decomposition route per patterndocs/verified-findings.jsonl— machine-readable implementation findings keyed into TRAPS/BACKENDS/SEMANTICS
If running under Hermes, the z3-regex-verification, z3-string-verification,
and z3-verification skills carry the same knowledge with the full evidence
base. This repo is the distributable, language-agnostic version.