pattern-dev
Skill5 starsChanged 4 months agoMITView on GitHub
Pattern detection internals — detection order, adding new patterns, normalization pipeline, timestamp architecture. Use when editing src/patterns/ or src/normalize.rs, adding a pattern, fixing detection, changing normalization order.
In this repository5 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- lessenceSkill
- product-managerSkill
- releaseSkill
- testingSkill
The file
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 1 is distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 66
Every format starts on a word boundary, and a weekday or month is spelled as the calendar name, not \w{3}
- Very specific: line 76
Add the token variant to Token enum in patterns/mod.rs, plus its KindFacts row in Token::facts() and its arm in Token::value_string() — the …
- Very specific: line 77
Add pub mod your_pattern; to patterns/mod.rs
- Very specific: line 79
Add to --disable-patterns handling in main.rs (the disable_patterns → config.normalize_* mapping)
- Very specific: line 80
Add stats counter to FoldingStats in folder/mod.rs
- Distinctive: line 81
Write unit tests with realistic log samples
- Very specific: line 82
Test ReDoS resistance with malicious inputs (see testing skill)
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 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
Pattern Development
Detection Order
Order matters — earlier patterns consume text first, preventing later patterns
from matching the same content. Timestamps before Network preserves URLs.
Quoted strings last to avoid consuming tokens detected by earlier patterns.
The order is declared in one place: the DETECTOR_ORDER table in
normalize.rs (one DetectorEntry per detector with its name, its tier
and the entries it must come after, the enabled config gate, only_when
rule, prefilter cheap byte check, and the run hook). A reorder that
breaks a tier or an after fails
detector_order_keeps_what_each_entry_declares. normalize_line just
walks the table:
- CPU quantities — millicpu fields (
cpu: 250m) before the JSON, key-value and minute-duration passes can take the value (DurationDetector::cpu_quantities,patterns/duration.rs) - Timestamps — one scored table of about 40 formats (
patterns/timestamp/detector.rs) - Email — RFC 5322 (
patterns/email.rs) - Paths — before Network to preserve URLs; also carries the
&Event{ObjectMeta:{…}pass, which therefore runs before JSON's copy. An escaped flat struct (\"{phase:Running}\") stays literal: its values are the event (patterns/path.rs) - JSON — the same Event pass (
patterns/json.rs); Paths takes the block first, so thejsonflag decides it only whenpathis disabled - UUIDs — standard format (
patterns/uuid.rs) - Network — IPs, ports, FQDNs (
patterns/network.rs) - Hashes — MD5, SHA1, SHA256, SHA512 (
patterns/hash.rs) - Process IDs — PIDs, thread IDs (
patterns/process.rs) - Syslog host — the positional host field between a normalized timestamp and a program tag (
replace_syslog_host,normalize.rs); gated by the FQDN flag - Kubernetes — namespaces, pods, volumes (
patterns/kubernetes.rs). A*name/*Namefield (filename=,podName:) is judged on its own value, whatever else the line says: it folds to<K8S_NAME>only when the value is compound (a-,.,/,_or digit) and not already one placeholder; a bare word (levelname=ERROR) stays literal - HTTP Status — status codes (
patterns/http_status.rs) - Bracket Context —
[proxy]-style context tags, a chain of them as one<BRACKET_CONTEXT>(patterns/bracket_context.rs). A level ([error],[NOTICE]) is never a context: it stays literal and splits a chain. "Is this a level" isbriefing::word_to_level, the crate's one level vocabulary — do not add a second list - Key-Value —
key=valuepairs; the key and separator stay and only the value folds (timeout=<KEY_VALUE>).levelis not a foldable key (patterns/key_value.rs) - Log Module — level + module token for the statistics; every form keeps its text: the Apache or nginx module, the systemd component and the Java logger name are the event's source and stay on the line (
patterns/log_module.rs) - Structured Messages — two table entries,
structured-json(gated by thejsonflag) andstructured-logfmt(gated bykey-value); component + level token for stats only; the line text is preserved verbatim so distinct messages fold into distinct groups (patterns/structured.rs) - Durations — time and size values; a
<name>Duration=field keeps its key (podStartSLOduration=<DURATION_FIELD>) (patterns/duration.rs) - Names — generated names; the component stays and only the generated tail folds (
nginx-<SUFFIX>,web-v2-<HASH>-hcwqj→web-v2-<SUFFIX>) (patterns/names.rs) — gated by--disable-patterns namelike the others - Quoted Strings — last to avoid consuming other tokens; its nested cascade honours the same
--disable-patternsgates (patterns/quoted.rs)
Normalization Pipeline
Normalizer struct in normalize.rs orchestrates detection:
Normalizer::normalize_line(original) -> Result<LogLine>is the entry point- Each detector has
DetectorName::detect_and_replace(&normalized) -> (String, Vec<Token>) normalize_linewalksDETECTOR_ORDER, each entry replacing matched content with tokens (<IP>,<TIMESTAMP>,<UUID>, etc.)- A gate asks about the shape its detector folds, never about a word elsewhere on the line: a word such as
pod/,etcd,param=orupdatemust not switch a detector on or off for the whole line (the kubernetes deference and the bracket and SQL-word vetoes were removed for this, lessence-enl) - The normalized line + tokens are returned as a
LogLine - A hash of the normalized text is computed for fast similarity comparison
Token variants are defined in patterns/mod.rs as the Token enum.
Timestamp Architecture
The whole timestamp engine is one table, PATTERNS in patterns/timestamp/detector.rs:
- About 40 formats, each a name, a regex and a score: ISO 8601, RFC 2822/822, syslog, klog, Apache, asctime, PostgreSQL, epochs and more
- Lowest score wins an overlap, whatever the lengths; equal scores fall back to position, then table order. A format that a stronger one always matches on the same text can never be chosen, so it does not belong in the table
- Unix epochs score last, so a plain number never outranks a real date
- A
RegexSetof the same table (ASCII_CANDIDATES) skips formats that cannot match a line before their regexes run - Every format starts on a word boundary, and a weekday or month is spelled as the calendar name, not
\w{3}
Key files:
patterns/timestamp/mod.rs— public API re-exports andDetectionResult/TimestampMatchpatterns/timestamp/detector.rs— thePATTERNStable andUnifiedTimestampDetector, the engine
Adding a New Pattern
- Create
src/patterns/your_pattern.rs - Implement
pub fn detect_and_replace(line: &str) -> (String, Vec<Token>) - Add the token variant to
Tokenenum inpatterns/mod.rs, plus itsKindFactsrow inToken::facts()and its arm inToken::value_string()— the taxonomy owns machine name, display label, stats bucket, sample-worthiness, and value stringification; the folder/renderer consumers are projections of it - Add
pub mod your_pattern;topatterns/mod.rs - Add a
DetectorEntrytoDETECTOR_ORDERinnormalize.rsat the correct position (setname,tier, and inafterevery entry that must read the text first, each with an invented line that normalizes differently when the two change places —every_declared_order_rule_changes_its_linerefuses a rule whose line does not;cargo nextest run --release --profile slow -E 'test(every_order_dependence_on_a_corpus_line_is_declared)'lists the pairs the corpora show that no entry declares; setenabled; aprefilterif a cheap byte check exists — it may only save time, and test builds panic when the detector changes a line its prefilter turned away;only_whenfor a rule that must keep the detector off a line it would change). An anchor pattern inprotect_anchored_spansis gated throughgate(...), checked the same way - Add to
--disable-patternshandling inmain.rs(thedisable_patterns→config.normalize_*mapping) - Add stats counter to
FoldingStatsinfolder/mod.rs - Write unit tests with realistic log samples
- Test ReDoS resistance with malicious inputs (see
testingskill)
Essence Mode
--essence is a flag on Config (essence_mode: bool in src/config.rs), not a
separate module. The standalone essence/ module was deleted as dead code.
Timestamps are already tokenized to <TIMESTAMP> by the normal TimestampDetector
in every mode — that's not essence-specific. What --essence actually does is
omit the time-range segment of the text rollup marker
(render_compact_marker in src/folder/mod.rs): the [+N similar | first → last | …]
marker is printed without its first → last timestamps, so two runs of the same
log over different periods render identically.
Net effect: structural comparison between log periods works, because the same template with a different time now counts as the same pattern.
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.

