Skip to content
Back to skills

Cfl

ASecurity

Context-free languages (КС-языки). Use it for CFL tasks: task_type classify_cfl, prove_cfl, prove_non_cfl, classify_and_prove_cfl or grammar_filter_cfl, or a task text that asks whether a language is context-free («является ли язык контекстно-свободным», «КС ли язык», L(G) ∩ фильтр). It gives the decision procedure, the pumping / Ogden / closure-with-REG / interchange statements quoted from docs/THEORY.md §2.0–§2.5, the tools to call at each step (input_grammar_cfg, grammar_vs_ir, pump_check_...

  • 3 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added November 9, 2026
ai-agentsrustgoexpress

Works with

  • terminal

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned November 15, 2026

npx -y skills add ark2016/TFL-automatisation --skill cfl --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Cfl?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Cfl
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/ark2016-cfl/badge)](https://www.skillsdirectory.com/skills/ark2016-cfl)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: cfl
description: >-
  Context-free languages (КС-языки). Use it for CFL tasks: task_type classify_cfl, prove_cfl,
  prove_non_cfl, classify_and_prove_cfl or grammar_filter_cfl, or a task text that asks whether a
  language is context-free («является ли язык контекстно-свободным», «КС ли язык», L(G) ∩ фильтр).
  It gives the decision procedure, the pumping / Ogden / closure-with-REG / interchange statements
  quoted from docs/THEORY.md §2.0–§2.5, the tools to call at each step (input_grammar_cfg,
  grammar_vs_ir, pump_check_cfl, cyk, check_membership, regex_to_dfa, ...), the CFL traps
  (traps.md in this folder) and which evidence makes a cfl / non_cfl claim verified, bounded or
  only well-formed. Not for DCFL or LL(k) questions: use the dcfl and ll skills, which reuse the
  same CFL tools.
metadata:
  sources: "docs/THEORY.md §I §2.0 §2 §2.3 §2.4 §2.5 §1.5; cfl_system/tz_cfl_agent_system.md; docs/VERDICT_POLICY.md; docs/EVAL_SET.md; docs/EVAL_RESULTS.md"
  supporting_files: "traps.md"
---

# CFL: is the language context-free?

Read this whole file (`read_file(..., limit=1000)`), then `traps.md` in the same folder
(normally `/skills/cfl/traps.md`) before you choose a method.

Quoted theory below is copied word for word from the named file and section. A test in
`tfl_deep_agent/tests/test_skill_cfl.py` checks every quote against the source. Everything outside
the quote blocks is guidance on procedure and tools, not a theorem. When you need a statement that is
not quoted here, fetch it with `get_theorem` (the tool returns the section verbatim). Never write
a lemma from memory, and never use a paragraph that THEORY.md marks **[ошибка]**: those quote a wrong
formulation in order to correct it.

## 1. When this skill applies

- The IR is a CFL IR: `validate_ir(cls="cfl", ir=...)` accepts it. Task types: `classify_cfl`,
  `prove_cfl`, `prove_non_cfl`, `classify_and_prove_cfl`, `grammar_filter_cfl`
  (tz_cfl §1.3).
- Format 1: the language is given as a set (set-builder notation, exponent notation, repeated
  subwords). Format 2: a CFG G and a filter F, and the question is about L(G) ∩ F (tz_cfl §1.1, §1.2).
- The answer is `cfl`, `non_cfl`, or inconclusive (verdict `null`, VERDICT_POLICY R1).
- Other skills: "DCFL / deterministic" → `dcfl`; "LL(k)" → `ll`; "regular" → `reg`; Lean
  details → the `lean-formalizer` subagent; the report format → `report-templates`.

## 2. Ground rules

1. **Relative to the IR.** Every oracle answer is about the IR you built and the human approved
   (HITL 1), never about the task text directly. Results carry the IR fingerprint (`ir-…`). The
   report must say which IR was checked.
2. **Trust comes from tool results only.** The evidence block and the trust labels in the report are
   generated by code from the tool calls. Your own confidence never raises a cap
   (VERDICT_POLICY §2). Cite the evidence ids of the tool calls you rely on.
3. **`None` is unknown.** An oracle answer `None` means "unknown". It is never "not in L"
   (THEORY.md §2.0, quoted below).
4. **Sandbox code is weak evidence.** Your own brute force run through `execute` is capped at
   `well_formed`. Prefer the oracle tools, whose trust is defined by VERDICT_POLICY.
5. **Budget.** Work on both sides when the class is unclear, but time-box each one. In the
   eval run cfl-12, the constructive builder spent 6 calls ($0.80 of $1.07) on a grammar for a
   wrong `cfl` hypothesis (EVAL_RESULTS, "Перепроверка после C2"). Call `budget_status` (when it
   is available) before you start a second attempt.

## 3. Decision procedure

### Step 1. IR and oracle

1. `describe_ir_schema(cls="cfl")` lists the kinds: `predicate`, `grammar`, `regex`, `natural`,
   `arithmetic_index`, `grammar_filter`, `repeated_subword`, `exists_decomposition`.
2. Build the IR, then `validate_ir(cls="cfl", ir=..., check_tools=True)`. Read
   `data.oracle.available` / `data.oracle.exact` and `data.lean_statement`.
3. If there is no oracle, try to express the language so that one exists before you go on:
   - a `natural` description only gets an oracle in exponent notation such as
     `{a^n b^n c^m | n, m >= 0}` (source `cfl_system.lib.exponent_pattern`, exact, but unknown
     above `max_word_len` 40);
   - write the parts of repeated subwords as `repeated_subword` / `exists_decomposition`;
   - write a filter as a predicate, not `natural_language_filter`. That oracle checks only the
     grammar, so the tools treat it as approximate: it never refutes, a sample check stays at
     most `well_formed`, and `pump_check_cfl` refuses it.

   Without an exact oracle, nothing semantic can be checked, and the caps in §6 apply
   (VERDICT_POLICY §4, last paragraph).
4. `ir_to_text(cls="cfl", ir=...)` gives the paraphrase and the labelled example words for HITL 1.

### Step 2. Shortcut: the language is given by a grammar

If `language_spec.kind == "grammar"` (the whole language is L(G), and there is no filter), call
`input_grammar_cfg(ir=...)`. `certified: true` gives trust `verified`: the verdict is `cfl` by
definition. You do not need another grammar or a sample comparison. The proof is the input grammar
itself (VERDICT_POLICY R2-CFG).

Verbatim, THEORY.md §2.0:
> Если весь исходный язык **задан корректной КС-грамматикой**, его контекстная свобода следует из определения [R-Pump, `cfl`; R-CFL, с. 3–4]. Поиск другой грамматики и выборочное сравнение не требуются. Это не относится к подмножеству L(G), заданному дополнительным фильтром, и не устанавливает DCFL или LL(k).

Verbatim, VERDICT_POLICY.md §3 R2-CFG:
> Правило не распространяется на `grammar_filter`: дополнительный фильтр может уничтожить контекстную свободу.

### Step 3. Hypothesis (advisory only)

Look at the structure. `sample_words(cls="cfl", ir=...)` (reference only, `not_verified`) and the
`ir_to_text` examples help. The tz_cfl §4.2 heuristics are hints, not evidence: a repeated subword
w₁…w₁ with at least one other subword between the copies suggests `non_cfl`; crossed dependencies
(w₁…w₂…w₁…w₂) are a strong `non_cfl` signal; vvᴿ (a palindrome) is CFL when it stands alone but
needs analysis inside a composition; a grammar with a regular filter is CFL (intersection theorem),
while a grammar with a non-regular filter needs analysis (§4.4); a bounded language
(w₁^k₁…wₙ^kₙ) calls for the stratification test; parts over the same alphabet with no repeat
suggest `cfl`. The spec gives no hint based on the number of counters, and none is reliable:
{aⁱbʲcᵏ | i + j = k} (eval cfl-15) and {aⁱbʲcᵏ | i = j ∨ j = k} (cfl-02) are `cfl`, while the
single two-counter filter #a = #b of cfl-07 gives `non_cfl` (THEORY.md §2.3). `traps.md` lists
known cases where such hints mislead. A hypothesis never decides the verdict, and it must not stop
you from checking the other side.

When the class is unclear and the budget allows, run the two branches in parallel
(`run_workflow` with a constructive branch and a destructive branch, or two `spawn_subagent`
calls). Opus needs a `reason`.

### Step 4. Constructive branch (towards `cfl`)

1. **Write a grammar.** Terminals must be single characters, ε is `rhs: []`, and the terminal and
   nonterminal sets must be disjoint. `to_cnf(grammar=...)` catches invalid symbols early: an
   invalid submitted grammar comes back `refuted`, `evidence_role: "invalid_artifact"`.
2. **Spot-check** it with `cyk(grammar=..., words=[...], expected={...})` on the shortest words
   in and out of L, with labels from `check_membership`.
3. **Check it against the IR:** `grammar_vs_ir(grammar=..., ir=...)`. The tool compares every word
   up to a length bound plus generator words up to `sample_max_len`.
   - `refuted` with a counterexample: the grammar is wrong. Fix it using the counterexample
     (VERDICT_POLICY R7). A refuted grammar forbids a `cfl` verdict on this attempt (R2).
   - `bounded_pass` (at least 30 decided words, exact oracle): this is the constructive basis for
     `cfl`, cap 0.85.
   - `well_formed` (approximate oracle, or fewer than 30 decided words) or `not_verified`: not
     enough for a `cfl` verdict (R2 needs at least `bounded_pass`).
4. **PDA.** `pda_run(pda=..., words=[...], push_order="top_first", acceptance_mode=...)` gives
   exact facts about this PDA: an acceptance is `verified`; a rejection is `verified` only when the
   stack bound was not hit, otherwise `bounded_pass`. There is no PDA-against-IR tool yet (the
   inventory defers the PDA variant of `grammar_vs_ir`). For a `cfl` basis, turn the idea into a
   grammar and use `grammar_vs_ir`. `push_order` matters: `top_first` is the prompt and textbook
   order, and misreading it changes the answers.
5. **Decomposition (∪, ·, \*).** Give a grammar for each component and one grammar for the whole
   language, then check the whole grammar with `grammar_vs_ir`. The copy language
   {ww | w ∈ {a,b}*} is not CFL (EVAL_SET cfl-03: pumping on aᵖbᵖaᵖbᵖ). The same holds over any
   alphabet with at least two letters, because intersecting with a*b*a*b* gives {aⁱbʲaⁱbʲ}. A
   decomposition that needs such a component proves nothing. A copy shape alone does not settle the
   class: {ww | w ∈ a*} = (aa)* is regular, and {ww | w ∈ a*b} = {aⁿbaⁿb} is CFL
   (S → Tb, T → aTa | b), so check each component with its own grammar. A failed decomposition, or
   one with a non-CFL component, is not evidence that L is non-CFL (R1).

   Verbatim, tz_cfl §4.5.3:
   > **Важно:** НЕ все декомпозиции корректны. {ww} сам по себе НЕ КС.

6. **Grammar + filter (Format 2).** See §4.4. With a regular filter, build a grammar for
   L(G) ∩ F (for example, track the filter's DFA state in the nonterminals) and check it with
   `grammar_vs_ir`. The closure theorem explains why the language is CFL; the checked grammar is
   the evidence.

Verbatim, VERDICT_POLICY.md §3 R1:
> **R1 — провал ≠ опровержение.** Неудача конструктивных агентов (`grammar_incorrect`, опровергнутый PDA/DFA, «не удалось построить») **не является** свидетельством деструктивного вердикта.

### Step 5. Destructive branch (towards `non_cfl`)

Pick a method from §4 (in this order: pumping; Ogden when plain pumping can pump the wrong block;
an intersection with a regular language when the words can be re-split; interchange only in the
rare cases of §4.5). Then:

1. Write the argument parametrically in p: the word z, the cases of the split, and the exit
   exponent i in each case.
2. **Instantiate it.** Give concrete words for p = 3 and p = 4 (`word_instances`; for Ogden also
   `marked_positions` per p). Compute them, do not guess them. The ticket-50 run printed
   `a⁸b(ab)⁵a⁸` for p = 4, which is not in L (`traps.md`).
3. `pump_check_cfl(ir=..., claim={...})` checks the structure. It also pumps every admissible
   split of each instance with i ∈ {0, 2, 3} against the IR's oracle.
   - `refuted`: a concrete chosen word is ∉ L by an exact oracle. This is a literal `word_chosen`
     or a `word_instances` entry for p = 3 or 4. Fix the word. Do not submit a refuted argument. In
     eval cfl-07 the gate refused every such attempt (EVAL_RESULTS, "Live-перепроверка после C4").
   - Claim mode does not read the exit exponents your cases declare. It tries i = 0, 2, 3 on every
     admissible split and counts the split as closed at the first i that leaves L, whichever i that
     is. A case analysis with a wrong declared exit therefore still comes back `well_formed` with
     every split closed. Check each case's declared exit in split mode (item 4): pick one
     representative split per case and pass the exit that case declares as `claimed_exit_i`. A
     `refuted` answer means the declared exit is wrong for that split, so fix the case analysis.
     Example, eval cfl-05 {aⁱbʲcᵏ | i ≤ j ≤ k}, z = aaabbbccc: the claim "i = 0 exits for every
     split" fails on u = "", v = "a", w = "", x = "", y = "aabbbccc", p = 3, claimed_exit_i = [0],
     because uwy = aabbbccc ∈ L. Only pumping up (i = 2, 3) exits there (`traps.md`: different
     cases need different i).
   - `well_formed`: the structure is complete and no checked premise is false. This is the ceiling
     of a pumping or Ogden argument, cap 0.55, even when every split closed (THEORY.md §2.0). The
     label does not say whether the splits closed. Read `data.bounded_check.status`,
     `bounds.unresolved_splits` and `bounds.n_unknown`. `closed_for_sampled_p` means that every
     admissible split of each instance left L at some i ∈ {0, 2, 3}. `inconclusive` means that some
     split stayed in L for every tried i, or that the oracle could not decide some word.
   - `not_verified`: the structure is incomplete (no `cases`, a case without `case` or
     `why_not_in_L`, or `all_cases_covered` not true), the oracle could not decide a literal
     (non-parametric) `word_chosen`, or an approximate oracle contradicted a premise (this is not a
     refutation). Read `data.issues` and the trust reason.
   - An undecided instance does not lower the trust. This happens when an instance is longer than
     the oracle's bound, as in cfl-11, or when the IR has no oracle. The result stays `well_formed`
     (structure only), with an empty `bounds.p_values` and `bounds.n_unknown` > 0. Nothing was
     pumped. Say in the report that the instances were not checked (traps.md cfl-11). An empty
     `bounds.p_values` always means that no instance was checked.
4. `pump_check_cfl(ir=..., split={u, v, w, x, y}, p=..., claimed_exit_i=[...])` checks one split.
   It is a diagnostic for one case of your analysis (`evidence_role: "diagnostic"`, at most
   `not_verified`). It is never a pumping argument. A split that survives the tried i is not a
   refutation: the exit may lie at a larger i.
5. **Unresolved splits are open cases.** A split that stays in L for i ∈ {0, 2, 3} does not
   refute the argument: the exit may lie at a larger i (THEORY.md §2.0). But your case analysis
   must still name an exit for that split. For each unresolved split:
   - Find the case that covers it.
   - Run it in split mode: `pump_check_cfl(ir=..., split={u, v, w, x, y}, p=..., claimed_exit_i=[<the case's i>])`.
     Exponents can go up to 10.
   - `refuted` means the case is wrong, so the argument is refuted.

   If the split stays in L for every i ≥ 0, the argument fails for this z, and you must change z
   or the method (Ogden, ∩REG). Example: cfl-12 with z = abᵖcᵖdᵖ, where the splits that pump only
   the leading a give aⁱbᵖcᵖdᵖ ∈ L for all i ≥ 0. In the report, list the unresolved splits and
   how each was settled.

Claim shape for `pump_check_cfl` (a pumping proof for eval cfl-01, IR
`cfl_system/examples/task_anbncn.json`; the test runs this exact JSON and expects `well_formed`):

```json
{
  "word_chosen": "a^p b^p c^p",
  "cases": [
    {"case": "vwx lies inside one block or meets two adjacent blocks; it cannot meet both the a-block and the c-block, because |vwx| <= p and the b-block has length p",
     "why_not_in_L": "i = 0 removes |vx| >= 1 letters and keeps the order a*b*c*; the letter whose block vwx does not meet keeps count p while some other count drops below p, so uwy is not in L"}
  ],
  "all_cases_covered": true,
  "word_instances": {"3": "aaabbbccc", "4": "aaaabbbbcccc"}
}
```

For Ogden, add `"agent": "ogden"` (or pass `method="ogden"`) and
`"marked_positions": {"3": [...], "4": [...]}` with 0-based positions in the instance, at least p of
them. Without `word_instances` the tool checks only the structure. It may still answer
`well_formed`, but nothing semantic was checked (VERDICT_POLICY §4: "Инстанцировать `word_chosen`
при p ∈ {3,4}").

### Step 6. Both sides have evidence: cross-check (R3, R3′)

If a grammar has `bounded_pass` and a destructive argument has `well_formed`, there is a
contradiction. Neither side wins by rank:

Verbatim, VERDICT_POLICY.md §3 R3:
> `bounded_pass` против `well_formed` **не** решает спор: выборочный оракул и LLM-доказательство ошибаются по-разному

Precedent (VERDICT_POLICY R3): in the wwvvR live run (2026-09-27), a grammar passed 50 sampled
words while the correct Ogden argument said "not CFL", and the old gate gave the verdict to the
grammar. THEORY.md §2.5 shows that the language is not CFL. Resolve such a conflict with oracle
checks (R3′):

- (a) Run the destructive witnesses through the grammar. In claim mode `data.destructive_witnesses`
  of `pump_check_cfl` holds the instances z for p = 3, 4 (`expected_in_l: true`) and, for each
  closed split, the first pumped word the oracle found ∉ L (`expected_in_l: false`; deduplicated, at
  most 30 words). These are oracle facts, not the exits your proof declares. Get the pumped words
  for the declared exits from split mode with `claimed_exit_i`. Call
  `cyk(grammar=..., words=..., expected=<labels from check_membership on the task IR>)`. If the
  grammar accepts a word that is ∉ L by the oracle, or rejects a word ∈ L, the grammar is `refuted`.
- (b) Run the words on which the grammar passed through the destructive claims. If the oracle says
  a word that the proof puts outside L (for example uwy) is in L, the proof is `refuted`.
- If both sides survive, report the contradiction: inconclusive, confidence ≤ 0.50, with both
  arguments in the report.

### Step 7. Verdict

Choose the strongest admissible basis (§6). If nothing admissible is left: inconclusive, ≤ 0.40.
A failed construction never becomes `non_cfl` (R1), and a failed destructive argument never
becomes `cfl`.

### Step 8. Lean (optional, settings and budget permitting)

When the lean tools are available (`lean_statement`, `lean_check`; the `lean-formalizer` subagent
uses them, there is no Lean skill file), the statement is rendered from the IR by code (direction
`cfl` or `non_cfl`). The model writes only the proof body. Only status `proved` gives `verified`
(0.98) for the proved direction. Every other status is not evidence either way (VERDICT_POLICY
R-Lean). The `tfl-lean4` image has CF closure lemmas (intersection with a regular language, union,
substitution, homomorphic images) and compiled examples for both directions: `non_cfl` for
{aⁿbⁿcⁿ} and {aⁿbⁿaⁿ}, `cfl` for a grammar, a grammar cut by a regular filter and
{aⁿbⁿ} ∪ {aⁿb²ⁿ}. The lean-formalizer prompt lists them. Parikh's theorem is not in the image: the
formalizer proves such an `¬ L.IsContextFree` by pumping or Ogden directly. An IR with no Lean
statement is `not_formalizable`. Writing a proof body is a model call and spends budget.

### Step 9. Report

Use the `report-templates` skill (`list_report_templates`, then `submit_report`, which is HITL 2).
State the IR fingerprint, the method, the parametric argument, the p = 3, 4 instances, and what was
checked by tools and what was not.

## 4. Proof methods and their statements

### 4.1 Pumping lemma (Bar-Hillel)

Verbatim, THEORY.md §2.0:
> У КС-языка существует p ≥ 1 такое, что **для каждого** z ∈ L, |z| ≥ p, **существует** допустимое разбиение z=uvwxy, |vwx| ≤ p, |vx| ≥ 1, с uvⁱwxⁱy ∈ L **для всех** i ≥ 0 [R-Pump, с. 7]. Не-КС доказательство должно отрицать именно этот порядок: ∀p ∃z ∀разбиение ∃i с выходом из L. Для Огдена длина заменяется числом отмеченных позиций [Sh, Lemma 4.3.1].

Verbatim, THEORY.md §2.0:
> Конечная проверка p=3,4 и i=0,2,3 — диагностика. Даже полное закрытие разбиений при этих p не доказывает общую теорему: у L={a¹⁰} оно выполняется, но константа p=11 удовлетворяет лемме вакуумно. И наоборот, выживание разбиения при трёх i не доказывает выживания при всех i. Нужное i может зависеть от p и разбиения. `None` оракула означает неизвестность, а не непринадлежность.

How to use it: z must depend on p, with |z| ≥ p, and z must be in L. The case analysis must cover
every split with |vwx| ≤ p and |vx| ≥ 1, including v or x that straddle a block boundary. For each
case, name one i that leads out of L. Tool: `pump_check_cfl` claim mode (Step 5).

### 4.2 Ogden's lemma

THEORY.md §2.0 gives Ogden only as "the length is replaced by the number of marked positions" (see
the quote in 4.1). `pump_check_cfl` reads it this way: at least p marked positions in z, vx contains
a marked position, and vwx contains at most p marked positions. It is the method for languages where
plain pumping can always pump a harmless block.

Verbatim, THEORY.md §2.0:
> L={aⁱbʲcᵏdˡ | i=0 или j=k=l}, показатели неотрицательны, удовлетворяет обычному условию накачки с p=1: при i>0 накачиваем одну начальную a (удаление последней a переводит в ветвь i=0), а при i=0 — любую букву непустого слова. Тем не менее L не КС. Для Огдена берём z=abᵖcᵖdᵖ, отмечаем все b, используем i=2.

`get_theorem("2.0")` returns the full case analysis of this example (eval cfl-12).

### 4.3 Intersection with a regular language (closure reduction)

Verbatim, THEORY.md §2:
> Поскольку CFL ∩ REG ⊆ CFL, L ∉ CFL. ∎

Verbatim, tz_cfl §4.5.7:
> 3. Поскольку CFL ∩ REG = CFL, если L ∩ R не КС → L не КС

Procedure with tools:

1. Choose a regex R and get its DFA: `regex_to_dfa(regex=...)`. The result is `verified` for "this
   DFA recognises L(R)", so R is regular. The syntax has no back-references, and the regex is at
   most 200 characters.
2. Describe L ∩ R as its own IR L′, preferably in exponent notation so that it gets an exact oracle.
   Run `validate_ir(cls="cfl", ir=L′, check_tools=True)`.
3. **Check the description L ∩ R = L′.** This is where the eval trap cfl-06 fails. The equality
   needs two checks, and both must pass on the sample.
   (a) Words of R: take words that `run_dfa` accepts on the DFA of R, and label them with
   `check_membership(cls="cfl", ir=<task IR>, words=...)`. Then call
   `check_membership(cls="cfl", ir=L′, words=..., expected=<those labels>)`. This checks
   L′ ∩ R = L ∩ R.
   (b) Words of L′: run them through `run_dfa` on the DFA of R, and require every one to be
   accepted. This checks L′ ⊆ R. Then call
   `check_membership(cls="cfl", ir=<task IR>, words=..., expected=<all true>)`.
   Either failure means the description is wrong: a `refuted` result, or a word of L′ that the DFA
   rejects. The L-label check alone is not enough for words of L′. It checks L′ ⊆ L, not L′ ⊆ R.
   For cfl-06, an L′ written with n, m ≥ 0 contains bacbac. That word is in L (w₁ = ba, w₂ = c,
   w₃ = c) but not in R = a⁺b⁺ac·a⁺b⁺ac, so only `run_dfa` catches it.
   The precedent: a closure_reduction claimed L ∩ a⁺b⁺ = {aⁿbⁿ} for a grammar that generates only
   {a²ᵐb²ᵐ | m ≥ 2} (THEORY.md Part II §5).
4. Prove that L′ is not CFL (pumping or Ogden) and check it with `pump_check_cfl(ir=L′, claim=...)`.
   It must be checked against L′, not against the task IR. A pumped word that leaves R can still be
   in L, so the L oracle would "refute" a correct exit from L ∩ R.

Verbatim, VERDICT_POLICY.md §4:
> Для **closure_reduction** вложенная накачка проверяется относительно L ∩ R по тем же правилам; примеры/антипримеры пересечения допускают `bounded_pass` лишь при достаточном числе определённых ответов.

The `bounded_pass` from step 3 is about the description of L ∩ R. The nested pumping stays
`well_formed`. Report both, and let the ledger compute the cap. Choose R so that the split of each
word into the task's parts is forced. THEORY.md §2 shows how a loose R leaves a CFL intersection:

Verbatim, THEORY.md §2:
> На самом деле L ∩ a⁺b⁺a⁺c⁺ = {aⁿbᵐaʲcᵏ | j ≥ n} — **это КС-язык** (лишние a уходят в w₃ ∈ {a,c}⁺)

Verbatim, THEORY.md §2:
> **Исправленный пример.** R = a⁺b⁺ac·a⁺b⁺ac (регулярный). L ∩ R = {aⁿbᵐac·aⁿbᵐac | n, m ≥ 1}.

`get_theorem("2")` returns the full argument for why this R forces the split, and the proof that
L ∩ R is not CFL. `get_theorem("2.5")` gives a second worked example (R* with odd exponents).

### 4.4 Grammar + filter (Format 2)

Verbatim, tz_cfl §1.2:
> Если F задаёт регулярное условие, пересечение КС ∩ REG = КС. Если F нерегулярно — нужен отдельный анализ.

Verbatim, THEORY.md §2.3:
> Регулярны только пороговые и модульные условия на один счётчик (|a| ≥ k, |a| ≡ r mod m) и regex; равенство двух счётчиков — нерегулярный КС-фильтр, L(G) ∩ F может не быть КС (CFL ∩ CFL не замкнуто).

Read "только" as the list of the usual regular filter forms, not as a complete characterisation.
EVAL_SET reg-03 ({#a ≡ #b (mod 2)}, a modular condition on two counters) is regular too. To use the
closure argument, F must be regular, and `regex_to_dfa` alone does not show that: its `verified` is
only for "this DFA recognises L(R)", never for L(R) = F. Write a regex R for F, get its DFA with
`regex_to_dfa(regex=R, alphabet=Σ)`, put F in its own IR (a `reg` IR of kind `predicate` whose
predicate is the filter) and run `dfa_vs_ir(cls="reg", ir=<IR of F>, dfa=...)`. A counterexample means
L(R) ≠ F. For the filter #a = #b, R = (ab|ba)* is `verified` by `regex_to_dfa`, but `dfa_vs_ir`
refutes it with aabb. A pass is only `bounded_pass` for L(R) = F. The claim that F is regular then
rests on your argument that L(R) = F, or on F being one of the forms quoted above. Without either,
"F is regular" is an unchecked claim. In every case the evidence for `cfl` is the grammar for
L(G) ∩ F checked with `grammar_vs_ir` (Step 4.6). A filter that compares two counters needs real
analysis: L(G) ∩ F may be CFL or not. For eval cfl-07 it is not CFL (THEORY.md §2.3: intersect with
b*a*b*a*, then Ogden; `get_theorem("2.3")`).

### 4.5 Interchange lemma (rarely the right tool)

Verbatim, THEORY.md §2.4:
> **Лемма 4.5.1 [Sh] (Ogden–Ross–Winklmann 1985).** Для всякого КС-языка L существует c > 0 такое, что для всех n ≥ m ≥ 2 и всякого R ⊆ L ∩ Σⁿ найдётся Z = {z₁,…,z_k} ⊆ R с k ≥ |R| / (c(n+1)²) и разложениями zᵢ = wᵢxᵢyᵢ: (a) |w₁| = … = |w_k|; (b) |y₁| = … = |y_k|; (c) m/2 < |x₁| = … = |x_k| ≤ m; (d) wᵢxⱼyᵢ ∈ L для всех i, j.

Verbatim, THEORY.md §2.4:
> Для экзаменационных языков над {a,b,c} лемма почти не нужна — агент должен предпочитать накачку/Огдена и честно возвращать inconclusive.

An interchange argument must use the lower bound k ≥ |R| / (c(n+1)²). "Two interchangeable words
exist" is not the lemma. No tool checks an interchange argument, so it stays an LLM argument. Do not
use Sokolowski's lemma: THEORY.md §2.4 removes it as unverifiable.

### 4.6 Homomorphisms

THEORY.md has no section on homomorphisms; the statement is from the spec. §1.6 (no marker) has a
worked example of the reduction, given below.

Verbatim, tz_cfl §4.5.9:
> Поскольку CFL замкнуты относительно гомоморфизмов, если h(L) не КС → L не КС

Verbatim, tz_cfl §4.5.9:
> Или найти обратный гомоморфизм h⁻¹ такой, что h⁻¹(L) не КС

No tool computes h or checks the image language. Until it is checked, the description h(L) = L′ or
h⁻¹(L) = L′ is an LLM claim. Pumping L′ proves nothing about L if the description is wrong; this is
the cfl-06 failure of §4.3.

1. Describe the image as its own IR L′, preferably in exponent notation so that it gets an exact
   oracle. Do NOT run a main-thread `validate_ir` on L′: every accepted main-thread `validate_ir`
   goes to HITL 1 as the task's formalization, and the verdict is about L, not about L′. Check L′
   inside an ir-builder subagent (started with the `task` tool) instead.
   With HITL 1 on (the default), the verdict gate binds the verdict to the IR approved there, so
   results computed on L′ count as "another IR" and are excluded. This route then gives `non_cfl`
   no tool basis: the verdict stays `inconclusive` (≤ 0.40) unless Lean proves it. Use it as an
   argument for the written proof, and prefer §4.3 (∩ R on the task IR itself) when it applies.
2. **Check the description.** Compute h on each word yourself.
   - h⁻¹(L), with h: Γ* → Σ*: a word w ∈ Γ* is in h⁻¹(L) exactly when h(w) ∈ L. Label the words
     h(w) with `check_membership(cls="cfl", ir=<task IR>, words=...)`. Then call
     `check_membership(cls="cfl", ir=L′, words=<the w>, expected=<those labels>)`. Take the w both
     from words of L′ and from other words over Γ.
   - h(L), with h: Σ* → Γ*: take words w of L (labelled by the task IR) and call
     `check_membership(cls="cfl", ir=L′, words=<the h(w)>, expected=<True for each>)`. For the
     other inclusion, u ∈ h(L) needs only that SOME preimage of u lies in L. Give each sampled word
     u of L′ a preimage w with h(w) = u and check w ∈ L with
     `check_membership(cls="cfl", ir=<task IR>, words=...)`. One preimage outside L refutes nothing
     unless h is injective. For a non-erasing h the preimages of u are finitely many: u ∉ h(L)
     follows only when ALL of them are outside L. When h erases a letter, the preimages are
     infinitely many and a failed search is never a refutation. In that case, first restrict L with
     ∩ R (§4.3) so that the split of each word is forced.
   A disagreement on the first inclusion (some h(w) with w ∈ L not in L′), or a u all of whose
   preimages are outside L, is `refuted`: the description is wrong. Agreement is at most `bounded_pass`, and
   it covers only the description.
3. Prove that L′ is not CFL with §4.1–4.3, and check it with `pump_check_cfl(ir=L′, claim=...)`,
   against L′, not the task IR.

Verbatim, THEORY.md §1.6:
> Тогда h⁻¹(K) ∩ A⁺EB⁺FC⁺GD⁺ = {AⁿEBⁿFCⁿGDⁿ | n ≥ 1}. Это равенство следует из уже доказанного разбора U по единственным разделяющим вхождениям aa и $, а не из предположения об инъективности h.

The image of that language under A↦a, B↦b, C↦c, D,E,F,G↦ε is {aⁿbⁿcⁿ | n ≥ 1}. The example uses
an inverse homomorphism, ∩ REG and an erasing homomorphism, and it proves the image equality rather
than assuming it.

### 4.7 Parikh image

Verbatim, tz_cfl §11.6:
> полулинейность коммутативного образа — НЕОБХОДИМОЕ, но НЕ достаточное условие для КС.

Verbatim, VERDICT_POLICY.md §4:
> Конечная выборка векторов всегда полулинейна; `looks_semilinear` — эвристика полного образа, а не сертификат.

`parikh` is always `well_formed` and never a basis for a verdict. A semilinear image says nothing
about CFL. An argument that the full image is not semilinear is LLM text, and the tool cannot
confirm it.

### 4.8 Ambiguity

Verbatim, THEORY.md §1.5:
> Существенно неоднозначный ⇒ не UnambCF ⇒ не DCFL (у DCFL есть LR(1)-грамматика, LR(k)-грамматики однозначны). Пример [Sh, Thm 4.4.1]: {aⁱbʲcᵏ | i = j ∨ j = k}. Неоднозначность **грамматики** не говорит ничего о языке (Format 2).

An inherently ambiguous language is still CFL when it has a CFG (eval cfl-02 is `cfl`). Ambiguity is
a DCFL argument, never a non-CFL argument.

## 5. Tool map

| Step | Tool | What it gives | Ceiling |
|---|---|---|---|
| IR | `describe_ir_schema`, `validate_ir`, `ir_to_text` | kinds, validity, oracle and Lean availability, paraphrase for HITL 1 | `well_formed` (reference / structure) |
| explore | `sample_words`, `check_membership` without `expected` | oracle-labelled words | `not_verified` (reference) |
| theory | `list_theorems(cls="cfl")`, `get_theorem(id=...)` | THEORY.md sections, verbatim | `not_verified` (reference) |
| definition | `input_grammar_cfg` | R2-CFG certificate for `kind: grammar` | `verified` |
| construct | `to_cnf`, `cyk`, `pda_run` | facts about this grammar / PDA | `well_formed` / `verified` (about the artifact only) |
| construct | `grammar_vs_ir` | grammar against the IR's language | `bounded_pass` / `refuted` |
| destruct | `pump_check_cfl` claim mode | pumping / Ogden argument check | `well_formed` / `refuted` |
| destruct | `pump_check_cfl` split mode | one split, diagnostic | `not_verified` / `refuted` |
| closure | `regex_to_dfa`, `run_dfa` | R is regular; words of R | `verified` (about R) |
| closure / cross-check | `check_membership` with `expected` | your labels against the oracle | `bounded_pass` / `refuted` |
| heuristics | `parikh` | Parikh vectors, image sample | `well_formed` |
| Lean (P6) | `lean_statement`, `lean_check` | formal proof check | `verified` only for `proved` |
| orchestration (P4) | `spawn_subagent`, `run_workflow`, `budget_status` | parallel branches, budget | `not_verified` |
| report (P3) | `list_report_templates`, `submit_report` | report, HITL 2 | `not_verified` |

## 6. Evidence: verified, bounded, well-formed

Caps from VERDICT_POLICY §2:

| trust | cap |
|---|---|
| verified | 0.98 |
| bounded_pass | 0.85 |
| well_formed | 0.55 |
| not_verified | 0.40 |

What each kind of CFL evidence is worth:

- **`cfl`, verified (0.98):** `input_grammar_cfg` certified the task grammar (`kind: grammar` only),
  or Lean `proved` in direction `cfl`.
- **`cfl`, bounded (≤ 0.85):** `grammar_vs_ir` gave `bounded_pass` for your grammar: at least 30
  decided words, an exact oracle and no counterexample. The checked lengths are in `bounds`. Say
  "checked on all words up to length N plus M sampled words", never "proved".
- **`cfl`, not admissible:** a grammar with `well_formed`/`not_verified` from `grammar_vs_ir`, a PDA
  checked only with `pda_run`, or a closure or decomposition argument without a checked grammar. R2
  needs an artifact with at least `bounded_pass`, otherwise the result is inconclusive.
- **`non_cfl`, verified (0.98):** only Lean `proved` in direction `non_cfl`.
- **`non_cfl`, well-formed (≤ 0.55):** `pump_check_cfl` claim mode with `word_instances` returned
  `well_formed` (pumping or Ogden, on the task IR or on L′ = L ∩ R). Closing every split for
  p = 3, 4 does not raise the cap. Note: the gate does NOT read `bounds.unresolved_splits`. It
  admits a claim-mode `well_formed` result even when some splits stay in L for every i (cfl-12 with
  plain pumping: 9 of 462 unresolved). That rule is yours to keep, not the gate's: before you submit
  a `non_cfl` report, every unresolved split must have a named exit that split mode did not refute
  (Step 5, item 5). If a split stays in L for every i, the argument is wrong for that z. Switch to
  Ogden or another z, and do not submit.
- **`non_cfl`, not admissible:** an argument with no tool check, a `refuted` argument, or only a
  failed construction (R1). The result is inconclusive, ≤ 0.40.
- **Contradiction left open (R3):** inconclusive, ≤ 0.50.
- **Never evidence for a verdict:** `sample_words`, `check_membership` without `expected`, a single
  pumping split, `parikh`, sandbox brute force (≤ `well_formed`), and the theory tools.

## 7. Status of the theory used here

The preamble of THEORY.md defines the brute-force marker:

Verbatim, THEORY.md §I:
> Метка «проверено перебором» означает только указанный конечный диапазон. Для общего утверждения требуется приведённое доказательство или точная ссылка; она не означает, что вся реализация формально верифицирована.

| Section | Marker in THEORY.md | What it covers |
|---|---|---|
| §2.0 | no marker | pumping quantifiers [R-Pump, p. 7]; Ogden by reference [Sh, Lemma 4.3.1]; the R2-CFG rule; the Ogden example |
| §2 | [проверено перебором] | ticket w₁w₂w₁w₃: the wrong intersection, R = a⁺b⁺ac·a⁺b⁺ac, the pumping proof for L ∩ R (brute force over the stated ranges) |
| §2.3 | no marker | grammar_filter_49: not CFL (b*a*b*a*, Ogden); counter filters |
| §2.4 | no marker | interchange lemma [Sh, Lemma 4.5.1]; Sokolowski removed |
| §2.5 | [проверено перебором] | wwvvR: not CFL (R*, pumping) |
| §1.5 | [проверено] | essential ambiguity; grammar ambiguity says nothing about the language |

None of the CFL sections carries the plain marker [проверено]. The preamble says the [Sh] references
(Ogden, interchange) were checked against H. J. Hoogeboom's slides for the book, and that the full
texts of some other sources were not read. [R-Pump] and [R-CFL] are Coq formalizations: they support
the mathematics, not this repository's code. When the report cites one of these sections, cite its
marker too, and do not call a "[проверено перебором]" result proved beyond its stated range unless
the section itself gives the general proof.

## 8. Traps

`traps.md` lists the CFL trap tasks from EVAL_SET with the expected verdicts, plus the failure
patterns seen in live runs. The ones that cost the most:

1. A loose regular language R in a closure argument gives a CFL intersection (cfl-06, THEORY.md §2).
2. "A counter filter is regular" (cfl-07, THEORY.md §2.3).
3. "L = Σ*" or an independent-copies grammar for wwvvᴿ (cfl-08, THEORY.md §2.5).
4. Plain pumping where Ogden is needed (cfl-12, THEORY.md §2.0). Claim mode still returns
   `well_formed`, but with `bounded_check.status: "inconclusive"` and 9 of 462 splits unresolved
   for z = abᵖcᵖdᵖ: the leading a is pumped.
5. A wrong concrete instance of a correct parametric word (ticket 50, p = 4).
6. Checking the nested pumping of L ∩ R against the oracle of L.
7. A failed grammar taken as a non-CFL proof (R1, the grammar_filter_49 precedent).

Files in this skill

  • SKILL.md38.7 KB
  • traps.md8.1 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.