@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,2880 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Conservative structure map extraction for code rereads.
|
|
3
|
+
|
|
4
|
+
This module summarizes a narrow set of code files into bounded structural views
|
|
5
|
+
that favor safety over completeness. It uses stdlib-only parsing and avoids
|
|
6
|
+
subprocess/network access. Unsupported, generated-looking, oversized, or
|
|
7
|
+
risky files degrade to a small digest instead of forcing a substitution.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import ast
|
|
13
|
+
import hashlib
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
from dataclasses import asdict, dataclass
|
|
17
|
+
from math import ceil
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import List, Optional, Sequence, Tuple
|
|
20
|
+
|
|
21
|
+
PYTHON_SUFFIX = ".py"
|
|
22
|
+
JS_TS_SUFFIXES = {".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".mts", ".cts"}
|
|
23
|
+
|
|
24
|
+
LANGUAGE_LABELS = {
|
|
25
|
+
PYTHON_SUFFIX: "python",
|
|
26
|
+
".js": "javascript",
|
|
27
|
+
".jsx": "javascript",
|
|
28
|
+
".mjs": "javascript",
|
|
29
|
+
".cjs": "javascript",
|
|
30
|
+
".ts": "typescript",
|
|
31
|
+
".tsx": "typescript",
|
|
32
|
+
".mts": "typescript",
|
|
33
|
+
".cts": "typescript",
|
|
34
|
+
".md": "markdown",
|
|
35
|
+
".json": "json",
|
|
36
|
+
".yaml": "yaml",
|
|
37
|
+
".yml": "yaml",
|
|
38
|
+
".toml": "toml",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
NON_CODE_SUFFIXES = frozenset({".md", ".json", ".yaml", ".yml", ".toml"})
|
|
42
|
+
|
|
43
|
+
MIN_TOKENS_FOR_STRUCTURE = 1000
|
|
44
|
+
MAX_AST_BYTES = 800 * 1024
|
|
45
|
+
MAX_AST_LINES = 20000
|
|
46
|
+
MAX_JS_TS_BYTES = 400 * 1024
|
|
47
|
+
MAX_JS_TS_LINES = 5000
|
|
48
|
+
|
|
49
|
+
MAX_REPLACEMENT_CHARS = {
|
|
50
|
+
"signatures": 800,
|
|
51
|
+
"top_level": 1200,
|
|
52
|
+
"skeleton": 2400,
|
|
53
|
+
"digest": 900,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
MAX_SIGNATURE_ITEMS = 12
|
|
57
|
+
MAX_TOP_LEVEL_IMPORTS = 10
|
|
58
|
+
MAX_TOP_LEVEL_SYMBOLS = 12
|
|
59
|
+
MAX_SKELETON_CLASSES = 4
|
|
60
|
+
MAX_SKELETON_METHODS_PER_CLASS = 4
|
|
61
|
+
MAX_SKELETON_TOP_LEVEL_FUNCTIONS = 8
|
|
62
|
+
MAX_SKELETON_TOP_LEVEL_IMPORTS = 8
|
|
63
|
+
MAX_SKELETON_TOP_LEVEL_ASSIGNMENTS = 8
|
|
64
|
+
MAX_DECORATORS = 2
|
|
65
|
+
MAX_BASES = 3
|
|
66
|
+
MAX_DOCSTRING_CHARS = 120
|
|
67
|
+
MAX_DIGEST_HEAD_LINES = 6
|
|
68
|
+
MAX_DIGEST_TAIL_LINES = 6
|
|
69
|
+
|
|
70
|
+
GENERATED_MARKERS = (
|
|
71
|
+
"generated by",
|
|
72
|
+
"auto-generated",
|
|
73
|
+
"autogenerated",
|
|
74
|
+
"do not edit",
|
|
75
|
+
"this file was generated",
|
|
76
|
+
"code generated",
|
|
77
|
+
"generated file",
|
|
78
|
+
"generated code",
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
JS_TS_METHOD_SKIP = {
|
|
82
|
+
"if",
|
|
83
|
+
"for",
|
|
84
|
+
"while",
|
|
85
|
+
"switch",
|
|
86
|
+
"catch",
|
|
87
|
+
"constructor",
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
JS_TS_EXPORT_PREFIX = re.compile(r"^(?:export\s+)?(?:default\s+)?")
|
|
91
|
+
JS_TS_IMPORT_RE = re.compile(
|
|
92
|
+
r"^(?:import\b.*|export\s+\{[^}]+\}\s+from\b.*|export\s+\*\s+from\b.*)$"
|
|
93
|
+
)
|
|
94
|
+
JS_TS_CLASS_RE = re.compile(
|
|
95
|
+
r"^(?P<prefix>(?:export\s+)?(?:default\s+)?(?:abstract\s+)?)class\s+(?P<name>[A-Za-z_$][\w$]*)"
|
|
96
|
+
)
|
|
97
|
+
JS_TS_INTERFACE_RE = re.compile(
|
|
98
|
+
r"^(?P<prefix>(?:export\s+)?(?:default\s+)?)interface\s+(?P<name>[A-Za-z_$][\w$]*)"
|
|
99
|
+
)
|
|
100
|
+
JS_TS_TYPE_RE = re.compile(
|
|
101
|
+
r"^(?P<prefix>(?:export\s+)?(?:default\s+)?)type\s+(?P<name>[A-Za-z_$][\w$]*)\b"
|
|
102
|
+
)
|
|
103
|
+
JS_TS_ENUM_RE = re.compile(
|
|
104
|
+
r"^(?P<prefix>(?:export\s+)?(?:default\s+)?)enum\s+(?P<name>[A-Za-z_$][\w$]*)\b"
|
|
105
|
+
)
|
|
106
|
+
JS_TS_FUNCTION_RE = re.compile(
|
|
107
|
+
r"^(?P<prefix>(?:export\s+)?(?:default\s+)?)(?P<async>async\s+)?function\s+(?P<name>[A-Za-z_$][\w$]*)\s*\("
|
|
108
|
+
)
|
|
109
|
+
JS_TS_VAR_FUNCTION_RE = re.compile(
|
|
110
|
+
r"^(?P<prefix>(?:export\s+)?(?:default\s+)?)"
|
|
111
|
+
r"(?P<kind>const|let|var)\s+"
|
|
112
|
+
r"(?P<name>[A-Za-z_$][\w$]*)"
|
|
113
|
+
r"(?P<type>\s*:\s*[^=]+)?\s*=\s*"
|
|
114
|
+
r"(?:(?P<async>async)\s+)?(?:(?:function\b)|(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)"
|
|
115
|
+
)
|
|
116
|
+
JS_TS_EXPORT_DEFAULT_IDENTIFIER_RE = re.compile(
|
|
117
|
+
r"^export\s+default\s+(?P<name>[A-Za-z_$][\w$]*)\s*;?$"
|
|
118
|
+
)
|
|
119
|
+
JS_TS_EXPORT_LIST_RE = re.compile(r"^export\s+\{(?P<body>[^}]+)\}(?:\s+from\b.*)?$")
|
|
120
|
+
JS_TS_METHOD_RE = re.compile(
|
|
121
|
+
r"^(?:(?:public|private|protected|static|readonly|async|abstract|override|get|set)\s+)*"
|
|
122
|
+
r"(?P<name>[A-Za-z_$][\w$]*)\s*\("
|
|
123
|
+
)
|
|
124
|
+
JS_TS_PROPERTY_ARROW_RE = re.compile(
|
|
125
|
+
r"^(?:(?:public|private|protected|static|readonly|async|override)\s+)*"
|
|
126
|
+
r"(?P<name>[A-Za-z_$][\w$]*)"
|
|
127
|
+
r"(?:\??\s*:\s*[^=]+)?\s*=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>"
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass(frozen=True)
|
|
132
|
+
class StructureMapResult:
|
|
133
|
+
"""Result of a conservative structure summary."""
|
|
134
|
+
|
|
135
|
+
file_path: str
|
|
136
|
+
language: str
|
|
137
|
+
replacement_type: str
|
|
138
|
+
replacement_text: str
|
|
139
|
+
replacement_tokens_est: int
|
|
140
|
+
confidence: float
|
|
141
|
+
fingerprint: str
|
|
142
|
+
eligible: bool
|
|
143
|
+
reason: str
|
|
144
|
+
generated_like: bool
|
|
145
|
+
parse_ok: bool
|
|
146
|
+
line_count: int
|
|
147
|
+
file_tokens_est: Optional[int] = None
|
|
148
|
+
file_size_bytes: Optional[int] = None
|
|
149
|
+
|
|
150
|
+
def to_dict(self) -> dict:
|
|
151
|
+
return asdict(self)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@dataclass(frozen=True)
|
|
155
|
+
class _FunctionSummary:
|
|
156
|
+
name: str
|
|
157
|
+
signature: str
|
|
158
|
+
lineno: int
|
|
159
|
+
decorators: Tuple[str, ...]
|
|
160
|
+
is_async: bool
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@dataclass(frozen=True)
|
|
164
|
+
class _ClassSummary:
|
|
165
|
+
name: str
|
|
166
|
+
signature: str
|
|
167
|
+
lineno: int
|
|
168
|
+
decorators: Tuple[str, ...]
|
|
169
|
+
methods: Tuple[_FunctionSummary, ...]
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@dataclass(frozen=True)
|
|
173
|
+
class _JsTsSymbolSummary:
|
|
174
|
+
kind: str
|
|
175
|
+
name: str
|
|
176
|
+
signature: str
|
|
177
|
+
lineno: int
|
|
178
|
+
exported: bool = False
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass(frozen=True)
|
|
182
|
+
class ReferenceGraph:
|
|
183
|
+
"""Intra-file symbol reference graph.
|
|
184
|
+
|
|
185
|
+
Directed: an edge ``(caller, callee)`` means ``caller`` references
|
|
186
|
+
``callee``. Nodes are the file's defined symbols (functions/classes/methods)
|
|
187
|
+
plus the synthetic ``"<module>"`` source for module-level references. The
|
|
188
|
+
graph is computed on-read from a single file's AST/source and is NEVER
|
|
189
|
+
persisted (no relationship graph storage beyond the hook process).
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
nodes: Tuple[str, ...]
|
|
193
|
+
edges: Tuple[Tuple[str, str], ...]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def is_python_file(file_path: str | os.PathLike[str]) -> bool:
|
|
197
|
+
"""Return True when the path looks like a Python source file."""
|
|
198
|
+
|
|
199
|
+
return Path(str(file_path)).suffix.lower() == PYTHON_SUFFIX
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def is_js_ts_file(file_path: str | os.PathLike[str]) -> bool:
|
|
203
|
+
"""Return True when the path looks like a JS/TS-family source file."""
|
|
204
|
+
|
|
205
|
+
return Path(str(file_path)).suffix.lower() in JS_TS_SUFFIXES
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def detect_structure_language(file_path: str | os.PathLike[str]) -> str:
|
|
209
|
+
"""Return the structure-language label used by summaries."""
|
|
210
|
+
|
|
211
|
+
suffix = Path(str(file_path)).suffix.lower()
|
|
212
|
+
return LANGUAGE_LABELS.get(suffix, "unknown")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def is_structure_supported_file(file_path: str | os.PathLike[str]) -> bool:
|
|
216
|
+
"""Return True when this module may attempt a structure map.
|
|
217
|
+
|
|
218
|
+
fix-6: the tree-sitter languages (.go/.rs/.c/.java/...) are included ONLY
|
|
219
|
+
when the optional backend is both flag-enabled and actually usable, so the
|
|
220
|
+
on-read path (handle_read gates on this predicate) genuinely delivers
|
|
221
|
+
multi-language structure instead of the backend being unreachable. The
|
|
222
|
+
default flag-OFF hot path is unchanged: the env flag is checked first with a
|
|
223
|
+
cheap string compare and structure_map_ts is not even imported when off.
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
if is_python_file(file_path) or is_js_ts_file(file_path):
|
|
227
|
+
return True
|
|
228
|
+
suffix = Path(str(file_path)).suffix.lower()
|
|
229
|
+
if suffix in NON_CODE_SUFFIXES:
|
|
230
|
+
return True
|
|
231
|
+
# Opt-in tree-sitter backend. Gate on the flag before importing the module
|
|
232
|
+
# (mirrors structure_map_ts._flag_enabled) so flag-off stays byte-identical.
|
|
233
|
+
flag = os.environ.get("TOKEN_OPTIMIZER_STRUCTURE_MAP_TREESITTER", "").strip().lower()
|
|
234
|
+
if flag in ("1", "true", "yes", "on"):
|
|
235
|
+
try:
|
|
236
|
+
from structure_map_ts import SUFFIX_TO_TS_LANG, is_available
|
|
237
|
+
if suffix in SUFFIX_TO_TS_LANG and is_available():
|
|
238
|
+
return True
|
|
239
|
+
except Exception:
|
|
240
|
+
pass
|
|
241
|
+
return False
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def estimate_tokens(text: str) -> int:
|
|
245
|
+
"""Estimate tokens via the shared calibrated estimator (U-F).
|
|
246
|
+
|
|
247
|
+
Kept as a thin wrapper so existing call sites keep importing
|
|
248
|
+
``structure_map.estimate_tokens`` unchanged, while the calibration
|
|
249
|
+
constant lives in one place (``token_estimate``). Falls back to the legacy
|
|
250
|
+
4 chars/token ratio only if the shared module is unavailable.
|
|
251
|
+
"""
|
|
252
|
+
|
|
253
|
+
if not text:
|
|
254
|
+
return 0
|
|
255
|
+
try:
|
|
256
|
+
from token_estimate import estimate_tokens as _shared
|
|
257
|
+
return _shared(text)
|
|
258
|
+
except ImportError:
|
|
259
|
+
return max(1, ceil(len(text) / 4))
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def summarize_python_file(
|
|
263
|
+
file_path: str | os.PathLike[str],
|
|
264
|
+
*,
|
|
265
|
+
content: Optional[str] = None,
|
|
266
|
+
offset: int = 0,
|
|
267
|
+
limit: int = 0,
|
|
268
|
+
file_tokens_est: Optional[int] = None,
|
|
269
|
+
file_size_bytes: Optional[int] = None,
|
|
270
|
+
) -> StructureMapResult:
|
|
271
|
+
"""Summarize a Python file from disk or supplied content.
|
|
272
|
+
|
|
273
|
+
The summary is conservative: it only produces structure maps for whole-file
|
|
274
|
+
rereads of Python sources and falls back to a small digest otherwise.
|
|
275
|
+
"""
|
|
276
|
+
|
|
277
|
+
path = Path(str(file_path))
|
|
278
|
+
source = content
|
|
279
|
+
if source is None:
|
|
280
|
+
try:
|
|
281
|
+
source = path.read_text(encoding="utf-8", errors="replace")
|
|
282
|
+
except OSError:
|
|
283
|
+
return _build_fallback_result(
|
|
284
|
+
file_path=str(path),
|
|
285
|
+
language=detect_structure_language(path),
|
|
286
|
+
source="",
|
|
287
|
+
reason="unreadable",
|
|
288
|
+
confidence=0.05,
|
|
289
|
+
parse_ok=False,
|
|
290
|
+
generated_like=False,
|
|
291
|
+
file_tokens_est=file_tokens_est,
|
|
292
|
+
file_size_bytes=file_size_bytes,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
if file_size_bytes is None:
|
|
296
|
+
file_size_bytes = len(source.encode("utf-8", errors="ignore"))
|
|
297
|
+
if file_tokens_est is None:
|
|
298
|
+
file_tokens_est = estimate_tokens(source)
|
|
299
|
+
|
|
300
|
+
return summarize_python_source(
|
|
301
|
+
source,
|
|
302
|
+
file_path=str(path),
|
|
303
|
+
offset=offset,
|
|
304
|
+
limit=limit,
|
|
305
|
+
file_tokens_est=file_tokens_est,
|
|
306
|
+
file_size_bytes=file_size_bytes,
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def summarize_code_file(
|
|
311
|
+
file_path: str | os.PathLike[str],
|
|
312
|
+
*,
|
|
313
|
+
content: Optional[str] = None,
|
|
314
|
+
offset: int = 0,
|
|
315
|
+
limit: int = 0,
|
|
316
|
+
file_tokens_est: Optional[int] = None,
|
|
317
|
+
file_size_bytes: Optional[int] = None,
|
|
318
|
+
) -> StructureMapResult:
|
|
319
|
+
"""Summarize a supported code file from disk or supplied content."""
|
|
320
|
+
|
|
321
|
+
path = Path(str(file_path))
|
|
322
|
+
source = content
|
|
323
|
+
if source is None:
|
|
324
|
+
try:
|
|
325
|
+
source = path.read_text(encoding="utf-8", errors="replace")
|
|
326
|
+
except OSError:
|
|
327
|
+
return _build_fallback_result(
|
|
328
|
+
file_path=str(path),
|
|
329
|
+
language=detect_structure_language(path),
|
|
330
|
+
source="",
|
|
331
|
+
reason="unreadable",
|
|
332
|
+
confidence=0.05,
|
|
333
|
+
parse_ok=False,
|
|
334
|
+
generated_like=False,
|
|
335
|
+
file_tokens_est=file_tokens_est,
|
|
336
|
+
file_size_bytes=file_size_bytes,
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
if file_size_bytes is None:
|
|
340
|
+
file_size_bytes = len(source.encode("utf-8", errors="ignore"))
|
|
341
|
+
if file_tokens_est is None:
|
|
342
|
+
file_tokens_est = estimate_tokens(source)
|
|
343
|
+
|
|
344
|
+
return summarize_code_source(
|
|
345
|
+
source,
|
|
346
|
+
file_path=str(path),
|
|
347
|
+
offset=offset,
|
|
348
|
+
limit=limit,
|
|
349
|
+
file_tokens_est=file_tokens_est,
|
|
350
|
+
file_size_bytes=file_size_bytes,
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def summarize_code_source(
|
|
355
|
+
source: str,
|
|
356
|
+
*,
|
|
357
|
+
file_path: str = "memory.py",
|
|
358
|
+
offset: int = 0,
|
|
359
|
+
limit: int = 0,
|
|
360
|
+
file_tokens_est: Optional[int] = None,
|
|
361
|
+
file_size_bytes: Optional[int] = None,
|
|
362
|
+
) -> StructureMapResult:
|
|
363
|
+
"""Summarize supported code source by language."""
|
|
364
|
+
|
|
365
|
+
path = str(file_path)
|
|
366
|
+
if is_python_file(path):
|
|
367
|
+
return summarize_python_source(
|
|
368
|
+
source,
|
|
369
|
+
file_path=path,
|
|
370
|
+
offset=offset,
|
|
371
|
+
limit=limit,
|
|
372
|
+
file_tokens_est=file_tokens_est,
|
|
373
|
+
file_size_bytes=file_size_bytes,
|
|
374
|
+
)
|
|
375
|
+
if is_js_ts_file(path):
|
|
376
|
+
return summarize_js_ts_source(
|
|
377
|
+
source,
|
|
378
|
+
file_path=path,
|
|
379
|
+
offset=offset,
|
|
380
|
+
limit=limit,
|
|
381
|
+
file_tokens_est=file_tokens_est,
|
|
382
|
+
file_size_bytes=file_size_bytes,
|
|
383
|
+
)
|
|
384
|
+
suffix = Path(path).suffix.lower()
|
|
385
|
+
if suffix in NON_CODE_SUFFIXES:
|
|
386
|
+
return _summarize_non_code_source(
|
|
387
|
+
source,
|
|
388
|
+
file_path=path,
|
|
389
|
+
suffix=suffix,
|
|
390
|
+
offset=offset,
|
|
391
|
+
limit=limit,
|
|
392
|
+
file_tokens_est=file_tokens_est,
|
|
393
|
+
file_size_bytes=file_size_bytes,
|
|
394
|
+
)
|
|
395
|
+
# optional tree-sitter backend for non-Python/non-JS-TS languages.
|
|
396
|
+
# Additive only: tried before the digest fallback, never replaces the
|
|
397
|
+
# stdlib ast/regex path. Gated by TOKEN_OPTIMIZER_STRUCTURE_MAP_TREESITTER
|
|
398
|
+
# (default off) and is_available(); on any error returns None and falls
|
|
399
|
+
# through to the digest path unchanged.
|
|
400
|
+
if suffix not in JS_TS_SUFFIXES and suffix != PYTHON_SUFFIX:
|
|
401
|
+
try:
|
|
402
|
+
from structure_map_ts import is_available as _ts_available
|
|
403
|
+
if _ts_available():
|
|
404
|
+
from structure_map_ts import summarize_with_tree_sitter
|
|
405
|
+
ts_result = summarize_with_tree_sitter(
|
|
406
|
+
source,
|
|
407
|
+
path,
|
|
408
|
+
file_tokens_est=file_tokens_est,
|
|
409
|
+
file_size_bytes=file_size_bytes,
|
|
410
|
+
)
|
|
411
|
+
if ts_result is not None:
|
|
412
|
+
return ts_result
|
|
413
|
+
except Exception:
|
|
414
|
+
pass
|
|
415
|
+
if file_size_bytes is None:
|
|
416
|
+
file_size_bytes = len(source.encode("utf-8", errors="ignore"))
|
|
417
|
+
if file_tokens_est is None:
|
|
418
|
+
file_tokens_est = estimate_tokens(source)
|
|
419
|
+
return _build_fallback_result(
|
|
420
|
+
file_path=path,
|
|
421
|
+
language=detect_structure_language(path),
|
|
422
|
+
source=source,
|
|
423
|
+
reason="unsupported_language",
|
|
424
|
+
confidence=0.10,
|
|
425
|
+
parse_ok=False,
|
|
426
|
+
generated_like=False,
|
|
427
|
+
file_tokens_est=file_tokens_est,
|
|
428
|
+
file_size_bytes=file_size_bytes,
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def summarize_python_source(
|
|
433
|
+
source: str,
|
|
434
|
+
*,
|
|
435
|
+
file_path: str = "memory.py",
|
|
436
|
+
offset: int = 0,
|
|
437
|
+
limit: int = 0,
|
|
438
|
+
file_tokens_est: Optional[int] = None,
|
|
439
|
+
file_size_bytes: Optional[int] = None,
|
|
440
|
+
) -> StructureMapResult:
|
|
441
|
+
"""Summarize Python source into a bounded structure map."""
|
|
442
|
+
|
|
443
|
+
path = str(file_path)
|
|
444
|
+
line_count = source.count("\n") + (1 if source else 0)
|
|
445
|
+
if file_size_bytes is None:
|
|
446
|
+
file_size_bytes = len(source.encode("utf-8", errors="ignore"))
|
|
447
|
+
if file_tokens_est is None:
|
|
448
|
+
file_tokens_est = estimate_tokens(source)
|
|
449
|
+
|
|
450
|
+
if not is_python_file(path):
|
|
451
|
+
return _build_fallback_result(
|
|
452
|
+
file_path=path,
|
|
453
|
+
language=detect_structure_language(path),
|
|
454
|
+
source=source,
|
|
455
|
+
reason="unsupported_language",
|
|
456
|
+
confidence=0.10,
|
|
457
|
+
parse_ok=False,
|
|
458
|
+
generated_like=False,
|
|
459
|
+
file_tokens_est=file_tokens_est,
|
|
460
|
+
file_size_bytes=file_size_bytes,
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
if offset != 0 or limit != 0:
|
|
464
|
+
return _build_fallback_result(
|
|
465
|
+
file_path=path,
|
|
466
|
+
language="python",
|
|
467
|
+
source=source,
|
|
468
|
+
reason="partial_range_not_supported",
|
|
469
|
+
confidence=0.12,
|
|
470
|
+
parse_ok=False,
|
|
471
|
+
generated_like=False,
|
|
472
|
+
file_tokens_est=file_tokens_est,
|
|
473
|
+
file_size_bytes=file_size_bytes,
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
if not source.strip():
|
|
477
|
+
return _build_fallback_result(
|
|
478
|
+
file_path=path,
|
|
479
|
+
language="python",
|
|
480
|
+
source=source,
|
|
481
|
+
reason="empty_file",
|
|
482
|
+
confidence=0.05,
|
|
483
|
+
parse_ok=False,
|
|
484
|
+
generated_like=False,
|
|
485
|
+
file_tokens_est=file_tokens_est,
|
|
486
|
+
file_size_bytes=file_size_bytes,
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
if file_tokens_est < MIN_TOKENS_FOR_STRUCTURE:
|
|
490
|
+
return _build_fallback_result(
|
|
491
|
+
file_path=path,
|
|
492
|
+
language="python",
|
|
493
|
+
source=source,
|
|
494
|
+
reason="below_min_tokens",
|
|
495
|
+
confidence=0.18,
|
|
496
|
+
parse_ok=False,
|
|
497
|
+
generated_like=False,
|
|
498
|
+
file_tokens_est=file_tokens_est,
|
|
499
|
+
file_size_bytes=file_size_bytes,
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
if file_size_bytes > MAX_AST_BYTES or line_count > MAX_AST_LINES:
|
|
503
|
+
return _build_fallback_result(
|
|
504
|
+
file_path=path,
|
|
505
|
+
language="python",
|
|
506
|
+
source=source,
|
|
507
|
+
reason="over_ast_caps",
|
|
508
|
+
confidence=0.20,
|
|
509
|
+
parse_ok=False,
|
|
510
|
+
generated_like=False,
|
|
511
|
+
file_tokens_est=file_tokens_est,
|
|
512
|
+
file_size_bytes=file_size_bytes,
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
generated_like = looks_generated_python(source)
|
|
516
|
+
if generated_like:
|
|
517
|
+
return _build_fallback_result(
|
|
518
|
+
file_path=path,
|
|
519
|
+
language="python",
|
|
520
|
+
source=source,
|
|
521
|
+
reason="generated_like",
|
|
522
|
+
confidence=0.16,
|
|
523
|
+
parse_ok=False,
|
|
524
|
+
generated_like=True,
|
|
525
|
+
file_tokens_est=file_tokens_est,
|
|
526
|
+
file_size_bytes=file_size_bytes,
|
|
527
|
+
)
|
|
528
|
+
|
|
529
|
+
try:
|
|
530
|
+
tree = ast.parse(source, filename=path)
|
|
531
|
+
parse_ok = True
|
|
532
|
+
except (SyntaxError, ValueError, RecursionError, MemoryError):
|
|
533
|
+
return _build_fallback_result(
|
|
534
|
+
file_path=path,
|
|
535
|
+
language="python",
|
|
536
|
+
source=source,
|
|
537
|
+
reason="ast_parse_failed",
|
|
538
|
+
confidence=0.14,
|
|
539
|
+
parse_ok=False,
|
|
540
|
+
generated_like=False,
|
|
541
|
+
file_tokens_est=file_tokens_est,
|
|
542
|
+
file_size_bytes=file_size_bytes,
|
|
543
|
+
)
|
|
544
|
+
|
|
545
|
+
module_docstring = ast.get_docstring(tree, clean=False)
|
|
546
|
+
top_level_imports, top_level_classes, top_level_functions, top_level_assignments = _collect_module_structure(tree)
|
|
547
|
+
total_methods = sum(len(cls.methods) for cls in top_level_classes)
|
|
548
|
+
replacement_type = _choose_replacement_type(
|
|
549
|
+
file_tokens_est=file_tokens_est,
|
|
550
|
+
line_count=line_count,
|
|
551
|
+
class_count=len(top_level_classes),
|
|
552
|
+
function_count=len(top_level_functions),
|
|
553
|
+
assignment_count=len(top_level_assignments),
|
|
554
|
+
method_count=total_methods,
|
|
555
|
+
)
|
|
556
|
+
|
|
557
|
+
# rank symbols by reference-graph centrality so skeleton truncation
|
|
558
|
+
# keeps the most-referenced symbols. Computed only from the graph already
|
|
559
|
+
# derivable on-read; empty/None ranking leaves source order unchanged.
|
|
560
|
+
# fix-2: fail open. A deep AST can raise RecursionError inside the
|
|
561
|
+
# reference-graph walk; ranking is a
|
|
562
|
+
# nice-to-have ordering hint, so any failure degrades to source order
|
|
563
|
+
# rather than crashing the (PreToolUse) redundant-read path.
|
|
564
|
+
try:
|
|
565
|
+
ranking = pagerank_symbols(extract_reference_graph(source, "python", path))
|
|
566
|
+
except Exception:
|
|
567
|
+
ranking = {}
|
|
568
|
+
|
|
569
|
+
rendered = _render_candidate(
|
|
570
|
+
replacement_type,
|
|
571
|
+
path=path,
|
|
572
|
+
line_count=line_count,
|
|
573
|
+
module_docstring=module_docstring,
|
|
574
|
+
imports=top_level_imports,
|
|
575
|
+
classes=top_level_classes,
|
|
576
|
+
functions=top_level_functions,
|
|
577
|
+
assignments=top_level_assignments,
|
|
578
|
+
ranking=ranking,
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
if len(rendered) > MAX_REPLACEMENT_CHARS[replacement_type]:
|
|
582
|
+
rendered, replacement_type = _shrink_or_fallback(
|
|
583
|
+
path=path,
|
|
584
|
+
line_count=line_count,
|
|
585
|
+
module_docstring=module_docstring,
|
|
586
|
+
imports=top_level_imports,
|
|
587
|
+
classes=top_level_classes,
|
|
588
|
+
functions=top_level_functions,
|
|
589
|
+
assignments=top_level_assignments,
|
|
590
|
+
preferred=replacement_type,
|
|
591
|
+
ranking=ranking,
|
|
592
|
+
)
|
|
593
|
+
|
|
594
|
+
if len(rendered) > MAX_REPLACEMENT_CHARS[replacement_type]:
|
|
595
|
+
return _build_fallback_result(
|
|
596
|
+
file_path=path,
|
|
597
|
+
language="python",
|
|
598
|
+
source=source,
|
|
599
|
+
reason="structure_over_cap",
|
|
600
|
+
confidence=0.22,
|
|
601
|
+
parse_ok=parse_ok,
|
|
602
|
+
generated_like=False,
|
|
603
|
+
file_tokens_est=file_tokens_est,
|
|
604
|
+
file_size_bytes=file_size_bytes,
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
eligible = replacement_type != "digest"
|
|
608
|
+
reason = "ok" if eligible else "fallback_digest"
|
|
609
|
+
|
|
610
|
+
confidence = _score_confidence(
|
|
611
|
+
replacement_type=replacement_type,
|
|
612
|
+
line_count=line_count,
|
|
613
|
+
file_tokens_est=file_tokens_est,
|
|
614
|
+
class_count=len(top_level_classes),
|
|
615
|
+
function_count=len(top_level_functions),
|
|
616
|
+
method_count=total_methods,
|
|
617
|
+
rendered_len=len(rendered),
|
|
618
|
+
parse_ok=parse_ok,
|
|
619
|
+
generated_like=False,
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
fingerprint = _fingerprint(
|
|
623
|
+
path=path,
|
|
624
|
+
replacement_type=replacement_type,
|
|
625
|
+
rendered=rendered,
|
|
626
|
+
line_count=line_count,
|
|
627
|
+
file_size_bytes=file_size_bytes,
|
|
628
|
+
)
|
|
629
|
+
|
|
630
|
+
return StructureMapResult(
|
|
631
|
+
file_path=path,
|
|
632
|
+
language="python",
|
|
633
|
+
replacement_type=replacement_type,
|
|
634
|
+
replacement_text=rendered,
|
|
635
|
+
replacement_tokens_est=estimate_tokens(rendered),
|
|
636
|
+
confidence=confidence,
|
|
637
|
+
fingerprint=fingerprint,
|
|
638
|
+
eligible=eligible,
|
|
639
|
+
reason=reason,
|
|
640
|
+
generated_like=False,
|
|
641
|
+
parse_ok=parse_ok,
|
|
642
|
+
line_count=line_count,
|
|
643
|
+
file_tokens_est=file_tokens_est,
|
|
644
|
+
file_size_bytes=file_size_bytes,
|
|
645
|
+
)
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def summarize_js_ts_source(
|
|
649
|
+
source: str,
|
|
650
|
+
*,
|
|
651
|
+
file_path: str = "memory.ts",
|
|
652
|
+
offset: int = 0,
|
|
653
|
+
limit: int = 0,
|
|
654
|
+
file_tokens_est: Optional[int] = None,
|
|
655
|
+
file_size_bytes: Optional[int] = None,
|
|
656
|
+
) -> StructureMapResult:
|
|
657
|
+
"""Summarize JS/TS-family source into a bounded structure map."""
|
|
658
|
+
|
|
659
|
+
path = str(file_path)
|
|
660
|
+
language = detect_structure_language(path)
|
|
661
|
+
line_count = source.count("\n") + (1 if source else 0)
|
|
662
|
+
if file_size_bytes is None:
|
|
663
|
+
file_size_bytes = len(source.encode("utf-8", errors="ignore"))
|
|
664
|
+
if file_tokens_est is None:
|
|
665
|
+
file_tokens_est = estimate_tokens(source)
|
|
666
|
+
|
|
667
|
+
if not is_js_ts_file(path):
|
|
668
|
+
return _build_fallback_result(
|
|
669
|
+
file_path=path,
|
|
670
|
+
language=language,
|
|
671
|
+
source=source,
|
|
672
|
+
reason="unsupported_language",
|
|
673
|
+
confidence=0.10,
|
|
674
|
+
parse_ok=False,
|
|
675
|
+
generated_like=False,
|
|
676
|
+
file_tokens_est=file_tokens_est,
|
|
677
|
+
file_size_bytes=file_size_bytes,
|
|
678
|
+
)
|
|
679
|
+
|
|
680
|
+
if offset != 0 or limit != 0:
|
|
681
|
+
return _build_fallback_result(
|
|
682
|
+
file_path=path,
|
|
683
|
+
language=language,
|
|
684
|
+
source=source,
|
|
685
|
+
reason="partial_range_not_supported",
|
|
686
|
+
confidence=0.12,
|
|
687
|
+
parse_ok=False,
|
|
688
|
+
generated_like=False,
|
|
689
|
+
file_tokens_est=file_tokens_est,
|
|
690
|
+
file_size_bytes=file_size_bytes,
|
|
691
|
+
)
|
|
692
|
+
|
|
693
|
+
if not source.strip():
|
|
694
|
+
return _build_fallback_result(
|
|
695
|
+
file_path=path,
|
|
696
|
+
language=language,
|
|
697
|
+
source=source,
|
|
698
|
+
reason="empty_file",
|
|
699
|
+
confidence=0.05,
|
|
700
|
+
parse_ok=False,
|
|
701
|
+
generated_like=False,
|
|
702
|
+
file_tokens_est=file_tokens_est,
|
|
703
|
+
file_size_bytes=file_size_bytes,
|
|
704
|
+
)
|
|
705
|
+
|
|
706
|
+
if file_tokens_est < MIN_TOKENS_FOR_STRUCTURE:
|
|
707
|
+
return _build_fallback_result(
|
|
708
|
+
file_path=path,
|
|
709
|
+
language=language,
|
|
710
|
+
source=source,
|
|
711
|
+
reason="below_min_tokens",
|
|
712
|
+
confidence=0.20,
|
|
713
|
+
parse_ok=False,
|
|
714
|
+
generated_like=False,
|
|
715
|
+
file_tokens_est=file_tokens_est,
|
|
716
|
+
file_size_bytes=file_size_bytes,
|
|
717
|
+
)
|
|
718
|
+
|
|
719
|
+
if file_size_bytes > MAX_JS_TS_BYTES or line_count > MAX_JS_TS_LINES:
|
|
720
|
+
return _build_fallback_result(
|
|
721
|
+
file_path=path,
|
|
722
|
+
language=language,
|
|
723
|
+
source=source,
|
|
724
|
+
reason="over_ast_caps",
|
|
725
|
+
confidence=0.22,
|
|
726
|
+
parse_ok=False,
|
|
727
|
+
generated_like=False,
|
|
728
|
+
file_tokens_est=file_tokens_est,
|
|
729
|
+
file_size_bytes=file_size_bytes,
|
|
730
|
+
)
|
|
731
|
+
|
|
732
|
+
generated_like = looks_generated_js_ts(source)
|
|
733
|
+
if generated_like:
|
|
734
|
+
return _build_fallback_result(
|
|
735
|
+
file_path=path,
|
|
736
|
+
language=language,
|
|
737
|
+
source=source,
|
|
738
|
+
reason="generated_like",
|
|
739
|
+
confidence=0.18,
|
|
740
|
+
parse_ok=False,
|
|
741
|
+
generated_like=True,
|
|
742
|
+
file_tokens_est=file_tokens_est,
|
|
743
|
+
file_size_bytes=file_size_bytes,
|
|
744
|
+
)
|
|
745
|
+
|
|
746
|
+
imports, classes, functions, symbols = _collect_js_ts_structure(source)
|
|
747
|
+
if not imports and not classes and not functions and not symbols:
|
|
748
|
+
return _build_fallback_result(
|
|
749
|
+
file_path=path,
|
|
750
|
+
language=language,
|
|
751
|
+
source=source,
|
|
752
|
+
reason="low_signal_structure",
|
|
753
|
+
confidence=0.24,
|
|
754
|
+
parse_ok=False,
|
|
755
|
+
generated_like=False,
|
|
756
|
+
file_tokens_est=file_tokens_est,
|
|
757
|
+
file_size_bytes=file_size_bytes,
|
|
758
|
+
)
|
|
759
|
+
|
|
760
|
+
replacement_type = _choose_js_ts_replacement_type(
|
|
761
|
+
file_tokens_est=file_tokens_est,
|
|
762
|
+
line_count=line_count,
|
|
763
|
+
class_count=len(classes),
|
|
764
|
+
function_count=len(functions),
|
|
765
|
+
symbol_count=len(symbols),
|
|
766
|
+
method_count=sum(len(cls.methods) for cls in classes),
|
|
767
|
+
)
|
|
768
|
+
rendered = _render_js_ts_candidate(
|
|
769
|
+
language=language,
|
|
770
|
+
replacement_type=replacement_type,
|
|
771
|
+
line_count=line_count,
|
|
772
|
+
imports=imports,
|
|
773
|
+
classes=classes,
|
|
774
|
+
functions=functions,
|
|
775
|
+
symbols=symbols,
|
|
776
|
+
)
|
|
777
|
+
|
|
778
|
+
if len(rendered) > MAX_REPLACEMENT_CHARS[replacement_type]:
|
|
779
|
+
rendered, replacement_type = _shrink_js_ts_or_fallback(
|
|
780
|
+
language=language,
|
|
781
|
+
line_count=line_count,
|
|
782
|
+
imports=imports,
|
|
783
|
+
classes=classes,
|
|
784
|
+
functions=functions,
|
|
785
|
+
symbols=symbols,
|
|
786
|
+
preferred=replacement_type,
|
|
787
|
+
)
|
|
788
|
+
|
|
789
|
+
if len(rendered) > MAX_REPLACEMENT_CHARS[replacement_type]:
|
|
790
|
+
return _build_fallback_result(
|
|
791
|
+
file_path=path,
|
|
792
|
+
language=language,
|
|
793
|
+
source=source,
|
|
794
|
+
reason="structure_over_cap",
|
|
795
|
+
confidence=0.24,
|
|
796
|
+
parse_ok=False,
|
|
797
|
+
generated_like=False,
|
|
798
|
+
file_tokens_est=file_tokens_est,
|
|
799
|
+
file_size_bytes=file_size_bytes,
|
|
800
|
+
)
|
|
801
|
+
|
|
802
|
+
confidence = _score_js_ts_confidence(
|
|
803
|
+
replacement_type=replacement_type,
|
|
804
|
+
line_count=line_count,
|
|
805
|
+
file_tokens_est=file_tokens_est,
|
|
806
|
+
class_count=len(classes),
|
|
807
|
+
function_count=len(functions),
|
|
808
|
+
symbol_count=len(symbols),
|
|
809
|
+
method_count=sum(len(cls.methods) for cls in classes),
|
|
810
|
+
rendered_len=len(rendered),
|
|
811
|
+
)
|
|
812
|
+
|
|
813
|
+
return StructureMapResult(
|
|
814
|
+
file_path=path,
|
|
815
|
+
language=language,
|
|
816
|
+
replacement_type=replacement_type,
|
|
817
|
+
replacement_text=rendered,
|
|
818
|
+
replacement_tokens_est=estimate_tokens(rendered),
|
|
819
|
+
confidence=confidence,
|
|
820
|
+
fingerprint=_fingerprint(
|
|
821
|
+
path=path,
|
|
822
|
+
replacement_type=replacement_type,
|
|
823
|
+
rendered=rendered,
|
|
824
|
+
line_count=line_count,
|
|
825
|
+
file_size_bytes=file_size_bytes,
|
|
826
|
+
),
|
|
827
|
+
eligible=replacement_type != "digest",
|
|
828
|
+
reason="ok" if replacement_type != "digest" else "fallback_digest",
|
|
829
|
+
generated_like=False,
|
|
830
|
+
parse_ok=False,
|
|
831
|
+
line_count=line_count,
|
|
832
|
+
file_tokens_est=file_tokens_est,
|
|
833
|
+
file_size_bytes=file_size_bytes,
|
|
834
|
+
)
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def looks_generated_js_ts(source: str) -> bool:
|
|
838
|
+
"""Heuristically detect generated or bundled JS/TS source."""
|
|
839
|
+
|
|
840
|
+
lower = source[:5000].lower()
|
|
841
|
+
for marker in GENERATED_MARKERS:
|
|
842
|
+
if marker in lower:
|
|
843
|
+
return True
|
|
844
|
+
|
|
845
|
+
lines = [line for line in source.splitlines() if line.strip()]
|
|
846
|
+
if len(lines) < 20:
|
|
847
|
+
return False
|
|
848
|
+
|
|
849
|
+
unique_lines = len(set(lines))
|
|
850
|
+
repeated_ratio = 1.0 - (unique_lines / len(lines))
|
|
851
|
+
average_len = sum(len(line) for line in lines) / len(lines)
|
|
852
|
+
long_line_ratio = sum(1 for line in lines if len(line) > 260) / len(lines)
|
|
853
|
+
|
|
854
|
+
if repeated_ratio >= 0.35 and len(lines) >= 80:
|
|
855
|
+
return True
|
|
856
|
+
if average_len >= 220 and long_line_ratio >= 0.30:
|
|
857
|
+
return True
|
|
858
|
+
return False
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def _collect_js_ts_structure(
|
|
862
|
+
source: str,
|
|
863
|
+
) -> Tuple[Tuple[str, ...], Tuple[_ClassSummary, ...], Tuple[_FunctionSummary, ...], Tuple[_JsTsSymbolSummary, ...]]:
|
|
864
|
+
raw_lines = source.splitlines()
|
|
865
|
+
clean_lines = _strip_js_ts_comments_and_strings(source).splitlines()
|
|
866
|
+
|
|
867
|
+
imports: List[str] = []
|
|
868
|
+
classes: List[_ClassSummary] = []
|
|
869
|
+
functions: List[_FunctionSummary] = []
|
|
870
|
+
symbols: List[_JsTsSymbolSummary] = []
|
|
871
|
+
|
|
872
|
+
depth = 0
|
|
873
|
+
current_class_index: Optional[int] = None
|
|
874
|
+
current_class_body_depth: Optional[int] = None
|
|
875
|
+
|
|
876
|
+
for lineno, (raw_line, clean_line) in enumerate(zip(raw_lines, clean_lines), 1):
|
|
877
|
+
clean = clean_line.strip()
|
|
878
|
+
raw = raw_line.strip()
|
|
879
|
+
if not clean:
|
|
880
|
+
depth = max(0, depth + clean_line.count("{") - clean_line.count("}"))
|
|
881
|
+
if current_class_index is not None and depth < (current_class_body_depth or 0):
|
|
882
|
+
current_class_index = None
|
|
883
|
+
current_class_body_depth = None
|
|
884
|
+
continue
|
|
885
|
+
|
|
886
|
+
if depth == 0:
|
|
887
|
+
if JS_TS_IMPORT_RE.match(clean):
|
|
888
|
+
imports.append(_normalize_js_ts_signature(raw))
|
|
889
|
+
else:
|
|
890
|
+
class_summary = _match_js_ts_class(clean, raw, lineno)
|
|
891
|
+
if class_summary is not None:
|
|
892
|
+
classes.append(class_summary)
|
|
893
|
+
current_class_index = len(classes) - 1
|
|
894
|
+
else:
|
|
895
|
+
function_summary = _match_js_ts_function(clean, raw, lineno)
|
|
896
|
+
if function_summary is not None:
|
|
897
|
+
functions.append(function_summary)
|
|
898
|
+
else:
|
|
899
|
+
symbol_summary = _match_js_ts_symbol(clean, raw, lineno)
|
|
900
|
+
if symbol_summary is not None:
|
|
901
|
+
symbols.append(symbol_summary)
|
|
902
|
+
|
|
903
|
+
elif current_class_index is not None and depth == current_class_body_depth:
|
|
904
|
+
method = _match_js_ts_method(clean, raw, lineno, classes[current_class_index].name)
|
|
905
|
+
if method is not None:
|
|
906
|
+
updated_methods = list(classes[current_class_index].methods)
|
|
907
|
+
updated_methods.append(method)
|
|
908
|
+
classes[current_class_index] = _ClassSummary(
|
|
909
|
+
name=classes[current_class_index].name,
|
|
910
|
+
signature=classes[current_class_index].signature,
|
|
911
|
+
lineno=classes[current_class_index].lineno,
|
|
912
|
+
decorators=(),
|
|
913
|
+
methods=tuple(updated_methods),
|
|
914
|
+
)
|
|
915
|
+
|
|
916
|
+
next_depth = max(0, depth + clean_line.count("{") - clean_line.count("}"))
|
|
917
|
+
if current_class_index is not None and depth == 0 and next_depth > depth:
|
|
918
|
+
current_class_body_depth = next_depth
|
|
919
|
+
if current_class_index is not None and next_depth < (current_class_body_depth or 0):
|
|
920
|
+
current_class_index = None
|
|
921
|
+
current_class_body_depth = None
|
|
922
|
+
depth = next_depth
|
|
923
|
+
|
|
924
|
+
return (
|
|
925
|
+
tuple(dict.fromkeys(imports)),
|
|
926
|
+
tuple(classes),
|
|
927
|
+
tuple(functions),
|
|
928
|
+
tuple(_dedupe_js_ts_symbols(symbols)),
|
|
929
|
+
)
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
def _strip_js_ts_comments_and_strings(source: str) -> str:
|
|
933
|
+
NORMAL = 0
|
|
934
|
+
LINE_COMMENT = 1
|
|
935
|
+
BLOCK_COMMENT = 2
|
|
936
|
+
SINGLE_QUOTE = 3
|
|
937
|
+
DOUBLE_QUOTE = 4
|
|
938
|
+
TEMPLATE = 5
|
|
939
|
+
|
|
940
|
+
state = NORMAL
|
|
941
|
+
escaped = False
|
|
942
|
+
out: List[str] = []
|
|
943
|
+
|
|
944
|
+
for index, char in enumerate(source):
|
|
945
|
+
nxt = source[index + 1] if index + 1 < len(source) else ""
|
|
946
|
+
if state == LINE_COMMENT:
|
|
947
|
+
if char == "\n":
|
|
948
|
+
state = NORMAL
|
|
949
|
+
out.append("\n")
|
|
950
|
+
else:
|
|
951
|
+
out.append(" ")
|
|
952
|
+
continue
|
|
953
|
+
if state == BLOCK_COMMENT:
|
|
954
|
+
if char == "*" and nxt == "/":
|
|
955
|
+
out.extend(" ")
|
|
956
|
+
state = NORMAL
|
|
957
|
+
continue
|
|
958
|
+
out.append("\n" if char == "\n" else " ")
|
|
959
|
+
continue
|
|
960
|
+
if state in {SINGLE_QUOTE, DOUBLE_QUOTE, TEMPLATE}:
|
|
961
|
+
if char == "\n" and state != TEMPLATE:
|
|
962
|
+
state = NORMAL
|
|
963
|
+
out.append("\n")
|
|
964
|
+
escaped = False
|
|
965
|
+
continue
|
|
966
|
+
if escaped:
|
|
967
|
+
out.append(" ")
|
|
968
|
+
escaped = False
|
|
969
|
+
continue
|
|
970
|
+
if char == "\\":
|
|
971
|
+
out.append(" ")
|
|
972
|
+
escaped = True
|
|
973
|
+
continue
|
|
974
|
+
if (state == SINGLE_QUOTE and char == "'") or (
|
|
975
|
+
state == DOUBLE_QUOTE and char == '"'
|
|
976
|
+
) or (state == TEMPLATE and char == "`"):
|
|
977
|
+
state = NORMAL
|
|
978
|
+
out.append(" ")
|
|
979
|
+
continue
|
|
980
|
+
out.append("\n" if char == "\n" else " ")
|
|
981
|
+
continue
|
|
982
|
+
|
|
983
|
+
if char == "/" and nxt == "/":
|
|
984
|
+
out.extend(" ")
|
|
985
|
+
state = LINE_COMMENT
|
|
986
|
+
continue
|
|
987
|
+
if char == "/" and nxt == "*":
|
|
988
|
+
out.extend(" ")
|
|
989
|
+
state = BLOCK_COMMENT
|
|
990
|
+
continue
|
|
991
|
+
if char == "'":
|
|
992
|
+
out.append(" ")
|
|
993
|
+
state = SINGLE_QUOTE
|
|
994
|
+
continue
|
|
995
|
+
if char == '"':
|
|
996
|
+
out.append(" ")
|
|
997
|
+
state = DOUBLE_QUOTE
|
|
998
|
+
continue
|
|
999
|
+
if char == "`":
|
|
1000
|
+
out.append(" ")
|
|
1001
|
+
state = TEMPLATE
|
|
1002
|
+
continue
|
|
1003
|
+
out.append(char)
|
|
1004
|
+
|
|
1005
|
+
return "".join(out)
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
def _match_js_ts_class(clean: str, raw: str, lineno: int) -> Optional[_ClassSummary]:
|
|
1009
|
+
match = JS_TS_CLASS_RE.match(clean)
|
|
1010
|
+
if not match:
|
|
1011
|
+
return None
|
|
1012
|
+
exported = clean.startswith("export ")
|
|
1013
|
+
signature = _normalize_js_ts_signature(raw, fallback=f"class {match.group('name')}")
|
|
1014
|
+
if exported and not signature.startswith("export "):
|
|
1015
|
+
signature = "export " + signature
|
|
1016
|
+
return _ClassSummary(
|
|
1017
|
+
name=match.group("name"),
|
|
1018
|
+
signature=signature,
|
|
1019
|
+
lineno=lineno,
|
|
1020
|
+
decorators=(),
|
|
1021
|
+
methods=(),
|
|
1022
|
+
)
|
|
1023
|
+
|
|
1024
|
+
|
|
1025
|
+
def _match_js_ts_function(clean: str, raw: str, lineno: int) -> Optional[_FunctionSummary]:
|
|
1026
|
+
match = JS_TS_FUNCTION_RE.match(clean)
|
|
1027
|
+
if match:
|
|
1028
|
+
exported = bool(match.group("prefix").strip())
|
|
1029
|
+
signature = _normalize_js_ts_signature(raw, fallback=f"function {match.group('name')}(...)")
|
|
1030
|
+
if exported and not signature.startswith("export "):
|
|
1031
|
+
signature = "export " + signature
|
|
1032
|
+
return _FunctionSummary(
|
|
1033
|
+
name=match.group("name"),
|
|
1034
|
+
signature=signature,
|
|
1035
|
+
lineno=lineno,
|
|
1036
|
+
decorators=(),
|
|
1037
|
+
is_async=bool(match.group("async")),
|
|
1038
|
+
)
|
|
1039
|
+
|
|
1040
|
+
match = JS_TS_VAR_FUNCTION_RE.match(clean)
|
|
1041
|
+
if not match:
|
|
1042
|
+
return None
|
|
1043
|
+
exported = bool(match.group("prefix").strip())
|
|
1044
|
+
prefix = f"{match.group('kind')} {match.group('name')}"
|
|
1045
|
+
if match.group("type"):
|
|
1046
|
+
prefix += ": " + " ".join(match.group("type").split()).lstrip(":").strip()
|
|
1047
|
+
if "=>" in clean:
|
|
1048
|
+
prefix += " = (...) =>"
|
|
1049
|
+
else:
|
|
1050
|
+
prefix += " = function(...)"
|
|
1051
|
+
if exported:
|
|
1052
|
+
prefix = "export " + prefix
|
|
1053
|
+
return _FunctionSummary(
|
|
1054
|
+
name=match.group("name"),
|
|
1055
|
+
signature=prefix,
|
|
1056
|
+
lineno=lineno,
|
|
1057
|
+
decorators=(),
|
|
1058
|
+
is_async=bool(match.group("async")),
|
|
1059
|
+
)
|
|
1060
|
+
|
|
1061
|
+
|
|
1062
|
+
def _match_js_ts_symbol(clean: str, raw: str, lineno: int) -> Optional[_JsTsSymbolSummary]:
|
|
1063
|
+
for regex, kind in (
|
|
1064
|
+
(JS_TS_INTERFACE_RE, "interface"),
|
|
1065
|
+
(JS_TS_TYPE_RE, "type"),
|
|
1066
|
+
(JS_TS_ENUM_RE, "enum"),
|
|
1067
|
+
):
|
|
1068
|
+
match = regex.match(clean)
|
|
1069
|
+
if match:
|
|
1070
|
+
exported = bool(match.group("prefix").strip())
|
|
1071
|
+
signature = _normalize_js_ts_signature(raw, fallback=f"{kind} {match.group('name')}")
|
|
1072
|
+
if exported and not signature.startswith("export "):
|
|
1073
|
+
signature = "export " + signature
|
|
1074
|
+
return _JsTsSymbolSummary(
|
|
1075
|
+
kind=kind,
|
|
1076
|
+
name=match.group("name"),
|
|
1077
|
+
signature=signature,
|
|
1078
|
+
lineno=lineno,
|
|
1079
|
+
exported=exported,
|
|
1080
|
+
)
|
|
1081
|
+
|
|
1082
|
+
match = JS_TS_EXPORT_DEFAULT_IDENTIFIER_RE.match(clean)
|
|
1083
|
+
if match:
|
|
1084
|
+
return _JsTsSymbolSummary(
|
|
1085
|
+
kind="export",
|
|
1086
|
+
name=match.group("name"),
|
|
1087
|
+
signature=f"export default {match.group('name')}",
|
|
1088
|
+
lineno=lineno,
|
|
1089
|
+
exported=True,
|
|
1090
|
+
)
|
|
1091
|
+
|
|
1092
|
+
match = JS_TS_EXPORT_LIST_RE.match(clean)
|
|
1093
|
+
if match:
|
|
1094
|
+
body = ", ".join(part.strip() for part in match.group("body").split(",") if part.strip())
|
|
1095
|
+
if body:
|
|
1096
|
+
return _JsTsSymbolSummary(
|
|
1097
|
+
kind="export",
|
|
1098
|
+
name=body.split(",")[0],
|
|
1099
|
+
signature=f"export {{ {body} }}",
|
|
1100
|
+
lineno=lineno,
|
|
1101
|
+
exported=True,
|
|
1102
|
+
)
|
|
1103
|
+
return None
|
|
1104
|
+
|
|
1105
|
+
|
|
1106
|
+
def _match_js_ts_method(
|
|
1107
|
+
clean: str,
|
|
1108
|
+
raw: str,
|
|
1109
|
+
lineno: int,
|
|
1110
|
+
owner: str,
|
|
1111
|
+
) -> Optional[_FunctionSummary]:
|
|
1112
|
+
method_match = JS_TS_METHOD_RE.match(clean)
|
|
1113
|
+
if method_match:
|
|
1114
|
+
name = method_match.group("name")
|
|
1115
|
+
if name not in JS_TS_METHOD_SKIP:
|
|
1116
|
+
return _FunctionSummary(
|
|
1117
|
+
name=name,
|
|
1118
|
+
signature=f"{owner}.{_normalize_js_ts_signature(raw, fallback=f'{name}(...)')}",
|
|
1119
|
+
lineno=lineno,
|
|
1120
|
+
decorators=(),
|
|
1121
|
+
is_async="async " in clean,
|
|
1122
|
+
)
|
|
1123
|
+
|
|
1124
|
+
arrow_match = JS_TS_PROPERTY_ARROW_RE.match(clean)
|
|
1125
|
+
if arrow_match:
|
|
1126
|
+
name = arrow_match.group("name")
|
|
1127
|
+
if name not in JS_TS_METHOD_SKIP:
|
|
1128
|
+
return _FunctionSummary(
|
|
1129
|
+
name=name,
|
|
1130
|
+
signature=f"{owner}.{name} = (...) =>",
|
|
1131
|
+
lineno=lineno,
|
|
1132
|
+
decorators=(),
|
|
1133
|
+
is_async="async " in clean,
|
|
1134
|
+
)
|
|
1135
|
+
return None
|
|
1136
|
+
|
|
1137
|
+
|
|
1138
|
+
def _render_js_ts_candidate(
|
|
1139
|
+
*,
|
|
1140
|
+
language: str,
|
|
1141
|
+
replacement_type: str,
|
|
1142
|
+
line_count: int,
|
|
1143
|
+
imports: Sequence[str],
|
|
1144
|
+
classes: Sequence[_ClassSummary],
|
|
1145
|
+
functions: Sequence[_FunctionSummary],
|
|
1146
|
+
symbols: Sequence[_JsTsSymbolSummary],
|
|
1147
|
+
) -> str:
|
|
1148
|
+
sections: List[str] = [f"{language} {replacement_type}", f"lines: {line_count}"]
|
|
1149
|
+
if replacement_type == "skeleton":
|
|
1150
|
+
sections.extend(
|
|
1151
|
+
_render_js_ts_skeleton(
|
|
1152
|
+
imports=imports,
|
|
1153
|
+
classes=classes,
|
|
1154
|
+
functions=functions,
|
|
1155
|
+
symbols=symbols,
|
|
1156
|
+
)
|
|
1157
|
+
)
|
|
1158
|
+
elif replacement_type == "top_level":
|
|
1159
|
+
sections.extend(
|
|
1160
|
+
_render_js_ts_top_level(
|
|
1161
|
+
imports=imports,
|
|
1162
|
+
classes=classes,
|
|
1163
|
+
functions=functions,
|
|
1164
|
+
symbols=symbols,
|
|
1165
|
+
)
|
|
1166
|
+
)
|
|
1167
|
+
elif replacement_type == "signatures":
|
|
1168
|
+
sections.extend(
|
|
1169
|
+
_render_js_ts_signatures(
|
|
1170
|
+
imports=imports,
|
|
1171
|
+
classes=classes,
|
|
1172
|
+
functions=functions,
|
|
1173
|
+
symbols=symbols,
|
|
1174
|
+
)
|
|
1175
|
+
)
|
|
1176
|
+
else:
|
|
1177
|
+
sections.extend(_render_digest_lines(path="memory", line_count=line_count))
|
|
1178
|
+
return "\n".join(section for section in sections if section)
|
|
1179
|
+
|
|
1180
|
+
|
|
1181
|
+
def _render_js_ts_skeleton(
|
|
1182
|
+
*,
|
|
1183
|
+
imports: Sequence[str],
|
|
1184
|
+
classes: Sequence[_ClassSummary],
|
|
1185
|
+
functions: Sequence[_FunctionSummary],
|
|
1186
|
+
symbols: Sequence[_JsTsSymbolSummary],
|
|
1187
|
+
) -> List[str]:
|
|
1188
|
+
lines: List[str] = []
|
|
1189
|
+
if imports:
|
|
1190
|
+
lines.append(f"imports ({len(imports)}):")
|
|
1191
|
+
for item in _shorten_list(imports, MAX_JS_TS_IMPORTS):
|
|
1192
|
+
lines.append(f" - {item}")
|
|
1193
|
+
if classes:
|
|
1194
|
+
lines.append(f"classes ({len(classes)}):")
|
|
1195
|
+
for cls in _shorten_list(classes, MAX_SKELETON_CLASSES):
|
|
1196
|
+
lines.append(f" - {cls.signature} @ L{cls.lineno}")
|
|
1197
|
+
if cls.methods:
|
|
1198
|
+
lines.append(" methods:")
|
|
1199
|
+
for method in _shorten_list(cls.methods, MAX_SKELETON_METHODS_PER_CLASS):
|
|
1200
|
+
lines.append(f" - {_strip_signature_prefix(method.signature)} @ L{method.lineno}")
|
|
1201
|
+
if functions:
|
|
1202
|
+
lines.append(f"functions ({len(functions)}):")
|
|
1203
|
+
for func in _shorten_list(functions, MAX_JS_TS_SKELETON_FUNCTIONS):
|
|
1204
|
+
lines.append(f" - {func.signature} @ L{func.lineno}")
|
|
1205
|
+
if symbols:
|
|
1206
|
+
lines.append(f"types/exports ({len(symbols)}):")
|
|
1207
|
+
for symbol in _shorten_list(symbols, MAX_JS_TS_SKELETON_SYMBOLS):
|
|
1208
|
+
lines.append(f" - {symbol.signature} @ L{symbol.lineno}")
|
|
1209
|
+
return lines
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
def _render_js_ts_top_level(
|
|
1213
|
+
*,
|
|
1214
|
+
imports: Sequence[str],
|
|
1215
|
+
classes: Sequence[_ClassSummary],
|
|
1216
|
+
functions: Sequence[_FunctionSummary],
|
|
1217
|
+
symbols: Sequence[_JsTsSymbolSummary],
|
|
1218
|
+
) -> List[str]:
|
|
1219
|
+
lines: List[str] = []
|
|
1220
|
+
if imports:
|
|
1221
|
+
lines.append(f"imports ({len(imports)}):")
|
|
1222
|
+
for item in _shorten_list(imports, MAX_JS_TS_IMPORTS):
|
|
1223
|
+
lines.append(f" - {item}")
|
|
1224
|
+
|
|
1225
|
+
symbol_lines: List[str] = [f"{cls.signature} @ L{cls.lineno}" for cls in classes]
|
|
1226
|
+
symbol_lines.extend(f"{func.signature} @ L{func.lineno}" for func in functions)
|
|
1227
|
+
symbol_lines.extend(f"{symbol.signature} @ L{symbol.lineno}" for symbol in symbols)
|
|
1228
|
+
if symbol_lines:
|
|
1229
|
+
lines.append(f"symbols ({len(symbol_lines)}):")
|
|
1230
|
+
for item in _shorten_list(symbol_lines, MAX_JS_TS_TOP_LEVEL_SYMBOLS):
|
|
1231
|
+
lines.append(f" - {item}")
|
|
1232
|
+
return lines
|
|
1233
|
+
|
|
1234
|
+
|
|
1235
|
+
def _render_js_ts_signatures(
|
|
1236
|
+
*,
|
|
1237
|
+
imports: Sequence[str],
|
|
1238
|
+
classes: Sequence[_ClassSummary],
|
|
1239
|
+
functions: Sequence[_FunctionSummary],
|
|
1240
|
+
symbols: Sequence[_JsTsSymbolSummary],
|
|
1241
|
+
) -> List[str]:
|
|
1242
|
+
lines: List[str] = []
|
|
1243
|
+
items: List[str] = []
|
|
1244
|
+
if imports:
|
|
1245
|
+
lines.append(f"imports ({len(imports)}):")
|
|
1246
|
+
for item in _shorten_list(imports, MAX_JS_TS_IMPORTS):
|
|
1247
|
+
lines.append(f" - {item}")
|
|
1248
|
+
for cls in classes:
|
|
1249
|
+
items.append(f"{cls.signature} @ L{cls.lineno}")
|
|
1250
|
+
for method in cls.methods:
|
|
1251
|
+
items.append(f"{_strip_signature_prefix(method.signature)} @ L{method.lineno}")
|
|
1252
|
+
for func in functions:
|
|
1253
|
+
items.append(f"{func.signature} @ L{func.lineno}")
|
|
1254
|
+
for symbol in symbols:
|
|
1255
|
+
items.append(f"{symbol.signature} @ L{symbol.lineno}")
|
|
1256
|
+
if items:
|
|
1257
|
+
lines.append(f"signatures ({len(items)}):")
|
|
1258
|
+
for item in _shorten_list(items, MAX_JS_TS_SIGNATURE_ITEMS):
|
|
1259
|
+
lines.append(f" - {item}")
|
|
1260
|
+
return lines
|
|
1261
|
+
|
|
1262
|
+
|
|
1263
|
+
def _choose_js_ts_replacement_type(
|
|
1264
|
+
*,
|
|
1265
|
+
file_tokens_est: int,
|
|
1266
|
+
line_count: int,
|
|
1267
|
+
class_count: int,
|
|
1268
|
+
function_count: int,
|
|
1269
|
+
symbol_count: int,
|
|
1270
|
+
method_count: int,
|
|
1271
|
+
) -> str:
|
|
1272
|
+
total_symbols = class_count + function_count + symbol_count
|
|
1273
|
+
large_file = file_tokens_est >= 3200 or line_count >= 850 or total_symbols >= 18
|
|
1274
|
+
moderate_file = file_tokens_est >= 1500 or line_count >= 220 or total_symbols >= 8
|
|
1275
|
+
if class_count > 0 and method_count > 0 and moderate_file:
|
|
1276
|
+
return "skeleton"
|
|
1277
|
+
if large_file:
|
|
1278
|
+
return "signatures"
|
|
1279
|
+
if total_symbols <= 6 and line_count <= 180:
|
|
1280
|
+
return "top_level"
|
|
1281
|
+
if class_count > 0 and moderate_file:
|
|
1282
|
+
return "skeleton"
|
|
1283
|
+
if total_symbols <= 12:
|
|
1284
|
+
return "top_level"
|
|
1285
|
+
return "signatures"
|
|
1286
|
+
|
|
1287
|
+
|
|
1288
|
+
def _shrink_js_ts_or_fallback(
|
|
1289
|
+
*,
|
|
1290
|
+
language: str,
|
|
1291
|
+
line_count: int,
|
|
1292
|
+
imports: Sequence[str],
|
|
1293
|
+
classes: Sequence[_ClassSummary],
|
|
1294
|
+
functions: Sequence[_FunctionSummary],
|
|
1295
|
+
symbols: Sequence[_JsTsSymbolSummary],
|
|
1296
|
+
preferred: str,
|
|
1297
|
+
) -> Tuple[str, str]:
|
|
1298
|
+
order = {
|
|
1299
|
+
"skeleton": ["skeleton", "top_level", "signatures", "digest"],
|
|
1300
|
+
"top_level": ["top_level", "signatures", "digest"],
|
|
1301
|
+
"signatures": ["signatures", "top_level", "digest"],
|
|
1302
|
+
"digest": ["digest"],
|
|
1303
|
+
}.get(preferred, ["digest"])
|
|
1304
|
+
|
|
1305
|
+
for replacement_type in order:
|
|
1306
|
+
rendered = _render_js_ts_candidate(
|
|
1307
|
+
language=language,
|
|
1308
|
+
replacement_type=replacement_type,
|
|
1309
|
+
line_count=line_count,
|
|
1310
|
+
imports=imports,
|
|
1311
|
+
classes=classes,
|
|
1312
|
+
functions=functions,
|
|
1313
|
+
symbols=symbols,
|
|
1314
|
+
)
|
|
1315
|
+
if len(rendered) <= MAX_REPLACEMENT_CHARS[replacement_type]:
|
|
1316
|
+
return rendered, replacement_type
|
|
1317
|
+
|
|
1318
|
+
rendered = _render_digest_lines(path="memory", line_count=line_count)
|
|
1319
|
+
return "\n".join(rendered), "digest"
|
|
1320
|
+
|
|
1321
|
+
|
|
1322
|
+
def _score_js_ts_confidence(
|
|
1323
|
+
*,
|
|
1324
|
+
replacement_type: str,
|
|
1325
|
+
line_count: int,
|
|
1326
|
+
file_tokens_est: int,
|
|
1327
|
+
class_count: int,
|
|
1328
|
+
function_count: int,
|
|
1329
|
+
symbol_count: int,
|
|
1330
|
+
method_count: int,
|
|
1331
|
+
rendered_len: int,
|
|
1332
|
+
) -> float:
|
|
1333
|
+
base = {
|
|
1334
|
+
"skeleton": 0.89,
|
|
1335
|
+
"top_level": 0.95,
|
|
1336
|
+
"signatures": 0.90,
|
|
1337
|
+
"digest": 0.30,
|
|
1338
|
+
}.get(replacement_type, 0.35)
|
|
1339
|
+
if file_tokens_est >= 4500:
|
|
1340
|
+
base -= 0.02
|
|
1341
|
+
if line_count >= 1200:
|
|
1342
|
+
base -= 0.02
|
|
1343
|
+
if class_count >= 4:
|
|
1344
|
+
base -= 0.02
|
|
1345
|
+
if method_count >= 10:
|
|
1346
|
+
base -= 0.02
|
|
1347
|
+
if function_count >= 14:
|
|
1348
|
+
base -= 0.02
|
|
1349
|
+
if symbol_count >= 16:
|
|
1350
|
+
base -= 0.01
|
|
1351
|
+
if rendered_len >= MAX_REPLACEMENT_CHARS.get(replacement_type, rendered_len):
|
|
1352
|
+
base -= 0.04
|
|
1353
|
+
return round(max(0.05, min(0.96, base)), 3)
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
def _normalize_js_ts_signature(raw: str, fallback: Optional[str] = None) -> str:
|
|
1357
|
+
compact = " ".join(raw.strip().rstrip("{").rstrip(";").split())
|
|
1358
|
+
if not compact:
|
|
1359
|
+
return fallback or "..."
|
|
1360
|
+
if compact.startswith("import "):
|
|
1361
|
+
compact = _compress_js_ts_import(compact)
|
|
1362
|
+
elif compact.startswith("export {"):
|
|
1363
|
+
compact = _compress_js_ts_export_list(compact)
|
|
1364
|
+
if len(compact) <= 120:
|
|
1365
|
+
return compact
|
|
1366
|
+
return compact[:119] + "…"
|
|
1367
|
+
|
|
1368
|
+
|
|
1369
|
+
def _compress_js_ts_import(compact: str) -> str:
|
|
1370
|
+
module_match = re.search(r"\sfrom\s+(['\"][^'\"]+['\"])", compact)
|
|
1371
|
+
module = f" from {module_match.group(1)}" if module_match else ""
|
|
1372
|
+
if compact.startswith("import * as "):
|
|
1373
|
+
left = compact.split(" from ", 1)[0]
|
|
1374
|
+
return left + module
|
|
1375
|
+
brace_match = re.match(r"import\s+\{(?P<body>[^}]+)\}", compact)
|
|
1376
|
+
if brace_match:
|
|
1377
|
+
names = [part.strip() for part in brace_match.group("body").split(",") if part.strip()]
|
|
1378
|
+
preview = ", ".join(names[:3])
|
|
1379
|
+
if len(names) > 3:
|
|
1380
|
+
preview += ", …"
|
|
1381
|
+
return f"import {{ {preview} }}{module}"
|
|
1382
|
+
return compact
|
|
1383
|
+
|
|
1384
|
+
|
|
1385
|
+
def _compress_js_ts_export_list(compact: str) -> str:
|
|
1386
|
+
match = JS_TS_EXPORT_LIST_RE.match(compact)
|
|
1387
|
+
if not match:
|
|
1388
|
+
return compact
|
|
1389
|
+
names = [part.strip() for part in match.group("body").split(",") if part.strip()]
|
|
1390
|
+
preview = ", ".join(names[:4])
|
|
1391
|
+
if len(names) > 4:
|
|
1392
|
+
preview += ", …"
|
|
1393
|
+
suffix = ""
|
|
1394
|
+
if " from " in compact:
|
|
1395
|
+
suffix = compact[compact.index(" from ") :]
|
|
1396
|
+
return f"export {{ {preview} }}{suffix}"
|
|
1397
|
+
|
|
1398
|
+
|
|
1399
|
+
def _dedupe_js_ts_symbols(symbols: Sequence[_JsTsSymbolSummary]) -> List[_JsTsSymbolSummary]:
|
|
1400
|
+
seen = set()
|
|
1401
|
+
deduped: List[_JsTsSymbolSummary] = []
|
|
1402
|
+
for symbol in symbols:
|
|
1403
|
+
key = (symbol.kind, symbol.name, symbol.signature)
|
|
1404
|
+
if key in seen:
|
|
1405
|
+
continue
|
|
1406
|
+
seen.add(key)
|
|
1407
|
+
deduped.append(symbol)
|
|
1408
|
+
return deduped
|
|
1409
|
+
|
|
1410
|
+
|
|
1411
|
+
def looks_generated_python(source: str) -> bool:
|
|
1412
|
+
"""Heuristically detect generated or minified-looking Python source."""
|
|
1413
|
+
|
|
1414
|
+
lower = source[:4000].lower()
|
|
1415
|
+
for marker in GENERATED_MARKERS:
|
|
1416
|
+
if marker in lower:
|
|
1417
|
+
return True
|
|
1418
|
+
|
|
1419
|
+
lines = [line for line in source.splitlines() if line.strip()]
|
|
1420
|
+
if len(lines) < 20:
|
|
1421
|
+
return False
|
|
1422
|
+
|
|
1423
|
+
unique_lines = len(set(lines))
|
|
1424
|
+
repeated_ratio = 1.0 - (unique_lines / len(lines))
|
|
1425
|
+
average_len = sum(len(line) for line in lines) / len(lines)
|
|
1426
|
+
long_line_ratio = sum(1 for line in lines if len(line) > 240) / len(lines)
|
|
1427
|
+
comment_ratio = sum(1 for line in lines if line.lstrip().startswith("#")) / len(lines)
|
|
1428
|
+
|
|
1429
|
+
if repeated_ratio >= 0.35 and len(lines) >= 80:
|
|
1430
|
+
return True
|
|
1431
|
+
if average_len >= 200 and long_line_ratio >= 0.30:
|
|
1432
|
+
return True
|
|
1433
|
+
if len(lines) >= 150 and comment_ratio <= 0.05 and average_len >= 120 and repeated_ratio >= 0.20:
|
|
1434
|
+
return True
|
|
1435
|
+
return False
|
|
1436
|
+
|
|
1437
|
+
|
|
1438
|
+
def _collect_module_structure(
|
|
1439
|
+
tree: ast.Module,
|
|
1440
|
+
) -> Tuple[Tuple[str, ...], Tuple[_ClassSummary, ...], Tuple[_FunctionSummary, ...], Tuple[str, ...]]:
|
|
1441
|
+
imports: List[str] = []
|
|
1442
|
+
classes: List[_ClassSummary] = []
|
|
1443
|
+
functions: List[_FunctionSummary] = []
|
|
1444
|
+
assignments: List[str] = []
|
|
1445
|
+
|
|
1446
|
+
for node in tree.body:
|
|
1447
|
+
if isinstance(node, ast.Import):
|
|
1448
|
+
imports.append(_render_import(node))
|
|
1449
|
+
elif isinstance(node, ast.ImportFrom):
|
|
1450
|
+
imports.append(_render_import_from(node))
|
|
1451
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
1452
|
+
functions.append(_summarize_function(node, owner=None))
|
|
1453
|
+
elif isinstance(node, ast.ClassDef):
|
|
1454
|
+
classes.append(_summarize_class(node))
|
|
1455
|
+
elif isinstance(node, ast.Assign):
|
|
1456
|
+
assignments.extend(_summarize_assign(node))
|
|
1457
|
+
elif isinstance(node, ast.AnnAssign):
|
|
1458
|
+
assignments.extend(_summarize_ann_assign(node))
|
|
1459
|
+
|
|
1460
|
+
return (
|
|
1461
|
+
tuple(imports),
|
|
1462
|
+
tuple(classes),
|
|
1463
|
+
tuple(functions),
|
|
1464
|
+
tuple(assignments),
|
|
1465
|
+
)
|
|
1466
|
+
|
|
1467
|
+
|
|
1468
|
+
def _summarize_class(node: ast.ClassDef) -> _ClassSummary:
|
|
1469
|
+
bases = tuple(_shorten_list([_render_expr(expr) for expr in node.bases], MAX_BASES))
|
|
1470
|
+
decorators = tuple(_shorten_list([_render_expr(expr) for expr in node.decorator_list], MAX_DECORATORS))
|
|
1471
|
+
methods: List[_FunctionSummary] = []
|
|
1472
|
+
|
|
1473
|
+
for child in node.body:
|
|
1474
|
+
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
1475
|
+
methods.append(_summarize_function(child, owner=node.name))
|
|
1476
|
+
elif isinstance(child, ast.ClassDef):
|
|
1477
|
+
# Nested classes are intentionally not expanded in v1.
|
|
1478
|
+
continue
|
|
1479
|
+
|
|
1480
|
+
signature = _build_class_signature(node.name, bases=bases, decorators=decorators)
|
|
1481
|
+
return _ClassSummary(
|
|
1482
|
+
name=node.name,
|
|
1483
|
+
signature=signature,
|
|
1484
|
+
lineno=getattr(node, "lineno", 1),
|
|
1485
|
+
decorators=decorators,
|
|
1486
|
+
methods=tuple(methods),
|
|
1487
|
+
)
|
|
1488
|
+
|
|
1489
|
+
|
|
1490
|
+
def _summarize_function(
|
|
1491
|
+
node: ast.FunctionDef | ast.AsyncFunctionDef,
|
|
1492
|
+
owner: Optional[str],
|
|
1493
|
+
) -> _FunctionSummary:
|
|
1494
|
+
signature = _build_function_signature(node, owner=owner)
|
|
1495
|
+
decorators = tuple(_shorten_list([_render_expr(expr) for expr in node.decorator_list], MAX_DECORATORS))
|
|
1496
|
+
return _FunctionSummary(
|
|
1497
|
+
name=node.name,
|
|
1498
|
+
signature=signature,
|
|
1499
|
+
lineno=getattr(node, "lineno", 1),
|
|
1500
|
+
decorators=decorators,
|
|
1501
|
+
is_async=isinstance(node, ast.AsyncFunctionDef),
|
|
1502
|
+
)
|
|
1503
|
+
|
|
1504
|
+
|
|
1505
|
+
def _summarize_assign(node: ast.Assign) -> List[str]:
|
|
1506
|
+
targets: List[str] = []
|
|
1507
|
+
for target in node.targets:
|
|
1508
|
+
targets.extend(_flatten_targets(target))
|
|
1509
|
+
|
|
1510
|
+
if any(target == "__all__" for target in targets):
|
|
1511
|
+
export_names = _extract_all_export_names(node.value)
|
|
1512
|
+
if export_names:
|
|
1513
|
+
return [f"__all__ = {', '.join(export_names)}"]
|
|
1514
|
+
return ["__all__"]
|
|
1515
|
+
|
|
1516
|
+
rendered: List[str] = []
|
|
1517
|
+
for target in targets:
|
|
1518
|
+
if _is_public_symbol(target):
|
|
1519
|
+
rendered.append(f"{target}")
|
|
1520
|
+
|
|
1521
|
+
return rendered
|
|
1522
|
+
|
|
1523
|
+
|
|
1524
|
+
def _summarize_ann_assign(node: ast.AnnAssign) -> List[str]:
|
|
1525
|
+
target_names = _flatten_targets(node.target)
|
|
1526
|
+
rendered: List[str] = []
|
|
1527
|
+
for target in target_names:
|
|
1528
|
+
if _is_public_symbol(target):
|
|
1529
|
+
rendered.append(f"{target}")
|
|
1530
|
+
return rendered
|
|
1531
|
+
|
|
1532
|
+
|
|
1533
|
+
def _extract_all_export_names(value: ast.AST) -> List[str]:
|
|
1534
|
+
names: List[str] = []
|
|
1535
|
+
sequence: Optional[Sequence[ast.AST]] = None
|
|
1536
|
+
|
|
1537
|
+
if isinstance(value, (ast.List, ast.Tuple)):
|
|
1538
|
+
sequence = value.elts
|
|
1539
|
+
elif isinstance(value, ast.Set):
|
|
1540
|
+
sequence = value.elts
|
|
1541
|
+
|
|
1542
|
+
if sequence is None:
|
|
1543
|
+
return names
|
|
1544
|
+
|
|
1545
|
+
for item in sequence:
|
|
1546
|
+
if isinstance(item, ast.Constant) and isinstance(item.value, str):
|
|
1547
|
+
names.append(item.value)
|
|
1548
|
+
else:
|
|
1549
|
+
rendered = _render_expr(item)
|
|
1550
|
+
if rendered:
|
|
1551
|
+
names.append(rendered)
|
|
1552
|
+
return names[:10]
|
|
1553
|
+
|
|
1554
|
+
|
|
1555
|
+
def _render_candidate(
|
|
1556
|
+
replacement_type: str,
|
|
1557
|
+
*,
|
|
1558
|
+
path: str,
|
|
1559
|
+
line_count: int,
|
|
1560
|
+
module_docstring: Optional[str],
|
|
1561
|
+
imports: Sequence[str],
|
|
1562
|
+
classes: Sequence[_ClassSummary],
|
|
1563
|
+
functions: Sequence[_FunctionSummary],
|
|
1564
|
+
assignments: Sequence[str],
|
|
1565
|
+
ranking: Optional[dict] = None,
|
|
1566
|
+
) -> str:
|
|
1567
|
+
sections: List[str] = [f"python {replacement_type}", f"lines: {line_count}"]
|
|
1568
|
+
|
|
1569
|
+
doc = _short_docstring(module_docstring)
|
|
1570
|
+
if doc:
|
|
1571
|
+
sections.append(f"docstring: {doc}")
|
|
1572
|
+
|
|
1573
|
+
if replacement_type == "skeleton":
|
|
1574
|
+
sections.extend(
|
|
1575
|
+
_render_skeleton(
|
|
1576
|
+
imports=imports,
|
|
1577
|
+
classes=classes,
|
|
1578
|
+
functions=functions,
|
|
1579
|
+
assignments=assignments,
|
|
1580
|
+
ranking=ranking,
|
|
1581
|
+
)
|
|
1582
|
+
)
|
|
1583
|
+
elif replacement_type == "top_level":
|
|
1584
|
+
sections.extend(
|
|
1585
|
+
_render_top_level(
|
|
1586
|
+
imports=imports,
|
|
1587
|
+
classes=classes,
|
|
1588
|
+
functions=functions,
|
|
1589
|
+
assignments=assignments,
|
|
1590
|
+
ranking=ranking,
|
|
1591
|
+
)
|
|
1592
|
+
)
|
|
1593
|
+
elif replacement_type == "signatures":
|
|
1594
|
+
sections.extend(
|
|
1595
|
+
_render_signatures(
|
|
1596
|
+
imports=imports,
|
|
1597
|
+
classes=classes,
|
|
1598
|
+
functions=functions,
|
|
1599
|
+
assignments=assignments,
|
|
1600
|
+
ranking=ranking,
|
|
1601
|
+
)
|
|
1602
|
+
)
|
|
1603
|
+
else:
|
|
1604
|
+
sections.extend(_render_digest_lines(path=path, line_count=line_count))
|
|
1605
|
+
|
|
1606
|
+
return "\n".join(section for section in sections if section)
|
|
1607
|
+
|
|
1608
|
+
|
|
1609
|
+
def _render_skeleton(
|
|
1610
|
+
*,
|
|
1611
|
+
imports: Sequence[str],
|
|
1612
|
+
classes: Sequence[_ClassSummary],
|
|
1613
|
+
functions: Sequence[_FunctionSummary],
|
|
1614
|
+
assignments: Sequence[str],
|
|
1615
|
+
ranking: Optional[dict] = None,
|
|
1616
|
+
) -> List[str]:
|
|
1617
|
+
lines: List[str] = []
|
|
1618
|
+
|
|
1619
|
+
if imports:
|
|
1620
|
+
lines.append(f"imports ({len(imports)}):")
|
|
1621
|
+
for item in _shorten_list(imports, MAX_SKELETON_TOP_LEVEL_IMPORTS):
|
|
1622
|
+
lines.append(f" - {item}")
|
|
1623
|
+
|
|
1624
|
+
if classes:
|
|
1625
|
+
ranked_classes = _rank_sort(classes, ranking)
|
|
1626
|
+
lines.append(f"classes ({len(classes)}):")
|
|
1627
|
+
for cls in _shorten_list(ranked_classes, MAX_SKELETON_CLASSES):
|
|
1628
|
+
lines.append(f" - {cls.signature} @ L{cls.lineno}")
|
|
1629
|
+
if cls.methods:
|
|
1630
|
+
lines.append(" methods:")
|
|
1631
|
+
ranked_methods = _rank_sort(cls.methods, ranking)
|
|
1632
|
+
for method in _shorten_list(ranked_methods, MAX_SKELETON_METHODS_PER_CLASS):
|
|
1633
|
+
lines.append(f" - {_strip_signature_prefix(method.signature)} @ L{method.lineno}")
|
|
1634
|
+
|
|
1635
|
+
if functions:
|
|
1636
|
+
ranked_functions = _rank_sort(functions, ranking)
|
|
1637
|
+
lines.append(f"functions ({len(functions)}):")
|
|
1638
|
+
for func in _shorten_list(ranked_functions, MAX_SKELETON_TOP_LEVEL_FUNCTIONS):
|
|
1639
|
+
lines.append(f" - {func.signature} @ L{func.lineno}")
|
|
1640
|
+
|
|
1641
|
+
if assignments:
|
|
1642
|
+
lines.append(f"assignments ({len(assignments)}):")
|
|
1643
|
+
for item in _shorten_list(assignments, MAX_SKELETON_TOP_LEVEL_ASSIGNMENTS):
|
|
1644
|
+
lines.append(f" - {item}")
|
|
1645
|
+
|
|
1646
|
+
return lines
|
|
1647
|
+
|
|
1648
|
+
|
|
1649
|
+
def _render_top_level(
|
|
1650
|
+
*,
|
|
1651
|
+
imports: Sequence[str],
|
|
1652
|
+
classes: Sequence[_ClassSummary],
|
|
1653
|
+
functions: Sequence[_FunctionSummary],
|
|
1654
|
+
assignments: Sequence[str],
|
|
1655
|
+
ranking: Optional[dict] = None,
|
|
1656
|
+
) -> List[str]:
|
|
1657
|
+
lines: List[str] = []
|
|
1658
|
+
|
|
1659
|
+
if imports:
|
|
1660
|
+
lines.append(f"imports ({len(imports)}):")
|
|
1661
|
+
for item in _shorten_list(imports, MAX_TOP_LEVEL_IMPORTS):
|
|
1662
|
+
lines.append(f" - {item}")
|
|
1663
|
+
|
|
1664
|
+
# Build (label, name, lineno) triples so centrality can order symbols
|
|
1665
|
+
# before the MAX_TOP_LEVEL_SYMBOLS truncation, keeping the most-referenced
|
|
1666
|
+
# symbols instead of the first-N-by-source-order.
|
|
1667
|
+
triples: List[Tuple[str, str, int]] = []
|
|
1668
|
+
for cls in classes:
|
|
1669
|
+
triples.append((f"{cls.signature} @ L{cls.lineno}", cls.name, cls.lineno))
|
|
1670
|
+
for func in functions:
|
|
1671
|
+
triples.append((f"{func.signature} @ L{func.lineno}", func.name, func.lineno))
|
|
1672
|
+
for item in assignments:
|
|
1673
|
+
triples.append((f"assign {item}", item, 0))
|
|
1674
|
+
|
|
1675
|
+
if triples:
|
|
1676
|
+
ordered = _rank_sort_triples(triples, ranking)
|
|
1677
|
+
symbol_lines = [label for label, _, _ in ordered]
|
|
1678
|
+
lines.append(f"symbols ({len(symbol_lines)}):")
|
|
1679
|
+
for item in _shorten_list(symbol_lines, MAX_TOP_LEVEL_SYMBOLS):
|
|
1680
|
+
lines.append(f" - {item}")
|
|
1681
|
+
|
|
1682
|
+
return lines
|
|
1683
|
+
|
|
1684
|
+
|
|
1685
|
+
def _render_signatures(
|
|
1686
|
+
*,
|
|
1687
|
+
imports: Sequence[str],
|
|
1688
|
+
classes: Sequence[_ClassSummary],
|
|
1689
|
+
functions: Sequence[_FunctionSummary],
|
|
1690
|
+
assignments: Sequence[str],
|
|
1691
|
+
ranking: Optional[dict] = None,
|
|
1692
|
+
) -> List[str]:
|
|
1693
|
+
lines: List[str] = []
|
|
1694
|
+
|
|
1695
|
+
if imports:
|
|
1696
|
+
lines.append(f"imports ({len(imports)}):")
|
|
1697
|
+
for item in _shorten_list(imports, MAX_SKELETON_TOP_LEVEL_IMPORTS):
|
|
1698
|
+
lines.append(f" - {item}")
|
|
1699
|
+
|
|
1700
|
+
triples: List[Tuple[str, str, int]] = []
|
|
1701
|
+
for cls in classes:
|
|
1702
|
+
triples.append((f"{cls.signature} @ L{cls.lineno}", cls.name, cls.lineno))
|
|
1703
|
+
for method in cls.methods:
|
|
1704
|
+
triples.append(
|
|
1705
|
+
(f"{_strip_signature_prefix(method.signature)} @ L{method.lineno}", method.name, method.lineno)
|
|
1706
|
+
)
|
|
1707
|
+
for func in functions:
|
|
1708
|
+
triples.append((f"{func.signature} @ L{func.lineno}", func.name, func.lineno))
|
|
1709
|
+
for item in assignments:
|
|
1710
|
+
triples.append((f"assign {item}", item, 0))
|
|
1711
|
+
|
|
1712
|
+
if triples:
|
|
1713
|
+
ordered = _rank_sort_triples(triples, ranking)
|
|
1714
|
+
items = [label for label, _, _ in ordered]
|
|
1715
|
+
lines.append(f"signatures ({len(items)}):")
|
|
1716
|
+
for item in _shorten_list(items, MAX_SIGNATURE_ITEMS):
|
|
1717
|
+
lines.append(f" - {item}")
|
|
1718
|
+
|
|
1719
|
+
return lines
|
|
1720
|
+
|
|
1721
|
+
|
|
1722
|
+
def _rank_sort_triples(
|
|
1723
|
+
triples: Sequence[Tuple[str, str, int]],
|
|
1724
|
+
ranking: Optional[dict],
|
|
1725
|
+
) -> List[Tuple[str, str, int]]:
|
|
1726
|
+
"""Order (label, name, lineno) triples by descending centrality, ties
|
|
1727
|
+
broken by source order (lineno). No ranking -> source order unchanged."""
|
|
1728
|
+
if not ranking:
|
|
1729
|
+
return list(triples)
|
|
1730
|
+
return sorted(
|
|
1731
|
+
triples,
|
|
1732
|
+
key=lambda t: (-float(ranking.get(t[1], 0.0)), t[2]),
|
|
1733
|
+
)
|
|
1734
|
+
|
|
1735
|
+
|
|
1736
|
+
def _render_digest_lines(*, path: str, line_count: int) -> List[str]:
|
|
1737
|
+
lines = [f"digest fallback for {Path(path).name or path}"]
|
|
1738
|
+
lines.append(f"lines: {line_count}")
|
|
1739
|
+
return lines
|
|
1740
|
+
|
|
1741
|
+
|
|
1742
|
+
def _strip_signature_prefix(signature: str) -> str:
|
|
1743
|
+
if signature.startswith("async def "):
|
|
1744
|
+
return "async " + signature[len("async def ") :]
|
|
1745
|
+
if signature.startswith("def "):
|
|
1746
|
+
return signature[len("def ") :]
|
|
1747
|
+
return signature
|
|
1748
|
+
|
|
1749
|
+
|
|
1750
|
+
def _render_import(node: ast.Import) -> str:
|
|
1751
|
+
parts = []
|
|
1752
|
+
for alias in node.names:
|
|
1753
|
+
if alias.asname:
|
|
1754
|
+
parts.append(f"{alias.name} as {alias.asname}")
|
|
1755
|
+
else:
|
|
1756
|
+
parts.append(alias.name)
|
|
1757
|
+
return f"import {', '.join(parts)}"
|
|
1758
|
+
|
|
1759
|
+
|
|
1760
|
+
def _render_import_from(node: ast.ImportFrom) -> str:
|
|
1761
|
+
module = "." * node.level + (node.module or "")
|
|
1762
|
+
parts = []
|
|
1763
|
+
for alias in node.names:
|
|
1764
|
+
if alias.asname:
|
|
1765
|
+
parts.append(f"{alias.name} as {alias.asname}")
|
|
1766
|
+
else:
|
|
1767
|
+
parts.append(alias.name)
|
|
1768
|
+
return f"from {module} import {', '.join(parts)}"
|
|
1769
|
+
|
|
1770
|
+
|
|
1771
|
+
def _build_class_signature(name: str, *, bases: Sequence[str], decorators: Sequence[str]) -> str:
|
|
1772
|
+
parts = []
|
|
1773
|
+
if decorators:
|
|
1774
|
+
parts.append(f"decorators={','.join(decorators)}")
|
|
1775
|
+
if bases:
|
|
1776
|
+
parts.append(f"bases={','.join(bases)}")
|
|
1777
|
+
if parts:
|
|
1778
|
+
return f"class {name} ({'; '.join(parts)})"
|
|
1779
|
+
return f"class {name}"
|
|
1780
|
+
|
|
1781
|
+
|
|
1782
|
+
def _build_function_signature(
|
|
1783
|
+
node: ast.FunctionDef | ast.AsyncFunctionDef,
|
|
1784
|
+
*,
|
|
1785
|
+
owner: Optional[str],
|
|
1786
|
+
) -> str:
|
|
1787
|
+
prefix = "async def" if isinstance(node, ast.AsyncFunctionDef) else "def"
|
|
1788
|
+
name = f"{owner}.{node.name}" if owner else node.name
|
|
1789
|
+
args = _render_arguments(node.args)
|
|
1790
|
+
signature = f"{prefix} {name}({args})"
|
|
1791
|
+
if node.returns is not None:
|
|
1792
|
+
signature += f" -> {_render_expr(node.returns)}"
|
|
1793
|
+
if node.decorator_list:
|
|
1794
|
+
decorators = _shorten_list([_render_expr(expr) for expr in node.decorator_list], MAX_DECORATORS)
|
|
1795
|
+
if decorators:
|
|
1796
|
+
signature += f" [decorators: {', '.join(decorators)}]"
|
|
1797
|
+
return signature
|
|
1798
|
+
|
|
1799
|
+
|
|
1800
|
+
def _render_arguments(args: ast.arguments) -> str:
|
|
1801
|
+
rendered: List[str] = []
|
|
1802
|
+
positional = list(args.posonlyargs) + list(args.args)
|
|
1803
|
+
defaults = [None] * (len(positional) - len(args.defaults)) + list(args.defaults)
|
|
1804
|
+
|
|
1805
|
+
for index, arg in enumerate(args.posonlyargs):
|
|
1806
|
+
rendered.append(_render_single_arg(arg, defaults[index]))
|
|
1807
|
+
if args.posonlyargs:
|
|
1808
|
+
rendered.append("/")
|
|
1809
|
+
|
|
1810
|
+
offset = len(args.posonlyargs)
|
|
1811
|
+
for index, arg in enumerate(args.args):
|
|
1812
|
+
rendered.append(_render_single_arg(arg, defaults[offset + index]))
|
|
1813
|
+
|
|
1814
|
+
if args.vararg is not None:
|
|
1815
|
+
rendered.append("*" + _render_arg_name(args.vararg))
|
|
1816
|
+
elif args.kwonlyargs:
|
|
1817
|
+
rendered.append("*")
|
|
1818
|
+
|
|
1819
|
+
for arg, default in zip(args.kwonlyargs, args.kw_defaults):
|
|
1820
|
+
rendered.append(_render_single_arg(arg, default))
|
|
1821
|
+
|
|
1822
|
+
if args.kwarg is not None:
|
|
1823
|
+
rendered.append("**" + _render_arg_name(args.kwarg))
|
|
1824
|
+
|
|
1825
|
+
return ", ".join(part for part in rendered if part)
|
|
1826
|
+
|
|
1827
|
+
|
|
1828
|
+
def _render_single_arg(arg: ast.arg, default: Optional[ast.expr]) -> str:
|
|
1829
|
+
rendered = _render_arg_name(arg)
|
|
1830
|
+
if arg.annotation is not None:
|
|
1831
|
+
rendered += f": {_render_expr(arg.annotation)}"
|
|
1832
|
+
if default is not None:
|
|
1833
|
+
rendered += f"={_render_expr(default)}"
|
|
1834
|
+
return rendered
|
|
1835
|
+
|
|
1836
|
+
|
|
1837
|
+
def _render_arg_name(arg: ast.arg) -> str:
|
|
1838
|
+
return arg.arg
|
|
1839
|
+
|
|
1840
|
+
|
|
1841
|
+
def _render_expr(node: ast.AST) -> str:
|
|
1842
|
+
if hasattr(ast, "unparse"):
|
|
1843
|
+
try:
|
|
1844
|
+
return ast.unparse(node)
|
|
1845
|
+
except Exception:
|
|
1846
|
+
pass
|
|
1847
|
+
return _fallback_render_expr(node)
|
|
1848
|
+
|
|
1849
|
+
|
|
1850
|
+
def _fallback_render_expr(node: ast.AST) -> str:
|
|
1851
|
+
if isinstance(node, ast.Name):
|
|
1852
|
+
return node.id
|
|
1853
|
+
if isinstance(node, ast.Attribute):
|
|
1854
|
+
return f"{_fallback_render_expr(node.value)}.{node.attr}"
|
|
1855
|
+
if isinstance(node, ast.Constant):
|
|
1856
|
+
return repr(node.value)
|
|
1857
|
+
if isinstance(node, ast.Subscript):
|
|
1858
|
+
return f"{_fallback_render_expr(node.value)}[{_fallback_render_expr(node.slice)}]"
|
|
1859
|
+
if isinstance(node, ast.Tuple):
|
|
1860
|
+
return ", ".join(_fallback_render_expr(item) for item in node.elts)
|
|
1861
|
+
if isinstance(node, ast.List):
|
|
1862
|
+
return "[" + ", ".join(_fallback_render_expr(item) for item in node.elts) + "]"
|
|
1863
|
+
if isinstance(node, ast.Dict):
|
|
1864
|
+
pairs = []
|
|
1865
|
+
for key, value in zip(node.keys, node.values):
|
|
1866
|
+
if key is None:
|
|
1867
|
+
pairs.append("**" + _fallback_render_expr(value))
|
|
1868
|
+
else:
|
|
1869
|
+
pairs.append(f"{_fallback_render_expr(key)}: {_fallback_render_expr(value)}")
|
|
1870
|
+
return "{" + ", ".join(pairs) + "}"
|
|
1871
|
+
if isinstance(node, ast.BinOp):
|
|
1872
|
+
return f"{_fallback_render_expr(node.left)} {_fallback_operator(node.op)} {_fallback_render_expr(node.right)}"
|
|
1873
|
+
if isinstance(node, ast.UnaryOp):
|
|
1874
|
+
return f"{_fallback_unary_operator(node.op)}{_fallback_render_expr(node.operand)}"
|
|
1875
|
+
if isinstance(node, ast.Call):
|
|
1876
|
+
args = [_fallback_render_expr(arg) for arg in node.args]
|
|
1877
|
+
kwargs = []
|
|
1878
|
+
for kw in node.keywords:
|
|
1879
|
+
if kw.arg is None:
|
|
1880
|
+
kwargs.append("**" + _fallback_render_expr(kw.value))
|
|
1881
|
+
else:
|
|
1882
|
+
kwargs.append(f"{kw.arg}={_fallback_render_expr(kw.value)}")
|
|
1883
|
+
all_args = args + kwargs
|
|
1884
|
+
return f"{_fallback_render_expr(node.func)}({', '.join(all_args)})"
|
|
1885
|
+
if isinstance(node, ast.JoinedStr):
|
|
1886
|
+
return "f" + repr("".join(_fallback_render_expr(value) for value in node.values))
|
|
1887
|
+
if isinstance(node, ast.FormattedValue):
|
|
1888
|
+
return "{" + _fallback_render_expr(node.value) + "}"
|
|
1889
|
+
return getattr(node, "id", getattr(node, "attr", node.__class__.__name__))
|
|
1890
|
+
|
|
1891
|
+
|
|
1892
|
+
def _fallback_operator(op: ast.AST) -> str:
|
|
1893
|
+
mapping = {
|
|
1894
|
+
ast.Add: "+",
|
|
1895
|
+
ast.Sub: "-",
|
|
1896
|
+
ast.Mult: "*",
|
|
1897
|
+
ast.MatMult: "@",
|
|
1898
|
+
ast.Div: "/",
|
|
1899
|
+
ast.FloorDiv: "//",
|
|
1900
|
+
ast.Mod: "%",
|
|
1901
|
+
ast.Pow: "**",
|
|
1902
|
+
ast.LShift: "<<",
|
|
1903
|
+
ast.RShift: ">>",
|
|
1904
|
+
ast.BitOr: "|",
|
|
1905
|
+
ast.BitXor: "^",
|
|
1906
|
+
ast.BitAnd: "&",
|
|
1907
|
+
ast.And: "and",
|
|
1908
|
+
ast.Or: "or",
|
|
1909
|
+
}
|
|
1910
|
+
for cls, symbol in mapping.items():
|
|
1911
|
+
if isinstance(op, cls):
|
|
1912
|
+
return symbol
|
|
1913
|
+
return "?"
|
|
1914
|
+
|
|
1915
|
+
|
|
1916
|
+
def _fallback_unary_operator(op: ast.AST) -> str:
|
|
1917
|
+
mapping = {
|
|
1918
|
+
ast.Not: "not ",
|
|
1919
|
+
ast.UAdd: "+",
|
|
1920
|
+
ast.USub: "-",
|
|
1921
|
+
ast.Invert: "~",
|
|
1922
|
+
}
|
|
1923
|
+
for cls, symbol in mapping.items():
|
|
1924
|
+
if isinstance(op, cls):
|
|
1925
|
+
return symbol
|
|
1926
|
+
return ""
|
|
1927
|
+
|
|
1928
|
+
|
|
1929
|
+
MAX_MD_HEADINGS = 20
|
|
1930
|
+
MAX_MD_HEADING_CHARS = 100
|
|
1931
|
+
MAX_JSON_KEYS = 30
|
|
1932
|
+
MAX_JSON_BYTES = 100 * 1024
|
|
1933
|
+
MAX_NON_CODE_KEYS = 30
|
|
1934
|
+
|
|
1935
|
+
MAX_REPLACEMENT_CHARS_NON_CODE = {
|
|
1936
|
+
"outline": 800,
|
|
1937
|
+
"key_tree": 800,
|
|
1938
|
+
"section_list": 600,
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
|
|
1942
|
+
def _summarize_non_code_source(
|
|
1943
|
+
source: str,
|
|
1944
|
+
*,
|
|
1945
|
+
file_path: str,
|
|
1946
|
+
suffix: str,
|
|
1947
|
+
offset: int = 0,
|
|
1948
|
+
limit: int = 0,
|
|
1949
|
+
file_tokens_est: Optional[int] = None,
|
|
1950
|
+
file_size_bytes: Optional[int] = None,
|
|
1951
|
+
) -> StructureMapResult:
|
|
1952
|
+
if file_size_bytes is None:
|
|
1953
|
+
file_size_bytes = len(source.encode("utf-8", errors="ignore"))
|
|
1954
|
+
if file_tokens_est is None:
|
|
1955
|
+
file_tokens_est = estimate_tokens(source)
|
|
1956
|
+
|
|
1957
|
+
language = LANGUAGE_LABELS.get(suffix, "unknown")
|
|
1958
|
+
line_count = source.count("\n") + (1 if source else 0)
|
|
1959
|
+
|
|
1960
|
+
if offset != 0 or limit != 0:
|
|
1961
|
+
return _build_fallback_result(
|
|
1962
|
+
file_path=file_path, language=language, source=source,
|
|
1963
|
+
reason="partial_range_not_supported", confidence=0.12,
|
|
1964
|
+
parse_ok=False, generated_like=False,
|
|
1965
|
+
file_tokens_est=file_tokens_est, file_size_bytes=file_size_bytes,
|
|
1966
|
+
)
|
|
1967
|
+
|
|
1968
|
+
if not source.strip():
|
|
1969
|
+
return _build_fallback_result(
|
|
1970
|
+
file_path=file_path, language=language, source=source,
|
|
1971
|
+
reason="empty_file", confidence=0.05,
|
|
1972
|
+
parse_ok=False, generated_like=False,
|
|
1973
|
+
file_tokens_est=file_tokens_est, file_size_bytes=file_size_bytes,
|
|
1974
|
+
)
|
|
1975
|
+
|
|
1976
|
+
if suffix == ".md":
|
|
1977
|
+
return _summarize_markdown(source, file_path=file_path,
|
|
1978
|
+
line_count=line_count,
|
|
1979
|
+
file_tokens_est=file_tokens_est,
|
|
1980
|
+
file_size_bytes=file_size_bytes)
|
|
1981
|
+
if suffix == ".json":
|
|
1982
|
+
return _summarize_json(source, file_path=file_path,
|
|
1983
|
+
line_count=line_count,
|
|
1984
|
+
file_tokens_est=file_tokens_est,
|
|
1985
|
+
file_size_bytes=file_size_bytes)
|
|
1986
|
+
if suffix in (".yaml", ".yml"):
|
|
1987
|
+
return _summarize_yaml(source, file_path=file_path,
|
|
1988
|
+
line_count=line_count,
|
|
1989
|
+
file_tokens_est=file_tokens_est,
|
|
1990
|
+
file_size_bytes=file_size_bytes)
|
|
1991
|
+
if suffix == ".toml":
|
|
1992
|
+
return _summarize_toml(source, file_path=file_path,
|
|
1993
|
+
line_count=line_count,
|
|
1994
|
+
file_tokens_est=file_tokens_est,
|
|
1995
|
+
file_size_bytes=file_size_bytes)
|
|
1996
|
+
|
|
1997
|
+
return _build_fallback_result(
|
|
1998
|
+
file_path=file_path, language=language, source=source,
|
|
1999
|
+
reason="unsupported_language", confidence=0.10,
|
|
2000
|
+
parse_ok=False, generated_like=False,
|
|
2001
|
+
file_tokens_est=file_tokens_est, file_size_bytes=file_size_bytes,
|
|
2002
|
+
)
|
|
2003
|
+
|
|
2004
|
+
|
|
2005
|
+
def _summarize_markdown(
|
|
2006
|
+
source: str, *, file_path: str, line_count: int,
|
|
2007
|
+
file_tokens_est: Optional[int], file_size_bytes: Optional[int],
|
|
2008
|
+
) -> StructureMapResult:
|
|
2009
|
+
lines = source.splitlines()
|
|
2010
|
+
headings: list[str] = []
|
|
2011
|
+
for line in lines:
|
|
2012
|
+
stripped = line.strip()
|
|
2013
|
+
if stripped.startswith("#"):
|
|
2014
|
+
level = len(stripped) - len(stripped.lstrip("#"))
|
|
2015
|
+
title = stripped.lstrip("#").strip()
|
|
2016
|
+
if 1 <= level <= 4 and title:
|
|
2017
|
+
indent = " " * (level - 1)
|
|
2018
|
+
headings.append(f"{indent}{title[:MAX_MD_HEADING_CHARS]}")
|
|
2019
|
+
if len(headings) >= MAX_MD_HEADINGS:
|
|
2020
|
+
break
|
|
2021
|
+
|
|
2022
|
+
if not headings:
|
|
2023
|
+
return _build_fallback_result(
|
|
2024
|
+
file_path=file_path, language="markdown", source=source,
|
|
2025
|
+
reason="no_headings", confidence=0.15,
|
|
2026
|
+
parse_ok=False, generated_like=False,
|
|
2027
|
+
file_tokens_est=file_tokens_est, file_size_bytes=file_size_bytes,
|
|
2028
|
+
)
|
|
2029
|
+
|
|
2030
|
+
name = Path(file_path).name
|
|
2031
|
+
rendered = f"Markdown outline for {name} ({line_count} lines):\n"
|
|
2032
|
+
rendered += "\n".join(headings)
|
|
2033
|
+
if len(headings) == MAX_MD_HEADINGS:
|
|
2034
|
+
rendered += f"\n... (truncated at {MAX_MD_HEADINGS} headings)"
|
|
2035
|
+
|
|
2036
|
+
cap = MAX_REPLACEMENT_CHARS_NON_CODE["outline"]
|
|
2037
|
+
if len(rendered) > cap:
|
|
2038
|
+
rendered = rendered[:cap - 3] + "..."
|
|
2039
|
+
|
|
2040
|
+
fp = _fingerprint(path=file_path, replacement_type="outline",
|
|
2041
|
+
rendered=rendered, line_count=line_count,
|
|
2042
|
+
file_size_bytes=file_size_bytes)
|
|
2043
|
+
return StructureMapResult(
|
|
2044
|
+
file_path=file_path, language="markdown",
|
|
2045
|
+
replacement_type="outline", replacement_text=rendered,
|
|
2046
|
+
replacement_tokens_est=estimate_tokens(rendered),
|
|
2047
|
+
confidence=0.90, fingerprint=fp, eligible=True,
|
|
2048
|
+
reason="ok", generated_like=False, parse_ok=True,
|
|
2049
|
+
line_count=line_count, file_tokens_est=file_tokens_est,
|
|
2050
|
+
file_size_bytes=file_size_bytes,
|
|
2051
|
+
)
|
|
2052
|
+
|
|
2053
|
+
|
|
2054
|
+
def _json_type_hint(val: object) -> str:
|
|
2055
|
+
if isinstance(val, dict):
|
|
2056
|
+
return f"object({len(val)} keys)"
|
|
2057
|
+
if isinstance(val, list):
|
|
2058
|
+
return f"array({len(val)})"
|
|
2059
|
+
if isinstance(val, str):
|
|
2060
|
+
return f"string({len(val)}ch)" if len(val) > 40 else f'"{val}"'
|
|
2061
|
+
if isinstance(val, bool):
|
|
2062
|
+
return str(val).lower()
|
|
2063
|
+
if isinstance(val, (int, float)):
|
|
2064
|
+
return str(val)
|
|
2065
|
+
if val is None:
|
|
2066
|
+
return "null"
|
|
2067
|
+
return type(val).__name__
|
|
2068
|
+
|
|
2069
|
+
|
|
2070
|
+
def _extract_json_keys(
|
|
2071
|
+
data: object, depth: int, max_depth: int, max_keys: int,
|
|
2072
|
+
) -> list[str]:
|
|
2073
|
+
result: list[str] = []
|
|
2074
|
+
if depth > max_depth or len(result) >= max_keys:
|
|
2075
|
+
return result
|
|
2076
|
+
if isinstance(data, dict):
|
|
2077
|
+
for key in list(data.keys())[:max_keys - len(result)]:
|
|
2078
|
+
val = data[key]
|
|
2079
|
+
indent = " " * depth
|
|
2080
|
+
hint = _json_type_hint(val)
|
|
2081
|
+
result.append(f"{indent}{key}: {hint}")
|
|
2082
|
+
if isinstance(val, dict) and depth < max_depth:
|
|
2083
|
+
result.extend(_extract_json_keys(val, depth + 1, max_depth, max_keys - len(result)))
|
|
2084
|
+
if len(result) >= max_keys:
|
|
2085
|
+
break
|
|
2086
|
+
elif isinstance(data, list) and data:
|
|
2087
|
+
result.append(f"{' ' * depth}[{len(data)} items, first: {_json_type_hint(data[0])}]")
|
|
2088
|
+
return result[:max_keys]
|
|
2089
|
+
|
|
2090
|
+
|
|
2091
|
+
def _summarize_json(
|
|
2092
|
+
source: str, *, file_path: str, line_count: int,
|
|
2093
|
+
file_tokens_est: Optional[int], file_size_bytes: Optional[int],
|
|
2094
|
+
) -> StructureMapResult:
|
|
2095
|
+
raw_bytes = len(source.encode("utf-8", errors="replace"))
|
|
2096
|
+
if raw_bytes > MAX_JSON_BYTES:
|
|
2097
|
+
return _build_fallback_result(
|
|
2098
|
+
file_path=file_path, language="json", source=source,
|
|
2099
|
+
reason="too_large_to_parse", confidence=0.10,
|
|
2100
|
+
parse_ok=False, generated_like=False,
|
|
2101
|
+
file_tokens_est=file_tokens_est, file_size_bytes=file_size_bytes,
|
|
2102
|
+
)
|
|
2103
|
+
try:
|
|
2104
|
+
import json as _json
|
|
2105
|
+
data = _json.loads(source)
|
|
2106
|
+
except (ValueError, RecursionError):
|
|
2107
|
+
return _build_fallback_result(
|
|
2108
|
+
file_path=file_path, language="json", source=source,
|
|
2109
|
+
reason="parse_error", confidence=0.10,
|
|
2110
|
+
parse_ok=False, generated_like=False,
|
|
2111
|
+
file_tokens_est=file_tokens_est, file_size_bytes=file_size_bytes,
|
|
2112
|
+
)
|
|
2113
|
+
|
|
2114
|
+
keys = _extract_json_keys(data, depth=0, max_depth=2, max_keys=MAX_JSON_KEYS)
|
|
2115
|
+
if not keys:
|
|
2116
|
+
return _build_fallback_result(
|
|
2117
|
+
file_path=file_path, language="json", source=source,
|
|
2118
|
+
reason="no_keys", confidence=0.15,
|
|
2119
|
+
parse_ok=True, generated_like=False,
|
|
2120
|
+
file_tokens_est=file_tokens_est, file_size_bytes=file_size_bytes,
|
|
2121
|
+
)
|
|
2122
|
+
|
|
2123
|
+
name = Path(file_path).name
|
|
2124
|
+
rendered = f"JSON structure for {name}:\n" + "\n".join(keys)
|
|
2125
|
+
cap = MAX_REPLACEMENT_CHARS_NON_CODE["key_tree"]
|
|
2126
|
+
if len(rendered) > cap:
|
|
2127
|
+
rendered = rendered[:cap - 3] + "..."
|
|
2128
|
+
|
|
2129
|
+
fp = _fingerprint(path=file_path, replacement_type="key_tree",
|
|
2130
|
+
rendered=rendered, line_count=line_count,
|
|
2131
|
+
file_size_bytes=file_size_bytes)
|
|
2132
|
+
return StructureMapResult(
|
|
2133
|
+
file_path=file_path, language="json",
|
|
2134
|
+
replacement_type="key_tree", replacement_text=rendered,
|
|
2135
|
+
replacement_tokens_est=estimate_tokens(rendered),
|
|
2136
|
+
confidence=0.92, fingerprint=fp, eligible=True,
|
|
2137
|
+
reason="ok", generated_like=False, parse_ok=True,
|
|
2138
|
+
line_count=line_count, file_tokens_est=file_tokens_est,
|
|
2139
|
+
file_size_bytes=file_size_bytes,
|
|
2140
|
+
)
|
|
2141
|
+
|
|
2142
|
+
|
|
2143
|
+
def _summarize_yaml(
|
|
2144
|
+
source: str, *, file_path: str, line_count: int,
|
|
2145
|
+
file_tokens_est: Optional[int], file_size_bytes: Optional[int],
|
|
2146
|
+
) -> StructureMapResult:
|
|
2147
|
+
lines = source.splitlines()
|
|
2148
|
+
indent_unit = 2
|
|
2149
|
+
for ln in lines:
|
|
2150
|
+
if ln and ln[0] == " ":
|
|
2151
|
+
spaces = len(ln) - len(ln.lstrip())
|
|
2152
|
+
if spaces > 0:
|
|
2153
|
+
indent_unit = spaces
|
|
2154
|
+
break
|
|
2155
|
+
|
|
2156
|
+
keys: list[str] = []
|
|
2157
|
+
for line in lines:
|
|
2158
|
+
stripped = line.rstrip()
|
|
2159
|
+
if not stripped or stripped.lstrip().startswith("#"):
|
|
2160
|
+
continue
|
|
2161
|
+
indent = len(line) - len(line.lstrip())
|
|
2162
|
+
depth = indent // max(indent_unit, 1)
|
|
2163
|
+
if depth <= 2 and ":" in stripped:
|
|
2164
|
+
key_part = stripped.split(":")[0].strip().lstrip("- ")
|
|
2165
|
+
if key_part and not key_part.startswith("#"):
|
|
2166
|
+
keys.append(f"{' ' * depth}{key_part}")
|
|
2167
|
+
if len(keys) >= MAX_NON_CODE_KEYS:
|
|
2168
|
+
break
|
|
2169
|
+
|
|
2170
|
+
if not keys:
|
|
2171
|
+
return _build_fallback_result(
|
|
2172
|
+
file_path=file_path, language="yaml", source=source,
|
|
2173
|
+
reason="no_keys", confidence=0.15,
|
|
2174
|
+
parse_ok=False, generated_like=False,
|
|
2175
|
+
file_tokens_est=file_tokens_est, file_size_bytes=file_size_bytes,
|
|
2176
|
+
)
|
|
2177
|
+
|
|
2178
|
+
name = Path(file_path).name
|
|
2179
|
+
rendered = f"YAML key tree for {name} ({line_count} lines):\n" + "\n".join(keys)
|
|
2180
|
+
cap = MAX_REPLACEMENT_CHARS_NON_CODE["key_tree"]
|
|
2181
|
+
if len(rendered) > cap:
|
|
2182
|
+
rendered = rendered[:cap - 3] + "..."
|
|
2183
|
+
|
|
2184
|
+
fp = _fingerprint(path=file_path, replacement_type="key_tree",
|
|
2185
|
+
rendered=rendered, line_count=line_count,
|
|
2186
|
+
file_size_bytes=file_size_bytes)
|
|
2187
|
+
return StructureMapResult(
|
|
2188
|
+
file_path=file_path, language="yaml",
|
|
2189
|
+
replacement_type="key_tree", replacement_text=rendered,
|
|
2190
|
+
replacement_tokens_est=estimate_tokens(rendered),
|
|
2191
|
+
confidence=0.85, fingerprint=fp, eligible=True,
|
|
2192
|
+
reason="ok", generated_like=False, parse_ok=True,
|
|
2193
|
+
line_count=line_count, file_tokens_est=file_tokens_est,
|
|
2194
|
+
file_size_bytes=file_size_bytes,
|
|
2195
|
+
)
|
|
2196
|
+
|
|
2197
|
+
|
|
2198
|
+
def _summarize_toml(
|
|
2199
|
+
source: str, *, file_path: str, line_count: int,
|
|
2200
|
+
file_tokens_est: Optional[int], file_size_bytes: Optional[int],
|
|
2201
|
+
) -> StructureMapResult:
|
|
2202
|
+
sections: list[str] = []
|
|
2203
|
+
top_keys: list[str] = []
|
|
2204
|
+
for line in source.splitlines():
|
|
2205
|
+
stripped = line.strip()
|
|
2206
|
+
if stripped.startswith("[") and stripped.endswith("]"):
|
|
2207
|
+
sections.append(stripped)
|
|
2208
|
+
elif "=" in stripped and not stripped.startswith("#"):
|
|
2209
|
+
key = stripped.split("=")[0].strip()
|
|
2210
|
+
if key and len(top_keys) < 15:
|
|
2211
|
+
top_keys.append(key)
|
|
2212
|
+
|
|
2213
|
+
if not sections and not top_keys:
|
|
2214
|
+
return _build_fallback_result(
|
|
2215
|
+
file_path=file_path, language="toml", source=source,
|
|
2216
|
+
reason="no_structure", confidence=0.15,
|
|
2217
|
+
parse_ok=False, generated_like=False,
|
|
2218
|
+
file_tokens_est=file_tokens_est, file_size_bytes=file_size_bytes,
|
|
2219
|
+
)
|
|
2220
|
+
|
|
2221
|
+
name = Path(file_path).name
|
|
2222
|
+
parts = [f"TOML structure for {name} ({line_count} lines):"]
|
|
2223
|
+
if sections:
|
|
2224
|
+
parts.append("Sections:")
|
|
2225
|
+
parts.extend(f" {s}" for s in sections[:15])
|
|
2226
|
+
if len(sections) > 15:
|
|
2227
|
+
parts.append(f" ... ({len(sections) - 15} more)")
|
|
2228
|
+
if top_keys:
|
|
2229
|
+
parts.append("Top-level keys:")
|
|
2230
|
+
parts.extend(f" {k}" for k in top_keys)
|
|
2231
|
+
|
|
2232
|
+
rendered = "\n".join(parts)
|
|
2233
|
+
cap = MAX_REPLACEMENT_CHARS_NON_CODE["section_list"]
|
|
2234
|
+
if len(rendered) > cap:
|
|
2235
|
+
rendered = rendered[:cap - 3] + "..."
|
|
2236
|
+
|
|
2237
|
+
fp = _fingerprint(path=file_path, replacement_type="section_list",
|
|
2238
|
+
rendered=rendered, line_count=line_count,
|
|
2239
|
+
file_size_bytes=file_size_bytes)
|
|
2240
|
+
return StructureMapResult(
|
|
2241
|
+
file_path=file_path, language="toml",
|
|
2242
|
+
replacement_type="section_list", replacement_text=rendered,
|
|
2243
|
+
replacement_tokens_est=estimate_tokens(rendered),
|
|
2244
|
+
confidence=0.88, fingerprint=fp, eligible=True,
|
|
2245
|
+
reason="ok", generated_like=False, parse_ok=True,
|
|
2246
|
+
line_count=line_count, file_tokens_est=file_tokens_est,
|
|
2247
|
+
file_size_bytes=file_size_bytes,
|
|
2248
|
+
)
|
|
2249
|
+
|
|
2250
|
+
|
|
2251
|
+
def _build_fallback_result(
|
|
2252
|
+
*,
|
|
2253
|
+
file_path: str,
|
|
2254
|
+
language: str,
|
|
2255
|
+
source: str,
|
|
2256
|
+
reason: str,
|
|
2257
|
+
confidence: float,
|
|
2258
|
+
parse_ok: bool,
|
|
2259
|
+
generated_like: bool,
|
|
2260
|
+
file_tokens_est: Optional[int],
|
|
2261
|
+
file_size_bytes: Optional[int],
|
|
2262
|
+
) -> StructureMapResult:
|
|
2263
|
+
line_count = source.count("\n") + (1 if source else 0)
|
|
2264
|
+
rendered = _render_digest(source=source, file_path=file_path, line_count=line_count)
|
|
2265
|
+
fingerprint = _fingerprint(
|
|
2266
|
+
path=file_path,
|
|
2267
|
+
replacement_type="digest",
|
|
2268
|
+
rendered=rendered,
|
|
2269
|
+
line_count=line_count,
|
|
2270
|
+
file_size_bytes=file_size_bytes,
|
|
2271
|
+
)
|
|
2272
|
+
return StructureMapResult(
|
|
2273
|
+
file_path=file_path,
|
|
2274
|
+
language=language,
|
|
2275
|
+
replacement_type="digest",
|
|
2276
|
+
replacement_text=rendered,
|
|
2277
|
+
replacement_tokens_est=estimate_tokens(rendered),
|
|
2278
|
+
confidence=max(0.05, min(1.0, confidence)),
|
|
2279
|
+
fingerprint=fingerprint,
|
|
2280
|
+
eligible=False,
|
|
2281
|
+
reason=reason,
|
|
2282
|
+
generated_like=generated_like,
|
|
2283
|
+
parse_ok=parse_ok,
|
|
2284
|
+
line_count=line_count,
|
|
2285
|
+
file_tokens_est=file_tokens_est,
|
|
2286
|
+
file_size_bytes=file_size_bytes,
|
|
2287
|
+
)
|
|
2288
|
+
|
|
2289
|
+
|
|
2290
|
+
def _render_digest(*, source: str, file_path: str, line_count: int) -> str:
|
|
2291
|
+
lines = source.splitlines()
|
|
2292
|
+
if not lines:
|
|
2293
|
+
return f"digest fallback for {Path(file_path).name or file_path}\nlines: 0"
|
|
2294
|
+
|
|
2295
|
+
non_empty = [line.rstrip() for line in lines if line.strip()]
|
|
2296
|
+
head = non_empty[:MAX_DIGEST_HEAD_LINES]
|
|
2297
|
+
tail = non_empty[-MAX_DIGEST_TAIL_LINES:] if len(non_empty) > MAX_DIGEST_HEAD_LINES + MAX_DIGEST_TAIL_LINES else []
|
|
2298
|
+
|
|
2299
|
+
parts = [f"digest fallback for {Path(file_path).name or file_path}", f"lines: {line_count}"]
|
|
2300
|
+
if head:
|
|
2301
|
+
parts.append("head:")
|
|
2302
|
+
parts.extend(f" - {line[:160]}" for line in head)
|
|
2303
|
+
if tail:
|
|
2304
|
+
parts.append("tail:")
|
|
2305
|
+
parts.extend(f" - {line[:160]}" for line in tail)
|
|
2306
|
+
|
|
2307
|
+
rendered = "\n".join(parts)
|
|
2308
|
+
cap = MAX_REPLACEMENT_CHARS["digest"]
|
|
2309
|
+
if len(rendered) <= cap:
|
|
2310
|
+
return rendered
|
|
2311
|
+
return rendered[: max(0, cap - 1)] + "…"
|
|
2312
|
+
|
|
2313
|
+
|
|
2314
|
+
def _choose_replacement_type(
|
|
2315
|
+
*,
|
|
2316
|
+
file_tokens_est: int,
|
|
2317
|
+
line_count: int,
|
|
2318
|
+
class_count: int,
|
|
2319
|
+
function_count: int,
|
|
2320
|
+
assignment_count: int,
|
|
2321
|
+
method_count: int,
|
|
2322
|
+
) -> str:
|
|
2323
|
+
total_symbols = class_count + function_count + assignment_count
|
|
2324
|
+
has_classes = class_count > 0
|
|
2325
|
+
has_methods = method_count > 0
|
|
2326
|
+
large_file = file_tokens_est >= 3500 or line_count >= 900 or total_symbols >= 18
|
|
2327
|
+
moderate_file = file_tokens_est >= 1500 or line_count >= 220 or total_symbols >= 8
|
|
2328
|
+
|
|
2329
|
+
if has_classes and has_methods and moderate_file:
|
|
2330
|
+
return "skeleton"
|
|
2331
|
+
if large_file:
|
|
2332
|
+
return "signatures"
|
|
2333
|
+
if total_symbols <= 6 and line_count <= 180:
|
|
2334
|
+
return "top_level"
|
|
2335
|
+
if has_classes and moderate_file:
|
|
2336
|
+
return "skeleton"
|
|
2337
|
+
if total_symbols <= 12:
|
|
2338
|
+
return "top_level"
|
|
2339
|
+
return "signatures"
|
|
2340
|
+
|
|
2341
|
+
|
|
2342
|
+
def _shrink_or_fallback(
|
|
2343
|
+
*,
|
|
2344
|
+
path: str,
|
|
2345
|
+
line_count: int,
|
|
2346
|
+
module_docstring: Optional[str],
|
|
2347
|
+
imports: Sequence[str],
|
|
2348
|
+
classes: Sequence[_ClassSummary],
|
|
2349
|
+
functions: Sequence[_FunctionSummary],
|
|
2350
|
+
assignments: Sequence[str],
|
|
2351
|
+
preferred: str,
|
|
2352
|
+
ranking: Optional[dict] = None,
|
|
2353
|
+
) -> Tuple[str, str]:
|
|
2354
|
+
order = {
|
|
2355
|
+
"skeleton": ["skeleton", "top_level", "signatures", "digest"],
|
|
2356
|
+
"top_level": ["top_level", "signatures", "digest"],
|
|
2357
|
+
"signatures": ["signatures", "top_level", "digest"],
|
|
2358
|
+
"digest": ["digest"],
|
|
2359
|
+
}.get(preferred, ["digest"])
|
|
2360
|
+
|
|
2361
|
+
for replacement_type in order:
|
|
2362
|
+
rendered = _render_candidate(
|
|
2363
|
+
replacement_type,
|
|
2364
|
+
path=path,
|
|
2365
|
+
line_count=line_count,
|
|
2366
|
+
module_docstring=module_docstring,
|
|
2367
|
+
imports=imports,
|
|
2368
|
+
classes=classes,
|
|
2369
|
+
functions=functions,
|
|
2370
|
+
assignments=assignments,
|
|
2371
|
+
ranking=ranking,
|
|
2372
|
+
)
|
|
2373
|
+
if len(rendered) <= MAX_REPLACEMENT_CHARS[replacement_type]:
|
|
2374
|
+
return rendered, replacement_type
|
|
2375
|
+
|
|
2376
|
+
rendered = _render_digest_lines(path=path, line_count=line_count)
|
|
2377
|
+
return "\n".join(rendered), "digest"
|
|
2378
|
+
|
|
2379
|
+
|
|
2380
|
+
def _score_confidence(
|
|
2381
|
+
*,
|
|
2382
|
+
replacement_type: str,
|
|
2383
|
+
line_count: int,
|
|
2384
|
+
file_tokens_est: int,
|
|
2385
|
+
class_count: int,
|
|
2386
|
+
function_count: int,
|
|
2387
|
+
method_count: int,
|
|
2388
|
+
rendered_len: int,
|
|
2389
|
+
parse_ok: bool,
|
|
2390
|
+
generated_like: bool,
|
|
2391
|
+
) -> float:
|
|
2392
|
+
base = {
|
|
2393
|
+
"skeleton": 0.90,
|
|
2394
|
+
"top_level": 0.94,
|
|
2395
|
+
"signatures": 0.86,
|
|
2396
|
+
"digest": 0.28,
|
|
2397
|
+
}.get(replacement_type, 0.35)
|
|
2398
|
+
|
|
2399
|
+
if parse_ok:
|
|
2400
|
+
base += 0.02
|
|
2401
|
+
if generated_like:
|
|
2402
|
+
base -= 0.20
|
|
2403
|
+
if file_tokens_est >= 4000:
|
|
2404
|
+
base -= 0.05
|
|
2405
|
+
if line_count >= 1200:
|
|
2406
|
+
base -= 0.05
|
|
2407
|
+
if class_count >= 3:
|
|
2408
|
+
base -= 0.03
|
|
2409
|
+
if method_count >= 8:
|
|
2410
|
+
base -= 0.04
|
|
2411
|
+
if function_count >= 12:
|
|
2412
|
+
base -= 0.03
|
|
2413
|
+
if rendered_len >= MAX_REPLACEMENT_CHARS.get(replacement_type, rendered_len):
|
|
2414
|
+
base -= 0.04
|
|
2415
|
+
|
|
2416
|
+
return round(max(0.05, min(0.98, base)), 3)
|
|
2417
|
+
|
|
2418
|
+
|
|
2419
|
+
def _fingerprint(
|
|
2420
|
+
*,
|
|
2421
|
+
path: str,
|
|
2422
|
+
replacement_type: str,
|
|
2423
|
+
rendered: str,
|
|
2424
|
+
line_count: int,
|
|
2425
|
+
file_size_bytes: Optional[int],
|
|
2426
|
+
) -> str:
|
|
2427
|
+
payload = "\n".join(
|
|
2428
|
+
[
|
|
2429
|
+
"structure-map-v1",
|
|
2430
|
+
replacement_type,
|
|
2431
|
+
path,
|
|
2432
|
+
str(line_count),
|
|
2433
|
+
str(file_size_bytes or 0),
|
|
2434
|
+
rendered,
|
|
2435
|
+
]
|
|
2436
|
+
)
|
|
2437
|
+
return hashlib.sha256(payload.encode("utf-8", errors="ignore")).hexdigest()
|
|
2438
|
+
|
|
2439
|
+
|
|
2440
|
+
def _short_docstring(docstring: Optional[str]) -> str:
|
|
2441
|
+
if not docstring:
|
|
2442
|
+
return ""
|
|
2443
|
+
compact = " ".join(docstring.strip().split())
|
|
2444
|
+
if len(compact) <= MAX_DOCSTRING_CHARS:
|
|
2445
|
+
return compact
|
|
2446
|
+
return compact[: MAX_DOCSTRING_CHARS - 1] + "…"
|
|
2447
|
+
|
|
2448
|
+
|
|
2449
|
+
def _shorten_list(items: Sequence, limit: int) -> List:
|
|
2450
|
+
if len(items) <= limit:
|
|
2451
|
+
return list(items)
|
|
2452
|
+
return list(items[:limit])
|
|
2453
|
+
|
|
2454
|
+
|
|
2455
|
+
def _flatten_targets(node: ast.AST) -> List[str]:
|
|
2456
|
+
names: List[str] = []
|
|
2457
|
+
if isinstance(node, ast.Name):
|
|
2458
|
+
names.append(node.id)
|
|
2459
|
+
elif isinstance(node, (ast.Tuple, ast.List)):
|
|
2460
|
+
for child in node.elts:
|
|
2461
|
+
names.extend(_flatten_targets(child))
|
|
2462
|
+
elif isinstance(node, ast.Attribute):
|
|
2463
|
+
names.append(_render_expr(node))
|
|
2464
|
+
return names
|
|
2465
|
+
|
|
2466
|
+
|
|
2467
|
+
def _is_public_symbol(name: str) -> bool:
|
|
2468
|
+
if name == "__all__":
|
|
2469
|
+
return True
|
|
2470
|
+
return not name.startswith("_")
|
|
2471
|
+
|
|
2472
|
+
|
|
2473
|
+
# ---------------------------------------------------------------------------
|
|
2474
|
+
# structure_map v2 — periphery reference graph + one-hop relationships
|
|
2475
|
+
#
|
|
2476
|
+
# On-read only. Nothing here writes to disk: the reference graph is derived
|
|
2477
|
+
# from a single file's AST/source and dropped after the hook returns. One-hop
|
|
2478
|
+
# edges are resolved against the filesystem at read time and bounded by
|
|
2479
|
+
# PERIPHERY_MAX_RELATIONS so the hot path never reads an unbounded fan-out.
|
|
2480
|
+
# ---------------------------------------------------------------------------
|
|
2481
|
+
|
|
2482
|
+
PERIPHERY_MAX_RELATIONS = 8
|
|
2483
|
+
PERIPHERY_MAX_FILES = 5
|
|
2484
|
+
PERIPHERY_BUDGET_CHARS = 1200
|
|
2485
|
+
|
|
2486
|
+
_MODULE_NODE = "<module>"
|
|
2487
|
+
|
|
2488
|
+
# Relative JS/TS import specifiers we resolve one hop out (bare module imports
|
|
2489
|
+
# like `react` are not filesystem-resolvable without a node_modules walk, which
|
|
2490
|
+
# would violate the no-subprocess/no-resident-store constraint, so they are
|
|
2491
|
+
# skipped).
|
|
2492
|
+
_JS_TS_FROM_SPEC_RE = re.compile(r"""from\s+['"]([^'"]+)['"]""")
|
|
2493
|
+
_JS_TS_SIDE_EFFECT_IMPORT_RE = re.compile(r"""import\s+['"]([^'"]+)['"]""")
|
|
2494
|
+
_JS_TS_EXT_PROBE = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts")
|
|
2495
|
+
_JS_TS_INDEX_PROBE = ("index.ts", "index.js", "index.mjs", "index.cjs", "index.mts", "index.cts")
|
|
2496
|
+
|
|
2497
|
+
|
|
2498
|
+
def _call_target_name(func: ast.AST) -> Optional[str]:
|
|
2499
|
+
"""Resolve an ast.Call func to a bare symbol name for the reference graph."""
|
|
2500
|
+
if isinstance(func, ast.Name):
|
|
2501
|
+
return func.id
|
|
2502
|
+
if isinstance(func, ast.Attribute):
|
|
2503
|
+
return func.attr
|
|
2504
|
+
return None
|
|
2505
|
+
|
|
2506
|
+
|
|
2507
|
+
def _collect_direct_calls(
|
|
2508
|
+
node: ast.AST,
|
|
2509
|
+
caller: str,
|
|
2510
|
+
edges: List[Tuple[str, str]],
|
|
2511
|
+
defined: set,
|
|
2512
|
+
) -> None:
|
|
2513
|
+
"""Collect Call edges inside ``node``'s body, NOT descending into nested
|
|
2514
|
+
def/class scopes (those get their own caller via _walk_scopes)."""
|
|
2515
|
+
for child in ast.iter_child_nodes(node):
|
|
2516
|
+
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
2517
|
+
continue
|
|
2518
|
+
if isinstance(child, ast.Call):
|
|
2519
|
+
name = _call_target_name(child.func)
|
|
2520
|
+
if name and name in defined:
|
|
2521
|
+
edges.append((caller, name))
|
|
2522
|
+
_collect_direct_calls(child, caller, edges, defined)
|
|
2523
|
+
|
|
2524
|
+
|
|
2525
|
+
def _walk_scopes(
|
|
2526
|
+
node: ast.AST,
|
|
2527
|
+
edges: List[Tuple[str, str]],
|
|
2528
|
+
defined: set,
|
|
2529
|
+
caller: str = _MODULE_NODE,
|
|
2530
|
+
) -> None:
|
|
2531
|
+
"""Scope-aware walk: each FunctionDef/ClassDef becomes its own caller scope."""
|
|
2532
|
+
_collect_direct_calls(node, caller, edges, defined)
|
|
2533
|
+
for child in ast.iter_child_nodes(node):
|
|
2534
|
+
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
2535
|
+
_walk_scopes(child, edges, defined, caller=child.name)
|
|
2536
|
+
|
|
2537
|
+
|
|
2538
|
+
def _extract_python_reference_graph(source: str, file_path: str) -> ReferenceGraph:
|
|
2539
|
+
try:
|
|
2540
|
+
tree = ast.parse(source, filename=file_path)
|
|
2541
|
+
except (SyntaxError, ValueError, RecursionError, MemoryError):
|
|
2542
|
+
return ReferenceGraph((), ())
|
|
2543
|
+
# fix-2: _walk_scopes/_collect_direct_calls recurse over the AST and can
|
|
2544
|
+
# hit RecursionError on a deeply-nested tree.
|
|
2545
|
+
# The reference graph only orders skeleton truncation, so any failure here
|
|
2546
|
+
# degrades to an empty graph (source order) rather than propagating.
|
|
2547
|
+
try:
|
|
2548
|
+
defined: set = set()
|
|
2549
|
+
for node in ast.walk(tree):
|
|
2550
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
2551
|
+
defined.add(node.name)
|
|
2552
|
+
edges: List[Tuple[str, str]] = []
|
|
2553
|
+
_walk_scopes(tree, edges, defined, caller=_MODULE_NODE)
|
|
2554
|
+
except Exception:
|
|
2555
|
+
return ReferenceGraph((), ())
|
|
2556
|
+
nodes = sorted(defined | {_MODULE_NODE})
|
|
2557
|
+
return ReferenceGraph(tuple(nodes), tuple(edges))
|
|
2558
|
+
|
|
2559
|
+
|
|
2560
|
+
def extract_reference_graph(
|
|
2561
|
+
source: str,
|
|
2562
|
+
language: Optional[str] = None,
|
|
2563
|
+
file_path: str = "memory",
|
|
2564
|
+
) -> ReferenceGraph:
|
|
2565
|
+
"""Extract the intra-file symbol reference graph.
|
|
2566
|
+
|
|
2567
|
+
Nodes are the file's defined symbols plus ``<module>``; edges are directed
|
|
2568
|
+
``(caller, callee)`` references. Pure stdlib, deterministic, no I/O. For
|
|
2569
|
+
unsupported languages returns an empty graph (callers fall back to source
|
|
2570
|
+
order). Used by ``pagerank_symbols`` to order skeleton symbol
|
|
2571
|
+
selection by reference centrality.
|
|
2572
|
+
|
|
2573
|
+
Only Python centrality ordering is wired into the summarizer
|
|
2574
|
+
(``summarize_python_source``). The JS/TS regex-based graph builder was
|
|
2575
|
+
never consumed by any caller -- the JS/TS render path does not thread a
|
|
2576
|
+
ranking -- so it was removed rather than left as dead code (fix, LOW). JS/TS
|
|
2577
|
+
(and every other language) returns an empty graph here.
|
|
2578
|
+
"""
|
|
2579
|
+
lang = (language or detect_structure_language(file_path)).lower()
|
|
2580
|
+
if lang == "python":
|
|
2581
|
+
return _extract_python_reference_graph(source, file_path)
|
|
2582
|
+
return ReferenceGraph((), ())
|
|
2583
|
+
|
|
2584
|
+
|
|
2585
|
+
def _python_search_roots(target: Path) -> List[Path]:
|
|
2586
|
+
"""Filesystem roots for absolute Python import resolution: the target's
|
|
2587
|
+
directory, the cwd, and any ``src/`` ancestor (src-layout packages)."""
|
|
2588
|
+
roots: List[Path] = [target.parent, Path.cwd()]
|
|
2589
|
+
for parent in target.parents:
|
|
2590
|
+
if parent.name == "src":
|
|
2591
|
+
roots.append(parent)
|
|
2592
|
+
# Dedupe preserving order.
|
|
2593
|
+
seen: set = set()
|
|
2594
|
+
out: List[Path] = []
|
|
2595
|
+
for r in roots:
|
|
2596
|
+
rp = str(r.resolve())
|
|
2597
|
+
if rp not in seen:
|
|
2598
|
+
seen.add(rp)
|
|
2599
|
+
out.append(r)
|
|
2600
|
+
return out
|
|
2601
|
+
|
|
2602
|
+
|
|
2603
|
+
def _module_to_file_candidates(module_dotted: str, base: Path) -> List[Path]:
|
|
2604
|
+
parts = [p for p in module_dotted.split(".") if p]
|
|
2605
|
+
if not parts:
|
|
2606
|
+
return []
|
|
2607
|
+
b = base.joinpath(*parts)
|
|
2608
|
+
return [b.with_suffix(".py"), b / "__init__.py"]
|
|
2609
|
+
|
|
2610
|
+
|
|
2611
|
+
def _resolve_python_one_hop(target: Path, content: Optional[str] = None) -> List[Path]:
|
|
2612
|
+
try:
|
|
2613
|
+
# Reuse the caller's already-in-memory source when provided (hot path:
|
|
2614
|
+
# the just-read target), avoiding a second read+parse of the same file.
|
|
2615
|
+
source = content if content is not None else target.read_text(
|
|
2616
|
+
encoding="utf-8", errors="replace"
|
|
2617
|
+
)
|
|
2618
|
+
tree = ast.parse(source, filename=str(target))
|
|
2619
|
+
except (SyntaxError, ValueError, RecursionError, MemoryError, OSError):
|
|
2620
|
+
return []
|
|
2621
|
+
roots = _python_search_roots(target)
|
|
2622
|
+
out: List[Path] = []
|
|
2623
|
+
for node in tree.body:
|
|
2624
|
+
if isinstance(node, ast.Import):
|
|
2625
|
+
for alias in node.names:
|
|
2626
|
+
for root in roots:
|
|
2627
|
+
out.extend(_module_to_file_candidates(alias.name, root))
|
|
2628
|
+
elif isinstance(node, ast.ImportFrom):
|
|
2629
|
+
if node.level and node.level > 0:
|
|
2630
|
+
base = target.parent
|
|
2631
|
+
for _ in range(max(0, node.level - 1)):
|
|
2632
|
+
base = base.parent
|
|
2633
|
+
if node.module:
|
|
2634
|
+
out.extend(_module_to_file_candidates(node.module, base))
|
|
2635
|
+
else:
|
|
2636
|
+
for alias in node.names:
|
|
2637
|
+
out.extend(_module_to_file_candidates(alias.name, base))
|
|
2638
|
+
elif node.module:
|
|
2639
|
+
for root in roots:
|
|
2640
|
+
out.extend(_module_to_file_candidates(node.module, root))
|
|
2641
|
+
return out
|
|
2642
|
+
|
|
2643
|
+
|
|
2644
|
+
def _resolve_js_ts_spec(spec: str, base_dir: Path) -> List[Path]:
|
|
2645
|
+
target_path = base_dir / spec
|
|
2646
|
+
if target_path.suffix.lower() in JS_TS_SUFFIXES:
|
|
2647
|
+
return [target_path]
|
|
2648
|
+
cands: List[Path] = [target_path.with_suffix(ext) for ext in _JS_TS_EXT_PROBE]
|
|
2649
|
+
cands.extend(target_path / idx for idx in _JS_TS_INDEX_PROBE)
|
|
2650
|
+
return cands
|
|
2651
|
+
|
|
2652
|
+
|
|
2653
|
+
def _resolve_js_ts_one_hop(target: Path, content: Optional[str] = None) -> List[Path]:
|
|
2654
|
+
try:
|
|
2655
|
+
source = content if content is not None else target.read_text(
|
|
2656
|
+
encoding="utf-8", errors="replace"
|
|
2657
|
+
)
|
|
2658
|
+
except OSError:
|
|
2659
|
+
return []
|
|
2660
|
+
raw_lines = source.splitlines()
|
|
2661
|
+
clean_lines = _strip_js_ts_comments_and_strings(source).splitlines()
|
|
2662
|
+
specs: List[str] = []
|
|
2663
|
+
for raw, clean_line in zip(raw_lines, clean_lines):
|
|
2664
|
+
cs = clean_line.strip()
|
|
2665
|
+
if not cs or not JS_TS_IMPORT_RE.match(cs):
|
|
2666
|
+
# Only resolve real import statements (the clean line gates out
|
|
2667
|
+
# commented-out imports); the specifier itself lives in a string
|
|
2668
|
+
# literal that the stripper blanks, so extract from the raw line.
|
|
2669
|
+
continue
|
|
2670
|
+
for rx in (_JS_TS_FROM_SPEC_RE, _JS_TS_SIDE_EFFECT_IMPORT_RE):
|
|
2671
|
+
for m in rx.finditer(raw):
|
|
2672
|
+
spec = m.group(1)
|
|
2673
|
+
if spec.startswith("."):
|
|
2674
|
+
specs.append(spec)
|
|
2675
|
+
base_dir = target.parent
|
|
2676
|
+
out: List[Path] = []
|
|
2677
|
+
for spec in specs:
|
|
2678
|
+
out.extend(_resolve_js_ts_spec(spec, base_dir))
|
|
2679
|
+
return out
|
|
2680
|
+
|
|
2681
|
+
|
|
2682
|
+
def _is_periphery_eligible(path: Path, target: Optional[Path] = None) -> bool:
|
|
2683
|
+
"""A periphery file worth skeletonizing: real, code/text-supported, under
|
|
2684
|
+
the AST cap, and not the target itself."""
|
|
2685
|
+
try:
|
|
2686
|
+
if not path.is_file():
|
|
2687
|
+
return False
|
|
2688
|
+
if target is not None and path.resolve() == target.resolve():
|
|
2689
|
+
return False
|
|
2690
|
+
if not is_structure_supported_file(path):
|
|
2691
|
+
return False
|
|
2692
|
+
if path.stat().st_size > MAX_AST_BYTES:
|
|
2693
|
+
return False
|
|
2694
|
+
return True
|
|
2695
|
+
except OSError:
|
|
2696
|
+
return False
|
|
2697
|
+
|
|
2698
|
+
|
|
2699
|
+
def resolve_one_hop_relationships(
|
|
2700
|
+
file_path: str | os.PathLike[str],
|
|
2701
|
+
language: Optional[str] = None,
|
|
2702
|
+
*,
|
|
2703
|
+
limit: int = PERIPHERY_MAX_RELATIONS,
|
|
2704
|
+
content: Optional[str] = None,
|
|
2705
|
+
) -> List[str]:
|
|
2706
|
+
"""Resolve one-hop call/import edges to candidate file paths at read time
|
|
2707
|
+
No result is written to disk. Bounded to ``limit`` paths; skips
|
|
2708
|
+
missing/binary/oversized paths and the target itself. One hop only -- no
|
|
2709
|
+
transitive closure.
|
|
2710
|
+
|
|
2711
|
+
``content`` (optional): the target's already-in-memory source. When the
|
|
2712
|
+
caller has it (the just-read target on the hot path), it is threaded through
|
|
2713
|
+
so the target is not re-read/re-parsed from disk.
|
|
2714
|
+
"""
|
|
2715
|
+
p = Path(str(file_path))
|
|
2716
|
+
lang = (language or detect_structure_language(p)).lower()
|
|
2717
|
+
try:
|
|
2718
|
+
if lang == "python":
|
|
2719
|
+
raw = _resolve_python_one_hop(p, content=content)
|
|
2720
|
+
elif lang in ("javascript", "typescript"):
|
|
2721
|
+
raw = _resolve_js_ts_one_hop(p, content=content)
|
|
2722
|
+
else:
|
|
2723
|
+
raw = []
|
|
2724
|
+
seen: set = set()
|
|
2725
|
+
out: List[str] = []
|
|
2726
|
+
for cand in raw:
|
|
2727
|
+
try:
|
|
2728
|
+
resolved = str(cand.resolve())
|
|
2729
|
+
except OSError:
|
|
2730
|
+
continue
|
|
2731
|
+
if resolved in seen:
|
|
2732
|
+
continue
|
|
2733
|
+
seen.add(resolved)
|
|
2734
|
+
if _is_periphery_eligible(cand, target=p):
|
|
2735
|
+
out.append(str(cand))
|
|
2736
|
+
if len(out) >= limit:
|
|
2737
|
+
break
|
|
2738
|
+
return out
|
|
2739
|
+
except Exception:
|
|
2740
|
+
return []
|
|
2741
|
+
|
|
2742
|
+
|
|
2743
|
+
def build_periphery_skeleton(
|
|
2744
|
+
related_paths: Sequence[str],
|
|
2745
|
+
*,
|
|
2746
|
+
limit: int = PERIPHERY_MAX_FILES,
|
|
2747
|
+
budget: int = PERIPHERY_BUDGET_CHARS,
|
|
2748
|
+
) -> str:
|
|
2749
|
+
"""Build a bounded periphery skeleton block from resolved related files
|
|
2750
|
+
Reuses ``summarize_code_file`` so the skeleton format is identical
|
|
2751
|
+
to the existing one -- no new skeleton format. Capped by ``budget`` chars
|
|
2752
|
+
and ``limit`` files. Returns ``""`` when nothing fits or no paths resolve.
|
|
2753
|
+
Never raises.
|
|
2754
|
+
"""
|
|
2755
|
+
parts: List[str] = []
|
|
2756
|
+
total = 0
|
|
2757
|
+
count = 0
|
|
2758
|
+
for raw in related_paths:
|
|
2759
|
+
if count >= limit or total >= budget:
|
|
2760
|
+
break
|
|
2761
|
+
p = Path(raw)
|
|
2762
|
+
try:
|
|
2763
|
+
result = summarize_code_file(p)
|
|
2764
|
+
except Exception:
|
|
2765
|
+
continue
|
|
2766
|
+
if not result.replacement_text:
|
|
2767
|
+
continue
|
|
2768
|
+
chunk = f"# periphery: {p.name} ({result.replacement_type})\n{result.replacement_text}"
|
|
2769
|
+
if total + len(chunk) > budget:
|
|
2770
|
+
break
|
|
2771
|
+
parts.append(chunk)
|
|
2772
|
+
total += len(chunk)
|
|
2773
|
+
count += 1
|
|
2774
|
+
return "\n\n".join(parts)
|
|
2775
|
+
|
|
2776
|
+
|
|
2777
|
+
# ---------------------------------------------------------------------------
|
|
2778
|
+
# PageRank symbol ranking for skeleton selection
|
|
2779
|
+
#
|
|
2780
|
+
# Pure stdlib, deterministic, no network. Ranks a file's symbols by reference
|
|
2781
|
+
# centrality so skeleton truncation keeps the most-referenced symbols instead
|
|
2782
|
+
# of the first-N-by-source-order. Capped iterations/node count for hot-path
|
|
2783
|
+
# latency. When no graph is available the ranking is empty and callers keep
|
|
2784
|
+
# source order unchanged.
|
|
2785
|
+
# ---------------------------------------------------------------------------
|
|
2786
|
+
|
|
2787
|
+
_PAGERANK_MAX_NODES = 5000
|
|
2788
|
+
_PAGERANK_MAX_ITERATIONS = 50
|
|
2789
|
+
|
|
2790
|
+
|
|
2791
|
+
def pagerank_symbols(
|
|
2792
|
+
graph: ReferenceGraph,
|
|
2793
|
+
damping: float = 0.85,
|
|
2794
|
+
iterations: int = _PAGERANK_MAX_ITERATIONS,
|
|
2795
|
+
) -> dict:
|
|
2796
|
+
"""Run standard PageRank over the intra-file reference graph; return a
|
|
2797
|
+
mapping ``symbol -> centrality score``. Pure stdlib, deterministic. Caps
|
|
2798
|
+
iterations (<=50) and node count (<=5000) so the hot path never runs away
|
|
2799
|
+
on a large graph. An empty/degenerate graph returns a stable uniform
|
|
2800
|
+
ranking (or empty dict) without raising.
|
|
2801
|
+
"""
|
|
2802
|
+
nodes = list(graph.nodes)
|
|
2803
|
+
if not nodes:
|
|
2804
|
+
return {}
|
|
2805
|
+
n = len(nodes)
|
|
2806
|
+
if n > _PAGERANK_MAX_NODES:
|
|
2807
|
+
# Degenerate large graph: uniform ranking, no iteration.
|
|
2808
|
+
return {node: 1.0 / n for node in nodes}
|
|
2809
|
+
node_set = set(nodes)
|
|
2810
|
+
out_degree = {node: 0 for node in nodes}
|
|
2811
|
+
incoming: dict = {node: [] for node in nodes}
|
|
2812
|
+
for src, dst in graph.edges:
|
|
2813
|
+
if src in node_set and dst in node_set:
|
|
2814
|
+
out_degree[src] = out_degree.get(src, 0) + 1
|
|
2815
|
+
incoming[dst].append(src)
|
|
2816
|
+
score = {node: 1.0 / n for node in nodes}
|
|
2817
|
+
iters = max(1, min(iterations, _PAGERANK_MAX_ITERATIONS))
|
|
2818
|
+
for _ in range(iters):
|
|
2819
|
+
dangling_sum = sum(score[node] for node in nodes if out_degree[node] == 0)
|
|
2820
|
+
new_score = {}
|
|
2821
|
+
for node in nodes:
|
|
2822
|
+
rank = (1.0 - damping) / n
|
|
2823
|
+
in_sum = 0.0
|
|
2824
|
+
for src in incoming[node]:
|
|
2825
|
+
od = out_degree[src]
|
|
2826
|
+
if od > 0:
|
|
2827
|
+
in_sum += score[src] / od
|
|
2828
|
+
rank += damping * in_sum
|
|
2829
|
+
# Standard dangling-node redistribution: a node with no out-edges
|
|
2830
|
+
# distributes its score uniformly across all nodes.
|
|
2831
|
+
rank += damping * dangling_sum / n
|
|
2832
|
+
new_score[node] = rank
|
|
2833
|
+
score = new_score
|
|
2834
|
+
return score
|
|
2835
|
+
|
|
2836
|
+
|
|
2837
|
+
def _rank_sort(items: Sequence, ranking: Optional[dict]) -> List:
|
|
2838
|
+
"""Stable sort by descending centrality, ties broken by source order
|
|
2839
|
+
(``lineno``). Items with no centrality score (absent or 0) keep source
|
|
2840
|
+
order at the tail. ``ranking`` None/empty -> source order unchanged.
|
|
2841
|
+
"""
|
|
2842
|
+
if not ranking:
|
|
2843
|
+
return list(items)
|
|
2844
|
+
return sorted(
|
|
2845
|
+
items,
|
|
2846
|
+
key=lambda it: (
|
|
2847
|
+
-float(ranking.get(getattr(it, "name", ""), 0.0)),
|
|
2848
|
+
getattr(it, "lineno", 0),
|
|
2849
|
+
),
|
|
2850
|
+
)
|
|
2851
|
+
|
|
2852
|
+
|
|
2853
|
+
__all__ = [
|
|
2854
|
+
"PERIPHERY_BUDGET_CHARS",
|
|
2855
|
+
"PERIPHERY_MAX_FILES",
|
|
2856
|
+
"PERIPHERY_MAX_RELATIONS",
|
|
2857
|
+
"ReferenceGraph",
|
|
2858
|
+
"StructureMapResult",
|
|
2859
|
+
"build_periphery_skeleton",
|
|
2860
|
+
"detect_structure_language",
|
|
2861
|
+
"estimate_tokens",
|
|
2862
|
+
"extract_reference_graph",
|
|
2863
|
+
"is_js_ts_file",
|
|
2864
|
+
"is_python_file",
|
|
2865
|
+
"is_structure_supported_file",
|
|
2866
|
+
"looks_generated_js_ts",
|
|
2867
|
+
"looks_generated_python",
|
|
2868
|
+
"pagerank_symbols",
|
|
2869
|
+
"resolve_one_hop_relationships",
|
|
2870
|
+
"summarize_code_file",
|
|
2871
|
+
"summarize_code_source",
|
|
2872
|
+
"summarize_js_ts_source",
|
|
2873
|
+
"summarize_python_file",
|
|
2874
|
+
"summarize_python_source",
|
|
2875
|
+
]
|
|
2876
|
+
MAX_JS_TS_IMPORTS = 3
|
|
2877
|
+
MAX_JS_TS_SIGNATURE_ITEMS = 6
|
|
2878
|
+
MAX_JS_TS_TOP_LEVEL_SYMBOLS = 8
|
|
2879
|
+
MAX_JS_TS_SKELETON_FUNCTIONS = 5
|
|
2880
|
+
MAX_JS_TS_SKELETON_SYMBOLS = 4
|