@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +149 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +776 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +150 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3612 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +129 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +72 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +277 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +423 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +397 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +58739 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Optional tree-sitter backend for structure_map.
|
|
3
|
+
|
|
4
|
+
This module is imported LAZILY by ``structure_map.summarize_code_source`` only
|
|
5
|
+
when ``is_available()`` is true and the file's language is in the supported
|
|
6
|
+
set. It never imports ``tree_sitter`` at module load time, so importing
|
|
7
|
+
``structure_map`` (and therefore the hot read-cache path) never requires
|
|
8
|
+
tree-sitter to be installed.
|
|
9
|
+
|
|
10
|
+
Two tree-sitter packaging eras are supported:
|
|
11
|
+
* ``tree_sitter_languages`` -- the older bundled-grammars package.
|
|
12
|
+
* ``tree_sitter`` + ``tree_sitter_<lang>`` -- the 0.22+ per-language
|
|
13
|
+
grammar packages with the new ``Language`` / ``Parser`` API.
|
|
14
|
+
|
|
15
|
+
Both paths are probed at runtime; whichever is present wins. When neither is
|
|
16
|
+
present, ``is_available()`` returns False and ``summarize_code_source`` falls
|
|
17
|
+
through to the existing ast/regex/digest path unchanged.
|
|
18
|
+
|
|
19
|
+
This module is stdlib-only at import time (no top-level tree_sitter import),
|
|
20
|
+
uses no subprocess, no network, and no resident state. It produces
|
|
21
|
+
``StructureMapResult`` instances with the same keys as the stdlib path so
|
|
22
|
+
``read_cache.py`` consumes them unchanged.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import hashlib
|
|
28
|
+
import os
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import List, Optional, Tuple
|
|
31
|
+
|
|
32
|
+
# Re-use the canonical result shape and helpers so the output is byte-for-byte
|
|
33
|
+
# compatible with the stdlib path. Imported at module load (these are stdlib
|
|
34
|
+
# dataclasses / pure functions, NOT tree-sitter).
|
|
35
|
+
from structure_map import (
|
|
36
|
+
MAX_REPLACEMENT_CHARS,
|
|
37
|
+
MAX_SKELETON_CLASSES,
|
|
38
|
+
MAX_SKELETON_METHODS_PER_CLASS,
|
|
39
|
+
MAX_SKELETON_TOP_LEVEL_FUNCTIONS,
|
|
40
|
+
StructureMapResult,
|
|
41
|
+
detect_structure_language,
|
|
42
|
+
estimate_tokens,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
# ---------------------------------------------------------------------------
|
|
46
|
+
# Configuration
|
|
47
|
+
# ---------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
FLAG_ENV = "TOKEN_OPTIMIZER_STRUCTURE_MAP_TREESITTER"
|
|
50
|
+
|
|
51
|
+
# Suffix -> tree-sitter language name. These are the languages the backend
|
|
52
|
+
# can produce real structure for (over and above the stdlib Python/JS-TS path).
|
|
53
|
+
# The stdlib path remains the default for .py / .js / .ts; tree-sitter is
|
|
54
|
+
# additive for the rest.
|
|
55
|
+
SUFFIX_TO_TS_LANG = {
|
|
56
|
+
".go": "go",
|
|
57
|
+
".rs": "rust",
|
|
58
|
+
".c": "c",
|
|
59
|
+
".h": "c",
|
|
60
|
+
".cpp": "cpp",
|
|
61
|
+
".cc": "cpp",
|
|
62
|
+
".cxx": "cpp",
|
|
63
|
+
".hpp": "cpp",
|
|
64
|
+
".hh": "cpp",
|
|
65
|
+
".java": "java",
|
|
66
|
+
".kt": "kotlin",
|
|
67
|
+
".kts": "kotlin",
|
|
68
|
+
".scala": "scala",
|
|
69
|
+
".rb": "ruby",
|
|
70
|
+
".php": "php",
|
|
71
|
+
".swift": "swift",
|
|
72
|
+
".lua": "lua",
|
|
73
|
+
".sh": "bash",
|
|
74
|
+
".bash": "bash",
|
|
75
|
+
".cs": "c_sharp",
|
|
76
|
+
".dart": "dart",
|
|
77
|
+
".elixir": "elixir",
|
|
78
|
+
".ex": "elixir",
|
|
79
|
+
".erl": "erlang",
|
|
80
|
+
".hrl": "erlang",
|
|
81
|
+
".clj": "clojure",
|
|
82
|
+
".cljs": "clojure",
|
|
83
|
+
".cljc": "clojure",
|
|
84
|
+
".edn": "clojure",
|
|
85
|
+
".zig": "zig",
|
|
86
|
+
".nim": "nim",
|
|
87
|
+
".sql": "sql",
|
|
88
|
+
".graphql": "graphql",
|
|
89
|
+
".proto": "proto",
|
|
90
|
+
".hcl": "hcl",
|
|
91
|
+
".tf": "hcl",
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
# Node types that represent a function/method definition, per language family.
|
|
95
|
+
# We keep this conservative: only unambiguous definition nodes.
|
|
96
|
+
_FUNCTION_NODE_TYPES = {
|
|
97
|
+
"function_definition", # Python, Go, Ruby, Bash, PHP, Lua, Zig, Nim
|
|
98
|
+
"function_declaration", # C, Java, Kotlin, Swift, Dart, JS/TS
|
|
99
|
+
"function_item", # Rust
|
|
100
|
+
"method_definition", # Ruby, PHP, Python (class methods)
|
|
101
|
+
"method_declaration", # Java, Kotlin, Swift, Dart
|
|
102
|
+
"constructor_declaration", # Java, C#, Dart
|
|
103
|
+
"function_signature", # C++
|
|
104
|
+
"function_declarator", # C++
|
|
105
|
+
"func_literal", # Go (anonymous)
|
|
106
|
+
"arrow_function", # JS/TS
|
|
107
|
+
"function_expression", # JS/TS
|
|
108
|
+
"generator_function_declaration", # JS/TS
|
|
109
|
+
"function_specification", # Ada
|
|
110
|
+
"proc_specification", # Ada
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
_CLASS_NODE_TYPES = {
|
|
114
|
+
"class_definition", # Python, Ruby, PHP, Lua
|
|
115
|
+
"class_declaration", # Java, Kotlin, Swift, Dart, JS/TS, C#
|
|
116
|
+
"class_specifier", # C++
|
|
117
|
+
"struct_specifier", # C, C++
|
|
118
|
+
"struct_item", # Rust
|
|
119
|
+
"union_specifier", # C, C++
|
|
120
|
+
"enum_specifier", # C, C++
|
|
121
|
+
"enum_item", # Rust
|
|
122
|
+
"interface_declaration", # Java, Kotlin, Swift, Dart, JS/TS, C#
|
|
123
|
+
"interface_definition", # PHP, Ruby
|
|
124
|
+
"trait_declaration", # Kotlin, PHP, Dart
|
|
125
|
+
"impl_item", # Rust
|
|
126
|
+
"object", # Scala
|
|
127
|
+
"record_declaration", # Kotlin data class, Swift
|
|
128
|
+
"extension_declaration", # Swift
|
|
129
|
+
"package_declaration", # Java, Kotlin
|
|
130
|
+
# namespace_declaration is intentionally NOT a class type: it is a CONTAINER
|
|
131
|
+
# of classes (see _NAMESPACE_CONTAINER_NODE_TYPES). Treating it as a leaf
|
|
132
|
+
# class would drop every class nested inside a C#/C++ namespace (fix-5b).
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
# Brace-body languages nest a class's members under an intermediate body node,
|
|
136
|
+
# so methods are GRANDCHILDREN of the class node, not direct children. The
|
|
137
|
+
# method collector descends exactly one such body level (fix-5a).
|
|
138
|
+
_CLASS_BODY_NODE_TYPES = {
|
|
139
|
+
"class_body", # Java, Kotlin, C#, Groovy
|
|
140
|
+
"declaration_list", # C++, C#, namespaces
|
|
141
|
+
"field_declaration_list", # C / C++ struct / union
|
|
142
|
+
"enum_body", # Java, C#
|
|
143
|
+
"interface_body", # Java, C#
|
|
144
|
+
"struct_body", # some grammars
|
|
145
|
+
"enum_class_body", # Java enum constants with bodies
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
# Namespace containers hold classes/functions (directly or under a body node)
|
|
149
|
+
# rather than being definitions themselves. The walker descends THROUGH them
|
|
150
|
+
# after emitting a compact label, so classes inside a C#/C++ namespace survive.
|
|
151
|
+
_NAMESPACE_CONTAINER_NODE_TYPES = {
|
|
152
|
+
"namespace_declaration", # C#, C++
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
_IMPORT_NODE_TYPES = {
|
|
156
|
+
"import_statement", # Python, Go, Java, Kotlin
|
|
157
|
+
"import_declaration", # JS/TS, Java, C, C++, Swift, Dart
|
|
158
|
+
"import_from_statement", # Python
|
|
159
|
+
"import_spec", # Go
|
|
160
|
+
"use_declaration", # Rust
|
|
161
|
+
"use_statement", # Zig, Clojure
|
|
162
|
+
"require_statement", # Ruby, Lua
|
|
163
|
+
"include_directive", # C, C++
|
|
164
|
+
"package_clause", # Go
|
|
165
|
+
"extern_import", # Zig
|
|
166
|
+
"using_directive", # C# (the actual `using` import node)
|
|
167
|
+
# NOTE: namespace_declaration is deliberately NOT here. It also appears in
|
|
168
|
+
# _CLASS_NODE_TYPES (C#/C++ namespaces), and imports are matched first; if
|
|
169
|
+
# it were treated as an import the walker would `return` without descending
|
|
170
|
+
# and every C#/C++ namespace (and the classes inside it) would be dropped
|
|
171
|
+
# (fix-5b). C#'s import is `using_directive`, not `namespace_declaration`.
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
# Per-language import-node text prefixes to extract a compact import label.
|
|
175
|
+
_IMPORT_TEXT_PREFIXES = {
|
|
176
|
+
"import_statement": "import",
|
|
177
|
+
"import_from_statement": "from",
|
|
178
|
+
"import_declaration": "import",
|
|
179
|
+
"import_spec": "import",
|
|
180
|
+
"use_declaration": "use",
|
|
181
|
+
"use_statement": "use",
|
|
182
|
+
"require_statement": "require",
|
|
183
|
+
"include_directive": "include",
|
|
184
|
+
"package_clause": "package",
|
|
185
|
+
"extern_import": "extern",
|
|
186
|
+
"using_directive": "using",
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
_MAX_IMPORTS = 8
|
|
190
|
+
_MAX_CLASSES = MAX_SKELETON_CLASSES
|
|
191
|
+
_MAX_METHODS_PER_CLASS = MAX_SKELETON_METHODS_PER_CLASS
|
|
192
|
+
_MAX_FUNCTIONS = MAX_SKELETON_TOP_LEVEL_FUNCTIONS
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# ---------------------------------------------------------------------------
|
|
196
|
+
# Availability probe (lazy, cached on first call)
|
|
197
|
+
# ---------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
_avail_cache: Optional[bool] = None
|
|
200
|
+
_avail_reason: str = ""
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _flag_enabled() -> bool:
|
|
204
|
+
"""The backend is opt-in: the env flag must be set to a truthy value
|
|
205
|
+
(default off) so the hot path never attempts tree-sitter unless a user
|
|
206
|
+
explicitly enables it."""
|
|
207
|
+
raw = os.environ.get(FLAG_ENV, "").strip().lower()
|
|
208
|
+
return raw in ("1", "true", "yes", "on")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _probe_runtime() -> Tuple[bool, str]:
|
|
212
|
+
"""Probe for a usable tree-sitter runtime + at least one grammar.
|
|
213
|
+
|
|
214
|
+
Returns (ok, reason). Tries ``tree_sitter_languages`` first (bundled),
|
|
215
|
+
then the per-language ``tree_sitter_<lang>`` packages. Never raises.
|
|
216
|
+
"""
|
|
217
|
+
try:
|
|
218
|
+
import tree_sitter # noqa: F401
|
|
219
|
+
except Exception:
|
|
220
|
+
return False, "tree_sitter package not installed"
|
|
221
|
+
# Try the bundled-grammars package first.
|
|
222
|
+
try:
|
|
223
|
+
import tree_sitter_languages # noqa: F401
|
|
224
|
+
return True, "tree_sitter_languages"
|
|
225
|
+
except Exception:
|
|
226
|
+
pass
|
|
227
|
+
# Fall back to any per-language grammar package.
|
|
228
|
+
for lang in SUFFIX_TO_TS_LANG.values():
|
|
229
|
+
pkg = f"tree_sitter_{lang}"
|
|
230
|
+
try:
|
|
231
|
+
__import__(pkg)
|
|
232
|
+
return True, f"per-language:{pkg}"
|
|
233
|
+
except Exception:
|
|
234
|
+
continue
|
|
235
|
+
return False, "no grammar packages installed"
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def is_available() -> bool:
|
|
239
|
+
"""Return True when the tree-sitter backend is enabled and usable.
|
|
240
|
+
|
|
241
|
+
Cached after the first call. The flag default-off means the hot path
|
|
242
|
+
never attempts tree-sitter unless opted in via ``TOKEN_OPTIMIZER_
|
|
243
|
+
STRUCTURE_MAP_TREESITTER=1``.
|
|
244
|
+
"""
|
|
245
|
+
global _avail_cache, _avail_reason
|
|
246
|
+
if _avail_cache is not None:
|
|
247
|
+
return _avail_cache
|
|
248
|
+
if not _flag_enabled():
|
|
249
|
+
_avail_cache = False
|
|
250
|
+
_avail_reason = "flag disabled (default off)"
|
|
251
|
+
return False
|
|
252
|
+
ok, reason = _probe_runtime()
|
|
253
|
+
_avail_cache = ok
|
|
254
|
+
_avail_reason = reason
|
|
255
|
+
return ok
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def supported_suffixes() -> Tuple[str, ...]:
|
|
259
|
+
"""Return the file suffixes the backend can produce real structure for."""
|
|
260
|
+
return tuple(SUFFIX_TO_TS_LANG.keys())
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# ---------------------------------------------------------------------------
|
|
264
|
+
# Grammar / parser construction (lazy, per-language)
|
|
265
|
+
# ---------------------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
def _load_language(lang: str) -> Optional[object]:
|
|
268
|
+
"""Load a tree-sitter Language for ``lang`` from whichever packaging era
|
|
269
|
+
is present. Returns None on any failure (caller falls through to digest)."""
|
|
270
|
+
# Era 1: tree_sitter_languages (bundled). Older API: tsl.get_language(lang).
|
|
271
|
+
try:
|
|
272
|
+
import tree_sitter_languages as tsl
|
|
273
|
+
get_lang = getattr(tsl, "get_language", None)
|
|
274
|
+
if get_lang is not None:
|
|
275
|
+
try:
|
|
276
|
+
return get_lang(lang)
|
|
277
|
+
except Exception:
|
|
278
|
+
pass
|
|
279
|
+
except Exception:
|
|
280
|
+
pass
|
|
281
|
+
# Era 2: per-language package tree_sitter_<lang>.
|
|
282
|
+
pkg = f"tree_sitter_{lang}"
|
|
283
|
+
try:
|
|
284
|
+
mod = __import__(pkg)
|
|
285
|
+
except Exception:
|
|
286
|
+
return None
|
|
287
|
+
# 0.22+ API: mod.language() returns a Language capsule; Language(mod.language())
|
|
288
|
+
# for the bindings-to-capsule bridge.
|
|
289
|
+
try:
|
|
290
|
+
from tree_sitter import Language
|
|
291
|
+
lang_fn = getattr(mod, "language", None)
|
|
292
|
+
if lang_fn is not None:
|
|
293
|
+
try:
|
|
294
|
+
return Language(lang_fn())
|
|
295
|
+
except Exception:
|
|
296
|
+
# Some bindings return a Language directly from language().
|
|
297
|
+
candidate = lang_fn()
|
|
298
|
+
if isinstance(candidate, Language):
|
|
299
|
+
return candidate
|
|
300
|
+
except Exception:
|
|
301
|
+
pass
|
|
302
|
+
return None
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _make_parser(language: object) -> Optional[object]:
|
|
306
|
+
"""Construct a Parser bound to ``language``. Returns None on failure."""
|
|
307
|
+
try:
|
|
308
|
+
from tree_sitter import Parser
|
|
309
|
+
# 0.22+ API: Parser(language)
|
|
310
|
+
try:
|
|
311
|
+
return Parser(language)
|
|
312
|
+
except Exception:
|
|
313
|
+
pass
|
|
314
|
+
# 0.20-era API: Parser(); parser.set_language(language)
|
|
315
|
+
try:
|
|
316
|
+
parser = Parser()
|
|
317
|
+
set_lang = getattr(parser, "set_language", None)
|
|
318
|
+
if set_lang is not None:
|
|
319
|
+
set_lang(language)
|
|
320
|
+
return parser
|
|
321
|
+
except Exception:
|
|
322
|
+
pass
|
|
323
|
+
except Exception:
|
|
324
|
+
pass
|
|
325
|
+
return None
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
# ---------------------------------------------------------------------------
|
|
329
|
+
# Tree walking
|
|
330
|
+
# ---------------------------------------------------------------------------
|
|
331
|
+
|
|
332
|
+
def _node_text(node: object, source_bytes: bytes) -> str:
|
|
333
|
+
try:
|
|
334
|
+
start = node.start_byte
|
|
335
|
+
end = node.end_byte
|
|
336
|
+
return source_bytes[start:end].decode("utf-8", errors="replace")
|
|
337
|
+
except Exception:
|
|
338
|
+
return ""
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _node_name(node: object, source_bytes: bytes) -> str:
|
|
342
|
+
"""Extract a definition's name from a tree-sitter node.
|
|
343
|
+
|
|
344
|
+
Most grammar node types carry the name as the first named child of type
|
|
345
|
+
``identifier`` / ``type_identifier`` / ``property_identifier``. Fall back
|
|
346
|
+
to the first line of the node text, truncated.
|
|
347
|
+
"""
|
|
348
|
+
try:
|
|
349
|
+
for child in node.children:
|
|
350
|
+
if child.type in ("identifier", "type_identifier", "property_identifier",
|
|
351
|
+
"field_identifier", "type_name", "name"):
|
|
352
|
+
return _node_text(child, source_bytes)
|
|
353
|
+
except Exception:
|
|
354
|
+
pass
|
|
355
|
+
text = _node_text(node, source_bytes)
|
|
356
|
+
first_line = text.split("\n", 1)[0].strip()
|
|
357
|
+
return first_line[:80] if first_line else "<anonymous>"
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _node_lineno(node: object) -> int:
|
|
361
|
+
try:
|
|
362
|
+
return int(node.start_point[0]) + 1
|
|
363
|
+
except Exception:
|
|
364
|
+
return 0
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _is_definition(node: object, kind_set: frozenset) -> bool:
|
|
368
|
+
try:
|
|
369
|
+
return node.type in kind_set
|
|
370
|
+
except Exception:
|
|
371
|
+
return False
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _walk_tree(
|
|
375
|
+
root: object,
|
|
376
|
+
source_bytes: bytes,
|
|
377
|
+
) -> Tuple[List[str], List[dict], List[dict]]:
|
|
378
|
+
"""Walk the tree-sitter tree collecting imports, classes, functions.
|
|
379
|
+
|
|
380
|
+
Returns (imports, classes, functions) where each class/function is a dict
|
|
381
|
+
with keys: name, signature, lineno, methods (classes only). Methods are
|
|
382
|
+
collected by descending one level into a class body.
|
|
383
|
+
"""
|
|
384
|
+
imports: List[str] = []
|
|
385
|
+
classes: List[dict] = []
|
|
386
|
+
functions: List[dict] = []
|
|
387
|
+
|
|
388
|
+
def _shorten_import(text: str) -> str:
|
|
389
|
+
first_line = text.split("\n", 1)[0].strip()
|
|
390
|
+
return first_line[:120] if first_line else ""
|
|
391
|
+
|
|
392
|
+
def _method_entry(node: object) -> dict:
|
|
393
|
+
m_name = _node_name(node, source_bytes)
|
|
394
|
+
return {
|
|
395
|
+
"name": m_name,
|
|
396
|
+
"signature": _short_signature(m_name, _node_text(node, source_bytes)),
|
|
397
|
+
"lineno": _node_lineno(node),
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
def _collect_methods(class_node: object) -> List[dict]:
|
|
401
|
+
"""Collect method definitions of a class, handling both grammar shapes:
|
|
402
|
+
direct children (Python-family) AND grandchildren nested under an
|
|
403
|
+
intermediate body node (Java/C#/C++/Kotlin/Swift brace bodies, fix-5a).
|
|
404
|
+
"""
|
|
405
|
+
methods: List[dict] = []
|
|
406
|
+
try:
|
|
407
|
+
for child in class_node.children:
|
|
408
|
+
if _is_definition(child, _FUNCTION_NODE_TYPES):
|
|
409
|
+
methods.append(_method_entry(child))
|
|
410
|
+
elif child.type in _CLASS_BODY_NODE_TYPES:
|
|
411
|
+
for gchild in child.children:
|
|
412
|
+
if _is_definition(gchild, _FUNCTION_NODE_TYPES):
|
|
413
|
+
methods.append(_method_entry(gchild))
|
|
414
|
+
except Exception:
|
|
415
|
+
pass
|
|
416
|
+
return methods
|
|
417
|
+
|
|
418
|
+
def _visit(node: object) -> None:
|
|
419
|
+
try:
|
|
420
|
+
ntype = node.type
|
|
421
|
+
except Exception:
|
|
422
|
+
ntype = ""
|
|
423
|
+
if ntype in _NAMESPACE_CONTAINER_NODE_TYPES:
|
|
424
|
+
# A namespace is a container, not a definition: emit a compact label
|
|
425
|
+
# then DESCEND so the classes/functions inside it are not dropped.
|
|
426
|
+
name = _node_name(node, source_bytes).split("{", 1)[0].strip()
|
|
427
|
+
if name:
|
|
428
|
+
imports.append(f"namespace {name}")
|
|
429
|
+
try:
|
|
430
|
+
for child in node.children:
|
|
431
|
+
_visit(child)
|
|
432
|
+
except Exception:
|
|
433
|
+
pass
|
|
434
|
+
return
|
|
435
|
+
if ntype in _IMPORT_NODE_TYPES:
|
|
436
|
+
label = _IMPORT_TEXT_PREFIXES.get(ntype, ntype)
|
|
437
|
+
text = _shorten_import(_node_text(node, source_bytes))
|
|
438
|
+
if text:
|
|
439
|
+
imports.append(f"{label} {text}" if not text.startswith(label) else text)
|
|
440
|
+
# Don't descend into imports.
|
|
441
|
+
return
|
|
442
|
+
if ntype in _CLASS_NODE_TYPES:
|
|
443
|
+
name = _node_name(node, source_bytes)
|
|
444
|
+
lineno = _node_lineno(node)
|
|
445
|
+
methods = _collect_methods(node)
|
|
446
|
+
classes.append({
|
|
447
|
+
"name": name,
|
|
448
|
+
"signature": f"class {name}",
|
|
449
|
+
"lineno": lineno,
|
|
450
|
+
"methods": methods,
|
|
451
|
+
})
|
|
452
|
+
# Do NOT descend further (no nested classes for now).
|
|
453
|
+
return
|
|
454
|
+
if ntype in _FUNCTION_NODE_TYPES:
|
|
455
|
+
name = _node_name(node, source_bytes)
|
|
456
|
+
lineno = _node_lineno(node)
|
|
457
|
+
sig = _short_signature(name, _node_text(node, source_bytes))
|
|
458
|
+
functions.append({"name": name, "signature": sig, "lineno": lineno})
|
|
459
|
+
return
|
|
460
|
+
# Recurse into unnamed children to find definitions at any depth.
|
|
461
|
+
try:
|
|
462
|
+
for child in node.children:
|
|
463
|
+
_visit(child)
|
|
464
|
+
except Exception:
|
|
465
|
+
pass
|
|
466
|
+
|
|
467
|
+
try:
|
|
468
|
+
_visit(root)
|
|
469
|
+
except Exception:
|
|
470
|
+
pass
|
|
471
|
+
return imports, classes, functions
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _short_signature(name: str, node_text: str) -> str:
|
|
475
|
+
"""Build a compact one-line signature from a definition node's text."""
|
|
476
|
+
first_line = node_text.split("\n", 1)[0].strip()
|
|
477
|
+
if not first_line:
|
|
478
|
+
return name
|
|
479
|
+
# Truncate at the first ``{`` or ``:`` to drop the body opener.
|
|
480
|
+
for sep in ("{", ":", "=>"):
|
|
481
|
+
idx = first_line.find(sep)
|
|
482
|
+
if idx > 0:
|
|
483
|
+
first_line = first_line[:idx].rstrip()
|
|
484
|
+
if len(first_line) > 120:
|
|
485
|
+
first_line = first_line[:117] + "..."
|
|
486
|
+
return first_line
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
# ---------------------------------------------------------------------------
|
|
490
|
+
# Rendering (mirrors structure_map._render_skeleton shape)
|
|
491
|
+
# ---------------------------------------------------------------------------
|
|
492
|
+
|
|
493
|
+
def _render_skeleton(
|
|
494
|
+
*,
|
|
495
|
+
language: str,
|
|
496
|
+
line_count: int,
|
|
497
|
+
imports: List[str],
|
|
498
|
+
classes: List[dict],
|
|
499
|
+
functions: List[dict],
|
|
500
|
+
) -> str:
|
|
501
|
+
sections: List[str] = [f"{language} skeleton", f"lines: {line_count}"]
|
|
502
|
+
|
|
503
|
+
if imports:
|
|
504
|
+
sections.append(f"imports ({len(imports)}):")
|
|
505
|
+
for item in imports[:_MAX_IMPORTS]:
|
|
506
|
+
sections.append(f" - {item}")
|
|
507
|
+
|
|
508
|
+
if classes:
|
|
509
|
+
sections.append(f"classes ({len(classes)}):")
|
|
510
|
+
for cls in classes[:_MAX_CLASSES]:
|
|
511
|
+
sections.append(f" - {cls['signature']} @ L{cls['lineno']}")
|
|
512
|
+
if cls["methods"]:
|
|
513
|
+
sections.append(" methods:")
|
|
514
|
+
for method in cls["methods"][:_MAX_METHODS_PER_CLASS]:
|
|
515
|
+
sections.append(f" - {method['signature']} @ L{method['lineno']}")
|
|
516
|
+
|
|
517
|
+
if functions:
|
|
518
|
+
sections.append(f"functions ({len(functions)}):")
|
|
519
|
+
for func in functions[:_MAX_FUNCTIONS]:
|
|
520
|
+
sections.append(f" - {func['signature']} @ L{func['lineno']}")
|
|
521
|
+
|
|
522
|
+
return "\n".join(section for section in sections if section)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _fingerprint(
|
|
526
|
+
*,
|
|
527
|
+
path: str,
|
|
528
|
+
replacement_type: str,
|
|
529
|
+
rendered: str,
|
|
530
|
+
line_count: int,
|
|
531
|
+
file_size_bytes: Optional[int],
|
|
532
|
+
) -> str:
|
|
533
|
+
payload = "\n".join(
|
|
534
|
+
[
|
|
535
|
+
"structure-map-ts-v1",
|
|
536
|
+
replacement_type,
|
|
537
|
+
path,
|
|
538
|
+
str(line_count),
|
|
539
|
+
str(file_size_bytes or 0),
|
|
540
|
+
rendered,
|
|
541
|
+
]
|
|
542
|
+
)
|
|
543
|
+
return hashlib.sha256(payload.encode("utf-8", errors="ignore")).hexdigest()
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
# ---------------------------------------------------------------------------
|
|
547
|
+
# Public entry point
|
|
548
|
+
# ---------------------------------------------------------------------------
|
|
549
|
+
|
|
550
|
+
def summarize_with_tree_sitter(
|
|
551
|
+
source: str,
|
|
552
|
+
file_path: str,
|
|
553
|
+
*,
|
|
554
|
+
file_tokens_est: Optional[int] = None,
|
|
555
|
+
file_size_bytes: Optional[int] = None,
|
|
556
|
+
) -> Optional[StructureMapResult]:
|
|
557
|
+
"""Summarize ``source`` using tree-sitter; return a ``StructureMapResult``
|
|
558
|
+
or ``None`` when the backend cannot handle the file (caller falls through
|
|
559
|
+
to the stdlib digest path). Never raises.
|
|
560
|
+
|
|
561
|
+
The result has the same shape as the stdlib path: ``replacement_type`` is
|
|
562
|
+
``"skeleton"`` when structure was extracted (capped at
|
|
563
|
+
``MAX_REPLACEMENT_CHARS["skeleton"]``), ``parse_ok=True``, and ``eligible``
|
|
564
|
+
consistent with the existing gate (``replacement_type != "digest"``).
|
|
565
|
+
"""
|
|
566
|
+
if not is_available():
|
|
567
|
+
return None
|
|
568
|
+
suffix = Path(file_path).suffix.lower()
|
|
569
|
+
lang_name = SUFFIX_TO_TS_LANG.get(suffix)
|
|
570
|
+
if lang_name is None:
|
|
571
|
+
return None
|
|
572
|
+
if file_size_bytes is None:
|
|
573
|
+
file_size_bytes = len(source.encode("utf-8", errors="ignore"))
|
|
574
|
+
if file_tokens_est is None:
|
|
575
|
+
file_tokens_est = estimate_tokens(source)
|
|
576
|
+
# Guard against oversized inputs (mirrors MAX_AST_BYTES).
|
|
577
|
+
if file_size_bytes > 800 * 1024:
|
|
578
|
+
return None
|
|
579
|
+
language_obj = _load_language(lang_name)
|
|
580
|
+
if language_obj is None:
|
|
581
|
+
return None
|
|
582
|
+
parser = _make_parser(language_obj)
|
|
583
|
+
if parser is None:
|
|
584
|
+
return None
|
|
585
|
+
source_bytes = source.encode("utf-8", errors="replace")
|
|
586
|
+
try:
|
|
587
|
+
tree = parser.parse(source_bytes)
|
|
588
|
+
except Exception:
|
|
589
|
+
return None
|
|
590
|
+
if tree is None:
|
|
591
|
+
return None
|
|
592
|
+
try:
|
|
593
|
+
root = tree.root_node
|
|
594
|
+
except Exception:
|
|
595
|
+
return None
|
|
596
|
+
if root is None:
|
|
597
|
+
return None
|
|
598
|
+
imports, classes, functions = _walk_tree(root, source_bytes)
|
|
599
|
+
# If the parse produced no recognizable structure, fall through to digest
|
|
600
|
+
# rather than emitting an empty skeleton.
|
|
601
|
+
if not imports and not classes and not functions:
|
|
602
|
+
return None
|
|
603
|
+
line_count = source.count("\n") + (1 if source else 0)
|
|
604
|
+
rendered = _render_skeleton(
|
|
605
|
+
language=lang_name,
|
|
606
|
+
line_count=line_count,
|
|
607
|
+
imports=imports,
|
|
608
|
+
classes=classes,
|
|
609
|
+
functions=functions,
|
|
610
|
+
)
|
|
611
|
+
# Cap at the skeleton budget; if over, drop to a top_level-style truncation
|
|
612
|
+
# then to digest, mirroring _shrink_or_fallback's order.
|
|
613
|
+
replacement_type = "skeleton"
|
|
614
|
+
if len(rendered) > MAX_REPLACEMENT_CHARS["skeleton"]:
|
|
615
|
+
# Truncate functions/classes to fit the top_level budget.
|
|
616
|
+
rendered = _render_skeleton(
|
|
617
|
+
language=lang_name,
|
|
618
|
+
line_count=line_count,
|
|
619
|
+
imports=imports[:_MAX_IMPORTS],
|
|
620
|
+
classes=classes[:_MAX_CLASSES],
|
|
621
|
+
functions=functions[:_MAX_FUNCTIONS],
|
|
622
|
+
)
|
|
623
|
+
replacement_type = "top_level"
|
|
624
|
+
if len(rendered) > MAX_REPLACEMENT_CHARS["top_level"]:
|
|
625
|
+
# Last resort: a compact signatures-only digest.
|
|
626
|
+
sig_lines = [f"{lang_name} signatures", f"lines: {line_count}"]
|
|
627
|
+
items: List[str] = []
|
|
628
|
+
for cls in classes[:_MAX_CLASSES]:
|
|
629
|
+
items.append(f"{cls['signature']} @ L{cls['lineno']}")
|
|
630
|
+
for func in functions[:_MAX_FUNCTIONS]:
|
|
631
|
+
items.append(f"{func['signature']} @ L{func['lineno']}")
|
|
632
|
+
if items:
|
|
633
|
+
sig_lines.append(f"signatures ({len(items)}):")
|
|
634
|
+
sig_lines.extend(f" - {it}" for it in items)
|
|
635
|
+
rendered = "\n".join(sig_lines)
|
|
636
|
+
replacement_type = "signatures"
|
|
637
|
+
if len(rendered) > MAX_REPLACEMENT_CHARS["signatures"]:
|
|
638
|
+
return None # caller falls through to digest
|
|
639
|
+
eligible = replacement_type != "digest"
|
|
640
|
+
fingerprint = _fingerprint(
|
|
641
|
+
path=file_path,
|
|
642
|
+
replacement_type=replacement_type,
|
|
643
|
+
rendered=rendered,
|
|
644
|
+
line_count=line_count,
|
|
645
|
+
file_size_bytes=file_size_bytes,
|
|
646
|
+
)
|
|
647
|
+
# Confidence mirrors the stdlib skeleton baseline (0.90) with a small
|
|
648
|
+
# discount because tree-sitter structure is less curated than the ast path.
|
|
649
|
+
confidence = 0.86 if replacement_type == "skeleton" else (
|
|
650
|
+
0.82 if replacement_type == "top_level" else 0.78
|
|
651
|
+
)
|
|
652
|
+
return StructureMapResult(
|
|
653
|
+
file_path=file_path,
|
|
654
|
+
language=detect_structure_language(file_path) or lang_name,
|
|
655
|
+
replacement_type=replacement_type,
|
|
656
|
+
replacement_text=rendered,
|
|
657
|
+
replacement_tokens_est=estimate_tokens(rendered),
|
|
658
|
+
confidence=confidence,
|
|
659
|
+
fingerprint=fingerprint,
|
|
660
|
+
eligible=eligible,
|
|
661
|
+
reason="ok" if eligible else "fallback_digest",
|
|
662
|
+
generated_like=False,
|
|
663
|
+
parse_ok=True,
|
|
664
|
+
line_count=line_count,
|
|
665
|
+
file_tokens_est=file_tokens_est,
|
|
666
|
+
file_size_bytes=file_size_bytes,
|
|
667
|
+
)
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
__all__ = [
|
|
671
|
+
"FLAG_ENV",
|
|
672
|
+
"SUFFIX_TO_TS_LANG",
|
|
673
|
+
"is_available",
|
|
674
|
+
"summarize_with_tree_sitter",
|
|
675
|
+
"supported_suffixes",
|
|
676
|
+
]
|