[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KSBE8WYSRYRYG6EHAPZ7R1":3,"skill-same:01M6KSBE8WYSRYRYG6EHAPZ7R1":72},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":34,"linkOnly":35,"markdownContent":36,"markdownBody":37,"frontMatter":38,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":6,"ownerHtmlUrl":45,"ownerBlogUrl":46,"ownerDescription":6,"updatedAt":47,"install":48,"resources":61},"01M6KSBE8WYSRYRYG6EHAPZ7R1","tokf-filter",null,"This skill should be used when the user asks to \"create a filter\", \"write a tokf filter\", \"add a filter for \u003Ctool>\", \"how do I filter output\", or needs guidance on tokf filter step types, templates, pipes, or placement conventions.","hollis-labs\u002Fnanite","hollis-labs","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F209122427?v=4","01M6KSB2TDHAKZP6JEBD24X8ZQ","Hollis Labs","01M6KSB31JT4Q9NEY4X5ZYWBT1",1,"MIT","https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite\u002Fblob\u002Fmain\u002Finternal\u002Fassets\u002Fframework\u002Fdocs\u002Fref-tokf-filter\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33],"filter","tokf filter","create","templates","how","tool","write","user","guidance","do","conventions","add","types","output","for","2026-11-10 10:12:30",false,"---\nname: tokf-filter\ndescription: This skill should be used when the user asks to \"create a filter\", \"write a tokf filter\", \"add a filter for \u003Ctool>\", \"how do I filter output\", or needs guidance on tokf filter step types, templates, pipes, or placement conventions.\nversion: 0.1.0\n---\n\n# tokf Filter Authoring\n\nYou are an expert at writing tokf filter files. tokf is a config-driven CLI that compresses command output before it reaches an LLM context. Filters are TOML files that define how to process a command's output.\n\nWhen the user asks you to create or modify a filter, follow this guide exactly. Produce valid, idiomatic TOML that matches the schema described below.\n\n---\n\n## Section 1 — What a Filter File Is\n\nA filter file is a TOML file that describes:\n- Which command(s) it applies to (`command`)\n- How to transform the raw output (steps, applied in a fixed order)\n- What to emit on success vs. failure\n\nFilters live in three places, searched in priority order:\n\n1. `.tokf\u002Ffilters\u002F` — project-local (repo-level overrides)\n2. `~\u002F.config\u002Ftokf\u002Ffilters\u002F` — user-level overrides\n3. Built-in library (embedded in the tokf binary)\n\nFirst match wins. Use `tokf which \"cargo test\"` to see which filter would activate for a given command.\n\n---\n\n## Section 2 — Processing Order\n\nSteps execute in this fixed order — **do not rearrange them**:\n\n1. **`match_output`** — whole-output substring checks; if matched, short-circuits the entire pipeline and emits immediately\n2. **`[[replace]]`** — per-line regex transforms applied to every line, in array order\n3. **`strip_ansi` \u002F `trim_lines`** — per-line cleanup (ANSI stripping, whitespace trimming)\n4. **`skip` \u002F `keep`** — line-level filtering (drop or retain lines by regex)\n5. **`dedup` \u002F `dedup_window`** — collapse duplicate consecutive lines\n6. **`lua_script`** — Luau escape hatch; runs after dedup, before JSON\u002Fsection\u002Fparse\n7. **`[json]`** — JSON extraction via `JSONPath`; when configured, replaces section\u002Fparse\u002Fchunk\n8. **`[[section]]` OR `[parse]`** — structured extraction (these are mutually exclusive; section is a state machine, parse is a declarative grouper). Skipped when `[json]` is configured.\n9. **`[[chunk]]`** — block-based structured extraction with per-block aggregation, grouping, and tree output (runs on raw output, alongside sections). Skipped when `[json]` is configured.\n10. **Exit-code branch** — `[on_success]` or `[on_failure]` depending on exit code\n11. **`[fallback]`** — if neither `on_success` nor `on_failure` produced output\n12. **`strip_empty_lines` \u002F `collapse_empty_lines`** — post-processing cleanup on the final output\n\nWithin `[on_success]` and `[on_failure]`, fields are processed as:\n- `head` \u002F `tail` → trim lines\n- `skip` \u002F `extract` → further filter\n- `aggregate` → reduce collected sections\n- `output` → final template render\n\n---\n\n## Section 3 — Top-Level Fields Reference\n\n| Field | Type | Default | Description |\n|---|---|---|---|\n| `command` | string or array of strings | required | Command pattern(s) to match. Supports `*` wildcard. |\n| `run` | string | (same as command) | Override the actual command executed. Use `{args}` to forward arguments. |\n| `match_output` | array of tables | `[]` | Whole-output checks. Short-circuit on first match. |\n| `[[replace]]` | array of tables | `[]` | Per-line regex replacements, in order. |\n| `skip` | array of strings (regex) | `[]` | Drop lines matching any regex. |\n| `keep` | array of strings (regex) | `[]` | Retain only lines matching any regex. (Inverse of skip.) |\n| `dedup` | bool | `false` | Collapse consecutive identical lines. |\n| `dedup_window` | integer | `0` (off) | Dedup within a sliding window of N lines. |\n| `strip_ansi` | bool | `false` | Strip ANSI escape sequences before skip\u002Fkeep. |\n| `trim_lines` | bool | `false` | Trim leading\u002Ftrailing whitespace from each line. |\n| `lua_script` | table | (absent) | Luau escape hatch. |\n| `[json]` | table | (absent) | JSON extraction via `JSONPath`. When configured, replaces `[[section]]`\u002F`[parse]`\u002F`[[chunk]]`. |\n| `[[section]]` | array of tables | `[]` | State-machine section collectors. |\n| `[[chunk]]` | array of tables | `[]` | Block-based structured extraction with per-block aggregation and grouping. |\n| `[parse]` | table | (absent) | Declarative structured parser (branch + group). |\n| `[on_success]` | table | (absent) | Output branch for exit code 0. |\n| `[on_failure]` | table | (absent) | Output branch for non-zero exit. |\n| `[output]` | table | (absent) | Top-level output template (used by `[parse]`). |\n| `[fallback]` | table | (absent) | Fallback when no branch matched. |\n| `strip_empty_lines` | bool | `false` | Remove all blank lines from the final output. |\n| `collapse_empty_lines` | bool | `false` | Collapse consecutive blank lines into one. |\n| `show_history_hint` | bool | `false` | Append a hint line after filtered output pointing to the full output in history. |\n| `[[variant]]` | array of tables | `[]` | Context-aware delegation to specialized child filters. |\n\n---\n\n## Section 4 — Step Types\n\n### 4.1 `match_output` — Whole-Output Short-Circuit\n\nCheck the entire raw output for a substring. If matched, emit a fixed string and stop — no further processing.\n\n```toml\nmatch_output = [\n  { contains = \"Everything up-to-date\", output = \"ok (up-to-date)\" },\n  { contains = \"rejected\", output = \"✗ push rejected (try pulling first)\" },\n]\n```\n\n- `contains`: literal substring to search for (case-sensitive)\n- `output`: string to emit if matched\n- `{line_containing}` template variable: the first line that contains the substring\n\n```toml\nmatch_output = [\n  { contains = \"error\", output = \"Error on: {line_containing}\" },\n]\n```\n\n**When to use**: for well-known one-liner outcomes that make the rest of filtering irrelevant (e.g., \"already up to date\", \"nothing to push\", \"authentication failed\").\n\n---\n\n### 4.2 `[[replace]]` — Per-Line Regex Transforms\n\nApplied to every line, in array order, before skip\u002Fkeep. Use to reformat noisy lines.\n\n```toml\n[[replace]]\npattern = '^(\\S+)\\s+\\S+\\s+(\\S+)\\s+(\\S+)'\noutput = \"{1}: {2} → {3}\"\n\n[[replace]]\npattern = '^\\s+Compiling (\\S+) v(\\S+)'\noutput = \"compiling {1}@{2}\"\n```\n\n- `pattern`: Rust regex (RE2 syntax, no lookaheads)\n- `output`: template with `{1}`, `{2}`, … for capture groups; `{0}` is the full match\n- If the pattern doesn't match a line, that line passes through unchanged\n- Invalid patterns are silently skipped at runtime\n\n**When to use**: when a line contains useful information but in a verbose format — reformat it rather than dropping it.\n\n---\n\n### 4.3 `skip` \u002F `keep` — Line Filtering\n\n`skip` drops lines matching any regex. `keep` retains only lines matching any regex. They compose:\n\n```toml\nskip = [\n  \"^\\\\s*Compiling \",\n  \"^\\\\s*Downloading \",\n  \"^\\\\s*$\",\n]\n\nkeep = [\"^error\", \"^warning\"]\n```\n\n- Both are arrays of regex strings\n- Applied after `[[replace]]`\n- `skip` is checked first, then `keep`\n- A line must pass both: not skipped, and (if keep is non-empty) matching keep\n\n**When to use**: `skip` for removing known noise patterns; `keep` for allow-listing (e.g., keep only lines that start with `error` or `warning`).\n\nAlso available inside `[on_success]` and `[on_failure]` for branch-level filtering.\n\n---\n\n### 4.4 `dedup` \u002F `dedup_window` — Deduplication\n\n```toml\ndedup = true           # collapse consecutive identical lines\ndedup_window = 10      # dedup within a 10-line sliding window\n```\n\n- `dedup = true`: removes consecutive duplicate lines (like `uniq`)\n- `dedup_window = N`: deduplicates within a sliding window of N lines (catches near-consecutive repeats)\n- They are independent; you can use both\n\n**When to use**: for commands that emit repetitive progress lines (e.g., `npm install` printing the same package multiple times, spinner frames, repeated warnings).\n\n---\n\n### 4.5 `lua_script` — Luau Escape Hatch\n\nFor logic that pure TOML cannot express: numeric math, multi-line lookahead, conditional branching.\n\n```toml\n[lua_script]\nlang = \"luau\"\nsource = '''\nif exit_code == 0 then\n    return \"passed\"\nelse\n    local msg = output:match(\"Error: (.+)\") or \"unknown error\"\n    return \"FAILED: \" .. msg\nend\n'''\n```\n\nOr load the script from an external file:\n\n```toml\n[lua_script]\nlang = \"luau\"\nfile = \"scripts\u002Fmy-filter.luau\"\n```\n\nThe `file` path resolves relative to the current working directory. Exactly one of `source` or `file` must be set.\n\n**Globals available**:\n- `output` (string): the full output after skip\u002Fkeep\u002Fdedup\n- `exit_code` (integer): the command's exit code\n- `args` (table of strings): the arguments passed to the command\n\n**Return semantics**:\n- Return a string → replaces output, skips remaining TOML pipeline\n- Return `nil` → fall through to `[[section]]` \u002F `[parse]` \u002F `[on_success]` \u002F `[on_failure]`\n\n**Sandbox**: `io`, `os`, and `package` are blocked. No filesystem or network access. Standard math\u002Fstring\u002Ftable libraries are available.\n\n**When to use**: only when no TOML step can express the logic. Most filters do not need this. Consider it after exhausting `match_output`, `skip\u002Fkeep`, `[[replace]]`, `[[section]]`, and `[parse]`.\n\n---\n\n### 4.6 `[json]` — JSON Extraction via `JSONPath`\n\nFor commands that produce JSON output (e.g. `kubectl get pods -o json`, `gh api`, `docker inspect`). Extracts values using `JSONPath` (RFC 9535) queries and produces template variables and structured collections.\n\n```toml\n[json]\n\n[[json.extract]]\npath = \"$.items[*]\"\nas = \"pods\"\n\n[[json.extract.fields]]\nfield = \"metadata.name\"\nas = \"name\"\n\n[[json.extract.fields]]\nfield = \"status.phase\"\nas = \"phase\"\n\n[on_success]\noutput = \"Pods ({pods_count}):\\n{pods | each: \\\"  {name}: {phase}\\\" | join: \\\"\\\\n\\\"}\"\n```\n\n**`[[json.extract]]` fields**:\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `path` | string | yes | `JSONPath` expression (RFC 9535), e.g. `\"$.items[*]\"`, `\"$.version\"` |\n| `as` | string | yes | Variable name to bind the result to |\n| `fields` | array of tables | no | Sub-field extraction for each matched object |\n\n**`[[json.extract.fields]]` fields**:\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `field` | string | yes | Dot-separated path within each object (e.g. `\"metadata.name\"`, `\"containers.0.name\"`). Not JSONPath — uses simple dot-notation. Supports numeric array indices. |\n| `as` | string | yes | Variable name for the extracted value |\n\n**Result mapping**:\n- **Single scalar** → `vars[\"as_name\"] = string_value` (no count, no chunk)\n- **Array** → `ChunkData::Flat` collection + `{as_name_count}` variable\n- **Objects without `fields`** → top-level scalars auto-flattened into chunk items\n- **Objects with `fields`** → named fields extracted per item\n\n**Pipeline behavior**: when `[json]` is configured, `[[section]]`, `[parse]`, and `[[chunk]]` are skipped. JSON replaces line-based structural processing. Extracted vars and chunks flow into `[on_success]`\u002F`[on_failure]` template rendering.\n\n**Error handling**: invalid JSON input → extraction skipped, pipeline falls back to raw output (templates are not rendered). Invalid JSONPath → rule silently skipped, other rules still run. Empty array with `fields` → emits `{as_name_count} = \"0\"`.\n\n**When to use**: when the command produces structured JSON output and you need to extract specific fields. Prefer this over `[parse]` + `skip`\u002F`keep` for JSON-native commands.\n\n---\n\n### 4.7 `[[section]]` — State-Machine Section Collector\n\nThe most powerful step. Defines a state machine that collects lines into named variables as it scans top-to-bottom.\n\n```toml\n[[section]]\nname = \"failures\"\nenter = \"^failures:$\"      # regex: start collecting when this matches\nexit = \"^failures:$\"       # regex: stop collecting when this matches (after start)\nsplit_on = \"^\\\\s*$\"        # regex: split collected lines into blocks on blank lines\ncollect_as = \"failure_blocks\"\n\n[[section]]\nname = \"summary\"\nmatch = \"^test result:\"    # regex: collect only lines matching this (no enter\u002Fexit)\ncollect_as = \"summary_lines\"\n```\n\n**Fields**:\n| Field | Required | Description |\n|---|---|---|\n| `name` | yes | Identifier for this section (used in error messages) |\n| `enter` | no | Regex to start collecting (state transitions to \"inside\") |\n| `exit` | no | Regex to stop collecting (state transitions to \"outside\") |\n| `match` | no | Collect any line matching this regex, without enter\u002Fexit state |\n| `split_on` | no | Split collected lines into blocks when this regex matches |\n| `collect_as` | yes | Variable name to bind the result to |\n\n**Accessing collected variables in templates**:\n| Expression | Type | Description |\n|---|---|---|\n| `{name}` | string | Full collected text joined with newlines |\n| `{name.lines}` | collection | Individual lines as a list |\n| `{name.blocks}` | collection | Blocks split by `split_on` |\n| `{name.count}` | integer | Number of blocks (or lines if no split_on) |\n\n**When to use**: when the output has distinct sections with clear start\u002Fend markers — test failure blocks, error sections, file change groups.\n\n---\n\n### 4.8 `[[chunk]]` — Block-Based Structured Extraction\n\nChunks split raw output into repeating structural blocks (e.g., per-crate test suites in a Cargo workspace), extract structured data per-block, and produce named collections for template rendering. Like sections, chunks operate on the raw (unfiltered) command output — skip\u002Fkeep patterns do not affect chunk processing.\n\n```toml\n[[chunk]]\nsplit_on = \"^\\\\s*Running \"       # regex marking the start of each chunk\ninclude_split_line = true         # include the splitting line in the chunk (default: true)\ncollect_as = \"suites_detail\"      # name for the structured collection\ngroup_by = \"crate_name\"           # merge chunks sharing this field value\nchildren_as = \"children\"          # preserve original items as nested collection\n\n[chunk.extract]\npattern = 'unittests.+deps\u002F([\\w_-]+)-'  # extract a field from the header line\nas = \"crate_name\"\ncarry_forward = true              # inherit value from previous chunk when pattern doesn't match\n\n[[chunk.body_extract]]\npattern = 'Running\\s+(.+?)\\s+\\('\nas = \"suite_name\"\n\n[[chunk.aggregate]]\npattern = '(\\d+) passed'          # aggregates run within each chunk's lines\nsum = \"passed\"\n\n[[chunk.aggregate]]\npattern = '^test result:'\ncount_as = \"suite_count\"\n```\n\n**Fields**:\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `split_on` | string (regex) | yes | Regex marking the start of each chunk |\n| `include_split_line` | bool | no | Whether the splitting line is part of the chunk (default: `true`) |\n| `collect_as` | string | yes | Name for the resulting structured collection |\n| `extract` | table | no | Extract a named field from the header line (`pattern` + `as`) |\n| `body_extract` | array of tables | no | Extract fields from body lines (`pattern` + `as`, first match wins) |\n| `aggregate` | array of tables | no | Per-chunk aggregation rules (`pattern` + `sum`\u002F`count_as`) |\n| `group_by` | string | no | Merge chunks sharing the same field value, summing numeric fields |\n| `children_as` | string | no | When set with `group_by`, preserve original items as a nested collection |\n\n**`carry_forward`** (on `extract` or `body_extract`): when a chunk's pattern doesn't match, inherit the value from the most recent chunk that did. Useful when boundary markers (like `Running unittests`) identify a group, and subsequent chunks should inherit that identity.\n\n**Structured collections in templates**: each item has named fields accessible in `each` pipes:\n\n```toml\n[on_success]\noutput = \"\"\"\\\n{suites_detail | each: \"  {crate_name}: {passed} passed ({suite_count} suites)\" | join: \"\\\\n\"}\"\"\"\n```\n\n**Tree output with `children_as`**: groups preserve their child items for nested template rendering:\n\n```toml\n[on_success]\noutput = \"\"\"\\\n{suites_detail | each: \"  {crate_name}: {passed} passed\\\\n{children | each: \\\"    {suite_name}: {passed} passed\\\" | join: \\\"\\\\n\\\"}\" | join: \"\\\\n\"}\"\"\"\n```\n\n**When to use**: when output contains repeating structural blocks with per-block data you want to aggregate and display. Common for workspace build tools (Cargo, Gradle, Nx) where output is organized by sub-project.\n\n---\n\n### 4.9 `[parse]` — Declarative Structured Parser\n\nAlternative to `[[section]]` for commands with table-like output. Declaratively extracts a header field and groups remaining lines.\n\n```toml\n[parse]\nbranch = { line = 1, pattern = '## (\\S+?)(?:\\.\\.\\.(\\S+))?(?:\\s+\\[(.+)\\])?$', output = \"{1}\" }\n\n[parse.group]\nkey = { pattern = '^(.{2}) ', output = \"{1}\" }\nlabels = { \"M \" = \"modified\", \"??\" = \"untracked\", \"D \" = \"deleted\" }\n\n[output]\nformat = \"\"\"\n{branch}{tracking_info}\n{group_counts}\"\"\"\ngroup_counts_format = \"  {label}: {count}\"\nempty = \"clean — nothing to commit\"\n```\n\n**`[parse]` fields**:\n| Field | Description |\n|---|---|\n| `branch` | Extract a single value from a specific line (`line`, `pattern`, `output`) |\n| `[parse.group]` | Group remaining lines by a key pattern |\n\n**`[parse.group]` fields**:\n| Field | Description |\n|---|---|\n| `key` | `{ pattern, output }` — extract the grouping key from each line |\n| `labels` | Map from raw key string to human-readable label |\n\n**`[output]` fields** (used with `[parse]`):\n| Field | Description |\n|---|---|\n| `format` | Template string for the overall output |\n| `group_counts_format` | Template for each group entry: `{label}`, `{count}` |\n| `empty` | String to emit when no lines were grouped |\n\n**When to use**: for commands like `git status`, `docker ps`, `kubectl get` — table-formatted output where you want to extract a header and count\u002Fgroup rows.\n\n---\n\n### 4.10 `[on_success]` \u002F `[on_failure]` — Exit Code Branches\n\nThese branches run after all top-level steps. They have their own sub-fields:\n\n```toml\n[on_success]\noutput = \"ok ✓ {2}\"          # template; collected variables are available\nhead = 20                     # keep first N lines\ntail = 10                     # keep last N lines\nskip = [\"^\\\\s*$\"]            # additional line filtering\nextract = { pattern = '(\\S+)\\s*->\\s*(\\S+)', output = \"ok ✓ {2}\" }\n\n# Singular form (one rule):\naggregate = { from = \"summary_lines\", pattern = 'ok\\. (\\d+) passed', sum = \"passed\", count_as = \"suites\" }\n\n# Plural form (multiple rules):\n# [[on_success.aggregates]]\n# from = \"summary_lines\"\n# pattern = 'ok\\. (\\d+) passed'\n# sum = \"passed\"\n# count_as = \"suites\"\n#\n# [[on_success.aggregates]]\n# from = \"summary_lines\"\n# pattern = '(\\d+) failed'\n# sum = \"failed\"\n\n[on_failure]\ntail = 10\noutput = \"FAILED: {summary_lines | join: \\\"\\\\n\\\"}\"\n```\n\n**Branch sub-fields**:\n| Field | Description |\n|---|---|\n| `output` | Template string for the output. Has access to all `[[section]]` and `[[chunk]]` variables. `{output}` = the filtered output text. |\n| `head` | Keep first N lines of filtered output |\n| `tail` | Keep last N lines of filtered output |\n| `skip` | Array of regexes to filter output lines within this branch |\n| `extract` | `{ pattern, output }` — find first match, render template with capture groups |\n| `aggregate` | Reduce collected section lines into numeric summaries (singular form) |\n| `aggregates` | Array of aggregate rules (plural form — use `[[on_success.aggregates]]`) |\n\n**`aggregate` \u002F `aggregates` fields**:\n| Field | Description |\n|---|---|\n| `from` | Variable name (a `collect_as` result from `[[section]]`) |\n| `pattern` | Regex with one capture group to extract a number |\n| `sum` | Variable name to bind the sum to |\n| `count_as` | Variable name to bind the count (number of lines matched) to |\n\nBoth singular `aggregate` and plural `aggregates` can be used together — they are merged at runtime.\n\n**When to use**: Always. Every filter should have at least one of `[on_success]` or `[on_failure]`. Use `[on_success]` to produce a clean summary. Use `[on_failure]` to show enough context to diagnose the issue.\n\n---\n\n### 4.11 `[fallback]` — Last Resort\n\nEmits output when neither `[on_success]` nor `[on_failure]` produced anything.\n\n```toml\n[fallback]\ntail = 5\n```\n\n**When to use**: as a safety net when you have complex branching logic. Ensures tokf never silently swallows output.\n\n---\n\n### 4.12 `[[variant]]` — Context-Aware Filter Delegation\n\nSome commands are wrappers around different underlying tools (e.g. `npm test` may run Jest, Vitest, or Mocha). A parent filter can declare `[[variant]]` entries that delegate to specialized child filters based on project context.\n\n```toml\ncommand = [\"npm test\", \"pnpm test\", \"yarn test\"]\n\nstrip_ansi = true\nskip = [\"^> \", \"^\\\\s*npm (warn|notice|WARN|verbose|info|timing|error|ERR)\"]\n\n[on_success]\noutput = \"{output}\"\n\n[on_failure]\ntail = 20\n\n[[variant]]\nname = \"vitest\"\ndetect.files = [\"vitest.config.ts\", \"vitest.config.js\", \"vitest.config.mts\"]\nfilter = \"npm\u002Ftest-vitest\"\n\n[[variant]]\nname = \"jest\"\ndetect.files = [\"jest.config.js\", \"jest.config.ts\", \"jest.config.json\"]\nfilter = \"npm\u002Ftest-jest\"\n```\n\n**Fields**:\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `name` | string | yes | Human-readable identifier for this variant |\n| `detect.files` | array of strings | no | File paths to check in CWD (pre-execution detection) |\n| `detect.output_pattern` | string (regex) | no | Regex to match against command output (post-execution fallback) |\n| `filter` | string | yes | Filter to delegate to (relative path without `.toml`, e.g. `\"npm\u002Ftest-vitest\"`) |\n\n**Two-phase detection**:\n1. **File detection** (before execution) — checks if any listed config files exist in the current directory. First match wins.\n2. **Output pattern** (after execution) — regex-matches the command output. Used as a fallback when no file was detected.\n\nAt least one of `detect.files` or `detect.output_pattern` must be set.\n\n**Behavior**:\n- When a variant matches, the child filter **replaces** the parent entirely — no field inheritance or merging\n- When no variant matches, the parent filter's own fields (`skip`, `on_success`, etc.) apply as the fallback\n- The `filter` field references another filter by its discovery name (e.g. `\"npm\u002Ftest-vitest\"` maps to `filters\u002Fnpm\u002Ftest-vitest.toml`)\n\n**TOML ordering**: `[[variant]]` entries must appear **after** all top-level fields (`skip`, `[on_success]`, etc.) because TOML array-of-tables sections capture subsequent keys.\n\n**When to use**: when a single command pattern maps to different underlying tools that produce fundamentally different output formats. Create a parent filter with a generic fallback, then create specialized child filters for each tool.\n\n---\n\n## Section 5 — Template Pipes\n\nOutput templates support pipe chains: `{var | pipe | pipe: \"arg\"}`.\n\n| Pipe | Input → Output | Description |\n|---|---|---|\n| `lines` | Str → Collection | Split string on newlines into a list |\n| `join: \"sep\"` | Collection → Str | Join list items with separator string |\n| `each: \"tmpl\"` | Collection → Collection | Map each item through a sub-template; `{value}` = item, `{index}` = 1-based index. For structured collections (from chunks), all named fields are also available (e.g. `{crate_name}`, `{passed}`). |\n| `keep: \"re\"` | Collection → Collection | Retain items matching the regex |\n| `where: \"re\"` | Collection → Collection | Alias for `keep:` |\n| `truncate: N` | Str → Str | Truncate to N characters, appending `…` |\n\n**Examples**:\n\nFilter a multi-line output variable to only error lines:\n```toml\n[on_failure]\noutput = \"{output | lines | keep: \\\"^error\\\" | join: \\\"\\\\n\\\"}\"\n```\n\nFor each collected block, show only `>` (pointer) and `E` (assertion) lines:\n```toml\n[on_failure]\noutput = \"{failure_blocks | each: \\\"{value | lines | keep: \\\\\\\"^[>E] \\\\\\\"}\\\" | join: \\\"\\\\n\\\"}\"\n```\n\nTruncate long lines and number them:\n```toml\n[on_failure]\noutput = \"{summary_lines | each: \\\"{index}. {value | truncate: 120}\\\" | join: \\\"\\\\n\\\"}\"\n```\n\n---\n\n## Section 6 — Naming & Placement Conventions\n\n**File naming**:\n- `filters\u002F\u003Ctool>\u002F\u003Csubcommand>.toml` for two-word commands: `filters\u002Fgit\u002Fpush.toml` for `git push`\n- `filters\u002F\u003Ctool>.toml` for single-word commands: `filters\u002Fpytest.toml` for `pytest`\n- For wildcards: `filters\u002Fnpm\u002Frun.toml` with `command = \"npm run *\"` in the TOML\n- Lowercase filenames only, no spaces\n\n**Placement**:\n| Location | Purpose |\n|---|---|\n| `.tokf\u002Ffilters\u002F` | Project-local override (committed to the repo) |\n| `~\u002F.config\u002Ftokf\u002Ffilters\u002F` | User-level override (your personal filters) |\n| `filters\u002F` in the tokf source repo | Built-in library (requires a tokf release) |\n\nWhen creating a filter for a user's project, default to `.tokf\u002Ffilters\u002F` unless they specify otherwise.\n\n**Command field**:\n- Exact match: `command = \"git push\"` matches `git push` and `git push origin main`\n- Wildcard: `command = \"npm run *\"` matches `npm run dev`, `npm run build`, etc.\n- Array: `command = [\"cargo test\", \"cargo t\"]` matches either form\n\n---\n\n## Section 7 — Workflow for Creating a New Filter\n\nFollow these steps when asked to create a filter:\n\n### Step 1: Understand the command's output\n\nAsk the user to provide (or capture) example output from the command. If they don't have it, generate a plausible example based on the tool's known output format. Look for:\n- What's signal (errors, results, summaries)\n- What's noise (progress bars, compilation lines, download progress, blank lines)\n- What patterns mark sections (e.g., \"failures:\", \"test result:\")\n\n### Step 2: Choose the right complexity level\n\n| Level | When to use | Steps to use |\n|---|---|---|\n| Level 1 (simple) | Command produces one-liner outcomes | `match_output`, `skip`, `extract` |\n| Level 2 (structured) | Table-like output needing grouping | `[parse]` + `[output]` |\n| Level 2J (JSON) | Command produces JSON output | `[json]` + `on_success`\u002F`on_failure` templates |\n| Level 3 (stateful) | Multi-section output with nested structure | `[[section]]` + `aggregate` + pipes |\n| Level 4 (chunked) | Repeating blocks with per-block aggregation (workspaces) | `[[chunk]]` + `[[section]]` + `aggregates` + tree templates |\n\nStart at the lowest level that handles the use case. Don't reach for `[[section]]` when `skip` + `extract` suffices.\n\n### Step 3: Draft the filter\n\n1. Set `command` to match the command pattern\n2. Add `match_output` for well-known short-circuit cases (empty output, auth failure, \"already done\")\n3. Add `skip` to drop noise lines (progress, compile output, blank lines)\n4. Add `[[replace]]` to reformat noisy-but-useful lines\n5. Add `[[section]]` or `[parse]` if you need structured extraction\n6. Write `[on_success]` with the desired output format\n7. Write `[on_failure]` with enough context to diagnose (`tail = 20` is a safe default)\n8. Add `[fallback]` with `tail = 5` as a safety net for complex filters\n\n### Step 4: Write test cases and verify\n\nCreate a `\u003Cstem>_test\u002F` directory adjacent to the filter TOML and add at least one test case per meaningful outcome (success, failure, edge cases):\n\n```\nfilters\u002Fmytool\u002F\n  mysubcmd.toml       ← filter config\n  mysubcmd_test\u002F      ← test suite\n    success.toml\n    failure.toml\n```\n\nEach test case is a TOML file:\n\n```toml\nname = \"success shows one clean line\"\nfixture = \"tests\u002Ffixtures\u002Fmytool_success.txt\"  # path relative to this file, then CWD\nexit_code = 0\n\n[[expect]]\nequals = \"ok ✓\"\n\n[[expect]]\nnot_contains = \"noise\"\n```\n\nOr with an inline fixture (no file needed):\n\n```toml\nname = \"known error message\"\ninline = \"Error: connection refused\\n\"\nexit_code = 1\n\n[[expect]]\ncontains = \"connection refused\"\n```\n\nRun the suite:\n\n```sh\ntokf verify mytool\u002Fmysubcmd   # run one suite\ntokf verify                   # run all suites\n```\n\nFor quick one-off testing without creating test files:\n\n```sh\ntokf test filters\u002Fmytool\u002Fmysubcmd.toml tests\u002Ffixtures\u002Fmytool_output.txt --exit-code 0\n```\n\n### Step 5: Place and name the file correctly\n\n- Two-word command: `.tokf\u002Ffilters\u002Fmytool\u002Fmysubcmd.toml`\n- Single-word command: `.tokf\u002Ffilters\u002Fmytool.toml`\n- Wildcard command: `.tokf\u002Ffilters\u002Fmytool\u002Frun.toml` with `command = \"mytool run *\"`\n\n---\n\n## Section 8 — Three Annotated Examples\n\n### Example 1: `git push` (Level 1 — match_output + extract)\n\nGoal: 15 lines of push noise → \"ok ✓ main\" (or failure message).\n\n```toml\n# filters\u002Fgit\u002Fpush.toml — Level 1\n# Raw output: 15 lines of object counting, compression, \"remote:\" lines\n# Filtered (success): \"ok ✓ main\"\n# Filtered (up-to-date): \"ok (up-to-date)\"\n# Filtered (rejected): \"✗ push rejected (try pulling first)\"\n\ncommand = \"git push\"\n\n# Check full output for well-known outcomes before any processing\nmatch_output = [\n  { contains = \"Everything up-to-date\", output = \"ok (up-to-date)\" },\n  { contains = \"rejected\", output = \"✗ push rejected (try pulling first)\" },\n]\n\n[on_success]\n# Drop all the noise lines\nskip = [\n  \"^Enumerating objects:\",\n  \"^Counting objects:\",\n  \"^Delta compression\",\n  \"^Compressing objects:\",\n  \"^Writing objects:\",\n  \"^Total \\\\d+\",\n  \"^remote:\",\n  \"^To \",\n]\n# Extract the branch name from the ref update line: \"abc1234..def5678  main -> main\"\nextract = { pattern = '(\\S+)\\s*->\\s*(\\S+)', output = \"ok ✓ {2}\" }\n\n[on_failure]\ntail = 10\n```\n\n**Key decisions**:\n- `match_output` handles the two most common \"instant\" outcomes\n- `extract` captures the branch name from the ref update line\n- `tail = 10` on failure gives enough context without overwhelming\n\n---\n\n### Example 2: `git status` (Level 2 — parse + group)\n\nGoal: 30+ lines of verbose status → branch name + grouped file counts.\n\n```toml\n# filters\u002Fgit\u002Fstatus.toml — Level 2\n# Raw output: 30+ lines with hints, file paths, status codes\n# Filtered: \"main [ahead 2]\\n  modified: 3\\n  untracked: 2\"\n\ncommand = \"git status\"\n\n# Override: use porcelain format for reliable machine parsing\nrun = \"git status --porcelain -b\"\n\nmatch_output = [\n  { contains = \"not a git repository\", output = \"Not a git repository\" },\n]\n\n[parse]\n# First line: \"## main...origin\u002Fmain [ahead 2]\"\n# Extract: branch name, upstream, ahead\u002Fbehind info\nbranch = { line = 1, pattern = '## (\\S+?)(?:\\.\\.\\.(\\S+))?(?:\\s+\\[(.+)\\])?$', output = \"{1}\" }\n\n[parse.group]\n# Group remaining lines by their two-character status code\nkey = { pattern = '^(.{2}) ', output = \"{1}\" }\nlabels = {\n  \"M \" = \"modified\",\n  \" M\" = \"modified (unstaged)\",\n  \"MM\" = \"modified (staged+unstaged)\",\n  \"A \" = \"added\",\n  \"??\" = \"untracked\",\n  \"D \" = \"deleted\",\n  \" D\" = \"deleted (unstaged)\",\n  \"R \" = \"renamed\",\n  \"UU\" = \"conflict\",\n  \"AM\" = \"added+modified\"\n}\n\n[output]\nformat = \"\"\"\n{branch}{tracking_info}\n{group_counts}\"\"\"\ngroup_counts_format = \"  {label}: {count}\"\nempty = \"clean — nothing to commit\"\n```\n\n**Key decisions**:\n- `run` overrides to porcelain format — machine-readable is easier to parse\n- `[parse]` extracts the branch header line declaratively\n- `[parse.group]` groups by status code without needing `[[section]]`\n- `[output]` uses built-in `{group_counts}` variable populated by the parser\n\n---\n\n### Example 3: `cargo test` (Level 4 — section + chunk + aggregates + tree)\n\nGoal: 200+ lines with compile noise, per-test \"ok\" lines, failure blocks → per-crate tree summary on pass, structured failure report on fail.\n\n```toml\n# filters\u002Fcargo\u002Ftest.toml — Level 4\n# Raw output: 200+ lines\n# Filtered (pass): \"✓ cargo test: 1279 passed, 0 failed, 119 ignored (42 suites)\"\n#                   with per-crate tree breakdown showing individual test suites\n# Filtered (fail): failure details + summary\n\ncommand = \"cargo test\"\nstrip_ansi = true\n\n# Drop all the noise\nskip = [\n  \"^\\\\s*Compiling \",\n  \"^\\\\s*Downloading \",\n  \"^\\\\s*Downloaded \",\n  \"^\\\\s*Finished \",\n  \"^\\\\s*Locking \",\n  \"^running \\\\d+ tests?$\",\n  \"^test .+ \\\\.\\\\.\\\\. ok$\",   # individual passing tests\n  \"^\\\\s*$\",\n  \"^\\\\s*Doc-tests \",\n]\n\n# State machine: collect the \"failures:\" section into blocks split by blank lines\n[[section]]\nname = \"failures\"\nenter = \"^failures:$\"\nexit = \"^failures:$\"\nsplit_on = \"^\\\\s*$\"\ncollect_as = \"failure_blocks\"\n\n# Collect \"test result: ok\u002FFAILED\" summary lines (one per test suite)\n[[section]]\nname = \"summary\"\nmatch = \"^test result:\"\ncollect_as = \"summary_lines\"\n\n# Chunk processing: per-crate breakdown from \"Running\" headers.\n# \"unittests\" lines define crate boundaries; integration test suites\n# inherit the crate name via carry_forward.\n[[chunk]]\nsplit_on = \"^\\\\s*Running \"\ninclude_split_line = true\ncollect_as = \"suites_detail\"\ngroup_by = \"crate_name\"\nchildren_as = \"children\"\n\n[chunk.extract]\npattern = 'unittests.+deps\u002F([\\w_-]+)-'\nas = \"crate_name\"\ncarry_forward = true\n\n[[chunk.body_extract]]\npattern = 'Running\\s+(.+?)\\s+\\('\nas = \"suite_name\"\n\n[[chunk.aggregate]]\npattern = '(\\d+) passed'\nsum = \"passed\"\n\n[[chunk.aggregate]]\npattern = '(\\d+) failed'\nsum = \"failed\"\n\n[[chunk.aggregate]]\npattern = '(\\d+) ignored'\nsum = \"ignored\"\n\n[[chunk.aggregate]]\npattern = '^test result:'\ncount_as = \"suite_count\"\n\n# Success: aggregate summaries + per-crate tree breakdown\n[on_success]\noutput = \"✓ cargo test: {passed} passed, {failed} failed, {ignored} ignored ({suites} suites)\\n{suites_detail | each: \\\"  {crate_name}: {passed} passed ({suite_count} suites)\\\\n{children | each: \\\\\\\"    {suite_name}: {passed} passed\\\\\\\" | join: \\\\\\\"\\\\\\\\n\\\\\\\"}\\\" | join: \\\"\\\\n\\\"}\"\n\n[[on_success.aggregates]]\nfrom = \"summary_lines\"\npattern = 'ok\\. (\\d+) passed'\nsum = \"passed\"\ncount_as = \"suites\"\n\n[[on_success.aggregates]]\nfrom = \"summary_lines\"\npattern = '(\\d+) failed'\nsum = \"failed\"\n\n[[on_success.aggregates]]\nfrom = \"summary_lines\"\npattern = '(\\d+) ignored'\nsum = \"ignored\"\n\n# Failure: show failure details + summary\n[on_failure]\noutput = \"✗ cargo test: {passed} passed, {failed} failed ({suites} suites)\\n\\nFAILURES ({failure_blocks.count}):\\n{failure_blocks | each: \\\"\\\\n── {index}. ──\\\\n{value}\\\" | join: \\\"\\\\n\\\"}\\n\\n{summary_lines | join: \\\"\\\\n\\\"}\"\n\n[[on_failure.aggregates]]\nfrom = \"summary_lines\"\npattern = '(\\d+) passed'\nsum = \"passed\"\ncount_as = \"suites\"\n\n[[on_failure.aggregates]]\nfrom = \"summary_lines\"\npattern = '(\\d+) failed'\nsum = \"failed\"\n\n[fallback]\ntail = 5\n```\n\n**Key decisions**:\n- `skip` removes all per-test \"ok\" lines — only failures and summaries remain\n- `[[section]]` collectors handle failure blocks and summary lines\n- `[[chunk]]` splits on `Running` headers, extracts crate names from `unittests` lines\n- `carry_forward = true` makes integration test suites inherit the crate name from the preceding unit test suite\n- `children_as = \"children\"` preserves per-suite detail within each crate group\n- `[[on_success.aggregates]]` (plural) sums passed\u002Ffailed\u002Fignored across all suite summary lines\n- Nested `each` pipes produce tree output: crate → suites\n- `[fallback]` catches edge cases (compile errors with no test output)\n\n---\n\n## Section 9 — Writing Test Cases\n\nEvery filter in the standard library has a `\u003Cstem>_test\u002F` directory with declarative test cases. When writing or modifying a filter, write test cases alongside it.\n\n### Test case format\n\n```toml\nname = \"success output is a single clean line\"   # required, human-readable\nfixture = \"tests\u002Ffixtures\u002Fcargo_build_success.txt\"  # path to raw output file\n# inline = \"some raw output\\nline two\"            # alternative: inline fixture\nexit_code = 0                                    # optional, default 0\nargs = []                                        # optional, forwarded to filter\n\n[[expect]]\nequals = \"ok ✓\"          # exact match\n\n[[expect]]\nnot_contains = \"Compiling\"  # noise must be gone\n```\n\n### Assertion types\n\n| Field | Description |\n|---|---|\n| `equals` | Output exactly equals this string |\n| `contains` | Output contains this substring |\n| `not_contains` | Output does not contain this substring |\n| `starts_with` | Output starts with this string |\n| `ends_with` | Output ends with this string |\n| `line_count` | Output has exactly N non-empty lines |\n| `matches` | Output matches this regex |\n| `not_matches` | Output does not match this regex |\n\nEvery `[[expect]]` entry checks one assertion. A test case with multiple `[[expect]]` entries must pass all of them. A test case with no `[[expect]]` entries is an error.\n\n### What to test\n\nFor every filter, write at least:\n- **Success case**: the happy path produces the expected one-liner or summary\n- **Failure case**: a failing exit code produces enough context to diagnose\n- **Edge cases**: cover each `match_output` branch (e.g., \"up-to-date\", \"rejected\")\n\n### Directory convention\n\n```\nfilters\u002F\n  git\u002F\n    push.toml          ← filter config\n    push_test\u002F         ← test suite (identified by _test suffix)\n      success.toml\n      up_to_date.toml\n      rejected.toml\n      failure.toml\n```\n\nThe `_test` suffix makes suite directories immediately identifiable in file listings and distinguishes them from filter category directories.\n\n---\n\n## Section 10 — Common Mistakes to Avoid\n\n1. **Don't use `keep` when `skip` is enough.** `keep` is an allow-list — it drops everything that doesn't match. Use it only when you want to radically filter to a specific type of line.\n\n2. **Escape backslashes in TOML strings.** In regular strings, `\\\\d` means literal `\\d` in the regex. In TOML raw strings (`'...'`), backslashes are literal. Use raw strings for complex patterns.\n\n3. **`match_output` is a short-circuit.** If it matches, nothing else runs. Don't put it at the end expecting it to be a fallback — it runs first.\n\n4. **`[[section]]`, `[parse]`, and `[json]` are mutually exclusive in practice.** `[json]` replaces `[[section]]`\u002F`[parse]`\u002F`[[chunk]]` — when `[json]` is configured, those line-based steps are skipped. Use `[json]` for JSON output, `[[section]]`\u002F`[parse]`\u002F`[[chunk]]` for line-based output.\n\n5. **`{output}` in branch templates is the filtered output text** (after skip\u002Fkeep\u002Freplace\u002Fdedup), not the raw command output.\n\n6. **Pipe chains need careful quoting.** When nesting templates inside `each:`, escape inner quotes: `{each: \"{value | lines | keep: \\\\\\\"^error\\\\\\\"}\"}`.\n\n7. **Don't skip the `[fallback]`.** Complex filters with `[[section]]` can produce empty output if sections don't match. Always add `[fallback] tail = 5` as a safety net.\n\n8. **Test with realistic fixture data.** A filter that works on a trimmed example may miss edge cases. Use real command output saved to a `.txt` fixture file.\n","# tokf Filter Authoring\n\nYou are an expert at writing tokf filter files. tokf is a config-driven CLI that compresses command output before it reaches an LLM context. Filters are TOML files that define how to process a command's output.\n\nWhen the user asks you to create or modify a filter, follow this guide exactly. Produce valid, idiomatic TOML that matches the schema described below.\n\n---\n\n## Section 1 — What a Filter File Is\n\nA filter file is a TOML file that describes:\n- Which command(s) it applies to (`command`)\n- How to transform the raw output (steps, applied in a fixed order)\n- What to emit on success vs. failure\n\nFilters live in three places, searched in priority order:\n\n1. `.tokf\u002Ffilters\u002F` — project-local (repo-level overrides)\n2. `~\u002F.config\u002Ftokf\u002Ffilters\u002F` — user-level overrides\n3. Built-in library (embedded in the tokf binary)\n\nFirst match wins. Use `tokf which \"cargo test\"` to see which filter would activate for a given command.\n\n---\n\n## Section 2 — Processing Order\n\nSteps execute in this fixed order — **do not rearrange them**:\n\n1. **`match_output`** — whole-output substring checks; if matched, short-circuits the entire pipeline and emits immediately\n2. **`[[replace]]`** — per-line regex transforms applied to every line, in array order\n3. **`strip_ansi` \u002F `trim_lines`** — per-line cleanup (ANSI stripping, whitespace trimming)\n4. **`skip` \u002F `keep`** — line-level filtering (drop or retain lines by regex)\n5. **`dedup` \u002F `dedup_window`** — collapse duplicate consecutive lines\n6. **`lua_script`** — Luau escape hatch; runs after dedup, before JSON\u002Fsection\u002Fparse\n7. **`[json]`** — JSON extraction via `JSONPath`; when configured, replaces section\u002Fparse\u002Fchunk\n8. **`[[section]]` OR `[parse]`** — structured extraction (these are mutually exclusive; section is a state machine, parse is a declarative grouper). Skipped when `[json]` is configured.\n9. **`[[chunk]]`** — block-based structured extraction with per-block aggregation, grouping, and tree output (runs on raw output, alongside sections). Skipped when `[json]` is configured.\n10. **Exit-code branch** — `[on_success]` or `[on_failure]` depending on exit code\n11. **`[fallback]`** — if neither `on_success` nor `on_failure` produced output\n12. **`strip_empty_lines` \u002F `collapse_empty_lines`** — post-processing cleanup on the final output\n\nWithin `[on_success]` and `[on_failure]`, fields are processed as:\n- `head` \u002F `tail` → trim lines\n- `skip` \u002F `extract` → further filter\n- `aggregate` → reduce collected sections\n- `output` → final template render\n\n---\n\n## Section 3 — Top-Level Fields Reference\n\n| Field | Type | Default | Description |\n|---|---|---|---|\n| `command` | string or array of strings | required | Command pattern(s) to match. Supports `*` wildcard. |\n| `run` | string | (same as command) | Override the actual command executed. Use `{args}` to forward arguments. |\n| `match_output` | array of tables | `[]` | Whole-output checks. Short-circuit on first match. |\n| `[[replace]]` | array of tables | `[]` | Per-line regex replacements, in order. |\n| `skip` | array of strings (regex) | `[]` | Drop lines matching any regex. |\n| `keep` | array of strings (regex) | `[]` | Retain only lines matching any regex. (Inverse of skip.) |\n| `dedup` | bool | `false` | Collapse consecutive identical lines. |\n| `dedup_window` | integer | `0` (off) | Dedup within a sliding window of N lines. |\n| `strip_ansi` | bool | `false` | Strip ANSI escape sequences before skip\u002Fkeep. |\n| `trim_lines` | bool | `false` | Trim leading\u002Ftrailing whitespace from each line. |\n| `lua_script` | table | (absent) | Luau escape hatch. |\n| `[json]` | table | (absent) | JSON extraction via `JSONPath`. When configured, replaces `[[section]]`\u002F`[parse]`\u002F`[[chunk]]`. |\n| `[[section]]` | array of tables | `[]` | State-machine section collectors. |\n| `[[chunk]]` | array of tables | `[]` | Block-based structured extraction with per-block aggregation and grouping. |\n| `[parse]` | table | (absent) | Declarative structured parser (branch + group). |\n| `[on_success]` | table | (absent) | Output branch for exit code 0. |\n| `[on_failure]` | table | (absent) | Output branch for non-zero exit. |\n| `[output]` | table | (absent) | Top-level output template (used by `[parse]`). |\n| `[fallback]` | table | (absent) | Fallback when no branch matched. |\n| `strip_empty_lines` | bool | `false` | Remove all blank lines from the final output. |\n| `collapse_empty_lines` | bool | `false` | Collapse consecutive blank lines into one. |\n| `show_history_hint` | bool | `false` | Append a hint line after filtered output pointing to the full output in history. |\n| `[[variant]]` | array of tables | `[]` | Context-aware delegation to specialized child filters. |\n\n---\n\n## Section 4 — Step Types\n\n### 4.1 `match_output` — Whole-Output Short-Circuit\n\nCheck the entire raw output for a substring. If matched, emit a fixed string and stop — no further processing.\n\n```toml\nmatch_output = [\n  { contains = \"Everything up-to-date\", output = \"ok (up-to-date)\" },\n  { contains = \"rejected\", output = \"✗ push rejected (try pulling first)\" },\n]\n```\n\n- `contains`: literal substring to search for (case-sensitive)\n- `output`: string to emit if matched\n- `{line_containing}` template variable: the first line that contains the substring\n\n```toml\nmatch_output = [\n  { contains = \"error\", output = \"Error on: {line_containing}\" },\n]\n```\n\n**When to use**: for well-known one-liner outcomes that make the rest of filtering irrelevant (e.g., \"already up to date\", \"nothing to push\", \"authentication failed\").\n\n---\n\n### 4.2 `[[replace]]` — Per-Line Regex Transforms\n\nApplied to every line, in array order, before skip\u002Fkeep. Use to reformat noisy lines.\n\n```toml\n[[replace]]\npattern = '^(\\S+)\\s+\\S+\\s+(\\S+)\\s+(\\S+)'\noutput = \"{1}: {2} → {3}\"\n\n[[replace]]\npattern = '^\\s+Compiling (\\S+) v(\\S+)'\noutput = \"compiling {1}@{2}\"\n```\n\n- `pattern`: Rust regex (RE2 syntax, no lookaheads)\n- `output`: template with `{1}`, `{2}`, … for capture groups; `{0}` is the full match\n- If the pattern doesn't match a line, that line passes through unchanged\n- Invalid patterns are silently skipped at runtime\n\n**When to use**: when a line contains useful information but in a verbose format — reformat it rather than dropping it.\n\n---\n\n### 4.3 `skip` \u002F `keep` — Line Filtering\n\n`skip` drops lines matching any regex. `keep` retains only lines matching any regex. They compose:\n\n```toml\nskip = [\n  \"^\\\\s*Compiling \",\n  \"^\\\\s*Downloading \",\n  \"^\\\\s*$\",\n]\n\nkeep = [\"^error\", \"^warning\"]\n```\n\n- Both are arrays of regex strings\n- Applied after `[[replace]]`\n- `skip` is checked first, then `keep`\n- A line must pass both: not skipped, and (if keep is non-empty) matching keep\n\n**When to use**: `skip` for removing known noise patterns; `keep` for allow-listing (e.g., keep only lines that start with `error` or `warning`).\n\nAlso available inside `[on_success]` and `[on_failure]` for branch-level filtering.\n\n---\n\n### 4.4 `dedup` \u002F `dedup_window` — Deduplication\n\n```toml\ndedup = true           # collapse consecutive identical lines\ndedup_window = 10      # dedup within a 10-line sliding window\n```\n\n- `dedup = true`: removes consecutive duplicate lines (like `uniq`)\n- `dedup_window = N`: deduplicates within a sliding window of N lines (catches near-consecutive repeats)\n- They are independent; you can use both\n\n**When to use**: for commands that emit repetitive progress lines (e.g., `npm install` printing the same package multiple times, spinner frames, repeated warnings).\n\n---\n\n### 4.5 `lua_script` — Luau Escape Hatch\n\nFor logic that pure TOML cannot express: numeric math, multi-line lookahead, conditional branching.\n\n```toml\n[lua_script]\nlang = \"luau\"\nsource = '''\nif exit_code == 0 then\n    return \"passed\"\nelse\n    local msg = output:match(\"Error: (.+)\") or \"unknown error\"\n    return \"FAILED: \" .. msg\nend\n'''\n```\n\nOr load the script from an external file:\n\n```toml\n[lua_script]\nlang = \"luau\"\nfile = \"scripts\u002Fmy-filter.luau\"\n```\n\nThe `file` path resolves relative to the current working directory. Exactly one of `source` or `file` must be set.\n\n**Globals available**:\n- `output` (string): the full output after skip\u002Fkeep\u002Fdedup\n- `exit_code` (integer): the command's exit code\n- `args` (table of strings): the arguments passed to the command\n\n**Return semantics**:\n- Return a string → replaces output, skips remaining TOML pipeline\n- Return `nil` → fall through to `[[section]]` \u002F `[parse]` \u002F `[on_success]` \u002F `[on_failure]`\n\n**Sandbox**: `io`, `os`, and `package` are blocked. No filesystem or network access. Standard math\u002Fstring\u002Ftable libraries are available.\n\n**When to use**: only when no TOML step can express the logic. Most filters do not need this. Consider it after exhausting `match_output`, `skip\u002Fkeep`, `[[replace]]`, `[[section]]`, and `[parse]`.\n\n---\n\n### 4.6 `[json]` — JSON Extraction via `JSONPath`\n\nFor commands that produce JSON output (e.g. `kubectl get pods -o json`, `gh api`, `docker inspect`). Extracts values using `JSONPath` (RFC 9535) queries and produces template variables and structured collections.\n\n```toml\n[json]\n\n[[json.extract]]\npath = \"$.items[*]\"\nas = \"pods\"\n\n[[json.extract.fields]]\nfield = \"metadata.name\"\nas = \"name\"\n\n[[json.extract.fields]]\nfield = \"status.phase\"\nas = \"phase\"\n\n[on_success]\noutput = \"Pods ({pods_count}):\\n{pods | each: \\\"  {name}: {phase}\\\" | join: \\\"\\\\n\\\"}\"\n```\n\n**`[[json.extract]]` fields**:\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `path` | string | yes | `JSONPath` expression (RFC 9535), e.g. `\"$.items[*]\"`, `\"$.version\"` |\n| `as` | string | yes | Variable name to bind the result to |\n| `fields` | array of tables | no | Sub-field extraction for each matched object |\n\n**`[[json.extract.fields]]` fields**:\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `field` | string | yes | Dot-separated path within each object (e.g. `\"metadata.name\"`, `\"containers.0.name\"`). Not JSONPath — uses simple dot-notation. Supports numeric array indices. |\n| `as` | string | yes | Variable name for the extracted value |\n\n**Result mapping**:\n- **Single scalar** → `vars[\"as_name\"] = string_value` (no count, no chunk)\n- **Array** → `ChunkData::Flat` collection + `{as_name_count}` variable\n- **Objects without `fields`** → top-level scalars auto-flattened into chunk items\n- **Objects with `fields`** → named fields extracted per item\n\n**Pipeline behavior**: when `[json]` is configured, `[[section]]`, `[parse]`, and `[[chunk]]` are skipped. JSON replaces line-based structural processing. Extracted vars and chunks flow into `[on_success]`\u002F`[on_failure]` template rendering.\n\n**Error handling**: invalid JSON input → extraction skipped, pipeline falls back to raw output (templates are not rendered). Invalid JSONPath → rule silently skipped, other rules still run. Empty array with `fields` → emits `{as_name_count} = \"0\"`.\n\n**When to use**: when the command produces structured JSON output and you need to extract specific fields. Prefer this over `[parse]` + `skip`\u002F`keep` for JSON-native commands.\n\n---\n\n### 4.7 `[[section]]` — State-Machine Section Collector\n\nThe most powerful step. Defines a state machine that collects lines into named variables as it scans top-to-bottom.\n\n```toml\n[[section]]\nname = \"failures\"\nenter = \"^failures:$\"      # regex: start collecting when this matches\nexit = \"^failures:$\"       # regex: stop collecting when this matches (after start)\nsplit_on = \"^\\\\s*$\"        # regex: split collected lines into blocks on blank lines\ncollect_as = \"failure_blocks\"\n\n[[section]]\nname = \"summary\"\nmatch = \"^test result:\"    # regex: collect only lines matching this (no enter\u002Fexit)\ncollect_as = \"summary_lines\"\n```\n\n**Fields**:\n| Field | Required | Description |\n|---|---|---|\n| `name` | yes | Identifier for this section (used in error messages) |\n| `enter` | no | Regex to start collecting (state transitions to \"inside\") |\n| `exit` | no | Regex to stop collecting (state transitions to \"outside\") |\n| `match` | no | Collect any line matching this regex, without enter\u002Fexit state |\n| `split_on` | no | Split collected lines into blocks when this regex matches |\n| `collect_as` | yes | Variable name to bind the result to |\n\n**Accessing collected variables in templates**:\n| Expression | Type | Description |\n|---|---|---|\n| `{name}` | string | Full collected text joined with newlines |\n| `{name.lines}` | collection | Individual lines as a list |\n| `{name.blocks}` | collection | Blocks split by `split_on` |\n| `{name.count}` | integer | Number of blocks (or lines if no split_on) |\n\n**When to use**: when the output has distinct sections with clear start\u002Fend markers — test failure blocks, error sections, file change groups.\n\n---\n\n### 4.8 `[[chunk]]` — Block-Based Structured Extraction\n\nChunks split raw output into repeating structural blocks (e.g., per-crate test suites in a Cargo workspace), extract structured data per-block, and produce named collections for template rendering. Like sections, chunks operate on the raw (unfiltered) command output — skip\u002Fkeep patterns do not affect chunk processing.\n\n```toml\n[[chunk]]\nsplit_on = \"^\\\\s*Running \"       # regex marking the start of each chunk\ninclude_split_line = true         # include the splitting line in the chunk (default: true)\ncollect_as = \"suites_detail\"      # name for the structured collection\ngroup_by = \"crate_name\"           # merge chunks sharing this field value\nchildren_as = \"children\"          # preserve original items as nested collection\n\n[chunk.extract]\npattern = 'unittests.+deps\u002F([\\w_-]+)-'  # extract a field from the header line\nas = \"crate_name\"\ncarry_forward = true              # inherit value from previous chunk when pattern doesn't match\n\n[[chunk.body_extract]]\npattern = 'Running\\s+(.+?)\\s+\\('\nas = \"suite_name\"\n\n[[chunk.aggregate]]\npattern = '(\\d+) passed'          # aggregates run within each chunk's lines\nsum = \"passed\"\n\n[[chunk.aggregate]]\npattern = '^test result:'\ncount_as = \"suite_count\"\n```\n\n**Fields**:\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `split_on` | string (regex) | yes | Regex marking the start of each chunk |\n| `include_split_line` | bool | no | Whether the splitting line is part of the chunk (default: `true`) |\n| `collect_as` | string | yes | Name for the resulting structured collection |\n| `extract` | table | no | Extract a named field from the header line (`pattern` + `as`) |\n| `body_extract` | array of tables | no | Extract fields from body lines (`pattern` + `as`, first match wins) |\n| `aggregate` | array of tables | no | Per-chunk aggregation rules (`pattern` + `sum`\u002F`count_as`) |\n| `group_by` | string | no | Merge chunks sharing the same field value, summing numeric fields |\n| `children_as` | string | no | When set with `group_by`, preserve original items as a nested collection |\n\n**`carry_forward`** (on `extract` or `body_extract`): when a chunk's pattern doesn't match, inherit the value from the most recent chunk that did. Useful when boundary markers (like `Running unittests`) identify a group, and subsequent chunks should inherit that identity.\n\n**Structured collections in templates**: each item has named fields accessible in `each` pipes:\n\n```toml\n[on_success]\noutput = \"\"\"\\\n{suites_detail | each: \"  {crate_name}: {passed} passed ({suite_count} suites)\" | join: \"\\\\n\"}\"\"\"\n```\n\n**Tree output with `children_as`**: groups preserve their child items for nested template rendering:\n\n```toml\n[on_success]\noutput = \"\"\"\\\n{suites_detail | each: \"  {crate_name}: {passed} passed\\\\n{children | each: \\\"    {suite_name}: {passed} passed\\\" | join: \\\"\\\\n\\\"}\" | join: \"\\\\n\"}\"\"\"\n```\n\n**When to use**: when output contains repeating structural blocks with per-block data you want to aggregate and display. Common for workspace build tools (Cargo, Gradle, Nx) where output is organized by sub-project.\n\n---\n\n### 4.9 `[parse]` — Declarative Structured Parser\n\nAlternative to `[[section]]` for commands with table-like output. Declaratively extracts a header field and groups remaining lines.\n\n```toml\n[parse]\nbranch = { line = 1, pattern = '## (\\S+?)(?:\\.\\.\\.(\\S+))?(?:\\s+\\[(.+)\\])?$', output = \"{1}\" }\n\n[parse.group]\nkey = { pattern = '^(.{2}) ', output = \"{1}\" }\nlabels = { \"M \" = \"modified\", \"??\" = \"untracked\", \"D \" = \"deleted\" }\n\n[output]\nformat = \"\"\"\n{branch}{tracking_info}\n{group_counts}\"\"\"\ngroup_counts_format = \"  {label}: {count}\"\nempty = \"clean — nothing to commit\"\n```\n\n**`[parse]` fields**:\n| Field | Description |\n|---|---|\n| `branch` | Extract a single value from a specific line (`line`, `pattern`, `output`) |\n| `[parse.group]` | Group remaining lines by a key pattern |\n\n**`[parse.group]` fields**:\n| Field | Description |\n|---|---|\n| `key` | `{ pattern, output }` — extract the grouping key from each line |\n| `labels` | Map from raw key string to human-readable label |\n\n**`[output]` fields** (used with `[parse]`):\n| Field | Description |\n|---|---|\n| `format` | Template string for the overall output |\n| `group_counts_format` | Template for each group entry: `{label}`, `{count}` |\n| `empty` | String to emit when no lines were grouped |\n\n**When to use**: for commands like `git status`, `docker ps`, `kubectl get` — table-formatted output where you want to extract a header and count\u002Fgroup rows.\n\n---\n\n### 4.10 `[on_success]` \u002F `[on_failure]` — Exit Code Branches\n\nThese branches run after all top-level steps. They have their own sub-fields:\n\n```toml\n[on_success]\noutput = \"ok ✓ {2}\"          # template; collected variables are available\nhead = 20                     # keep first N lines\ntail = 10                     # keep last N lines\nskip = [\"^\\\\s*$\"]            # additional line filtering\nextract = { pattern = '(\\S+)\\s*->\\s*(\\S+)', output = \"ok ✓ {2}\" }\n\n# Singular form (one rule):\naggregate = { from = \"summary_lines\", pattern = 'ok\\. (\\d+) passed', sum = \"passed\", count_as = \"suites\" }\n\n# Plural form (multiple rules):\n# [[on_success.aggregates]]\n# from = \"summary_lines\"\n# pattern = 'ok\\. (\\d+) passed'\n# sum = \"passed\"\n# count_as = \"suites\"\n#\n# [[on_success.aggregates]]\n# from = \"summary_lines\"\n# pattern = '(\\d+) failed'\n# sum = \"failed\"\n\n[on_failure]\ntail = 10\noutput = \"FAILED: {summary_lines | join: \\\"\\\\n\\\"}\"\n```\n\n**Branch sub-fields**:\n| Field | Description |\n|---|---|\n| `output` | Template string for the output. Has access to all `[[section]]` and `[[chunk]]` variables. `{output}` = the filtered output text. |\n| `head` | Keep first N lines of filtered output |\n| `tail` | Keep last N lines of filtered output |\n| `skip` | Array of regexes to filter output lines within this branch |\n| `extract` | `{ pattern, output }` — find first match, render template with capture groups |\n| `aggregate` | Reduce collected section lines into numeric summaries (singular form) |\n| `aggregates` | Array of aggregate rules (plural form — use `[[on_success.aggregates]]`) |\n\n**`aggregate` \u002F `aggregates` fields**:\n| Field | Description |\n|---|---|\n| `from` | Variable name (a `collect_as` result from `[[section]]`) |\n| `pattern` | Regex with one capture group to extract a number |\n| `sum` | Variable name to bind the sum to |\n| `count_as` | Variable name to bind the count (number of lines matched) to |\n\nBoth singular `aggregate` and plural `aggregates` can be used together — they are merged at runtime.\n\n**When to use**: Always. Every filter should have at least one of `[on_success]` or `[on_failure]`. Use `[on_success]` to produce a clean summary. Use `[on_failure]` to show enough context to diagnose the issue.\n\n---\n\n### 4.11 `[fallback]` — Last Resort\n\nEmits output when neither `[on_success]` nor `[on_failure]` produced anything.\n\n```toml\n[fallback]\ntail = 5\n```\n\n**When to use**: as a safety net when you have complex branching logic. Ensures tokf never silently swallows output.\n\n---\n\n### 4.12 `[[variant]]` — Context-Aware Filter Delegation\n\nSome commands are wrappers around different underlying tools (e.g. `npm test` may run Jest, Vitest, or Mocha). A parent filter can declare `[[variant]]` entries that delegate to specialized child filters based on project context.\n\n```toml\ncommand = [\"npm test\", \"pnpm test\", \"yarn test\"]\n\nstrip_ansi = true\nskip = [\"^> \", \"^\\\\s*npm (warn|notice|WARN|verbose|info|timing|error|ERR)\"]\n\n[on_success]\noutput = \"{output}\"\n\n[on_failure]\ntail = 20\n\n[[variant]]\nname = \"vitest\"\ndetect.files = [\"vitest.config.ts\", \"vitest.config.js\", \"vitest.config.mts\"]\nfilter = \"npm\u002Ftest-vitest\"\n\n[[variant]]\nname = \"jest\"\ndetect.files = [\"jest.config.js\", \"jest.config.ts\", \"jest.config.json\"]\nfilter = \"npm\u002Ftest-jest\"\n```\n\n**Fields**:\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `name` | string | yes | Human-readable identifier for this variant |\n| `detect.files` | array of strings | no | File paths to check in CWD (pre-execution detection) |\n| `detect.output_pattern` | string (regex) | no | Regex to match against command output (post-execution fallback) |\n| `filter` | string | yes | Filter to delegate to (relative path without `.toml`, e.g. `\"npm\u002Ftest-vitest\"`) |\n\n**Two-phase detection**:\n1. **File detection** (before execution) — checks if any listed config files exist in the current directory. First match wins.\n2. **Output pattern** (after execution) — regex-matches the command output. Used as a fallback when no file was detected.\n\nAt least one of `detect.files` or `detect.output_pattern` must be set.\n\n**Behavior**:\n- When a variant matches, the child filter **replaces** the parent entirely — no field inheritance or merging\n- When no variant matches, the parent filter's own fields (`skip`, `on_success`, etc.) apply as the fallback\n- The `filter` field references another filter by its discovery name (e.g. `\"npm\u002Ftest-vitest\"` maps to `filters\u002Fnpm\u002Ftest-vitest.toml`)\n\n**TOML ordering**: `[[variant]]` entries must appear **after** all top-level fields (`skip`, `[on_success]`, etc.) because TOML array-of-tables sections capture subsequent keys.\n\n**When to use**: when a single command pattern maps to different underlying tools that produce fundamentally different output formats. Create a parent filter with a generic fallback, then create specialized child filters for each tool.\n\n---\n\n## Section 5 — Template Pipes\n\nOutput templates support pipe chains: `{var | pipe | pipe: \"arg\"}`.\n\n| Pipe | Input → Output | Description |\n|---|---|---|\n| `lines` | Str → Collection | Split string on newlines into a list |\n| `join: \"sep\"` | Collection → Str | Join list items with separator string |\n| `each: \"tmpl\"` | Collection → Collection | Map each item through a sub-template; `{value}` = item, `{index}` = 1-based index. For structured collections (from chunks), all named fields are also available (e.g. `{crate_name}`, `{passed}`). |\n| `keep: \"re\"` | Collection → Collection | Retain items matching the regex |\n| `where: \"re\"` | Collection → Collection | Alias for `keep:` |\n| `truncate: N` | Str → Str | Truncate to N characters, appending `…` |\n\n**Examples**:\n\nFilter a multi-line output variable to only error lines:\n```toml\n[on_failure]\noutput = \"{output | lines | keep: \\\"^error\\\" | join: \\\"\\\\n\\\"}\"\n```\n\nFor each collected block, show only `>` (pointer) and `E` (assertion) lines:\n```toml\n[on_failure]\noutput = \"{failure_blocks | each: \\\"{value | lines | keep: \\\\\\\"^[>E] \\\\\\\"}\\\" | join: \\\"\\\\n\\\"}\"\n```\n\nTruncate long lines and number them:\n```toml\n[on_failure]\noutput = \"{summary_lines | each: \\\"{index}. {value | truncate: 120}\\\" | join: \\\"\\\\n\\\"}\"\n```\n\n---\n\n## Section 6 — Naming & Placement Conventions\n\n**File naming**:\n- `filters\u002F\u003Ctool>\u002F\u003Csubcommand>.toml` for two-word commands: `filters\u002Fgit\u002Fpush.toml` for `git push`\n- `filters\u002F\u003Ctool>.toml` for single-word commands: `filters\u002Fpytest.toml` for `pytest`\n- For wildcards: `filters\u002Fnpm\u002Frun.toml` with `command = \"npm run *\"` in the TOML\n- Lowercase filenames only, no spaces\n\n**Placement**:\n| Location | Purpose |\n|---|---|\n| `.tokf\u002Ffilters\u002F` | Project-local override (committed to the repo) |\n| `~\u002F.config\u002Ftokf\u002Ffilters\u002F` | User-level override (your personal filters) |\n| `filters\u002F` in the tokf source repo | Built-in library (requires a tokf release) |\n\nWhen creating a filter for a user's project, default to `.tokf\u002Ffilters\u002F` unless they specify otherwise.\n\n**Command field**:\n- Exact match: `command = \"git push\"` matches `git push` and `git push origin main`\n- Wildcard: `command = \"npm run *\"` matches `npm run dev`, `npm run build`, etc.\n- Array: `command = [\"cargo test\", \"cargo t\"]` matches either form\n\n---\n\n## Section 7 — Workflow for Creating a New Filter\n\nFollow these steps when asked to create a filter:\n\n### Step 1: Understand the command's output\n\nAsk the user to provide (or capture) example output from the command. If they don't have it, generate a plausible example based on the tool's known output format. Look for:\n- What's signal (errors, results, summaries)\n- What's noise (progress bars, compilation lines, download progress, blank lines)\n- What patterns mark sections (e.g., \"failures:\", \"test result:\")\n\n### Step 2: Choose the right complexity level\n\n| Level | When to use | Steps to use |\n|---|---|---|\n| Level 1 (simple) | Command produces one-liner outcomes | `match_output`, `skip`, `extract` |\n| Level 2 (structured) | Table-like output needing grouping | `[parse]` + `[output]` |\n| Level 2J (JSON) | Command produces JSON output | `[json]` + `on_success`\u002F`on_failure` templates |\n| Level 3 (stateful) | Multi-section output with nested structure | `[[section]]` + `aggregate` + pipes |\n| Level 4 (chunked) | Repeating blocks with per-block aggregation (workspaces) | `[[chunk]]` + `[[section]]` + `aggregates` + tree templates |\n\nStart at the lowest level that handles the use case. Don't reach for `[[section]]` when `skip` + `extract` suffices.\n\n### Step 3: Draft the filter\n\n1. Set `command` to match the command pattern\n2. Add `match_output` for well-known short-circuit cases (empty output, auth failure, \"already done\")\n3. Add `skip` to drop noise lines (progress, compile output, blank lines)\n4. Add `[[replace]]` to reformat noisy-but-useful lines\n5. Add `[[section]]` or `[parse]` if you need structured extraction\n6. Write `[on_success]` with the desired output format\n7. Write `[on_failure]` with enough context to diagnose (`tail = 20` is a safe default)\n8. Add `[fallback]` with `tail = 5` as a safety net for complex filters\n\n### Step 4: Write test cases and verify\n\nCreate a `\u003Cstem>_test\u002F` directory adjacent to the filter TOML and add at least one test case per meaningful outcome (success, failure, edge cases):\n\n```\nfilters\u002Fmytool\u002F\n  mysubcmd.toml       ← filter config\n  mysubcmd_test\u002F      ← test suite\n    success.toml\n    failure.toml\n```\n\nEach test case is a TOML file:\n\n```toml\nname = \"success shows one clean line\"\nfixture = \"tests\u002Ffixtures\u002Fmytool_success.txt\"  # path relative to this file, then CWD\nexit_code = 0\n\n[[expect]]\nequals = \"ok ✓\"\n\n[[expect]]\nnot_contains = \"noise\"\n```\n\nOr with an inline fixture (no file needed):\n\n```toml\nname = \"known error message\"\ninline = \"Error: connection refused\\n\"\nexit_code = 1\n\n[[expect]]\ncontains = \"connection refused\"\n```\n\nRun the suite:\n\n```sh\ntokf verify mytool\u002Fmysubcmd   # run one suite\ntokf verify                   # run all suites\n```\n\nFor quick one-off testing without creating test files:\n\n```sh\ntokf test filters\u002Fmytool\u002Fmysubcmd.toml tests\u002Ffixtures\u002Fmytool_output.txt --exit-code 0\n```\n\n### Step 5: Place and name the file correctly\n\n- Two-word command: `.tokf\u002Ffilters\u002Fmytool\u002Fmysubcmd.toml`\n- Single-word command: `.tokf\u002Ffilters\u002Fmytool.toml`\n- Wildcard command: `.tokf\u002Ffilters\u002Fmytool\u002Frun.toml` with `command = \"mytool run *\"`\n\n---\n\n## Section 8 — Three Annotated Examples\n\n### Example 1: `git push` (Level 1 — match_output + extract)\n\nGoal: 15 lines of push noise → \"ok ✓ main\" (or failure message).\n\n```toml\n# filters\u002Fgit\u002Fpush.toml — Level 1\n# Raw output: 15 lines of object counting, compression, \"remote:\" lines\n# Filtered (success): \"ok ✓ main\"\n# Filtered (up-to-date): \"ok (up-to-date)\"\n# Filtered (rejected): \"✗ push rejected (try pulling first)\"\n\ncommand = \"git push\"\n\n# Check full output for well-known outcomes before any processing\nmatch_output = [\n  { contains = \"Everything up-to-date\", output = \"ok (up-to-date)\" },\n  { contains = \"rejected\", output = \"✗ push rejected (try pulling first)\" },\n]\n\n[on_success]\n# Drop all the noise lines\nskip = [\n  \"^Enumerating objects:\",\n  \"^Counting objects:\",\n  \"^Delta compression\",\n  \"^Compressing objects:\",\n  \"^Writing objects:\",\n  \"^Total \\\\d+\",\n  \"^remote:\",\n  \"^To \",\n]\n# Extract the branch name from the ref update line: \"abc1234..def5678  main -> main\"\nextract = { pattern = '(\\S+)\\s*->\\s*(\\S+)', output = \"ok ✓ {2}\" }\n\n[on_failure]\ntail = 10\n```\n\n**Key decisions**:\n- `match_output` handles the two most common \"instant\" outcomes\n- `extract` captures the branch name from the ref update line\n- `tail = 10` on failure gives enough context without overwhelming\n\n---\n\n### Example 2: `git status` (Level 2 — parse + group)\n\nGoal: 30+ lines of verbose status → branch name + grouped file counts.\n\n```toml\n# filters\u002Fgit\u002Fstatus.toml — Level 2\n# Raw output: 30+ lines with hints, file paths, status codes\n# Filtered: \"main [ahead 2]\\n  modified: 3\\n  untracked: 2\"\n\ncommand = \"git status\"\n\n# Override: use porcelain format for reliable machine parsing\nrun = \"git status --porcelain -b\"\n\nmatch_output = [\n  { contains = \"not a git repository\", output = \"Not a git repository\" },\n]\n\n[parse]\n# First line: \"## main...origin\u002Fmain [ahead 2]\"\n# Extract: branch name, upstream, ahead\u002Fbehind info\nbranch = { line = 1, pattern = '## (\\S+?)(?:\\.\\.\\.(\\S+))?(?:\\s+\\[(.+)\\])?$', output = \"{1}\" }\n\n[parse.group]\n# Group remaining lines by their two-character status code\nkey = { pattern = '^(.{2}) ', output = \"{1}\" }\nlabels = {\n  \"M \" = \"modified\",\n  \" M\" = \"modified (unstaged)\",\n  \"MM\" = \"modified (staged+unstaged)\",\n  \"A \" = \"added\",\n  \"??\" = \"untracked\",\n  \"D \" = \"deleted\",\n  \" D\" = \"deleted (unstaged)\",\n  \"R \" = \"renamed\",\n  \"UU\" = \"conflict\",\n  \"AM\" = \"added+modified\"\n}\n\n[output]\nformat = \"\"\"\n{branch}{tracking_info}\n{group_counts}\"\"\"\ngroup_counts_format = \"  {label}: {count}\"\nempty = \"clean — nothing to commit\"\n```\n\n**Key decisions**:\n- `run` overrides to porcelain format — machine-readable is easier to parse\n- `[parse]` extracts the branch header line declaratively\n- `[parse.group]` groups by status code without needing `[[section]]`\n- `[output]` uses built-in `{group_counts}` variable populated by the parser\n\n---\n\n### Example 3: `cargo test` (Level 4 — section + chunk + aggregates + tree)\n\nGoal: 200+ lines with compile noise, per-test \"ok\" lines, failure blocks → per-crate tree summary on pass, structured failure report on fail.\n\n```toml\n# filters\u002Fcargo\u002Ftest.toml — Level 4\n# Raw output: 200+ lines\n# Filtered (pass): \"✓ cargo test: 1279 passed, 0 failed, 119 ignored (42 suites)\"\n#                   with per-crate tree breakdown showing individual test suites\n# Filtered (fail): failure details + summary\n\ncommand = \"cargo test\"\nstrip_ansi = true\n\n# Drop all the noise\nskip = [\n  \"^\\\\s*Compiling \",\n  \"^\\\\s*Downloading \",\n  \"^\\\\s*Downloaded \",\n  \"^\\\\s*Finished \",\n  \"^\\\\s*Locking \",\n  \"^running \\\\d+ tests?$\",\n  \"^test .+ \\\\.\\\\.\\\\. ok$\",   # individual passing tests\n  \"^\\\\s*$\",\n  \"^\\\\s*Doc-tests \",\n]\n\n# State machine: collect the \"failures:\" section into blocks split by blank lines\n[[section]]\nname = \"failures\"\nenter = \"^failures:$\"\nexit = \"^failures:$\"\nsplit_on = \"^\\\\s*$\"\ncollect_as = \"failure_blocks\"\n\n# Collect \"test result: ok\u002FFAILED\" summary lines (one per test suite)\n[[section]]\nname = \"summary\"\nmatch = \"^test result:\"\ncollect_as = \"summary_lines\"\n\n# Chunk processing: per-crate breakdown from \"Running\" headers.\n# \"unittests\" lines define crate boundaries; integration test suites\n# inherit the crate name via carry_forward.\n[[chunk]]\nsplit_on = \"^\\\\s*Running \"\ninclude_split_line = true\ncollect_as = \"suites_detail\"\ngroup_by = \"crate_name\"\nchildren_as = \"children\"\n\n[chunk.extract]\npattern = 'unittests.+deps\u002F([\\w_-]+)-'\nas = \"crate_name\"\ncarry_forward = true\n\n[[chunk.body_extract]]\npattern = 'Running\\s+(.+?)\\s+\\('\nas = \"suite_name\"\n\n[[chunk.aggregate]]\npattern = '(\\d+) passed'\nsum = \"passed\"\n\n[[chunk.aggregate]]\npattern = '(\\d+) failed'\nsum = \"failed\"\n\n[[chunk.aggregate]]\npattern = '(\\d+) ignored'\nsum = \"ignored\"\n\n[[chunk.aggregate]]\npattern = '^test result:'\ncount_as = \"suite_count\"\n\n# Success: aggregate summaries + per-crate tree breakdown\n[on_success]\noutput = \"✓ cargo test: {passed} passed, {failed} failed, {ignored} ignored ({suites} suites)\\n{suites_detail | each: \\\"  {crate_name}: {passed} passed ({suite_count} suites)\\\\n{children | each: \\\\\\\"    {suite_name}: {passed} passed\\\\\\\" | join: \\\\\\\"\\\\\\\\n\\\\\\\"}\\\" | join: \\\"\\\\n\\\"}\"\n\n[[on_success.aggregates]]\nfrom = \"summary_lines\"\npattern = 'ok\\. (\\d+) passed'\nsum = \"passed\"\ncount_as = \"suites\"\n\n[[on_success.aggregates]]\nfrom = \"summary_lines\"\npattern = '(\\d+) failed'\nsum = \"failed\"\n\n[[on_success.aggregates]]\nfrom = \"summary_lines\"\npattern = '(\\d+) ignored'\nsum = \"ignored\"\n\n# Failure: show failure details + summary\n[on_failure]\noutput = \"✗ cargo test: {passed} passed, {failed} failed ({suites} suites)\\n\\nFAILURES ({failure_blocks.count}):\\n{failure_blocks | each: \\\"\\\\n── {index}. ──\\\\n{value}\\\" | join: \\\"\\\\n\\\"}\\n\\n{summary_lines | join: \\\"\\\\n\\\"}\"\n\n[[on_failure.aggregates]]\nfrom = \"summary_lines\"\npattern = '(\\d+) passed'\nsum = \"passed\"\ncount_as = \"suites\"\n\n[[on_failure.aggregates]]\nfrom = \"summary_lines\"\npattern = '(\\d+) failed'\nsum = \"failed\"\n\n[fallback]\ntail = 5\n```\n\n**Key decisions**:\n- `skip` removes all per-test \"ok\" lines — only failures and summaries remain\n- `[[section]]` collectors handle failure blocks and summary lines\n- `[[chunk]]` splits on `Running` headers, extracts crate names from `unittests` lines\n- `carry_forward = true` makes integration test suites inherit the crate name from the preceding unit test suite\n- `children_as = \"children\"` preserves per-suite detail within each crate group\n- `[[on_success.aggregates]]` (plural) sums passed\u002Ffailed\u002Fignored across all suite summary lines\n- Nested `each` pipes produce tree output: crate → suites\n- `[fallback]` catches edge cases (compile errors with no test output)\n\n---\n\n## Section 9 — Writing Test Cases\n\nEvery filter in the standard library has a `\u003Cstem>_test\u002F` directory with declarative test cases. When writing or modifying a filter, write test cases alongside it.\n\n### Test case format\n\n```toml\nname = \"success output is a single clean line\"   # required, human-readable\nfixture = \"tests\u002Ffixtures\u002Fcargo_build_success.txt\"  # path to raw output file\n# inline = \"some raw output\\nline two\"            # alternative: inline fixture\nexit_code = 0                                    # optional, default 0\nargs = []                                        # optional, forwarded to filter\n\n[[expect]]\nequals = \"ok ✓\"          # exact match\n\n[[expect]]\nnot_contains = \"Compiling\"  # noise must be gone\n```\n\n### Assertion types\n\n| Field | Description |\n|---|---|\n| `equals` | Output exactly equals this string |\n| `contains` | Output contains this substring |\n| `not_contains` | Output does not contain this substring |\n| `starts_with` | Output starts with this string |\n| `ends_with` | Output ends with this string |\n| `line_count` | Output has exactly N non-empty lines |\n| `matches` | Output matches this regex |\n| `not_matches` | Output does not match this regex |\n\nEvery `[[expect]]` entry checks one assertion. A test case with multiple `[[expect]]` entries must pass all of them. A test case with no `[[expect]]` entries is an error.\n\n### What to test\n\nFor every filter, write at least:\n- **Success case**: the happy path produces the expected one-liner or summary\n- **Failure case**: a failing exit code produces enough context to diagnose\n- **Edge cases**: cover each `match_output` branch (e.g., \"up-to-date\", \"rejected\")\n\n### Directory convention\n\n```\nfilters\u002F\n  git\u002F\n    push.toml          ← filter config\n    push_test\u002F         ← test suite (identified by _test suffix)\n      success.toml\n      up_to_date.toml\n      rejected.toml\n      failure.toml\n```\n\nThe `_test` suffix makes suite directories immediately identifiable in file listings and distinguishes them from filter category directories.\n\n---\n\n## Section 10 — Common Mistakes to Avoid\n\n1. **Don't use `keep` when `skip` is enough.** `keep` is an allow-list — it drops everything that doesn't match. Use it only when you want to radically filter to a specific type of line.\n\n2. **Escape backslashes in TOML strings.** In regular strings, `\\\\d` means literal `\\d` in the regex. In TOML raw strings (`'...'`), backslashes are literal. Use raw strings for complex patterns.\n\n3. **`match_output` is a short-circuit.** If it matches, nothing else runs. Don't put it at the end expecting it to be a fallback — it runs first.\n\n4. **`[[section]]`, `[parse]`, and `[json]` are mutually exclusive in practice.** `[json]` replaces `[[section]]`\u002F`[parse]`\u002F`[[chunk]]` — when `[json]` is configured, those line-based steps are skipped. Use `[json]` for JSON output, `[[section]]`\u002F`[parse]`\u002F`[[chunk]]` for line-based output.\n\n5. **`{output}` in branch templates is the filtered output text** (after skip\u002Fkeep\u002Freplace\u002Fdedup), not the raw command output.\n\n6. **Pipe chains need careful quoting.** When nesting templates inside `each:`, escape inner quotes: `{each: \"{value | lines | keep: \\\\\\\"^error\\\\\\\"}\"}`.\n\n7. **Don't skip the `[fallback]`.** Complex filters with `[[section]]` can produce empty output if sections don't match. Always add `[fallback] tail = 5` as a safety net.\n\n8. **Test with realistic fixture data.** A filter that works on a trimmed example may miss edge cases. Use real command output saved to a `.txt` fixture file.\n",{"name":5,"version":39,"description":7},"0.1.0","main","8cba301ffd1b108fe3111f9e5017a338d9c2001f","internal\u002Fassets\u002Fframework\u002Fdocs\u002Fref-tokf-filter",0,"https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite","https:\u002F\u002Fgithub.com\u002Fhollis-labs","https:\u002F\u002Fhollislabs.com","2026-10-31 10:37:21",{"source":8,"skillName":5,"commands":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add hollis-labs\u002Fnanite --skill tokf-filter",{"tool":54,"command":55},"bunx","bunx skills add hollis-labs\u002Fnanite --skill tokf-filter",{"tool":57,"command":58},"pnpm","pnpm dlx skills add hollis-labs\u002Fnanite --skill tokf-filter","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite\u002Fblob\u002Fmain\u002Finternal\u002Fassets\u002Fframework\u002Fdocs\u002Fref-tokf-filter\u002FSKILL.md",true,[62,68],{"path":63,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":66,"sourceHtmlUrl":67},"references\u002Fexamples.toml","REFERENCE","参考文档",11832,"https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite\u002Fblob\u002Fmain\u002Finternal\u002Fassets\u002Fframework\u002Fdocs\u002Fref-tokf-filter\u002Freferences\u002Fexamples.toml",{"path":69,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":70,"sourceHtmlUrl":71},"references\u002Fstep-reference.md",27521,"https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite\u002Fblob\u002Fmain\u002Finternal\u002Fassets\u002Fframework\u002Fdocs\u002Fref-tokf-filter\u002Freferences\u002Fstep-reference.md",[73,101,114,124,139,149],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":84,"publishedAt":34},"01M6KSD3MCFGZXJ4Y5XJR44R3G","Sample Skill","A sample skill fixture exercising scripts\u002F, references\u002F, assets\u002F, and declared parameters\u002Fdependencies.","https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite\u002Fblob\u002Fmain\u002Finternal\u002Fskillinstall\u002Ftestdata\u002Ffixtures\u002Fsample-skill\u002FSKILL.md",[79],{"categoryNo":80,"categoryName":81,"taxonomyType":82,"taxonomyTypeDesc":83},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[85,86,87,88,89,90,91,92,93,94,95,96,32,97,98,99,100],"sample skill","sample","assets","test","notes","run","logo","references","dependencies","fixture","false","scripts","operate","true","inline","skill fixture",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":108,"publishedAt":34},"01M6KSD1NGHT9NRZER493Z1YSV","Malformed Skill","A malformed skill fixture whose scripts entry does not exist on disk.","https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite\u002Fblob\u002Fmain\u002Finternal\u002Fskillinstall\u002Ftestdata\u002Ffixtures\u002Fmalformed-missing-script\u002FSKILL.md",[107],{"categoryNo":80,"categoryName":81,"taxonomyType":82,"taxonomyTypeDesc":83},[109,110,96,111,94,112,99,100,113],"malformed","malformed skill","missing","script","disk",{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":34},"01M6KSCY7011R35WR86HZMMJCK","malformed-frontmatter","Missing the required name field.","https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite\u002Fblob\u002Fmain\u002Finternal\u002Fskillinstall\u002Ftestdata\u002Ffixtures\u002Fmalformed-frontmatter\u002FSKILL.md",[],[109,121,122,123,111,99],"frontmatter","malformed frontmatter","name",{"skillNo":125,"name":126,"nameZh":6,"description":127,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":128,"categories":129,"keywords":130,"publishedAt":34},"01M6KSCSP652QRJPQR3E8EQ07W","Resolver Parent","A skill declaring both a required, resolver-bound parameter and a nested dependency on resolver-child.","https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite\u002Fblob\u002Fmain\u002Finternal\u002Fskill\u002Ftestdata\u002Ffixtures\u002Fresolver-parent\u002FSKILL.md",[],[131,126,132,133,134,95,135,32,136,137,98,138],"resolver","nested","dependency","greeting","binding","note","with","child",{"skillNo":140,"name":141,"nameZh":6,"description":142,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":143,"categories":144,"keywords":145,"publishedAt":34},"01M6KSCNPVT56RAJNPYQN0W82Q","Resolver Child","A minimal nested skill, installed independently so the resolver dependency-address test can resolve a real dependency against it.","https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite\u002Fblob\u002Fmain\u002Finternal\u002Fskill\u002Ftestdata\u002Ffixtures\u002Fresolver-child\u002FSKILL.md",[],[141,138,131,88,133,146,132,147,148],"minimal","it","can",{"skillNo":150,"name":151,"nameZh":6,"description":152,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":153,"categories":154,"keywords":155,"publishedAt":34},"01M6KSCHFCQ1HA3Y4XNA6AQGJW","Compose Multilevel Root","Root skill for a 3-level composition chain crossing both inline and fork.","https:\u002F\u002Fgithub.com\u002Fhollis-labs\u002Fnanite\u002Fblob\u002Fmain\u002Finternal\u002Fskill\u002Ftestdata\u002Ffixtures\u002Fcompose-multilevel-root\u002FSKILL.md",[],[151,156,157,158,159,33,99,160,161],"root","compose","Composition","chain","fork","root skill"]