The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
style(plugins): sync vendored tameru ruff-clean under ruff.toml (engine b2b1b19)
Benjamin Angeb6598199038
diff --git a/plugins/context_engine/tameru/agent_extractive_engine.py b/plugins/context_engine/tameru/agent_extractive_engine.pyindex a3710b5d7bb..47c10818c93 100644--- a/plugins/context_engine/tameru/agent_extractive_engine.py+++ b/plugins/context_engine/tameru/agent_extractive_engine.py@@ -7,8 +7,8 @@ from .transcript import ()__all__ = [- "apply_extractive_tool_prune",- "last_user_text","MIN_TOOL_CHARS","PROTECT_LAST_TOOL",+ "apply_extractive_tool_prune",+ "last_user_text",]diff --git a/plugins/context_engine/tameru/agent_formats.py b/plugins/context_engine/tameru/agent_formats.pyindex 976986f3af7..a1ba8edf915 100644--- a/plugins/context_engine/tameru/agent_formats.py+++ b/plugins/context_engine/tameru/agent_formats.py@@ -413,12 +413,12 @@ def _diff_path(f: _DiffFile) -> str:elif ln.startswith("--- "):minus = ln[4:].split("\t")[0].strip()if plus and plus != "/dev/null":- return plus[2:] if plus.startswith("b/") else plus+ return plus.removeprefix("b/")if minus and minus != "/dev/null":- return minus[2:] if minus.startswith("a/") else minus+ return minus.removeprefix("a/")parts = f.header[0].split()last = parts[-1] if parts else "?"- return last[2:] if last.startswith("b/") else last+ return last.removeprefix("b/")def adapt_unified_diff(@@ -980,9 +980,9 @@ def _classify_pytest(lines: list[str]) -> tuple[list[bool], list[int], list[int]tests[i] = p.group(1).count(".")i += 1continue- if section == "" and ln.strip():- keep[i] = True- elif section == "drop" and _PYTEST_FAILURE_WORD_RE.search(ln):+ if (section == "" and ln.strip()) or (+ section == "drop" and _PYTEST_FAILURE_WORD_RE.search(ln)+ ):keep[i] = Truei += 1return keep, tests, suites, captured@@ -1079,9 +1079,9 @@ def _classify_cargo(lines: list[str]) -> tuple[list[bool], list[int], list[int]]if ln == "failures:":in_failures = Truekeep[i] = True- elif ln.startswith(("test result:", "running ", " Running ", " Doc-tests ")):- keep[i] = True- elif ln.startswith("---- ") and ln.endswith(" ----"):+ elif ln.startswith(("test result:", "running ", " Running ", " Doc-tests ")) or (+ ln.startswith("---- ") and ln.endswith(" ----")+ ):keep[i] = Trueelif _CARGO_OK_RE.match(ln):tests[i] = 1diff --git a/plugins/context_engine/tameru/compress_context.py b/plugins/context_engine/tameru/compress_context.pyindex 11a7518969e..e83cf8dfc9e 100644--- a/plugins/context_engine/tameru/compress_context.py+++ b/plugins/context_engine/tameru/compress_context.py@@ -34,7 +34,7 @@ from .contract_gates import (distinctive_query_terms,query_has_distinctive_selectors,)-from .folding import fold_lossless, json_brief, mask_template # noqa: F401 (fold_lossless re-exported)+from .folding import fold_lossless, json_brief, mask_templatefrom .format_adapters import FILLER_WORDSfrom .industrial import IndustrialLimits, IndustrialResult, industrial_preprocessfrom .supersession import apply_supersession@@ -46,11 +46,15 @@ from .unicode_profile import ()try: # optional semantic tier — never required- from .semantic import resolve_tier # noqa: F401+ from .semantic import resolve_tierexcept ImportError: # direct-script use without package contextdef resolve_tier(tier):return tier+# Public re-export (``from tameru.compress_context import fold_lossless``); naming it here+# keeps the import from looking unused.+_REEXPORTED = (fold_lossless,)+try:DEFAULT_CCR_DIR = Path.home() / ".tameru" / "cache" / "context-compress-ccr"except Exception:@@ -294,7 +298,7 @@ def classify_line(line: str) -> str:if re.match(r"^\|.*\|$", t):return "table"if re.match(r"^(User|Assistant|System|Tool|Developer):", t) or re.match(- r"^\[(user|assistant|system|tool|developer)\]", t, re.I+ r"^\[(user|assistant|system|tool|developer)\]", t, re.IGNORECASE):return "chat"if t[:1] in "{[" or re.match(r'^"[A-Za-z0-9_]+"\s*:', t):@@ -866,7 +870,7 @@ def _looks_like_csv(text: str) -> bool:def _selector_patterns(terms: Iterable[str]) -> list[re.Pattern[str]]:return [- re.compile(rf"(?<![A-Za-z0-9_]){re.escape(term)}(?![A-Za-z0-9_])", re.I)+ re.compile(rf"(?<![A-Za-z0-9_]){re.escape(term)}(?![A-Za-z0-9_])", re.IGNORECASE)for term in terms]@@ -942,7 +946,7 @@ def preprocess_flat_records(text: str, query: str) -> str:_ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")-_TEST_SUMMARY_RE = re.compile(r"Tests\s+\d+\s+passed", re.I)+_TEST_SUMMARY_RE = re.compile(r"Tests\s+\d+\s+passed", re.IGNORECASE)_TEST_FILE_NOISE_RE = re.compile(r"ExperimentalWarning|Use `node --trace-warnings|^\s*[✓✔]\s")@@ -992,19 +996,19 @@ def preprocess_test_runner(# A reduced test run at most this long is final (never re-scored)._TEST_REDUCTION_FINAL_CHARS = 16000-_FILLER_COMMENT_RE = re.compile(r"^(--|#)\s*filler\b", re.I)+_FILLER_COMMENT_RE = re.compile(r"^(--|#)\s*filler\b", re.IGNORECASE)_TRUST_RISK_RE = re.compile(r"\b(?:untrusted|not\s+operational)\b"r"|\b(?:obsolete|unrelated)\b.{0,24}"r"\b(?:glossary|example|sample|entry|data)\b"r"|\b(?:ignore|disregard|override|forget)\b.{0,48}"r"\b(?:instructions?|prompt|system)\b",- re.I,+ re.IGNORECASE,)_TRUST_QUERY_RE = re.compile(r"\b(?:injection|untrusted|malicious|prompt\s+attack|obsolete|unrelated)\b"r"|\bignore\s+(?:prior|previous)\b",- re.I,+ re.IGNORECASE,)# v0.6.0: a query that says "trust nothing from untrusted sources",# "exclude untrusted …" etc. is asking for the SAFE behaviour — it must@@ -1014,7 +1018,7 @@ _TRUST_EXCLUDE_CUE_RE = re.compile(r"\b(?:trust\s+nothing|don't\s+trust|do\s+not\s+trust|exclude|filter\s+out|omit)\b"r".{0,40}\b(?:untrusted|unverified|malicious)\b"r"|\b(?:exclude|drop|skip|omit)\s+(?:any\s+)?(?:untrusted|unverified|malicious)\b",- re.I,+ re.IGNORECASE,)@@ -1418,15 +1422,13 @@ def _segment_blocks_chunked(lines: list[str]) -> list[dict[str, Any]]:prev_type = kindcontinuenew = False- if start is None:- new = True- elif kind in {"heading", "fence", "definition"}:- new = True- elif kind == "list":- new = True- elif prev_type == "blank" and kind != "blank":- new = True- elif kind != prev_type and kind in {"log", "chat", "import", "list", "table", "json"}:+ if (+ start is None+ or kind in {"heading", "fence", "definition"}+ or kind == "list"+ or (prev_type == "blank" and kind != "blank")+ or (kind != prev_type and kind in {"log", "chat", "import", "list", "table", "json"})+ ):new = Trueelif btype == "text" and kind in {"definition", "code"}:# A code/definition region starting inside a text block: split so@@ -1887,7 +1889,7 @@ def _is_sink_noise(text: str) -> bool:lines = [ln.strip() for ln in text.splitlines() if ln.strip()]if not lines:return False- return all(re.match(r"^(--|#)\s*filler\b", ln, re.I) for ln in lines)+ return all(re.match(r"^(--|#)\s*filler\b", ln, re.IGNORECASE) for ln in lines)def _query_signal(blocks: list[dict[str, Any]]) -> float:@@ -1915,13 +1917,12 @@ def _important(blocks: list[dict[str, Any]]) -> set[int]:# injection finding). The rare-candidate loop above already skips.if b.get("trust_risk"):continue- if b["type"] == "trace":- ids.add(b["id"])- elif b["entity_hits"] and b["score"] >= 5.0:- ids.add(b["id"])- elif b["score"] >= 9 and (b["entity_hits"] or b["term_hits"]):- ids.add(b["id"])- elif b["type"] == "definition" and b["entity_hits"]:+ if (+ b["type"] == "trace"+ or (b["entity_hits"] and b["score"] >= 5.0)+ or (b["score"] >= 9 and (b["entity_hits"] or b["term_hits"]))+ or (b["type"] == "definition" and b["entity_hits"])+ ):ids.add(b["id"])cap = max(3, min(18, math.ceil(n * 0.22)))if len(ids) > cap:@@ -2589,10 +2590,10 @@ def select_fixed(# immovable — they must not consume the budget they outrank.pinned_tokens = sum(b["tokens"] for b in blocks if b["id"] in pinned_ids)budget = pinned_tokens + max(- 1, int(round(max(0, total - pinned_tokens) * budget_ratio))+ 1, round(max(0, total - pinned_tokens) * budget_ratio))else:- budget = max(1, int(round(total * budget_ratio)))+ budget = max(1, round(total * budget_ratio))if reserve_tokens > 0:# v1.4.0 (E8): tokens the caller's gap markers will occupy are not# available to content.@@ -2691,11 +2692,11 @@ def _extract_critical_lines(text: str) -> list[str]:critical.append(t)continuestart = _lead_ts_end(scan)- # Lines with key-value patterns (config, settings, identifiers)- if len(t) > 15 and _CRITICAL_KV_RE.search(scan, start):- critical.append(t)- # Lines containing specific numbers (dates, IDs, versions, counts)- elif _CRITICAL_NUM_RE.search(scan, start):+ # Lines with key-value patterns (config, settings, identifiers), or+ # lines containing specific numbers (dates, IDs, versions, counts)+ if (len(t) > 15 and _CRITICAL_KV_RE.search(scan, start)) or _CRITICAL_NUM_RE.search(+ scan, start+ ):critical.append(t)return critical@@ -3323,14 +3324,13 @@ def _clear_tool_payloads(text: str) -> str:# like a tool output marker.is_tool_result = Falseif (- line.startswith(" ") or line.startswith("\t")- ) and (- stripped.startswith("{")- or stripped.startswith("[")- or stripped.startswith('"')- ):- is_tool_result = True- elif stripped.startswith("TOOL:") and len(stripped) > 30:+ (line.startswith(" ") or line.startswith("\t"))+ and (+ stripped.startswith("{")+ or stripped.startswith("[")+ or stripped.startswith('"')+ )+ ) or (stripped.startswith("TOOL:") and len(stripped) > 30):is_tool_result = Trueelif re.match(r"^\s{2,}\w[^(]*\(", line) and "=>" in stripped:# Indented function-call line with an arrow (tool call result)@@ -3585,7 +3585,7 @@ def _summary_preserves_required_facts(rf"(?<!\w){re.escape(query_term)}(?!\w)\s+"r"(?:is|are|was|were|equals?|uses?|=)\s+(.+)$",segment,- re.I,+ re.IGNORECASE,)if not match:continuediff --git a/plugins/context_engine/tameru/folding.py b/plugins/context_engine/tameru/folding.pyindex 95ccbd30e0b..7563c17ee56 100644--- a/plugins/context_engine/tameru/folding.py+++ b/plugins/context_engine/tameru/folding.py@@ -20,7 +20,7 @@ import refrom collections import Counterfrom typing import Any-__all__ = ["fold_lossless", "mask_template", "json_brief"]+__all__ = ["fold_lossless", "json_brief", "mask_template"]# --------------------------------------------------------------------------# E9: fold_lossless@@ -265,12 +265,22 @@ def _dumps(obj: Any) -> str:return _UNSAFE_RAW_RE.sub(_escape_char, out)-def _escape_char(match: "re.Match[str]") -> str:+def _json_brief_body(+ count: int, keys: str, head: str, tail: str, notable: str, omitted: int+) -> str:+ """The JSON brief object; ``keys`` is already-dumped JSON, the row lists are joined dumps."""+ return (+ f'{{"_count":{count:d},"_keys":{keys},"_head":[{head}],"_tail":[{tail}],'+ f'"_notable":[{notable}],"_omitted":{omitted:d}}}'+ )+++def _escape_char(match: re.Match[str]) -> str:code = ord(match.group())if code > 0xFFFF: # JSON escapes astral characters as a surrogate paircode -= 0x10000- return "\\u%04x\\u%04x" % (0xD800 + (code >> 10), 0xDC00 + (code & 0x3FF))- return "\\u%04x" % code+ return f"\\u{0xD800 + (code >> 10):04x}\\u{0xDC00 + (code & 0x3FF):04x}"+ return f"\\u{code:04x}"def _find_rows(obj: Any) -> tuple[list[dict], str | None, dict] | None:@@ -424,7 +434,7 @@ def _json_brief(text: str, *, budget_chars: int, query: str = "") -> str | None:pre = [0] * (n + 1)for i, d in enumerate(dumped):pre[i + 1] = pre[i] + len(d) + 1- head_overhead = len('{"_count":%d,"_keys":%s,"_head":[],"_tail":[],"_notable":[],"_omitted":%d}' % (n, _dumps(keys), n))+ head_overhead = len(_json_brief_body(n, _dumps(keys), "", "", "", n))def parts(k: int) -> tuple[list[int], list[int]]:head = list(range(min(k, n)))@@ -446,16 +456,13 @@ def _json_brief(text: str, *, budget_chars: int, query: str = "") -> str | None:if size(head, tail, notable) > inner_budget + 3 * len(notable) + 4:return Noneomitted = n - len(shown) - len(notable)- body = (- '{"_count":%d,"_keys":%s,"_head":[%s],"_tail":[%s],"_notable":[%s],"_omitted":%d}'- % (- n,- _dumps(keys),- ",".join(dumped[i] for i in head),- ",".join(dumped[i] for i in tail),- ",".join(dumped[i] for i in sorted(notable)),- omitted,- )+ body = _json_brief_body(+ n,+ _dumps(keys),+ ",".join(dumped[i] for i in head),+ ",".join(dumped[i] for i in tail),+ ",".join(dumped[i] for i in sorted(notable)),+ omitted,)return (body, len(body)) if len(body) <= inner_budget else Nonediff --git a/plugins/context_engine/tameru/semantic.py b/plugins/context_engine/tameru/semantic.pyindex c152ce37f6a..229cefb0662 100644--- a/plugins/context_engine/tameru/semantic.py+++ b/plugins/context_engine/tameru/semantic.py@@ -68,7 +68,7 @@ class _DisabledTier:available = False- def __getattr__(self, name): # noqa: D105+ def __getattr__(self, name):def _raise(*a: Any, **k: Any):raise SemanticUnavailable("semantic tier disabled")diff --git a/plugins/context_engine/tameru/supersession.py b/plugins/context_engine/tameru/supersession.pyindex 189f721be99..81dd5cdf3b1 100644--- a/plugins/context_engine/tameru/supersession.py+++ b/plugins/context_engine/tameru/supersession.py@@ -147,7 +147,7 @@ def apply_supersession(scored: list[dict[str, Any]], kept: set[int]) -> set[int]# found by counting postings across this block's terms.counts: dict[int, int] = {}for t in n_terms:- for other in postings.get(t, ()): # noqa: B007+ for other in postings.get(t, ()):if other < new_id and len(terms_by_id[other]) <= _MAX_SUPERSESSION_TOKENS:counts[other] = counts.get(other, 0) + 1for old_id, shared_n in counts.items():diff --git a/plugins/context_engine/tameru/transcript.py b/plugins/context_engine/tameru/transcript.pyindex 528e1f7580b..e1a2cb97979 100644--- a/plugins/context_engine/tameru/transcript.py+++ b/plugins/context_engine/tameru/transcript.py@@ -428,7 +428,7 @@ def _boolean_requirement_satisfied(field: str, expected: bool, post: str) -> boorf"{field_ref}\s*(?:(?:is|equals?)\s+|[=:]\s*)?"r"(true|yes|on|false|no|off)\b",post,- re.I,+ re.IGNORECASE,)if explicit:return (explicit.group(1).casefold() in {"true", "yes", "on"}) is expected@@ -437,20 +437,20 @@ def _boolean_requirement_satisfied(field: str, expected: bool, post: str) -> boore.search(rf"\b(?:is\s+)?(?:not|never)\s+(?:currently\s+)?{field_ref}",post,- re.I,+ re.IGNORECASE,))- positive = bool(re.search(field_ref, post, re.I)) and not negated+ positive = bool(re.search(field_ref, post, re.IGNORECASE)) and not negatedfield_key = "_".join(words)if field_key == "enabled":- not_disabled = bool(re.search(r"\bnot\s+disabled\b", post, re.I))- disabled = bool(re.search(r"\bdisabled\b", post, re.I)) and not not_disabled+ not_disabled = bool(re.search(r"\bnot\s+disabled\b", post, re.IGNORECASE))+ disabled = bool(re.search(r"\bdisabled\b", post, re.IGNORECASE)) and not not_disabledpositive = positive or not_disablednegated = negated or disabledelif field_key == "active":- not_inactive = bool(re.search(r"\bnot\s+inactive\b", post, re.I))- inactive = bool(re.search(r"\binactive\b", post, re.I)) and not not_inactive+ not_inactive = bool(re.search(r"\bnot\s+inactive\b", post, re.IGNORECASE))+ inactive = bool(re.search(r"\binactive\b", post, re.IGNORECASE)) and not not_inactivepositive = positive or not_inactivenegated = negated or inactive