Skip to content

The agent that grows with you

feat(context): industrialize Tameru plugin v1.2.0

0xWhiteMage106d5c45bd49
diff --git a/plugins/context_engine/extractive/plugin.yaml b/plugins/context_engine/extractive/plugin.yaml
index 0cc47d83b62..37a836c89dc 100644
--- a/plugins/context_engine/extractive/plugin.yaml
+++ b/plugins/context_engine/extractive/plugin.yaml
@@ -1,4 +1,4 @@
name: extractive
display_name: Tameru compatibility alias
description: "Deprecated compatibility alias; migrate context.engine to tameru"
-version: 1.1.1
+version: 1.2.0
diff --git a/plugins/context_engine/tameru/__init__.py b/plugins/context_engine/tameru/__init__.py
index 414a33c7366..843d25119b1 100644
--- a/plugins/context_engine/tameru/__init__.py
+++ b/plugins/context_engine/tameru/__init__.py
@@ -1,4 +1,4 @@
-"""Hermes context-engine adapter for vendored Tameru 1.1.1."""
+"""Hermes context-engine adapter for vendored Tameru 1.2.0."""
from __future__ import annotations
from typing import Any
diff --git a/plugins/context_engine/tameru/compress_context.py b/plugins/context_engine/tameru/compress_context.py
index b2b605bb5c4..a54a1354059 100644
--- a/plugins/context_engine/tameru/compress_context.py
+++ b/plugins/context_engine/tameru/compress_context.py
@@ -8,6 +8,7 @@ the query signal is too weak to justify a cut.
from __future__ import annotations
import hashlib
+import bisect
import json
import math
import os
@@ -25,7 +26,9 @@ from .contract_gates import (
distinctive_query_terms,
query_has_distinctive_selectors,
)
+from .industrial import IndustrialLimits, IndustrialResult, industrial_preprocess
from .supersession import apply_supersession
+from .unicode_profile import script_of, search_units, token_units
try: # optional semantic tier — never required
from .semantic import resolve_tier # noqa: F401
@@ -79,6 +82,7 @@ _DOTTED_RE = re.compile(r"\b[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)+\b")
_QUOTED_RE = re.compile(r"[\"']([^\"']{2,64})[\"']")
_CAPS_RE = re.compile(r"\b[A-Z]{2,24}\b")
_URI_RE = re.compile(r"\b[a-z][a-z0-9+.-]*://\S+")
+_FAST_ACCOUNTING_PUNCT = frozenset("§…×–—“”‘’")
@dataclass
@@ -110,10 +114,61 @@ class CompressResult:
return asdict(self)
+def _sha256_text(text: str) -> str:
+ return hashlib.sha256(str(text).encode("utf-8", errors="surrogatepass")).hexdigest()
+
+
+def _bounded_id_manifest(ids: Iterable[int], limit: int) -> list[int] | dict[str, Any]:
+ ordered = sorted(int(item) for item in ids)
+ resolved = max(0, int(limit))
+ if len(ordered) <= resolved:
+ return ordered
+ head_count = (resolved + 1) // 2
+ tail_count = resolved - head_count
+ encoded = json.dumps(ordered, separators=(",", ":")).encode("ascii")
+ return {
+ "count": len(ordered),
+ "head": ordered[:head_count],
+ "tail": ordered[-tail_count:] if tail_count else [],
+ "sha256": hashlib.sha256(encoded).hexdigest(),
+ }
+
+
+def _receipt_hashes(
+ source: str,
+ output: str,
+ industrial: IndustrialResult,
+ *,
+ mode: str,
+ strategy: str,
+ budget_ratio: Optional[float],
+ citations: bool,
+) -> dict[str, str]:
+ config = {
+ "budget_ratio": budget_ratio,
+ "citations": bool(citations),
+ "limits": asdict(industrial.limits),
+ "mode": mode,
+ "strategy": strategy,
+ }
+ config_bytes = json.dumps(
+ config, ensure_ascii=False, sort_keys=True, separators=(",", ":")
+ ).encode("utf-8")
+ return {
+ "source_sha256": _sha256_text(source),
+ "output_sha256": _sha256_text(output),
+ "config_sha256": hashlib.sha256(config_bytes).hexdigest(),
+ }
+
+
def estimate_tokens(text: str) -> int:
if not text:
return 0
- return max(1, len(_TOKEN_RE.findall(text)))
+ if text.isascii() or all(
+ ord(char) < 128 or char in _FAST_ACCOUNTING_PUNCT for char in text
+ ):
+ return max(1, len(_TOKEN_RE.findall(text)))
+ return max(1, len(token_units(text)))
def _norm_newlines(text: str) -> str:
@@ -669,6 +724,18 @@ def _extract_terms(query: str) -> list[str]:
continue
seen.add(term)
terms.append(term)
+ for raw in search_units(query or "")[:128]:
+ term = raw.strip("؟?!.،,;:…\"'()[]")
+ if not term or term in seen or term in _STOP or term in _KANA_STOP:
+ continue
+ representative = next((char for char in term if char.isalnum()), term[0])
+ script = script_of(representative)
+ if script in {"han", "kana", "hangul", "arabic"}:
+ continue
+ if len(term) <= 2 and script in {None, "latin", "greek", "cyrillic"}:
+ continue
+ seen.add(term)
+ terms.append(term)
# Hyphenated compound names in the query ("titanium-torsion-rod") are
# single search terms too — the tokenizer splits them on "-".
for m in re.findall(r"\b\w+(?:-\w+)+\b", query or ""):
@@ -1936,6 +2003,8 @@ def _render(
citations: bool = False,
reorder_best: bool = False,
) -> str:
+ chronological_blocks = sorted(blocks, key=lambda block: block["start"])
+ block_starts = [block["start"] for block in chronological_blocks]
order = sorted((b for b in blocks if b["id"] in kept), key=lambda b: b["start"])
if reorder_best and len(order) >= 3:
# Lost-in-the-middle mitigation (LongLLMLingua / twotrim): models
@@ -1954,7 +2023,13 @@ def _render(
# knows it can recall the exact head/tail by hash later.
# Only emit citations when they're net-positive: the stub
# tokens must be less than the dropped block tokens they replace.
- dropped = [x for x in blocks if x["id"] not in kept and x["start"] > prev_end and x["end"] < b["start"]]
+ left = bisect.bisect_right(block_starts, prev_end)
+ right = bisect.bisect_left(block_starts, b["start"])
+ dropped = [
+ block
+ for block in chronological_blocks[left:right]
+ if block["id"] not in kept and block["end"] < b["start"]
+ ]
gap_tokens = 0
dropped_tokens = 0
for d in dropped:
@@ -2848,6 +2923,7 @@ def compress_context(
summary_models: Iterable[str] | str | None = None,
summary_timeout: float | None = None,
summary_allow_remote: bool | None = None,
+ limits: IndustrialLimits | None = None,
) -> CompressResult:
caller_text = str(context or "")
requested_mode = (mode or "adaptive").strip().lower()
@@ -2858,8 +2934,53 @@ def compress_context(
mode_norm = (
"adaptive" if requested_mode in {"compiler", "precision"} else requested_mode
)
+ industrial = industrial_preprocess(caller_text, query or "", limits)
+ if industrial.hard_fail_open:
+ tokens = estimate_tokens(caller_text)
+ reason = industrial.reason or "industrial preflight failed open"
+ fail_result = CompressResult(
+ compressed_text=caller_text,
+ original_tokens=tokens,
+ kept_tokens=tokens,
+ tokens_saved_pct=0.0,
+ policy_name="local-fail-open",
+ mode=requested_mode,
+ keep_ratio=1.0,
+ tokens_saved=0,
+ kept_line_ratio=1.0,
+ compression_risk="high",
+ confidence=0.0,
+ content_type=industrial.profile.format,
+ fail_open=True,
+ reasons=[reason],
+ receipt={
+ "schema_version": "1",
+ "engine": "tameru",
+ "policy": "local-fail-open",
+ "query_hash": hashlib.sha256(
+ (query or "").encode("utf-8")
+ ).hexdigest()[:12],
+ "savings_pct": 0.0,
+ "risk": "high",
+ "industrial": industrial.to_dict(),
+ },
+ )
+ assert fail_result.receipt is not None
+ fail_result.receipt.update(
+ _receipt_hashes(
+ caller_text,
+ caller_text,
+ industrial,
+ mode=requested_mode,
+ strategy=strategy,
+ budget_ratio=budget_ratio,
+ citations=citations,
+ )
+ )
+ return fail_result
original_text = _norm_newlines(caller_text)
- text = strip_ansi(original_text)
+ industrial_text = industrial.text if industrial.applied else caller_text
+ text = strip_ansi(_norm_newlines(industrial_text))
text = unwrap_hermes_tool(text)
text = preprocess_test_runner(text, query or "")
if not text.strip():
@@ -2966,17 +3087,74 @@ def compress_context(
).hexdigest()[:12],
"savings_pct": round((1.0 - keep_ratio) * 100.0, 2),
"risk": summary_risk,
+ "industrial": industrial.to_dict(),
+ **_receipt_hashes(
+ caller_text,
+ result_text,
+ industrial,
+ mode=requested_mode,
+ strategy=strategy,
+ budget_ratio=budget_ratio,
+ citations=citations,
+ ),
},
)
# LLM failed or returned a longer result — fall through to extract.
strategy_norm = "extract"
lines, content_type = preprocess(text, query or "")
+ if industrial.applied:
+ content_type = industrial.profile.format
if not query_has_distinctive_selectors(query or ""):
# Do not fingerprint-collapse logs or crush JSON on a generic query.
lines = text.split("\n")
content_type = route_content_type(lines)
blocks = segment_blocks(lines)
+ if len(blocks) > industrial.limits.max_blocks:
+ tokens = estimate_tokens(caller_text)
+ reason = (
+ f"block limit exceeded: {len(blocks)} > "
+ f"{industrial.limits.max_blocks}"
+ )
+ receipt = {
+ "schema_version": "1",
+ "engine": "tameru",
+ "policy": "local-fail-open",
+ "query_hash": hashlib.sha256(
+ (query or "").encode("utf-8")
+ ).hexdigest()[:12],
+ "savings_pct": 0.0,
+ "risk": "high",
+ "industrial": industrial.to_dict(),
+ }
+ receipt.update(
+ _receipt_hashes(
+ caller_text,
+ caller_text,
+ industrial,
+ mode=requested_mode,
+ strategy=strategy,
+ budget_ratio=budget_ratio,
+ citations=citations,
+ )
+ )
+ return CompressResult(
+ compressed_text=caller_text,
+ original_tokens=tokens,
+ kept_tokens=tokens,
+ tokens_saved_pct=0.0,
+ policy_name="local-fail-open",
+ mode=requested_mode,
+ keep_ratio=1.0,
+ tokens_saved=0,
+ kept_line_ratio=1.0,
+ compression_risk="high",
+ confidence=0.0,
+ content_type=industrial.profile.format,
+ fail_open=True,
+ reasons=[reason],
+ receipt=receipt,
+ )
scored = score_blocks(blocks, query or "")
# v0.10.0 (G2, KVzip sink semantics): pinned blocks are exempt from
@@ -3169,6 +3347,8 @@ def compress_context(
line_keep = len(kept_line_idx) / max(1, len(lines))
reasons = sorted({scored[i]["reason"] for i in kept if i < len(scored)})
+ if industrial.applied:
+ reasons.append(f"industrial adapter: {industrial.profile.format}")
if freeze_cache_saturated:
reasons.append("freeze cache capacity reached")
result_text = compressed
@@ -3255,13 +3435,31 @@ def compress_context(
"schema_version": "1",
"engine": "tameru",
"policy": policy,
- "kept_ids": sorted(i for i in kept if i < len(scored)),
- "dropped_ids": sorted(b["id"] for b in scored if b["id"] not in kept),
+ "kept_ids": _bounded_id_manifest(
+ (i for i in kept if i < len(scored)),
+ industrial.limits.max_receipt_ids,
+ ),
+ "dropped_ids": _bounded_id_manifest(
+ (b["id"] for b in scored if b["id"] not in kept),
+ industrial.limits.max_receipt_ids,
+ ),
"query_hash": query_hash,
"savings_pct": savings,
"risk": risk,
"verifier": verifier,
+ "industrial": industrial.to_dict(),
}
+ receipt.update(
+ _receipt_hashes(
+ caller_text,
+ result_text,
+ industrial,
+ mode=requested_mode,
+ strategy=strategy,
+ budget_ratio=budget_ratio,
+ citations=citations,
+ )
+ )
__cr.receipt = receipt
# v0.10.0 (G1 memorix checkpoints): append-only audit log, opt-in.
@@ -3285,12 +3483,19 @@ def compress_context(
"ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
"query_hash": query_hash,
"policy": policy,
- "kept": len(receipt["kept_ids"]),
+ "kept": len(kept),
"total": len(scored),
"savings_pct": savings,
"risk": risk,
"fail_open": fail_open,
"top_dropped": top_dropped,
+ "industrial_format": industrial.profile.format,
+ "industrial_applied": industrial.applied,
+ "direction": industrial.profile.direction,
+ "scripts": industrial.profile.scripts,
+ "input_chars": industrial.profile.characters,
+ "input_lines": industrial.profile.lines,
+ "profile_truncated": industrial.profile.profile_truncated,
}
log_file = log_path / "compactions.jsonl"
fd = os.open(log_file, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
@@ -3306,11 +3511,27 @@ def compress_context(
def main(argv: Optional[Iterable[str]] = None) -> int:
import argparse
+ limit_defaults = IndustrialLimits()
p = argparse.ArgumentParser(description="Local query-aware extractive compressor")
p.add_argument("context_file", help="Path to context text (or - for stdin)")
p.add_argument("query")
- p.add_argument("--mode", default="adaptive", choices=["adaptive", "fixed", "compiler"])
+ p.add_argument(
+ "--mode",
+ default="adaptive",
+ choices=["adaptive", "fixed", "compiler", "precision"],
+ )
p.add_argument("--budget-ratio", type=float, default=None)
+ p.add_argument("--max-input-chars", type=int, default=limit_defaults.max_input_chars)
+ p.add_argument("--max-lines", type=int, default=limit_defaults.max_lines)
+ p.add_argument("--max-records", type=int, default=limit_defaults.max_records)
+ p.add_argument("--max-record-chars", type=int, default=limit_defaults.max_record_chars)
+ p.add_argument("--max-fields", type=int, default=limit_defaults.max_fields)
+ p.add_argument("--max-profile-chars", type=int, default=limit_defaults.max_profile_chars)
+ p.add_argument("--max-bidi-controls", type=int, default=limit_defaults.max_bidi_controls)
+ p.add_argument("--max-bidi-overrides", type=int, default=limit_defaults.max_bidi_overrides)
+ p.add_argument("--max-query-chars", type=int, default=limit_defaults.max_query_chars)
+ p.add_argument("--max-blocks", type=int, default=limit_defaults.max_blocks)
+ p.add_argument("--max-receipt-ids", type=int, default=limit_defaults.max_receipt_ids)
p.add_argument("--ccr", action="store_true", default=None,
help="Enable CCR reversible store (on by default)")
p.add_argument("--no-ccr", dest="ccr", action="store_false",
@@ -3334,6 +3555,19 @@ def main(argv: Optional[Iterable[str]] = None) -> int:
# Resolve ccr/citations defaults (None = use library default True)
ccr_val = True if args.ccr is None else args.ccr
citations_val = True if args.citations is None else args.citations
+ limits = IndustrialLimits(
+ max_input_chars=args.max_input_chars,
+ max_lines=args.max_lines,
+ max_records=args.max_records,
+ max_record_chars=args.max_record_chars,
+ max_fields=args.max_fields,
+ max_profile_chars=args.max_profile_chars,
+ max_bidi_controls=args.max_bidi_controls,
+ max_bidi_overrides=args.max_bidi_overrides,
+ max_query_chars=args.max_query_chars,
+ max_blocks=args.max_blocks,
+ max_receipt_ids=args.max_receipt_ids,
+ )
# Load decision cache if provided
decision_cache = None
if args.decision_cache:
@@ -3357,6 +3591,7 @@ def main(argv: Optional[Iterable[str]] = None) -> int:
citations=citations_val,
decision_cache=decision_cache,
strategy=args.strategy,
+ limits=limits,
)
if args.stats:
stats = out.to_dict()
diff --git a/plugins/context_engine/tameru/contract_gates.py b/plugins/context_engine/tameru/contract_gates.py
index ea6d1f075d1..32c8f82e54e 100644
--- a/plugins/context_engine/tameru/contract_gates.py
+++ b/plugins/context_engine/tameru/contract_gates.py
@@ -8,6 +8,8 @@ from __future__ import annotations
import re
from dataclasses import dataclass, field
+from .unicode_profile import matching_shadow, script_of, search_units
+
GENERIC_WORDS = frozenset(
{
"what",
@@ -115,7 +117,8 @@ def distinctive_query_terms(query: str) -> list[str]:
"""Return first-seen distinctive selectors; empty if the query is generic."""
if not query or not str(query).strip():
return []
- text = str(query)
+ raw_text = str(query)
+ text = matching_shadow(raw_text)
seen: set[str] = set()
out: list[str] = []
@@ -126,11 +129,20 @@ def distinctive_query_terms(query: str) -> list[str]:
seen.add(key)
out.append(key)
- for m in LATIN_IDENT_RE.findall(text):
+ for m in LATIN_IDENT_RE.findall(raw_text):
_add(m)
for m in _HYPHEN_RE.findall(text):
if len(m) >= 3:
_add(m)
+ for unit in search_units(text)[:128]:
+ representative = next((char for char in unit if char.isalnum()), unit[0])
+ script = script_of(representative)
+ if (
+ script not in {"han", "kana", "hangul", "arabic", "thai", "latin"}
+ and any(ord(char) > 127 for char in unit)
+ and len(unit) >= 2
+ ):
+ _add(unit)
nl = NON_LATIN_RE.search(text)
if nl:
sentinel = f"script:{nl.group(0)}"
diff --git a/plugins/context_engine/tameru/format_adapters.py b/plugins/context_engine/tameru/format_adapters.py
new file mode 100644
index 00000000000..cbc1b96d49e
--- /dev/null
+++ b/plugins/context_engine/tameru/format_adapters.py
@@ -0,0 +1,644 @@
+"""Bounded, extractive format adapters for industrial compaction."""
+from __future__ import annotations
+
+import csv
+import io
+import json
+import re
+import xml.etree.ElementTree as ET
+from dataclasses import asdict, dataclass
+from typing import Callable
+
+from .contract_gates import GENERIC_WORDS, distinctive_query_terms
+from .unicode_profile import graphemes, matching_shadow, search_units
+
+
+@dataclass(frozen=True)
+class FormatLimits:
+ max_records: int = 100_000
+ max_record_chars: int = 1_000_000
+ max_fields: int = 4_096
+
+
+@dataclass(frozen=True)
+class FormatResult:
+ format: str
+ applied: bool
+ text: str
+ total_records: int = 0
+ kept_records: int = 0
+ structurally_valid: bool = True
+ reason: str = ""
+
+ def to_dict(self) -> dict[str, object]:
+ return asdict(self)
+
+
+def _decline(
+ text: str,
+ format_name: str,
+ reason: str,
+ *,
+ total_records: int = 0,
+ structurally_valid: bool = True,
+) -> FormatResult:
+ return FormatResult(
+ format=format_name,
+ applied=False,
+ text=text,
+ total_records=total_records,
+ structurally_valid=structurally_valid,
+ reason=reason,
+ )
+
+
+def _query_selectors(query: str) -> tuple[str, ...]:
+ candidates = list(distinctive_query_terms(query or ""))
+ candidates.extend(search_units(query or ""))
+ seen: set[str] = set()
+ selectors: list[str] = []
+ for raw in candidates:
+ value = matching_shadow(raw).strip()
+ if (
+ not value
+ or value.startswith("script:")
+ or value in GENERIC_WORDS
+ or value in seen
+ ):
+ continue
+ if len(value) < 2 and value.isascii():
+ continue
+ seen.add(value)
+ selectors.append(value)
+ if len(selectors) >= 128:
+ break
+ strong = [
+ value
+ for value in selectors
+ if any(char.isdigit() for char in value)
+ or any(separator in value for separator in "._:/-")
+ or any(ord(char) > 127 for char in value)
+ ]
+ return tuple(strong or selectors)
+
+
+def _contains_selector(text: str, selectors: tuple[str, ...]) -> bool:
+ shadow = matching_shadow(text)
+ for selector in selectors:
+ escaped = re.escape(selector)
+ if selector[:1].isascii() and selector[-1:].isascii():
+ pattern = re.compile(rf"(?<![\w]){escaped}(?![\w])", re.IGNORECASE)
+ if pattern.search(shadow):
+ return True
+ elif selector in shadow:
+ return True
+ return False
+
+
+def _json_loads(value: str):
+ try:
+ return json.loads(value)
+ except (json.JSONDecodeError, RecursionError):
+ return None
+
+
+def _looks_ndjson(text: str) -> bool:
+ lines = [line for line in text.splitlines() if line.strip()]
+ if len(lines) < 2:
+ return False
+ candidates = sum(line.lstrip().startswith(("{", "[")) for line in lines[:32])
+ parsed = sum(_json_loads(line) is not None for line in lines[:32])
+ sample = min(len(lines), 32)
+ return candidates >= max(2, sample // 2) and parsed >= 1
+
+
+def _line_separator(text: str) -> str:
+ return "\r\n" if "\r\n" in text else "\n"
+
+
+def _split_delimited_records(text: str) -> list[str] | None:
+ records: list[str] = []
+ start = 0
+ index = 0
+ in_quotes = False
+ while index < len(text):
+ char = text[index]
+ if char == '"':
+ if in_quotes and index + 1 < len(text) and text[index + 1] == '"':
+ index += 2
+ continue
+ in_quotes = not in_quotes
+ index += 1
+ continue
+ if not in_quotes and char in {"\n", "\r"}:
+ records.append(text[start:index])
+ if char == "\r" and index + 1 < len(text) and text[index + 1] == "\n":
+ index += 1
+ start = index + 1
+ index += 1
+ if in_quotes:
+ return None
+ if start < len(text):
+ records.append(text[start:])
+ elif text.endswith(("\n", "\r")):
+ records.append("")
+ while records and not records[-1]:
+ records.pop()
+ return records
+
+
+def _parse_delimited_record(record: str, delimiter: str, limits: FormatLimits) -> list[str] | None:
+ if len(record) > limits.max_record_chars:
+ return None
+ try:
+ rows = list(csv.reader(io.StringIO(record), delimiter=delimiter, strict=True))
+ except (csv.Error, UnicodeError):
+ return None
+ if len(rows) != 1 or len(rows[0]) > limits.max_fields:
+ return None
+ return rows[0]
+
+
+def _detect_delimiter(text: str) -> str | None:
+ records = _split_delimited_records(text)
+ if not records or len(records) < 2:
+ return None
+ for delimiter in ("\t", ","):
+ parsed = [_parse_delimited_record(record, delimiter, FormatLimits()) for record in records[:8]]
+ if any(row is None for row in parsed):
+ continue
+ widths = [len(row or []) for row in parsed]
+ if widths and min(widths) >= 2 and len(set(widths)) == 1:
+ return delimiter
+ return None
+
+
+def _looks_vertical(text: str) -> bool:
+ if _VERTICAL_MARKUP_RE.search(text):
+ return True
+ lines = [line for line in text.splitlines() if line.strip()][:128]
+ if len(lines) < 6:
+ return False
+ short = sum(
+ (len(line.strip()) if line.isascii() else len(graphemes(line.strip()))) <= 2
+ for line in lines
+ )
+ return short / len(lines) >= 0.8
+
+
+def detect_format(text: str) -> str:
+ value = str(text or "")
+ stripped = value.lstrip()
+ if re.search(r"<!doctype\s+html|<html\b", stripped[:512], re.IGNORECASE):
+ return "html"
+ if stripped.startswith("<") and stripped.rstrip().endswith(">"):
+ try:
+ ET.fromstring(stripped)
+ except (ET.ParseError, RecursionError):
+ pass
+ else:
+ return "xml"
+ if _looks_ndjson(value):
+ return "ndjson"
+ delimiter = _detect_delimiter(value)
+ if delimiter == "\t":
+ return "tsv"
+ if delimiter == ",":
+ return "csv"
+ if len(re.findall(r"(?im)^\s*(?:CREATE|INSERT|UPDATE|DELETE|SELECT|ALTER|DROP|WITH)\b", value)) >= 2:
+ return "sql"
+ if (
+ len(re.findall(r"(?m)^\s*\[[^\]\n]+\]\s*$", value)) >= 2
+ and re.search(r"(?m)^\s*[A-Za-z_][\w.-]*\s*=", value)
+ ):
+ return "ini"
+ if re.search(r"(?m)^#{1,6}\s+|^```|^~~~", value):
+ return "markdown"
+ yaml_parent = re.search(
+ r"(?m)^[^\s:#][^:\n]{0,120}:\s*$",
+ value,
+ )
+ yaml_child = re.search(
+ r"(?m)^[ \t]+(?:[-?][ \t]+)?[^\s:#][^:\n]{0,120}:\s*(?:\S.*)?$",
+ value,
+ )
+ if yaml_parent and yaml_child:
+ return "yaml"
+ if stripped[:1] in {"{", "["} and _json_loads(stripped) is not None:
+ return "json"
+ if _looks_vertical(value):
+ return "vertical"
+ return "text"
+
+
+_VERTICAL_MARKUP_RE = re.compile(r"writing-mode\s*:", re.IGNORECASE)
+
+
+def _adapt_ndjson(text: str, selectors: tuple[str, ...], limits: FormatLimits) -> FormatResult:
+ lines = [line for line in text.splitlines() if line.strip()]
+ if len(lines) > limits.max_records:
+ return _decline(text, "ndjson", "record limit exceeded", total_records=len(lines))
+ kept: list[str] = []
+ for line in lines:
+ if len(line) > limits.max_record_chars or _json_loads(line) is None:
+ return _decline(
+ text,
+ "ndjson",
+ "malformed JSON record",
+ total_records=len(lines),
+ structurally_valid=False,
+ )
+ if _contains_selector(line, selectors):
+ kept.append(line)
+ if not kept or len(kept) == len(lines):
+ return _decline(text, "ndjson", "no selective record match", total_records=len(lines))
+ return FormatResult(
+ format="ndjson",
+ applied=True,
+ text=_line_separator(text).join(kept),
+ total_records=len(lines),
+ kept_records=len(kept),
+ reason="exact matching NDJSON records",
+ )
+
+
+def _adapt_delimited(
+ text: str,
+ selectors: tuple[str, ...],
+ limits: FormatLimits,
+ delimiter: str,
+ format_name: str,
+) -> FormatResult:
+ records = _split_delimited_records(text)
+ if records is None:
+ return _decline(text, format_name, "unmatched quote", structurally_valid=False)
+ if len(records) - 1 > limits.max_records:
+ return _decline(text, format_name, "record limit exceeded", total_records=max(0, len(records) - 1))
+ parsed = [_parse_delimited_record(record, delimiter, limits) for record in records]
+ if not parsed or any(row is None for row in parsed):
+ return _decline(text, format_name, "invalid delimited record", structurally_valid=False)
+ width = len(parsed[0] or [])
+ if width < 2 or any(len(row or []) != width for row in parsed[1:]):
+ return _decline(text, format_name, "inconsistent field count", structurally_valid=False)
+ kept = [record for record, row in zip(records[1:], parsed[1:]) if _contains_selector("\t".join(row or []), selectors)]
+ total = max(0, len(records) - 1)
+ if not kept or len(kept) == total:
+ return _decline(text, format_name, "no selective record match", total_records=total)
+ result_records = [records[0], *kept]
+ return FormatResult(
+ format=format_name,
+ applied=True,
+ text=_line_separator(text).join(result_records),
+ total_records=total,
+ kept_records=len(kept),
+ reason="header plus exact matching records",
+ )
+
+
+def _adapt_markdown(text: str, selectors: tuple[str, ...], limits: FormatLimits) -> FormatResult:
+ del limits
+ lines = text.splitlines()
+ sections: list[tuple[list[str], list[str]]] = []
+ ancestors: dict[int, str] = {}
+ current_ancestors: list[str] = []
+ current: list[str] = []
+ in_fence = False
+ fence_marker = ""
+
+ def flush() -> None:
+ nonlocal current
+ if current:
+ sections.append((list(current_ancestors), current))
+ current = []
+
+ for line in lines:
+ stripped = line.lstrip()
+ marker = stripped[:3]
+ if marker in {"```", "~~~"}:
+ if not in_fence:
+ in_fence = True
+ fence_marker = marker
+ elif marker == fence_marker:
+ in_fence = False
+ current.append(line)
+ continue
+ heading = None if in_fence else re.match(r"^(#{1,6})\s+", line)
+ if heading:
+ flush()
+ level = len(heading.group(1))
+ ancestors = {depth: value for depth, value in ancestors.items() if depth < level}
+ current_ancestors = [ancestors[depth] for depth in sorted(ancestors)]
+ ancestors[level] = line
+ current = [line]
+ else:
+ current.append(line)
+ flush()
+ selected = [(parents, body) for parents, body in sections if _contains_selector("\n".join(body), selectors)]
+ if not selected or len(selected) == len(sections):
+ return _decline(text, "markdown", "no selective section match", total_records=len(sections))
+ output: list[str] = []
+ seen_headings: set[str] = set()
+ for parents, body in selected:
+ for heading in parents:
+ if heading not in seen_headings:
+ output.append(heading)
+ seen_headings.add(heading)
+ if output and output[-1].strip() and body and body[0].strip():
+ output.append("")
+ output.extend(body)
+ if body and body[0].startswith("#"):
+ seen_headings.add(body[0])
+ return FormatResult(
+ format="markdown",
+ applied=True,
+ text="\n".join(output).strip("\n"),
+ total_records=len(sections),
+ kept_records=len(selected),
+ reason="matching sections with ancestor headings",
+ )
+
+
+def _indent(line: str) -> int:
+ return len(line) - len(line.lstrip(" "))
+
+
+def _adapt_yaml(text: str, selectors: tuple[str, ...], limits: FormatLimits) -> FormatResult:
+ del limits
+ lines = text.splitlines()
+ selected: set[int] = set()
+ nonblank = [index for index, line in enumerate(lines) if line.strip()]
+ matches = [index for index in nonblank if _contains_selector(lines[index], selectors)]
+ for match in matches:
+ match_indent = _indent(lines[match])
+ anchor = match
+ list_anchor_found = False
+ for index in range(match, -1, -1):
+ if not lines[index].strip() or lines[index].lstrip().startswith("#"):
+ continue
+ indent = _indent(lines[index])
+ if indent <= match_indent and re.match(r"^\s*-\s+", lines[index]):
+ anchor = index
+ list_anchor_found = True
+ break
+ for index in range(match - 1, -1, -1):
+ if list_anchor_found:
+ break
+ if not lines[index].strip() or lines[index].lstrip().startswith("#"):
+ continue
+ indent = _indent(lines[index])
+ if indent < match_indent and lines[index].rstrip().endswith(":"):
+ anchor = index
+ break
+ anchor_indent = _indent(lines[anchor])
+ for index in range(anchor):
+ if not lines[index].strip():
+ continue
+ indent = _indent(lines[index])
+ if indent < anchor_indent and lines[index].rstrip().endswith(":"):
+ selected.add(index)
+ selected.add(anchor)
+ for index in range(anchor + 1, len(lines)):
+ if lines[index].strip() and _indent(lines[index]) <= anchor_indent:
+ break
+ selected.add(index)
+ if not selected or len(selected) >= len(lines):
+ return _decline(text, "yaml", "no selective subtree match", total_records=len(nonblank))
+ output = "\n".join(lines[index] for index in sorted(selected)).strip("\n")
+ return FormatResult(
+ format="yaml",
+ applied=True,
+ text=output,
+ total_records=len(nonblank),
+ kept_records=sum(bool(lines[index].strip()) for index in selected),
+ reason="matching subtree with parent keys",
+ )
+
+
+def _adapt_xml(text: str, selectors: tuple[str, ...], limits: FormatLimits) -> FormatResult:
+ del limits
+ upper = text.upper()
+ if "<!DOCTYPE" in upper or "<!ENTITY" in upper:
+ return _decline(text, "xml", "DTD/entity declarations are not processed", structurally_valid=False)
+ lines = [line for line in text.splitlines() if line.strip()]
+ if len(lines) < 3:
+ return _decline(text, "xml", "no line-oriented child records")
+ root = re.match(r"^\s*<([A-Za-z_][\w.:-]*)(?:\s[^>]*)?>\s*$", lines[0])
+ if root is None or not re.match(rf"^\s*</{re.escape(root.group(1))}>\s*$", lines[-1]):
+ return _decline(text, "xml", "root is not line-oriented")
+ children = lines[1:-1]
+ for child in children:
+ try:
+ ET.fromstring(child)
+ except (ET.ParseError, RecursionError):
+ return _decline(text, "xml", "child spans multiple lines", structurally_valid=True)
+ kept = [child for child in children if _contains_selector(child, selectors)]
+ if not kept or len(kept) == len(children):
+ return _decline(text, "xml", "no selective child match", total_records=len(children))
+ return FormatResult(
+ format="xml",
+ applied=True,
+ text="\n".join([lines[0], *kept, lines[-1]]),
+ total_records=len(children),
+ kept_records=len(kept),
+ reason="balanced root plus exact child elements",
+ )
+
+
+def _split_sql_statements(text: str) -> list[str] | None:
+ statements: list[str] = []
+ start = 0
+ index = 0
+ quote = ""
+ dollar_tag = ""
+ line_comment = False
+ block_comment = False
+ while index < len(text):
+ if line_comment:
+ if text[index] in "\r\n":
+ line_comment = False
+ index += 1
+ continue
+ if block_comment:
+ if text.startswith("*/", index):
+ block_comment = False
+ index += 2
+ else:
+ index += 1
+ continue
+ if dollar_tag:
+ if text.startswith(dollar_tag, index):
+ index += len(dollar_tag)
+ dollar_tag = ""
+ else:
+ index += 1
+ continue
+ if quote:
+ char = text[index]
+ if char == quote:
+ if index + 1 < len(text) and text[index + 1] == quote:
+ index += 2
+ continue
+ quote = ""
+ elif char == "\\" and index + 1 < len(text):
+ index += 2
+ continue
+ index += 1
+ continue
+ if text.startswith("--", index):
+ line_comment = True
+ index += 2
+ continue
+ if text.startswith("/*", index):
+ block_comment = True
+ index += 2
+ continue
+ char = text[index]
+ if char in {"'", '"', "`"}:
+ quote = char
+ index += 1
+ continue
+ if char == "$":
+ match = re.match(r"\$[A-Za-z_][A-Za-z0-9_]*\$|\$\$", text[index:])
+ if match:
+ dollar_tag = match.group(0)
+ index += len(dollar_tag)
+ continue
+ if char == ";":
+ statement = text[start : index + 1].strip()
+ if statement:
+ statements.append(statement)
+ start = index + 1
+ index += 1
+ if quote or dollar_tag or block_comment:
+ return None
+ tail = text[start:].strip()
+ if tail:
+ statements.append(tail)
+ return statements
+
+
+def _adapt_sql(text: str, selectors: tuple[str, ...], limits: FormatLimits) -> FormatResult:
+ statements = _split_sql_statements(text)
+ if statements is None:
+ return _decline(text, "sql", "unterminated SQL quote or comment", structurally_valid=False)
+ if len(statements) > limits.max_records:
+ return _decline(text, "sql", "record limit exceeded", total_records=len(statements))
+ if any(len(statement) > limits.max_record_chars for statement in statements):
+ return _decline(text, "sql", "statement size limit exceeded")
+ kept = [statement for statement in statements if _contains_selector(statement, selectors)]
+ if not kept or len(kept) == len(statements):
+ return _decline(text, "sql", "no selective statement match", total_records=len(statements))
+ return FormatResult(
+ format="sql",
+ applied=True,
+ text="\n".join(kept),
+ total_records=len(statements),
+ kept_records=len(kept),
+ reason="exact matching SQL statements",
+ )
+
+
+def _adapt_ini(text: str, selectors: tuple[str, ...], limits: FormatLimits) -> FormatResult:
+ del limits
+ lines = text.splitlines()
+ starts = [index for index, line in enumerate(lines) if re.match(r"^\s*\[[^\]]+\]\s*$", line)]
+ if len(starts) < 2:
+ return _decline(text, "ini", "fewer than two complete sections")
+ sections: list[str] = []
+ for position, start in enumerate(starts):
+ end = starts[position + 1] if position + 1 < len(starts) else len(lines)
+ sections.append("\n".join(lines[start:end]).strip("\n"))
+ kept = [section for section in sections if _contains_selector(section, selectors)]
+ if not kept or len(kept) == len(sections):
+ return _decline(text, "ini", "no selective section match", total_records=len(sections))
+ return FormatResult(
+ format="ini",
+ applied=True,
+ text="\n\n".join(kept),
+ total_records=len(sections),
+ kept_records=len(kept),
+ reason="exact matching INI/TOML sections",
+ )
+
+
+_HTML_OPEN_WRAPPER_RE = re.compile(r"^\s*(?:<!doctype\s+html\s*>|<html(?:\s[^>]*)?>|<body(?:\s[^>]*)?>)\s*$", re.IGNORECASE)
+_HTML_CLOSE_WRAPPER_RE = re.compile(r"^\s*</(?:body|html)>\s*$", re.IGNORECASE)
+_HTML_CHILD_RE = re.compile(r"^\s*<([A-Za-z][\w:-]*)(?:\s[^>]*)?>.*</\1>\s*$", re.IGNORECASE)
+
+
+def _adapt_html(text: str, selectors: tuple[str, ...], limits: FormatLimits) -> FormatResult:
+ del limits
+ lines = [line for line in text.splitlines() if line.strip()]
+ opening: list[str] = []
+ closing: list[str] = []
+ children: list[str] = []
+ for line in lines:
+ if _HTML_OPEN_WRAPPER_RE.match(line):
+ opening.append(line)
+ elif _HTML_CLOSE_WRAPPER_RE.match(line):
+ closing.append(line)
+ elif _HTML_CHILD_RE.match(line):
+ children.append(line)
+ else:
+ return _decline(text, "html", "child spans multiple lines")
+ if not opening or not closing or not children:
+ return _decline(text, "html", "missing line-oriented wrappers or children")
+ kept = [child for child in children if _contains_selector(child, selectors)]
+ if not kept or len(kept) == len(children):
+ return _decline(text, "html", "no selective child match", total_records=len(children))
+ return FormatResult(
+ format="html",
+ applied=True,
+ text="\n".join([*opening, *kept, *closing]),
+ total_records=len(children),
+ kept_records=len(kept),
+ reason="HTML wrappers plus exact child elements",
+ )
+
+
+def _adapt_vertical(text: str, selectors: tuple[str, ...], limits: FormatLimits) -> FormatResult:
+ del limits
+ blocks = [block for block in re.split(r"(?:\r?\n){2,}", text) if block.strip()]
+ kept = [block for block in blocks if _contains_selector("".join(block.splitlines()), selectors)]
+ if not kept or len(kept) == len(blocks):
+ return _decline(text, "vertical", "no selective vertical column match", total_records=len(blocks))
+ return FormatResult(
+ format="vertical",
+ applied=True,
+ text="\n\n".join(kept),
+ total_records=len(blocks),
+ kept_records=len(kept),
+ reason="matching logical-order OCR columns",
+ )
+
+
+_ADAPTERS: dict[str, Callable[[str, tuple[str, ...], FormatLimits], FormatResult]] = {
+ "ndjson": _adapt_ndjson,
+ "csv": lambda text, selectors, limits: _adapt_delimited(text, selectors, limits, ",", "csv"),
+ "tsv": lambda text, selectors, limits: _adapt_delimited(text, selectors, limits, "\t", "tsv"),
+ "markdown": _adapt_markdown,
+ "yaml": _adapt_yaml,
+ "xml": _adapt_xml,
+ "html": _adapt_html,
+ "sql": _adapt_sql,
+ "ini": _adapt_ini,
+ "vertical": _adapt_vertical,
+}
+
+
+def adapt_format(
+ text: str,
+ query: str,
+ limits: FormatLimits | None = None,
+ *,
+ format_name: str | None = None,
+) -> FormatResult:
+ value = str(text or "")
+ resolved_format = format_name or detect_format(value)
+ selectors = _query_selectors(query)
+ if not selectors:
+ return _decline(value, resolved_format, "query has no distinctive selectors")
+ adapter = _ADAPTERS.get(resolved_format)
+ if adapter is None:
+ return _decline(value, resolved_format, "no safe extractive adapter")
+ return adapter(value, selectors, limits or FormatLimits())
diff --git a/plugins/context_engine/tameru/industrial.py b/plugins/context_engine/tameru/industrial.py
new file mode 100644
index 00000000000..67b370c0c52
--- /dev/null
+++ b/plugins/context_engine/tameru/industrial.py
@@ -0,0 +1,210 @@
+"""Industrial preflight, limits, profiling, and format orchestration."""
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass, replace
+
+from .format_adapters import FormatLimits, FormatResult, adapt_format, detect_format
+from .unicode_profile import profile_text, unicode_safety_counts
+
+
+@dataclass(frozen=True)
+class IndustrialLimits:
+ max_input_chars: int = 8_000_000
+ max_lines: int = 250_000
+ max_records: int = 100_000
+ max_record_chars: int = 1_000_000
+ max_fields: int = 4_096
+ max_profile_chars: int = 16_384
+ max_bidi_controls: int = 10_000
+ max_bidi_overrides: int = 128
+ max_query_chars: int = 32_768
+ max_blocks: int = 20_000
+ max_receipt_ids: int = 512
+
+ def __post_init__(self) -> None:
+ for name, value in asdict(self).items():
+ if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
+ raise ValueError(f"{name} must be a positive integer, got {value!r}")
+
+ def format_limits(self) -> FormatLimits:
+ return FormatLimits(
+ max_records=self.max_records,
+ max_record_chars=self.max_record_chars,
+ max_fields=self.max_fields,
+ )
+
+ def to_dict(self) -> dict[str, int]:
+ return asdict(self)
+
+
+@dataclass(frozen=True)
+class InputProfile:
+ characters: int
+ lines: int
+ format: str
+ direction: str
+ scripts: tuple[str, ...]
+ graphemes: int
+ bidi_controls: int
+ bidi_overrides: int
+ vertical_hint: bool
+ malformed_surrogates: int
+ sampled_chars: int
+ profile_truncated: bool
+ limit_reason: str = ""
+
+ def to_dict(self) -> dict[str, object]:
+ return asdict(self)
+
+
+@dataclass(frozen=True)
+class IndustrialResult:
+ text: str
+ applied: bool
+ hard_fail_open: bool
+ profile: InputProfile
+ limits: IndustrialLimits
+ format_result: FormatResult | None = None
+ reason: str = ""
+
+ def to_dict(self) -> dict[str, object]:
+ return {
+ "applied": self.applied,
+ "hard_fail_open": self.hard_fail_open,
+ "reason": self.reason,
+ "profile": self.profile.to_dict(),
+ "limits": self.limits.to_dict(),
+ "format_result": (
+ self.format_result.to_dict() if self.format_result is not None else None
+ ),
+ }
+
+
+def _profile_sample(text: str, max_profile_chars: int) -> tuple[str, bool]:
+ if len(text) <= max_profile_chars * 2:
+ return text, False
+ return text[:max_profile_chars] + text[-max_profile_chars:], True
+
+
+def profile_input(text: str, limits: IndustrialLimits | None = None) -> InputProfile:
+ value = str(text or "")
+ resolved = limits or IndustrialLimits()
+ line_count = value.count("\n") + (1 if value else 0)
+ limit_reason = ""
+ if len(value) > resolved.max_input_chars:
+ limit_reason = (
+ f"character limit exceeded: {len(value)} > {resolved.max_input_chars}"
+ )
+ elif line_count > resolved.max_lines:
+ limit_reason = f"line limit exceeded: {line_count} > {resolved.max_lines}"
+ sample, truncated = _profile_sample(value, resolved.max_profile_chars)
+ unicode = profile_text(sample)
+ if not limit_reason:
+ controls, overrides, malformed = unicode_safety_counts(value)
+ unicode = replace(
+ unicode,
+ bidi_controls=controls,
+ bidi_overrides=overrides,
+ malformed_surrogates=malformed,
+ )
+ if controls > resolved.max_bidi_controls:
+ limit_reason = (
+ f"bidi control limit exceeded: {controls} > "
+ f"{resolved.max_bidi_controls}"
+ )
+ elif overrides > resolved.max_bidi_overrides:
+ limit_reason = (
+ f"bidi override limit exceeded: {overrides} > "
+ f"{resolved.max_bidi_overrides}"
+ )
+ return InputProfile(
+ characters=len(value),
+ lines=line_count,
+ format=detect_format(sample),
+ direction=unicode.direction,
+ scripts=tuple(sorted(unicode.scripts)),
+ graphemes=unicode.grapheme_count,
+ bidi_controls=unicode.bidi_controls,
+ bidi_overrides=unicode.bidi_overrides,
+ vertical_hint=unicode.vertical_hint,
+ malformed_surrogates=unicode.malformed_surrogates,
+ sampled_chars=len(sample),
+ profile_truncated=truncated,
+ limit_reason=limit_reason,
+ )
+
+
+def industrial_preprocess(
+ text: str,
+ query: str,
+ limits: IndustrialLimits | None = None,
+) -> IndustrialResult:
+ value = str(text or "")
+ resolved = limits or IndustrialLimits()
+ profile = profile_input(value, resolved)
+ if len(str(query or "")) > resolved.max_query_chars:
+ reason = (
+ f"query character limit exceeded: {len(str(query or ''))} > "
+ f"{resolved.max_query_chars}"
+ )
+ return IndustrialResult(
+ text=value,
+ applied=False,
+ hard_fail_open=True,
+ profile=profile,
+ limits=resolved,
+ reason=reason,
+ )
+ if profile.limit_reason:
+ return IndustrialResult(
+ text=value,
+ applied=False,
+ hard_fail_open=True,
+ profile=profile,
+ limits=resolved,
+ reason=profile.limit_reason,
+ )
+ if profile.malformed_surrogates:
+ return IndustrialResult(
+ text=value,
+ applied=False,
+ hard_fail_open=True,
+ profile=profile,
+ limits=resolved,
+ reason="malformed surrogate code point detected",
+ )
+ format_result = adapt_format(
+ value,
+ query,
+ resolved.format_limits(),
+ format_name=profile.format,
+ )
+ if not format_result.structurally_valid:
+ return IndustrialResult(
+ text=value,
+ applied=False,
+ hard_fail_open=True,
+ profile=profile,
+ limits=resolved,
+ format_result=format_result,
+ reason=format_result.reason or "malformed structured input",
+ )
+ if format_result.applied and len(format_result.text) < len(value):
+ return IndustrialResult(
+ text=format_result.text,
+ applied=True,
+ hard_fail_open=False,
+ profile=profile,
+ limits=resolved,
+ format_result=format_result,
+ reason=format_result.reason,
+ )
+ return IndustrialResult(
+ text=value,
+ applied=False,
+ hard_fail_open=False,
+ profile=profile,
+ limits=resolved,
+ format_result=format_result,
+ reason=format_result.reason,
+ )
diff --git a/plugins/context_engine/tameru/plugin.yaml b/plugins/context_engine/tameru/plugin.yaml
index e6a57880a3b..7c9b82985bc 100644
--- a/plugins/context_engine/tameru/plugin.yaml
+++ b/plugins/context_engine/tameru/plugin.yaml
@@ -1,4 +1,4 @@
name: tameru
display_name: Tameru (貯める)
-description: "Tameru 1.1.1 deterministic query-aware context compaction"
-version: 1.1.1
+description: "Tameru 1.2.0 industrial deterministic context compaction"
+version: 1.2.0
diff --git a/plugins/context_engine/tameru/unicode_profile.py b/plugins/context_engine/tameru/unicode_profile.py
new file mode 100644
index 00000000000..8c274140446
--- /dev/null
+++ b/plugins/context_engine/tameru/unicode_profile.py
@@ -0,0 +1,359 @@
+"""Bounded Unicode profiling for industrial compaction.
+
+The module analyses logical text order only. Matching may use a normalised
+shadow, while callers retain and return original substrings.
+"""
+from __future__ import annotations
+
+import re
+import unicodedata
+from dataclasses import asdict, dataclass
+from typing import Iterator
+
+_BIDI_CONTROLS = frozenset(
+ {
+ "\u061c", # Arabic letter mark
+ "\u200e", # left-to-right mark
+ "\u200f", # right-to-left mark
+ "\u202a", # embeddings / overrides / pop directional format
+ "\u202b",
+ "\u202c",
+ "\u202d",
+ "\u202e",
+ "\u2066", # isolates
+ "\u2067",
+ "\u2068",
+ "\u2069",
+ "\ufeff", # BOM / zero-width no-break space
+ }
+)
+_BIDI_OVERRIDES = frozenset({"\u202d", "\u202e"})
+_ZWJ = "\u200d"
+_ZWNJ = "\u200c"
+_VARIATION_RANGES = ((0xFE00, 0xFE0F), (0xE0100, 0xE01EF))
+_EMOJI_MODIFIER_RANGE = (0x1F3FB, 0x1F3FF)
+_REGIONAL_RANGE = (0x1F1E6, 0x1F1FF)
+_TAG_RANGE = (0xE0020, 0xE007F)
+_VERTICAL_RE = re.compile(
+ r"writing-mode\s*:\s*(?:vertical-(?:rl|lr)|sideways-(?:rl|lr))",
+ re.IGNORECASE,
+)
+_WORD_JOINERS = frozenset("_-./:@+")
+_NO_SPACE_SCRIPTS = frozenset({"han", "kana", "hangul", "thai", "lao", "khmer", "myanmar"})
+
+
+@dataclass(frozen=True)
+class UnicodeProfile:
+ direction: str
+ scripts: frozenset[str]
+ grapheme_count: int
+ bidi_controls: int
+ bidi_overrides: int
+ vertical_hint: bool
+ malformed_surrogates: bool
+
+ def to_dict(self) -> dict[str, object]:
+ data = asdict(self)
+ data["scripts"] = sorted(self.scripts)
+ return data
+
+
+def _in_ranges(codepoint: int, ranges: tuple[tuple[int, int], ...]) -> bool:
+ return any(start <= codepoint <= end for start, end in ranges)
+
+
+def _is_variation_selector(char: str) -> bool:
+ return _in_ranges(ord(char), _VARIATION_RANGES)
+
+
+def _is_emoji_modifier(char: str) -> bool:
+ return _EMOJI_MODIFIER_RANGE[0] <= ord(char) <= _EMOJI_MODIFIER_RANGE[1]
+
+
+def _is_regional_indicator(char: str) -> bool:
+ return _REGIONAL_RANGE[0] <= ord(char) <= _REGIONAL_RANGE[1]
+
+
+def _is_extend(char: str) -> bool:
+ category = unicodedata.category(char)
+ codepoint = ord(char)
+ return (
+ category in {"Mn", "Mc", "Me"}
+ or _is_variation_selector(char)
+ or _is_emoji_modifier(char)
+ or codepoint == 0x20E3
+ or _TAG_RANGE[0] <= codepoint <= _TAG_RANGE[1]
+ )
+
+
+def _is_virama(char: str) -> bool:
+ name = unicodedata.name(char, "")
+ return "VIRAMA" in name or "HALANT" in name
+
+
+def iter_graphemes(text: str) -> Iterator[str]:
+ """Yield deterministic approximate extended grapheme clusters.
+
+ This is a documented UAX #29 tailoring suitable for stdlib-only matching;
+ it is intentionally conservative around combining and join sequences.
+ """
+ current = ""
+ regional_count = 0
+ for char in str(text or ""):
+ if not current:
+ current = char
+ regional_count = 1 if _is_regional_indicator(char) else 0
+ continue
+ previous = current[-1]
+ append = (
+ _is_extend(char)
+ or char in {_ZWJ, _ZWNJ}
+ or previous in {_ZWJ, _ZWNJ}
+ or (_is_virama(previous) and unicodedata.category(char).startswith("L"))
+ or (
+ _is_regional_indicator(char)
+ and _is_regional_indicator(previous)
+ and regional_count % 2 == 1
+ )
+ )
+ if append:
+ current += char
+ if _is_regional_indicator(char):
+ regional_count += 1
+ continue
+ yield current
+ current = char
+ regional_count = 1 if _is_regional_indicator(char) else 0
+ if current:
+ yield current
+
+
+def graphemes(text: str) -> list[str]:
+ return list(iter_graphemes(text))
+
+
+def matching_shadow(text: str) -> str:
+ """Return case-folded NFKC text with presentation-only bidi controls removed."""
+ normalised = unicodedata.normalize("NFKC", str(text or ""))
+ return "".join(char for char in normalised if char not in _BIDI_CONTROLS).casefold()
+
+
+def unicode_safety_counts(text: str) -> tuple[int, int, bool]:
+ """Return bidi controls, overrides, and malformed-surrogate presence."""
+ value = str(text or "")
+ if value.isascii():
+ return 0, 0, False
+ controls = 0
+ overrides = 0
+ malformed = False
+ for char in value:
+ malformed = malformed or unicodedata.category(char) == "Cs"
+ if char in _BIDI_CONTROLS:
+ controls += 1
+ overrides += int(char in _BIDI_OVERRIDES)
+ return controls, overrides, malformed
+
+
+def script_of(char: str) -> str | None:
+ """Return a stable script family for a representative character."""
+ if not char:
+ return None
+ codepoint = ord(char)
+ ranges = (
+ ("hebrew", 0x0590, 0x05FF),
+ ("arabic", 0x0600, 0x08FF),
+ ("devanagari", 0x0900, 0x097F),
+ ("bengali", 0x0980, 0x09FF),
+ ("gurmukhi", 0x0A00, 0x0A7F),
+ ("gujarati", 0x0A80, 0x0AFF),
+ ("odia", 0x0B00, 0x0B7F),
+ ("tamil", 0x0B80, 0x0BFF),
+ ("telugu", 0x0C00, 0x0C7F),
+ ("kannada", 0x0C80, 0x0CFF),
+ ("malayalam", 0x0D00, 0x0D7F),
+ ("sinhala", 0x0D80, 0x0DFF),
+ ("thai", 0x0E00, 0x0E7F),
+ ("lao", 0x0E80, 0x0EFF),
+ ("tibetan", 0x0F00, 0x0FFF),
+ ("myanmar", 0x1000, 0x109F),
+ ("georgian", 0x10A0, 0x10FF),
+ ("ethiopic", 0x1200, 0x137F),
+ ("khmer", 0x1780, 0x17FF),
+ ("mongolian", 0x1800, 0x18AF),
+ ("han", 0x3400, 0x9FFF),
+ ("kana", 0x3040, 0x30FF),
+ ("hangul", 0xAC00, 0xD7AF),
+ ("armenian", 0x0530, 0x058F),
+ ("greek", 0x0370, 0x03FF),
+ ("cyrillic", 0x0400, 0x052F),
+ )
+ for name, start, end in ranges:
+ if start <= codepoint <= end:
+ return name
+ unicode_name = unicodedata.name(char, "")
+ for name, marker in (
+ ("latin", "LATIN"),
+ ("greek", "GREEK"),
+ ("cyrillic", "CYRILLIC"),
+ ("arabic", "ARABIC"),
+ ("hebrew", "HEBREW"),
+ ):
+ if marker in unicode_name:
+ return name
+ return "other" if unicodedata.category(char).startswith("L") else None
+
+
+def _representative(cluster: str) -> str:
+ for char in cluster:
+ if unicodedata.category(char)[0] in {"L", "N"}:
+ return char
+ return cluster[0] if cluster else ""
+
+
+def _flush_run(run: list[str], units: list[str]) -> None:
+ if not run:
+ return
+ representative = _representative(run[0])
+ script = script_of(representative)
+ joined = "".join(run)
+ if script in _NO_SPACE_SCRIPTS:
+ if len(joined) <= 64:
+ units.append(joined)
+ if len(run) == 1 and run[0].strip():
+ units.append(run[0])
+ for width in (2, 3, 4):
+ if len(run) < width:
+ continue
+ units.extend("".join(run[index : index + width]) for index in range(len(run) - width + 1))
+ elif joined:
+ units.append(joined)
+ run.clear()
+
+
+def search_units(text: str) -> list[str]:
+ """Return ordered, deduplicated Unicode-aware units for query matching."""
+ shadow = matching_shadow(text)
+ units: list[str] = []
+ run: list[str] = []
+ for cluster in iter_graphemes(shadow):
+ representative = _representative(cluster)
+ category = unicodedata.category(representative) if representative else ""
+ if category[:1] in {"L", "N", "M"} or all(char in _WORD_JOINERS for char in cluster):
+ run.append(cluster)
+ else:
+ _flush_run(run, units)
+ _flush_run(run, units)
+ seen: set[str] = set()
+ ordered: list[str] = []
+ for unit in units:
+ cleaned = unit.strip("_-./:@+")
+ value = unit if cleaned else ""
+ if value and value not in seen:
+ seen.add(value)
+ ordered.append(value)
+ return ordered
+
+
+def token_units(text: str) -> list[str]:
+ """Return non-overlapping logical units for deterministic token estimates."""
+ units: list[str] = []
+ run: list[str] = []
+ run_script: str | None = None
+
+ def flush() -> None:
+ nonlocal run_script
+ if run:
+ units.append("".join(run))
+ run.clear()
+ run_script = None
+
+ for cluster in iter_graphemes(matching_shadow(text)):
+ if not cluster or cluster.isspace():
+ flush()
+ continue
+ representative = _representative(cluster)
+ category = unicodedata.category(representative) if representative else ""
+ script = script_of(representative)
+ if category[:1] in {"L", "N", "M"}:
+ if script in _NO_SPACE_SCRIPTS:
+ flush()
+ units.append(cluster)
+ continue
+ if run and script and run_script and script != run_script:
+ flush()
+ run.append(cluster)
+ run_script = run_script or script
+ continue
+ if all(char in _WORD_JOINERS for char in cluster) and run:
+ run.append(cluster)
+ continue
+ flush()
+ if any(unicodedata.category(char) == "So" for char in cluster):
+ units.append(cluster)
+ flush()
+ return units
+
+
+def _looks_vertical_ocr(text: str) -> bool:
+ lines = [line.strip() for line in str(text or "").splitlines() if line.strip()]
+ if len(lines) < 6:
+ return False
+ short = sum(1 for line in lines[:128] if len(graphemes(line)) <= 2)
+ return short / min(len(lines), 128) >= 0.8
+
+
+def profile_text(text: str) -> UnicodeProfile:
+ value = str(text or "")
+ if value.isascii():
+ has_latin = any(char.isalpha() for char in value)
+ lines = [line.strip() for line in value.splitlines() if line.strip()][:128]
+ vertical = bool(_VERTICAL_RE.search(value)) or (
+ len(lines) >= 6
+ and sum(len(line) <= 2 for line in lines) / len(lines) >= 0.8
+ )
+ return UnicodeProfile(
+ direction="ltr" if has_latin else "neutral",
+ scripts=frozenset({"latin"}) if has_latin else frozenset(),
+ grapheme_count=len(value),
+ bidi_controls=0,
+ bidi_overrides=0,
+ vertical_hint=vertical,
+ malformed_surrogates=False,
+ )
+ scripts: set[str] = set()
+ ltr = 0
+ rtl = 0
+ controls = 0
+ overrides = 0
+ malformed = False
+ for char in value:
+ category = unicodedata.category(char)
+ malformed = malformed or category == "Cs"
+ if char in _BIDI_CONTROLS:
+ controls += 1
+ overrides += int(char in _BIDI_OVERRIDES)
+ bidi = unicodedata.bidirectional(char)
+ if bidi == "L":
+ ltr += 1
+ elif bidi in {"R", "AL"}:
+ rtl += 1
+ script = script_of(char)
+ if script:
+ scripts.add(script)
+ if ltr and rtl:
+ direction = "mixed"
+ elif rtl:
+ direction = "rtl"
+ elif ltr:
+ direction = "ltr"
+ else:
+ direction = "neutral"
+ return UnicodeProfile(
+ direction=direction,
+ scripts=frozenset(scripts),
+ grapheme_count=sum(1 for _ in iter_graphemes(value)),
+ bidi_controls=controls,
+ bidi_overrides=overrides,
+ vertical_hint=bool(_VERTICAL_RE.search(value)) or _looks_vertical_ocr(value),
+ malformed_surrogates=malformed,
+ )