tzero-mcp 11.0.0 → 11.12.1

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.
Files changed (126) hide show
  1. package/CHANGELOG.md +56 -56
  2. package/CONTRIBUTING.md +71 -71
  3. package/LICENSE +21 -21
  4. package/README.md +64 -64
  5. package/bin/tzero-mcp.js +62 -62
  6. package/bin/tzero.js +61 -61
  7. package/index.d.ts +25 -25
  8. package/index.js +15 -15
  9. package/package.json +89 -88
  10. package/src/addmcp.py +1203 -1197
  11. package/src/app.py +1810 -1810
  12. package/src/main.py +60 -60
  13. package/src/pc_fixer_mcp.py +25 -25
  14. package/src/tzero/__init__.py +54 -54
  15. package/src/tzero/__main__.py +6 -6
  16. package/src/tzero/siber_akademi_icon.py +77 -77
  17. package/src/tzero/tzero_arch_test.py +463 -463
  18. package/src/tzero/tzero_benchmark.py +475 -475
  19. package/src/tzero/tzero_blackboard.py +257 -257
  20. package/src/tzero/tzero_bridge.py +546 -546
  21. package/src/tzero/tzero_budget.py +195 -195
  22. package/src/tzero/tzero_card.py +431 -0
  23. package/src/tzero/tzero_ci.py +153 -153
  24. package/src/tzero/tzero_commit.py +192 -192
  25. package/src/tzero/tzero_contracts.py +1093 -1093
  26. package/src/tzero/tzero_cost.py +166 -166
  27. package/src/tzero/tzero_dashboard.py +1960 -1960
  28. package/src/tzero/tzero_debt.py +461 -461
  29. package/src/tzero/tzero_deps.py +462 -462
  30. package/src/tzero/tzero_drift.py +208 -208
  31. package/src/tzero/tzero_explain.py +306 -306
  32. package/src/tzero/tzero_features.py +3024 -3024
  33. package/src/tzero/tzero_federation.py +299 -299
  34. package/src/tzero/tzero_fix.py +557 -228
  35. package/src/tzero/tzero_fixer/__init__.py +63 -63
  36. package/src/tzero/tzero_fixer/amalgamation.py +334 -334
  37. package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
  38. package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
  39. package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
  40. package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
  41. package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
  42. package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
  43. package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
  44. package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
  45. package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
  46. package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
  47. package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
  48. package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
  49. package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
  50. package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
  51. package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
  52. package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
  53. package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
  54. package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
  55. package/src/tzero/tzero_fixer/mcp_server.py +489 -489
  56. package/src/tzero/tzero_fixer/models.py +385 -385
  57. package/src/tzero/tzero_fixer/orchestrator.py +375 -375
  58. package/src/tzero/tzero_fixer/os_doctor.py +502 -502
  59. package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
  60. package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
  61. package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
  62. package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
  63. package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
  64. package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
  65. package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
  66. package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
  67. package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
  68. package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
  69. package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
  70. package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
  71. package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
  72. package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
  73. package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
  74. package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
  75. package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
  76. package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
  77. package/src/tzero/tzero_golden.py +319 -319
  78. package/src/tzero/tzero_graph_hud.html +338 -338
  79. package/src/tzero/tzero_graph_rag.py +263 -263
  80. package/src/tzero/tzero_growth.py +415 -0
  81. package/src/tzero/tzero_guard.py +251 -243
  82. package/src/tzero/tzero_hooks.py +565 -565
  83. package/src/tzero/tzero_infra.py +274 -274
  84. package/src/tzero/tzero_jarvis/__init__.py +134 -124
  85. package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
  86. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  87. package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
  88. package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
  89. package/src/tzero/tzero_jarvis/latent_press.py +137 -137
  90. package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
  91. package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
  92. package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
  93. package/src/tzero/tzero_jarvis/self_healing.py +308 -308
  94. package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
  95. package/src/tzero/tzero_jarvis/swarm.py +261 -261
  96. package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
  97. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
  98. package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
  99. package/src/tzero/tzero_lsp.py +634 -634
  100. package/src/tzero/tzero_mcp.py +5314 -5237
  101. package/src/tzero/tzero_mutation.py +358 -358
  102. package/src/tzero/tzero_neural_cortex.py +1425 -1425
  103. package/src/tzero/tzero_packer.py +577 -577
  104. package/src/tzero/tzero_patch.py +624 -624
  105. package/src/tzero/tzero_pc_fixer.py +12699 -12699
  106. package/src/tzero/tzero_pipe.py +95 -95
  107. package/src/tzero/tzero_polyglot.py +799 -799
  108. package/src/tzero/tzero_proxy.py +127 -127
  109. package/src/tzero/tzero_reachability.py +272 -272
  110. package/src/tzero/tzero_replay.py +141 -141
  111. package/src/tzero/tzero_rust_bridge.py +198 -198
  112. package/src/tzero/tzero_scip.py +368 -368
  113. package/src/tzero/tzero_security.py +573 -573
  114. package/src/tzero/tzero_semantic_merge.py +189 -189
  115. package/src/tzero/tzero_snapshot.py +471 -471
  116. package/src/tzero/tzero_stubs.py +313 -313
  117. package/src/tzero/tzero_subagent_engine.py +459 -459
  118. package/src/tzero/tzero_superdesign.py +774 -774
  119. package/src/tzero/tzero_sync.py +241 -241
  120. package/src/tzero/tzero_task_benchmark.py +506 -458
  121. package/src/tzero/tzero_tui.py +313 -313
  122. package/src/tzero/tzero_turbo.py +264 -264
  123. package/src/tzero/tzero_v3.py +9997 -9900
  124. package/src/tzero.py +6 -6
  125. package/src/tzero_mcp.py +25 -0
  126. package/test/package.test.js +55 -55
@@ -1,577 +1,577 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- Siber Akademi — T-Zero Dynamic Context Window & Token Budget Packer.
4
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
- License: MIT
6
-
7
- Solves the context window packing problem for LLMs: packs an entire repository or
8
- focused subsystem into an EXACT token budget (e.g. 8k, 16k, 32k, 64k, 128k) using
9
- multi-tier AST representations (T-1 Raw, T-2 Light, T-3 Ultra, T-4 Signature) and
10
- greedy relevance-weighted knapsack optimization.
11
- """
12
-
13
- import sys
14
- if sys.platform == "win32":
15
- try:
16
- sys.stdout.reconfigure(encoding="utf-8")
17
- sys.stderr.reconfigure(encoding="utf-8")
18
- except Exception:
19
- pass
20
-
21
- import ast
22
- import io
23
- import os
24
- import re
25
- import math
26
- import hashlib
27
- import struct
28
- from dataclasses import dataclass, field
29
- from typing import Dict, List, Tuple, Optional, Any, Set
30
-
31
- from tzero.tzero_polyglot import PolyglotTokenReducer
32
- from tzero.tzero_features import should_skip_dir, get_ignore_patterns
33
-
34
-
35
- @dataclass(frozen=True)
36
- class SymbolContext:
37
- text: str
38
- source_tokens: int
39
- context_tokens: int
40
- encoding: str
41
-
42
- @property
43
- def reduction_pct(self) -> float:
44
- return 100 * (self.source_tokens - self.context_tokens) / self.source_tokens
45
-
46
-
47
- def pack_python_symbols(
48
- source: str, symbols: List[str], min_reduction: int = 95,
49
- encoding: str = "o200k_base",
50
- ) -> SymbolContext:
51
- """Extract complete Python definitions and enforce an exact BPE reduction floor."""
52
- if not symbols:
53
- raise ValueError("Select at least one Python definition")
54
- if not 0 <= min_reduction <= 100:
55
- raise ValueError("Minimum token reduction must be between 0 and 100")
56
- if encoding not in ("o200k_base", "cl100k_base"):
57
- raise ValueError("Use the o200k_base or cl100k_base encoding")
58
-
59
- requested = set(symbols)
60
- scopes = {".".join(name.split(".")[:depth])
61
- for name in requested for depth in range(1, name.count(".") + 1)}
62
- ranges: Dict[str, Tuple[int, int]] = {}
63
- definition_types = (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)
64
-
65
- def collect(node: ast.AST, scope: str = "") -> None:
66
- if isinstance(node, definition_types):
67
- scope = f"{scope}.{node.name}" if scope else node.name
68
- if scope in requested:
69
- if scope in ranges:
70
- raise ValueError(f"Ambiguous Python definition: {scope}")
71
- start = min([node.lineno] + [item.lineno for item in node.decorator_list])
72
- ranges[scope] = (start - 1, node.end_lineno)
73
- if scope not in scopes:
74
- return
75
- for child in ast.iter_child_nodes(node):
76
- collect(child, scope)
77
-
78
- collect(ast.parse(source))
79
- missing = requested - ranges.keys()
80
- if missing:
81
- raise ValueError(f"Python definitions not found: {', '.join(sorted(missing))}")
82
-
83
- # AST line numbers recognize CR, CRLF, and LF. Preserve those original endings.
84
- lines = io.StringIO(source, newline="").readlines()
85
- segments = []
86
- previous_end = 0
87
- for start, end in sorted(ranges.values()):
88
- segments.extend(lines[max(start, previous_end):end])
89
- previous_end = max(previous_end, end)
90
- context = "".join(segments)
91
-
92
- from tzero.tzero_security import ZeroLeakEngine
93
-
94
- if ZeroLeakEngine.scan_text(context):
95
- raise ValueError("Selected source contains a potential secret")
96
- try:
97
- import tiktoken
98
- except ImportError as exc:
99
- raise ValueError("Exact token measurement requires the optional tiktoken package") from exc
100
- tokenizer = tiktoken.get_encoding(encoding)
101
- result = SymbolContext(
102
- context, len(tokenizer.encode_ordinary(source)),
103
- len(tokenizer.encode_ordinary(context)), encoding,
104
- )
105
- if result.context_tokens * 100 > result.source_tokens * (100 - min_reduction):
106
- raise ValueError(
107
- f"Selected definitions require {result.context_tokens:,} of "
108
- f"{result.source_tokens:,} tokens ({result.reduction_pct:.2f}% reduction, "
109
- f"target {min_reduction}%, {encoding})"
110
- )
111
- return result
112
-
113
-
114
- _DELTA_HEADER = struct.Struct(">4s32s32sQQ")
115
- _DELTA_MAGIC = b"TZD1"
116
-
117
-
118
- def _common_prefix_length(left: bytes, right: bytes) -> int:
119
- limit = min(len(left), len(right))
120
- block_size = 64 * 1024
121
- for start in range(0, limit, block_size):
122
- end = min(start + block_size, limit)
123
- left_block, right_block = left[start:end], right[start:end]
124
- if left_block != right_block:
125
- return start + len(os.path.commonprefix((left_block, right_block)))
126
- return limit
127
-
128
-
129
- def encode_context_delta(base: bytes, current: bytes) -> bytes:
130
- """Store the changed middle of a context relative to a known base."""
131
- prefix = _common_prefix_length(base, current)
132
- max_suffix = min(len(base), len(current)) - prefix
133
- suffix = _common_prefix_length(
134
- base[len(base) - max_suffix:][::-1],
135
- current[len(current) - max_suffix:][::-1],
136
- )
137
- end = len(current) - suffix
138
- return _DELTA_HEADER.pack(
139
- _DELTA_MAGIC, hashlib.sha256(base).digest(),
140
- hashlib.sha256(current).digest(), prefix, suffix,
141
- ) + current[prefix:end]
142
-
143
-
144
- def restore_context_delta(base: bytes, delta: bytes) -> bytes:
145
- """Restore exact context bytes and reject incompatible or corrupt deltas."""
146
- if len(delta) < _DELTA_HEADER.size:
147
- raise ValueError("Context delta is missing its header")
148
- magic, base_digest, current_digest, prefix, suffix = _DELTA_HEADER.unpack_from(delta)
149
- if magic != _DELTA_MAGIC:
150
- raise ValueError("Unsupported context delta format")
151
- if hashlib.sha256(base).digest() != base_digest:
152
- raise ValueError("Context delta does not match the base")
153
- if prefix + suffix > len(base):
154
- raise ValueError("Context delta references bytes outside the base")
155
- current = base[:prefix] + delta[_DELTA_HEADER.size:] + base[len(base) - suffix:]
156
- if hashlib.sha256(current).digest() != current_digest:
157
- raise ValueError("Restored context failed its SHA-256 check")
158
- return current
159
-
160
-
161
- @dataclass
162
- class ModuleBudgetEntry:
163
- """Represents a module with multi-tier representations and token counts."""
164
- rel_path: str
165
- abs_path: str
166
- lang: Optional[str]
167
- raw_code: str
168
- raw_tokens: int
169
- relevance_score: float = 1.0
170
- centrality_score: float = 0.0
171
- tier_versions: Dict[str, str] = field(default_factory=dict)
172
- tier_tokens: Dict[str, int] = field(default_factory=dict)
173
- selected_tier: Optional[str] = None
174
-
175
-
176
- @dataclass
177
- class PackResult:
178
- """Result of context budget packing."""
179
- target_budget: int
180
- total_tokens: int
181
- utilization_pct: float
182
- raw_total_tokens: int
183
- token_savings_pct: float
184
- focus_target: str
185
- entries: List[ModuleBudgetEntry] = field(default_factory=list)
186
- bundle_text: str = ""
187
- tier_counts: Dict[str, int] = field(default_factory=dict)
188
-
189
-
190
- class TokenBudgetPacker:
191
- """Dynamically packs codebase AST tiers to fit an exact LLM token budget."""
192
-
193
- TOKEN_DIVISOR = 3.8 # Fallback ratio when tiktoken is unavailable
194
-
195
- @classmethod
196
- def estimate_tokens(cls, text: str, model_name: str = "gpt-4o") -> int:
197
- """Exact cached BPE token counter for source code with deterministic char-ratio fallback."""
198
- from tzero.tzero_polyglot import count_bpe_tokens
199
- return count_bpe_tokens(text, model_name=model_name, fallback_divisor=cls.TOKEN_DIVISOR)
200
-
201
- @classmethod
202
- def extract_t4_signatures(cls, code: str, lang: Optional[str]) -> str:
203
- """Extracts minimal one-line signature repomap (T-4)."""
204
- lines = code.splitlines()
205
- sig_lines = []
206
- for line in lines:
207
- trimmed = line.strip()
208
- if not trimmed or trimmed.startswith(("#", "//", "/*", "*")):
209
- continue
210
- if re.match(r"^(?:export\s+)?(?:class|interface|type|struct|enum|def|async\s+def|func|fn|pub\s+fn|pub\s+struct)\b", trimmed):
211
- sig_lines.append(trimmed.split("{")[0].split(":")[0].strip())
212
- if not sig_lines:
213
- sig_lines = [l.strip() for l in lines[:5] if l.strip()]
214
- return "\n".join(sig_lines[:25])
215
-
216
- @staticmethod
217
- def _compute_centrality_scores(
218
- raw_files: List[Tuple[str, str, Optional[str], str]]
219
- ) -> Dict[str, float]:
220
- """Computes inbound import centrality across all workspace source files."""
221
- stem_to_paths: Dict[str, List[str]] = {}
222
- for rel_p, _, _, _ in raw_files:
223
- stem = os.path.splitext(os.path.basename(rel_p))[0]
224
- if stem and stem != "__init__":
225
- stem_to_paths.setdefault(stem, []).append(rel_p)
226
-
227
- inbound: Dict[str, int] = {rel_p: 0 for rel_p, _, _, _ in raw_files}
228
- imp_re = re.compile(
229
- r"""(?:^\s*(?:from|import)\s+([A-Za-z0-9_.]+)|require\(\s*['"]([^'"]+)['"]|import\s+.*?from\s+['"]([^'"]+)['"]|^\s*use\s+([A-Za-z0-9_:]+))""",
230
- re.MULTILINE,
231
- )
232
- for src_rel, _, _, raw_code in raw_files:
233
- seen_targets: Set[str] = set()
234
- for m in imp_re.finditer(raw_code):
235
- mod = next((g for g in m.groups() if g), "")
236
- if not mod:
237
- continue
238
- for part in re.split(r"[./:\\]+", mod):
239
- if part in stem_to_paths:
240
- for tgt in stem_to_paths[part]:
241
- if tgt != src_rel and tgt not in seen_targets:
242
- seen_targets.add(tgt)
243
- inbound[tgt] += 1
244
-
245
- scores: Dict[str, float] = {}
246
- for rel_p, _, _, _ in raw_files:
247
- rel_lower = rel_p.lower()
248
- role_bonus = 2.0 if any(k in rel_lower for k in ("core", "main", "server", "router", "manager", "engine", "service", "hub")) else 0.0
249
- test_penalty = -1.5 if any(k in rel_lower for k in ("test_", "/tests/", "_test.", ".spec.")) else 0.0
250
- scores[rel_p] = inbound[rel_p] * 3.0 + role_bonus + test_penalty
251
- return scores
252
-
253
- @classmethod
254
- def scan_workspace(cls, workspace_dir: str, max_files: Optional[int] = None) -> List[ModuleBudgetEntry]:
255
- """Scans workspace and prepares multi-tier representations prioritized by centrality."""
256
- entries: List[ModuleBudgetEntry] = []
257
- raw_files: List[Tuple[str, str, Optional[str], str]] = []
258
- workspace_dir = os.path.abspath(workspace_dir)
259
-
260
- for root, dirs, files in os.walk(workspace_dir):
261
- if should_skip_dir(root, workspace_dir):
262
- dirs[:] = []
263
- continue
264
-
265
- # Filter out hidden or build directories
266
- dirs[:] = sorted(
267
- d for d in dirs
268
- if not d.startswith(".") and d not in ("node_modules", "dist", "build", "venv", ".venv", "__pycache__")
269
- )
270
-
271
- for fname in sorted(files):
272
- lang = PolyglotTokenReducer.detect_language(fname)
273
- if not lang:
274
- continue
275
-
276
- abs_p = os.path.join(root, fname)
277
- rel_p = os.path.relpath(abs_p, workspace_dir).replace("\\", "/")
278
-
279
- try:
280
- with open(abs_p, "r", encoding="utf-8", errors="replace") as f:
281
- raw_code = f.read()
282
- except Exception:
283
- continue
284
-
285
- if not raw_code.strip():
286
- continue
287
- raw_files.append((rel_p, abs_p, lang, raw_code))
288
-
289
- centrality_map = cls._compute_centrality_scores(raw_files)
290
- raw_files.sort(key=lambda item: (-centrality_map.get(item[0], 0.0), item[0]))
291
- if max_files is not None:
292
- raw_files = raw_files[:max_files]
293
-
294
- for rel_p, abs_p, lang, raw_code in raw_files:
295
- fname = os.path.basename(abs_p)
296
- raw_tok = cls.estimate_tokens(raw_code)
297
- t1 = raw_code
298
- t2 = PolyglotTokenReducer.reduce_code(raw_code, fname, mode="light")
299
- t3 = PolyglotTokenReducer.reduce_code(raw_code, fname, mode="ultra")
300
- t4 = cls.extract_t4_signatures(raw_code, lang)
301
-
302
- tier_versions = {"T-1": t1, "T-2": t2, "T-3": t3, "T-4": t4}
303
- tier_tokens = {
304
- "T-1": raw_tok,
305
- "T-2": cls.estimate_tokens(t2),
306
- "T-3": cls.estimate_tokens(t3),
307
- "T-4": cls.estimate_tokens(t4),
308
- }
309
- c_score = max(0.0, centrality_map.get(rel_p, 0.0))
310
- entries.append(ModuleBudgetEntry(
311
- rel_path=rel_p,
312
- abs_path=abs_p,
313
- lang=lang,
314
- raw_code=raw_code,
315
- raw_tokens=raw_tok,
316
- relevance_score=1.0 + c_score,
317
- centrality_score=c_score,
318
- tier_versions=tier_versions,
319
- tier_tokens=tier_tokens,
320
- ))
321
-
322
- return entries
323
-
324
- @classmethod
325
- def score_relevance(cls, entries: List[ModuleBudgetEntry], focus: str = "") -> None:
326
- """Assigns relevance scores to each file based on focus query and module centrality."""
327
- focus_clean = (focus or "").strip().lower()
328
- focus_terms = set(re.findall(r"\w+", focus_clean))
329
-
330
- for entry in entries:
331
- score = 1.0
332
- rel_lower = entry.rel_path.lower()
333
-
334
- # Direct file path match
335
- if focus_clean and (focus_clean == rel_lower or focus_clean in rel_lower):
336
- score += 100.0
337
- elif focus_terms:
338
- # Match terms in filename
339
- for term in focus_terms:
340
- if term in rel_lower:
341
- score += 25.0
342
- # Match terms in code
343
- for term in focus_terms:
344
- matches = len(re.findall(r"\b" + re.escape(term) + r"\b", entry.raw_code.lower()))
345
- score += min(matches * 2.0, 20.0)
346
-
347
- # Centrality bonuses
348
- if any(name in rel_lower for name in ("core", "main", "server", "router", "manager", "engine", "service")):
349
- score += 5.0
350
- if any(name in rel_lower for name in ("test", "spec", "mock")):
351
- score *= 0.5 # Deprioritize tests unless specifically focused
352
-
353
- entry.relevance_score = score + entry.centrality_score
354
-
355
- @classmethod
356
- def pack(
357
- cls,
358
- workspace_dir: str = ".",
359
- budget_tokens: int = 16000,
360
- focus: str = "",
361
- max_files: Optional[int] = None,
362
- cache_aligned: bool = False,
363
- ) -> PackResult:
364
- """Packs workspace files to fill budget_tokens with optimal AST tiers."""
365
- entries = cls.scan_workspace(workspace_dir, max_files=max_files)
366
- if not entries:
367
- return PackResult(
368
- target_budget=budget_tokens,
369
- total_tokens=0,
370
- utilization_pct=0.0,
371
- raw_total_tokens=0,
372
- token_savings_pct=0.0,
373
- focus_target=focus,
374
- bundle_text="// No matching source files found in workspace."
375
- )
376
-
377
- cls.score_relevance(entries, focus=focus)
378
- raw_total = sum(e.raw_tokens for e in entries)
379
- usable_budget = max(500, budget_tokens - 400)
380
- allocated_tokens = 0
381
- tier_counts = {"T-1": 0, "T-2": 0, "T-3": 0, "T-4": 0}
382
- prefix_entries: List[ModuleBudgetEntry] = []
383
-
384
- if cache_aligned:
385
- prefix_budget = int(usable_budget * 0.65)
386
- static_sorted = sorted(entries, key=lambda e: (-e.centrality_score, e.rel_path))
387
- for e in static_sorted:
388
- t3_tok = e.tier_tokens["T-3"]
389
- if allocated_tokens + t3_tok <= prefix_budget:
390
- e.selected_tier = "T-3"
391
- allocated_tokens += t3_tok
392
- tier_counts["T-3"] += 1
393
- prefix_entries.append(e)
394
-
395
- # Sort entries by relevance score descending for focus / remaining budget assignment
396
- entries.sort(key=lambda e: (-e.relevance_score, e.rel_path))
397
-
398
- # Step 1: Assign top-priority focus files Tier 1 (or upgrade from prefix T-3 delta in suffix)
399
- for e in entries:
400
- if e.relevance_score >= 100.0: # Direct focus match
401
- prev_tok = e.tier_tokens.get(e.selected_tier, 0) if e.selected_tier else 0
402
- prev_tier = e.selected_tier
403
- t1_tok = e.tier_tokens["T-1"]
404
- t2_tok = e.tier_tokens["T-2"]
405
- if allocated_tokens + t1_tok <= usable_budget:
406
- if prev_tier:
407
- tier_counts[prev_tier] = max(0, tier_counts[prev_tier] - 1)
408
- e.selected_tier = "T-1"
409
- allocated_tokens += t1_tok - (0 if cache_aligned else prev_tok)
410
- tier_counts["T-1"] += 1
411
- elif allocated_tokens + t2_tok <= usable_budget:
412
- if prev_tier:
413
- tier_counts[prev_tier] = max(0, tier_counts[prev_tier] - 1)
414
- e.selected_tier = "T-2"
415
- allocated_tokens += t2_tok - (0 if cache_aligned else prev_tok)
416
- tier_counts["T-2"] += 1
417
-
418
- # Step 2: Try to assign Tier 2 (Light) or Tier 3 (Ultra) to high-relevance modules
419
- for e in entries:
420
- if e.selected_tier is not None:
421
- continue
422
-
423
- if e.relevance_score > 10.0:
424
- t2_tok = e.tier_tokens["T-2"]
425
- t3_tok = e.tier_tokens["T-3"]
426
- if allocated_tokens + t2_tok <= usable_budget:
427
- e.selected_tier = "T-2"
428
- allocated_tokens += t2_tok
429
- tier_counts["T-2"] += 1
430
- elif allocated_tokens + t3_tok <= usable_budget:
431
- e.selected_tier = "T-3"
432
- allocated_tokens += t3_tok
433
- tier_counts["T-3"] += 1
434
-
435
- # Step 3: Fill remainder with Tier 3 (Ultra) or Tier 4 (Signatures)
436
- for e in entries:
437
- if e.selected_tier is not None:
438
- continue
439
-
440
- t3_tok = e.tier_tokens["T-3"]
441
- t4_tok = e.tier_tokens["T-4"]
442
-
443
- if allocated_tokens + t3_tok <= usable_budget:
444
- e.selected_tier = "T-3"
445
- allocated_tokens += t3_tok
446
- tier_counts["T-3"] += 1
447
- elif allocated_tokens + t4_tok <= usable_budget:
448
- e.selected_tier = "T-4"
449
- allocated_tokens += t4_tok
450
- tier_counts["T-4"] += 1
451
- else:
452
- # Budget exhausted; this file is omitted from packed context
453
- e.selected_tier = None
454
-
455
- packed_entries = [e for e in entries if e.selected_tier is not None]
456
-
457
- # Step 4: Render Markdown Context Bundle
458
- bundle_md = cls.render_bundle_markdown(
459
- packed_entries=packed_entries,
460
- budget=budget_tokens,
461
- allocated_tokens=allocated_tokens,
462
- raw_total=raw_total,
463
- focus=focus,
464
- tier_counts=tier_counts,
465
- prefix_entries=prefix_entries,
466
- cache_aligned=cache_aligned,
467
- )
468
-
469
- final_total = cls.estimate_tokens(bundle_md)
470
- util_pct = min(100.0, (final_total / budget_tokens) * 100.0)
471
- savings_pct = max(0.0, ((raw_total - final_total) / max(raw_total, 1)) * 100.0)
472
-
473
- return PackResult(
474
- target_budget=budget_tokens,
475
- total_tokens=final_total,
476
- utilization_pct=round(util_pct, 1),
477
- raw_total_tokens=raw_total,
478
- token_savings_pct=round(savings_pct, 1),
479
- focus_target=focus,
480
- entries=packed_entries,
481
- bundle_text=bundle_md,
482
- tier_counts=tier_counts
483
- )
484
-
485
- @classmethod
486
- def render_bundle_markdown(
487
- cls,
488
- packed_entries: List[ModuleBudgetEntry],
489
- budget: int,
490
- allocated_tokens: int,
491
- raw_total: int,
492
- focus: str,
493
- tier_counts: Dict[str, int],
494
- prefix_entries: Optional[List[ModuleBudgetEntry]] = None,
495
- cache_aligned: bool = False,
496
- ) -> str:
497
- """Formats the unified AI context pack with manifest table and delimited code sections."""
498
- out: List[str] = []
499
- focus_tag = f" (Focus: `{focus}`)" if focus else ""
500
- tier_summary = ", ".join(f"{cnt}x {t}" for t, cnt in tier_counts.items() if cnt > 0)
501
-
502
- if cache_aligned:
503
- out.append("# 📦 T-ZERO PACKED CONTEXT BUNDLE (KV-CACHE ALIGNED)")
504
- out.append(f"- **Target Token Budget:** {budget:,} tokens")
505
- out.append("- **Alignment:** Deterministic Static AST Prefix -> Dynamic Focus Suffix\n")
506
- out.append("---\n")
507
- for pe in (prefix_entries or []):
508
- t3_code = pe.tier_versions.get("T-3", "")
509
- out.append(f"<!-- STATIC_BACKBONE: {pe.rel_path} [TIER: T-3 | {pe.lang}] -->")
510
- out.append(f"```{pe.lang or 'text'}\n// [T-Zero Context: {pe.rel_path} (T-3)]\n{t3_code.strip()}\n```\n")
511
- out.append("<!-- TZERO_DYNAMIC_SUFFIX -->")
512
- out.append(f"## Dynamic Focus & Manifest{focus_tag}")
513
- out.append(f"- **Packed Token Volume:** ~{allocated_tokens:,} tokens ({allocated_tokens/max(budget,1)*100:.1f}% capacity)")
514
- out.append(f"- **Raw Codebase Tokens:** ~{raw_total:,} tokens (**{max(0.0, (1 - allocated_tokens/max(raw_total,1))*100):.1f}% reduction**)")
515
- out.append(f"- **Files Included:** {len(packed_entries)} files ({tier_summary})\n")
516
- out.append("| File | Tier | Language | Tokens | Status |")
517
- out.append("| :--- | :---: | :---: | :---: | :--- |")
518
- for e in packed_entries:
519
- tok = e.tier_tokens.get(e.selected_tier, 0)
520
- status = "Full Body" if e.selected_tier == "T-1" else "AST Skeleton"
521
- out.append(f"| `{e.rel_path}` | **{e.selected_tier}** | {e.lang} | ~{tok:,} | {status} |")
522
- out.append("")
523
- prefix_paths = {pe.rel_path for pe in (prefix_entries or [])}
524
- for e in packed_entries:
525
- if e.rel_path in prefix_paths and e.selected_tier == "T-3":
526
- continue
527
- code = e.tier_versions.get(e.selected_tier, "")
528
- out.append(f"<!-- FILE: {e.rel_path} [TIER: {e.selected_tier} | {e.lang}] -->")
529
- out.append(f"```{e.lang or 'text'}\n// [T-Zero Context: {e.rel_path} ({e.selected_tier})]\n{code.strip()}\n```\n")
530
- return "\n".join(out).strip()
531
-
532
- out.append(f"# 📦 T-ZERO PACKED CONTEXT BUNDLE{focus_tag}")
533
- out.append(f"- **Target Token Budget:** {budget:,} tokens")
534
- out.append(f"- **Packed Token Volume:** ~{allocated_tokens:,} tokens ({allocated_tokens/max(budget,1)*100:.1f}% capacity)")
535
- out.append(f"- **Raw Codebase Tokens:** ~{raw_total:,} tokens (**{max(0.0, (1 - allocated_tokens/max(raw_total,1))*100):.1f}% reduction**)")
536
- out.append(f"- **Files Included:** {len(packed_entries)} files ({tier_summary})\n")
537
-
538
- # Manifest Table
539
- out.append("### 📑 Context Manifest")
540
- out.append("| File | Tier | Language | Tokens | Status |")
541
- out.append("| :--- | :---: | :---: | :---: | :--- |")
542
- for e in packed_entries:
543
- tok = e.tier_tokens.get(e.selected_tier, 0)
544
- status = "Full Body" if e.selected_tier == "T-1" else "AST Skeleton"
545
- out.append(f"| `{e.rel_path}` | **{e.selected_tier}** | {e.lang} | ~{tok:,} | {status} |")
546
- out.append("\n---\n")
547
-
548
- # File Content Blocks
549
- for e in packed_entries:
550
- code = e.tier_versions.get(e.selected_tier, "")
551
- out.append(f"<!-- FILE: {e.rel_path} [TIER: {e.selected_tier} | {e.lang}] -->")
552
- out.append(f"```{e.lang or 'text'}\n// [T-Zero Context: {e.rel_path} ({e.selected_tier})]")
553
- out.append(code.strip())
554
- out.append("```\n")
555
-
556
- return "\n".join(out).strip()
557
-
558
-
559
- def pack_workspace(
560
- workspace_dir: str = ".",
561
- budget_tokens: int = 16000,
562
- focus: str = "",
563
- out_file: Optional[str] = None,
564
- cache_aligned: bool = False,
565
- ) -> PackResult:
566
- """Convenience helper to pack workspace context into a budget and optionally write to disk."""
567
- res = TokenBudgetPacker.pack(
568
- workspace_dir=workspace_dir,
569
- budget_tokens=budget_tokens,
570
- focus=focus,
571
- cache_aligned=cache_aligned,
572
- )
573
- if out_file:
574
- out_path = os.path.join(workspace_dir, out_file) if not os.path.isabs(out_file) else out_file
575
- with open(out_path, "w", encoding="utf-8") as f:
576
- f.write(res.bundle_text)
577
- return res
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Siber Akademi — T-Zero Dynamic Context Window & Token Budget Packer.
4
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
+ License: MIT
6
+
7
+ Solves the context window packing problem for LLMs: packs an entire repository or
8
+ focused subsystem into an EXACT token budget (e.g. 8k, 16k, 32k, 64k, 128k) using
9
+ multi-tier AST representations (T-1 Raw, T-2 Light, T-3 Ultra, T-4 Signature) and
10
+ greedy relevance-weighted knapsack optimization.
11
+ """
12
+
13
+ import sys
14
+ if sys.platform == "win32":
15
+ try:
16
+ sys.stdout.reconfigure(encoding="utf-8")
17
+ sys.stderr.reconfigure(encoding="utf-8")
18
+ except Exception:
19
+ pass
20
+
21
+ import ast
22
+ import io
23
+ import os
24
+ import re
25
+ import math
26
+ import hashlib
27
+ import struct
28
+ from dataclasses import dataclass, field
29
+ from typing import Dict, List, Tuple, Optional, Any, Set
30
+
31
+ from tzero.tzero_polyglot import PolyglotTokenReducer
32
+ from tzero.tzero_features import should_skip_dir, get_ignore_patterns
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class SymbolContext:
37
+ text: str
38
+ source_tokens: int
39
+ context_tokens: int
40
+ encoding: str
41
+
42
+ @property
43
+ def reduction_pct(self) -> float:
44
+ return 100 * (self.source_tokens - self.context_tokens) / self.source_tokens
45
+
46
+
47
+ def pack_python_symbols(
48
+ source: str, symbols: List[str], min_reduction: int = 95,
49
+ encoding: str = "o200k_base",
50
+ ) -> SymbolContext:
51
+ """Extract complete Python definitions and enforce an exact BPE reduction floor."""
52
+ if not symbols:
53
+ raise ValueError("Select at least one Python definition")
54
+ if not 0 <= min_reduction <= 100:
55
+ raise ValueError("Minimum token reduction must be between 0 and 100")
56
+ if encoding not in ("o200k_base", "cl100k_base"):
57
+ raise ValueError("Use the o200k_base or cl100k_base encoding")
58
+
59
+ requested = set(symbols)
60
+ scopes = {".".join(name.split(".")[:depth])
61
+ for name in requested for depth in range(1, name.count(".") + 1)}
62
+ ranges: Dict[str, Tuple[int, int]] = {}
63
+ definition_types = (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)
64
+
65
+ def collect(node: ast.AST, scope: str = "") -> None:
66
+ if isinstance(node, definition_types):
67
+ scope = f"{scope}.{node.name}" if scope else node.name
68
+ if scope in requested:
69
+ if scope in ranges:
70
+ raise ValueError(f"Ambiguous Python definition: {scope}")
71
+ start = min([node.lineno] + [item.lineno for item in node.decorator_list])
72
+ ranges[scope] = (start - 1, node.end_lineno)
73
+ if scope not in scopes:
74
+ return
75
+ for child in ast.iter_child_nodes(node):
76
+ collect(child, scope)
77
+
78
+ collect(ast.parse(source))
79
+ missing = requested - ranges.keys()
80
+ if missing:
81
+ raise ValueError(f"Python definitions not found: {', '.join(sorted(missing))}")
82
+
83
+ # AST line numbers recognize CR, CRLF, and LF. Preserve those original endings.
84
+ lines = io.StringIO(source, newline="").readlines()
85
+ segments = []
86
+ previous_end = 0
87
+ for start, end in sorted(ranges.values()):
88
+ segments.extend(lines[max(start, previous_end):end])
89
+ previous_end = max(previous_end, end)
90
+ context = "".join(segments)
91
+
92
+ from tzero.tzero_security import ZeroLeakEngine
93
+
94
+ if ZeroLeakEngine.scan_text(context):
95
+ raise ValueError("Selected source contains a potential secret")
96
+ try:
97
+ import tiktoken
98
+ except ImportError as exc:
99
+ raise ValueError("Exact token measurement requires the optional tiktoken package") from exc
100
+ tokenizer = tiktoken.get_encoding(encoding)
101
+ result = SymbolContext(
102
+ context, len(tokenizer.encode_ordinary(source)),
103
+ len(tokenizer.encode_ordinary(context)), encoding,
104
+ )
105
+ if result.context_tokens * 100 > result.source_tokens * (100 - min_reduction):
106
+ raise ValueError(
107
+ f"Selected definitions require {result.context_tokens:,} of "
108
+ f"{result.source_tokens:,} tokens ({result.reduction_pct:.2f}% reduction, "
109
+ f"target {min_reduction}%, {encoding})"
110
+ )
111
+ return result
112
+
113
+
114
+ _DELTA_HEADER = struct.Struct(">4s32s32sQQ")
115
+ _DELTA_MAGIC = b"TZD1"
116
+
117
+
118
+ def _common_prefix_length(left: bytes, right: bytes) -> int:
119
+ limit = min(len(left), len(right))
120
+ block_size = 64 * 1024
121
+ for start in range(0, limit, block_size):
122
+ end = min(start + block_size, limit)
123
+ left_block, right_block = left[start:end], right[start:end]
124
+ if left_block != right_block:
125
+ return start + len(os.path.commonprefix((left_block, right_block)))
126
+ return limit
127
+
128
+
129
+ def encode_context_delta(base: bytes, current: bytes) -> bytes:
130
+ """Store the changed middle of a context relative to a known base."""
131
+ prefix = _common_prefix_length(base, current)
132
+ max_suffix = min(len(base), len(current)) - prefix
133
+ suffix = _common_prefix_length(
134
+ base[len(base) - max_suffix:][::-1],
135
+ current[len(current) - max_suffix:][::-1],
136
+ )
137
+ end = len(current) - suffix
138
+ return _DELTA_HEADER.pack(
139
+ _DELTA_MAGIC, hashlib.sha256(base).digest(),
140
+ hashlib.sha256(current).digest(), prefix, suffix,
141
+ ) + current[prefix:end]
142
+
143
+
144
+ def restore_context_delta(base: bytes, delta: bytes) -> bytes:
145
+ """Restore exact context bytes and reject incompatible or corrupt deltas."""
146
+ if len(delta) < _DELTA_HEADER.size:
147
+ raise ValueError("Context delta is missing its header")
148
+ magic, base_digest, current_digest, prefix, suffix = _DELTA_HEADER.unpack_from(delta)
149
+ if magic != _DELTA_MAGIC:
150
+ raise ValueError("Unsupported context delta format")
151
+ if hashlib.sha256(base).digest() != base_digest:
152
+ raise ValueError("Context delta does not match the base")
153
+ if prefix + suffix > len(base):
154
+ raise ValueError("Context delta references bytes outside the base")
155
+ current = base[:prefix] + delta[_DELTA_HEADER.size:] + base[len(base) - suffix:]
156
+ if hashlib.sha256(current).digest() != current_digest:
157
+ raise ValueError("Restored context failed its SHA-256 check")
158
+ return current
159
+
160
+
161
+ @dataclass
162
+ class ModuleBudgetEntry:
163
+ """Represents a module with multi-tier representations and token counts."""
164
+ rel_path: str
165
+ abs_path: str
166
+ lang: Optional[str]
167
+ raw_code: str
168
+ raw_tokens: int
169
+ relevance_score: float = 1.0
170
+ centrality_score: float = 0.0
171
+ tier_versions: Dict[str, str] = field(default_factory=dict)
172
+ tier_tokens: Dict[str, int] = field(default_factory=dict)
173
+ selected_tier: Optional[str] = None
174
+
175
+
176
+ @dataclass
177
+ class PackResult:
178
+ """Result of context budget packing."""
179
+ target_budget: int
180
+ total_tokens: int
181
+ utilization_pct: float
182
+ raw_total_tokens: int
183
+ token_savings_pct: float
184
+ focus_target: str
185
+ entries: List[ModuleBudgetEntry] = field(default_factory=list)
186
+ bundle_text: str = ""
187
+ tier_counts: Dict[str, int] = field(default_factory=dict)
188
+
189
+
190
+ class TokenBudgetPacker:
191
+ """Dynamically packs codebase AST tiers to fit an exact LLM token budget."""
192
+
193
+ TOKEN_DIVISOR = 3.8 # Fallback ratio when tiktoken is unavailable
194
+
195
+ @classmethod
196
+ def estimate_tokens(cls, text: str, model_name: str = "gpt-4o") -> int:
197
+ """Exact cached BPE token counter for source code with deterministic char-ratio fallback."""
198
+ from tzero.tzero_polyglot import count_bpe_tokens
199
+ return count_bpe_tokens(text, model_name=model_name, fallback_divisor=cls.TOKEN_DIVISOR)
200
+
201
+ @classmethod
202
+ def extract_t4_signatures(cls, code: str, lang: Optional[str]) -> str:
203
+ """Extracts minimal one-line signature repomap (T-4)."""
204
+ lines = code.splitlines()
205
+ sig_lines = []
206
+ for line in lines:
207
+ trimmed = line.strip()
208
+ if not trimmed or trimmed.startswith(("#", "//", "/*", "*")):
209
+ continue
210
+ if re.match(r"^(?:export\s+)?(?:class|interface|type|struct|enum|def|async\s+def|func|fn|pub\s+fn|pub\s+struct)\b", trimmed):
211
+ sig_lines.append(trimmed.split("{")[0].split(":")[0].strip())
212
+ if not sig_lines:
213
+ sig_lines = [l.strip() for l in lines[:5] if l.strip()]
214
+ return "\n".join(sig_lines[:25])
215
+
216
+ @staticmethod
217
+ def _compute_centrality_scores(
218
+ raw_files: List[Tuple[str, str, Optional[str], str]]
219
+ ) -> Dict[str, float]:
220
+ """Computes inbound import centrality across all workspace source files."""
221
+ stem_to_paths: Dict[str, List[str]] = {}
222
+ for rel_p, _, _, _ in raw_files:
223
+ stem = os.path.splitext(os.path.basename(rel_p))[0]
224
+ if stem and stem != "__init__":
225
+ stem_to_paths.setdefault(stem, []).append(rel_p)
226
+
227
+ inbound: Dict[str, int] = {rel_p: 0 for rel_p, _, _, _ in raw_files}
228
+ imp_re = re.compile(
229
+ r"""(?:^\s*(?:from|import)\s+([A-Za-z0-9_.]+)|require\(\s*['"]([^'"]+)['"]|import\s+.*?from\s+['"]([^'"]+)['"]|^\s*use\s+([A-Za-z0-9_:]+))""",
230
+ re.MULTILINE,
231
+ )
232
+ for src_rel, _, _, raw_code in raw_files:
233
+ seen_targets: Set[str] = set()
234
+ for m in imp_re.finditer(raw_code):
235
+ mod = next((g for g in m.groups() if g), "")
236
+ if not mod:
237
+ continue
238
+ for part in re.split(r"[./:\\]+", mod):
239
+ if part in stem_to_paths:
240
+ for tgt in stem_to_paths[part]:
241
+ if tgt != src_rel and tgt not in seen_targets:
242
+ seen_targets.add(tgt)
243
+ inbound[tgt] += 1
244
+
245
+ scores: Dict[str, float] = {}
246
+ for rel_p, _, _, _ in raw_files:
247
+ rel_lower = rel_p.lower()
248
+ role_bonus = 2.0 if any(k in rel_lower for k in ("core", "main", "server", "router", "manager", "engine", "service", "hub")) else 0.0
249
+ test_penalty = -1.5 if any(k in rel_lower for k in ("test_", "/tests/", "_test.", ".spec.")) else 0.0
250
+ scores[rel_p] = inbound[rel_p] * 3.0 + role_bonus + test_penalty
251
+ return scores
252
+
253
+ @classmethod
254
+ def scan_workspace(cls, workspace_dir: str, max_files: Optional[int] = None) -> List[ModuleBudgetEntry]:
255
+ """Scans workspace and prepares multi-tier representations prioritized by centrality."""
256
+ entries: List[ModuleBudgetEntry] = []
257
+ raw_files: List[Tuple[str, str, Optional[str], str]] = []
258
+ workspace_dir = os.path.abspath(workspace_dir)
259
+
260
+ for root, dirs, files in os.walk(workspace_dir):
261
+ if should_skip_dir(root, workspace_dir):
262
+ dirs[:] = []
263
+ continue
264
+
265
+ # Filter out hidden or build directories
266
+ dirs[:] = sorted(
267
+ d for d in dirs
268
+ if not d.startswith(".") and d not in ("node_modules", "dist", "build", "venv", ".venv", "__pycache__")
269
+ )
270
+
271
+ for fname in sorted(files):
272
+ lang = PolyglotTokenReducer.detect_language(fname)
273
+ if not lang:
274
+ continue
275
+
276
+ abs_p = os.path.join(root, fname)
277
+ rel_p = os.path.relpath(abs_p, workspace_dir).replace("\\", "/")
278
+
279
+ try:
280
+ with open(abs_p, "r", encoding="utf-8", errors="replace") as f:
281
+ raw_code = f.read()
282
+ except Exception:
283
+ continue
284
+
285
+ if not raw_code.strip():
286
+ continue
287
+ raw_files.append((rel_p, abs_p, lang, raw_code))
288
+
289
+ centrality_map = cls._compute_centrality_scores(raw_files)
290
+ raw_files.sort(key=lambda item: (-centrality_map.get(item[0], 0.0), item[0]))
291
+ if max_files is not None:
292
+ raw_files = raw_files[:max_files]
293
+
294
+ for rel_p, abs_p, lang, raw_code in raw_files:
295
+ fname = os.path.basename(abs_p)
296
+ raw_tok = cls.estimate_tokens(raw_code)
297
+ t1 = raw_code
298
+ t2 = PolyglotTokenReducer.reduce_code(raw_code, fname, mode="light")
299
+ t3 = PolyglotTokenReducer.reduce_code(raw_code, fname, mode="ultra")
300
+ t4 = cls.extract_t4_signatures(raw_code, lang)
301
+
302
+ tier_versions = {"T-1": t1, "T-2": t2, "T-3": t3, "T-4": t4}
303
+ tier_tokens = {
304
+ "T-1": raw_tok,
305
+ "T-2": cls.estimate_tokens(t2),
306
+ "T-3": cls.estimate_tokens(t3),
307
+ "T-4": cls.estimate_tokens(t4),
308
+ }
309
+ c_score = max(0.0, centrality_map.get(rel_p, 0.0))
310
+ entries.append(ModuleBudgetEntry(
311
+ rel_path=rel_p,
312
+ abs_path=abs_p,
313
+ lang=lang,
314
+ raw_code=raw_code,
315
+ raw_tokens=raw_tok,
316
+ relevance_score=1.0 + c_score,
317
+ centrality_score=c_score,
318
+ tier_versions=tier_versions,
319
+ tier_tokens=tier_tokens,
320
+ ))
321
+
322
+ return entries
323
+
324
+ @classmethod
325
+ def score_relevance(cls, entries: List[ModuleBudgetEntry], focus: str = "") -> None:
326
+ """Assigns relevance scores to each file based on focus query and module centrality."""
327
+ focus_clean = (focus or "").strip().lower()
328
+ focus_terms = set(re.findall(r"\w+", focus_clean))
329
+
330
+ for entry in entries:
331
+ score = 1.0
332
+ rel_lower = entry.rel_path.lower()
333
+
334
+ # Direct file path match
335
+ if focus_clean and (focus_clean == rel_lower or focus_clean in rel_lower):
336
+ score += 100.0
337
+ elif focus_terms:
338
+ # Match terms in filename
339
+ for term in focus_terms:
340
+ if term in rel_lower:
341
+ score += 25.0
342
+ # Match terms in code
343
+ for term in focus_terms:
344
+ matches = len(re.findall(r"\b" + re.escape(term) + r"\b", entry.raw_code.lower()))
345
+ score += min(matches * 2.0, 20.0)
346
+
347
+ # Centrality bonuses
348
+ if any(name in rel_lower for name in ("core", "main", "server", "router", "manager", "engine", "service")):
349
+ score += 5.0
350
+ if any(name in rel_lower for name in ("test", "spec", "mock")):
351
+ score *= 0.5 # Deprioritize tests unless specifically focused
352
+
353
+ entry.relevance_score = score + entry.centrality_score
354
+
355
+ @classmethod
356
+ def pack(
357
+ cls,
358
+ workspace_dir: str = ".",
359
+ budget_tokens: int = 16000,
360
+ focus: str = "",
361
+ max_files: Optional[int] = None,
362
+ cache_aligned: bool = False,
363
+ ) -> PackResult:
364
+ """Packs workspace files to fill budget_tokens with optimal AST tiers."""
365
+ entries = cls.scan_workspace(workspace_dir, max_files=max_files)
366
+ if not entries:
367
+ return PackResult(
368
+ target_budget=budget_tokens,
369
+ total_tokens=0,
370
+ utilization_pct=0.0,
371
+ raw_total_tokens=0,
372
+ token_savings_pct=0.0,
373
+ focus_target=focus,
374
+ bundle_text="// No matching source files found in workspace."
375
+ )
376
+
377
+ cls.score_relevance(entries, focus=focus)
378
+ raw_total = sum(e.raw_tokens for e in entries)
379
+ usable_budget = max(500, budget_tokens - 400)
380
+ allocated_tokens = 0
381
+ tier_counts = {"T-1": 0, "T-2": 0, "T-3": 0, "T-4": 0}
382
+ prefix_entries: List[ModuleBudgetEntry] = []
383
+
384
+ if cache_aligned:
385
+ prefix_budget = int(usable_budget * 0.65)
386
+ static_sorted = sorted(entries, key=lambda e: (-e.centrality_score, e.rel_path))
387
+ for e in static_sorted:
388
+ t3_tok = e.tier_tokens["T-3"]
389
+ if allocated_tokens + t3_tok <= prefix_budget:
390
+ e.selected_tier = "T-3"
391
+ allocated_tokens += t3_tok
392
+ tier_counts["T-3"] += 1
393
+ prefix_entries.append(e)
394
+
395
+ # Sort entries by relevance score descending for focus / remaining budget assignment
396
+ entries.sort(key=lambda e: (-e.relevance_score, e.rel_path))
397
+
398
+ # Step 1: Assign top-priority focus files Tier 1 (or upgrade from prefix T-3 delta in suffix)
399
+ for e in entries:
400
+ if e.relevance_score >= 100.0: # Direct focus match
401
+ prev_tok = e.tier_tokens.get(e.selected_tier, 0) if e.selected_tier else 0
402
+ prev_tier = e.selected_tier
403
+ t1_tok = e.tier_tokens["T-1"]
404
+ t2_tok = e.tier_tokens["T-2"]
405
+ if allocated_tokens + t1_tok <= usable_budget:
406
+ if prev_tier:
407
+ tier_counts[prev_tier] = max(0, tier_counts[prev_tier] - 1)
408
+ e.selected_tier = "T-1"
409
+ allocated_tokens += t1_tok - (0 if cache_aligned else prev_tok)
410
+ tier_counts["T-1"] += 1
411
+ elif allocated_tokens + t2_tok <= usable_budget:
412
+ if prev_tier:
413
+ tier_counts[prev_tier] = max(0, tier_counts[prev_tier] - 1)
414
+ e.selected_tier = "T-2"
415
+ allocated_tokens += t2_tok - (0 if cache_aligned else prev_tok)
416
+ tier_counts["T-2"] += 1
417
+
418
+ # Step 2: Try to assign Tier 2 (Light) or Tier 3 (Ultra) to high-relevance modules
419
+ for e in entries:
420
+ if e.selected_tier is not None:
421
+ continue
422
+
423
+ if e.relevance_score > 10.0:
424
+ t2_tok = e.tier_tokens["T-2"]
425
+ t3_tok = e.tier_tokens["T-3"]
426
+ if allocated_tokens + t2_tok <= usable_budget:
427
+ e.selected_tier = "T-2"
428
+ allocated_tokens += t2_tok
429
+ tier_counts["T-2"] += 1
430
+ elif allocated_tokens + t3_tok <= usable_budget:
431
+ e.selected_tier = "T-3"
432
+ allocated_tokens += t3_tok
433
+ tier_counts["T-3"] += 1
434
+
435
+ # Step 3: Fill remainder with Tier 3 (Ultra) or Tier 4 (Signatures)
436
+ for e in entries:
437
+ if e.selected_tier is not None:
438
+ continue
439
+
440
+ t3_tok = e.tier_tokens["T-3"]
441
+ t4_tok = e.tier_tokens["T-4"]
442
+
443
+ if allocated_tokens + t3_tok <= usable_budget:
444
+ e.selected_tier = "T-3"
445
+ allocated_tokens += t3_tok
446
+ tier_counts["T-3"] += 1
447
+ elif allocated_tokens + t4_tok <= usable_budget:
448
+ e.selected_tier = "T-4"
449
+ allocated_tokens += t4_tok
450
+ tier_counts["T-4"] += 1
451
+ else:
452
+ # Budget exhausted; this file is omitted from packed context
453
+ e.selected_tier = None
454
+
455
+ packed_entries = [e for e in entries if e.selected_tier is not None]
456
+
457
+ # Step 4: Render Markdown Context Bundle
458
+ bundle_md = cls.render_bundle_markdown(
459
+ packed_entries=packed_entries,
460
+ budget=budget_tokens,
461
+ allocated_tokens=allocated_tokens,
462
+ raw_total=raw_total,
463
+ focus=focus,
464
+ tier_counts=tier_counts,
465
+ prefix_entries=prefix_entries,
466
+ cache_aligned=cache_aligned,
467
+ )
468
+
469
+ final_total = cls.estimate_tokens(bundle_md)
470
+ util_pct = min(100.0, (final_total / budget_tokens) * 100.0)
471
+ savings_pct = max(0.0, ((raw_total - final_total) / max(raw_total, 1)) * 100.0)
472
+
473
+ return PackResult(
474
+ target_budget=budget_tokens,
475
+ total_tokens=final_total,
476
+ utilization_pct=round(util_pct, 1),
477
+ raw_total_tokens=raw_total,
478
+ token_savings_pct=round(savings_pct, 1),
479
+ focus_target=focus,
480
+ entries=packed_entries,
481
+ bundle_text=bundle_md,
482
+ tier_counts=tier_counts
483
+ )
484
+
485
+ @classmethod
486
+ def render_bundle_markdown(
487
+ cls,
488
+ packed_entries: List[ModuleBudgetEntry],
489
+ budget: int,
490
+ allocated_tokens: int,
491
+ raw_total: int,
492
+ focus: str,
493
+ tier_counts: Dict[str, int],
494
+ prefix_entries: Optional[List[ModuleBudgetEntry]] = None,
495
+ cache_aligned: bool = False,
496
+ ) -> str:
497
+ """Formats the unified AI context pack with manifest table and delimited code sections."""
498
+ out: List[str] = []
499
+ focus_tag = f" (Focus: `{focus}`)" if focus else ""
500
+ tier_summary = ", ".join(f"{cnt}x {t}" for t, cnt in tier_counts.items() if cnt > 0)
501
+
502
+ if cache_aligned:
503
+ out.append("# 📦 T-ZERO PACKED CONTEXT BUNDLE (KV-CACHE ALIGNED)")
504
+ out.append(f"- **Target Token Budget:** {budget:,} tokens")
505
+ out.append("- **Alignment:** Deterministic Static AST Prefix -> Dynamic Focus Suffix\n")
506
+ out.append("---\n")
507
+ for pe in (prefix_entries or []):
508
+ t3_code = pe.tier_versions.get("T-3", "")
509
+ out.append(f"<!-- STATIC_BACKBONE: {pe.rel_path} [TIER: T-3 | {pe.lang}] -->")
510
+ out.append(f"```{pe.lang or 'text'}\n// [T-Zero Context: {pe.rel_path} (T-3)]\n{t3_code.strip()}\n```\n")
511
+ out.append("<!-- TZERO_DYNAMIC_SUFFIX -->")
512
+ out.append(f"## Dynamic Focus & Manifest{focus_tag}")
513
+ out.append(f"- **Packed Token Volume:** ~{allocated_tokens:,} tokens ({allocated_tokens/max(budget,1)*100:.1f}% capacity)")
514
+ out.append(f"- **Raw Codebase Tokens:** ~{raw_total:,} tokens (**{max(0.0, (1 - allocated_tokens/max(raw_total,1))*100):.1f}% reduction**)")
515
+ out.append(f"- **Files Included:** {len(packed_entries)} files ({tier_summary})\n")
516
+ out.append("| File | Tier | Language | Tokens | Status |")
517
+ out.append("| :--- | :---: | :---: | :---: | :--- |")
518
+ for e in packed_entries:
519
+ tok = e.tier_tokens.get(e.selected_tier, 0)
520
+ status = "Full Body" if e.selected_tier == "T-1" else "AST Skeleton"
521
+ out.append(f"| `{e.rel_path}` | **{e.selected_tier}** | {e.lang} | ~{tok:,} | {status} |")
522
+ out.append("")
523
+ prefix_paths = {pe.rel_path for pe in (prefix_entries or [])}
524
+ for e in packed_entries:
525
+ if e.rel_path in prefix_paths and e.selected_tier == "T-3":
526
+ continue
527
+ code = e.tier_versions.get(e.selected_tier, "")
528
+ out.append(f"<!-- FILE: {e.rel_path} [TIER: {e.selected_tier} | {e.lang}] -->")
529
+ out.append(f"```{e.lang or 'text'}\n// [T-Zero Context: {e.rel_path} ({e.selected_tier})]\n{code.strip()}\n```\n")
530
+ return "\n".join(out).strip()
531
+
532
+ out.append(f"# 📦 T-ZERO PACKED CONTEXT BUNDLE{focus_tag}")
533
+ out.append(f"- **Target Token Budget:** {budget:,} tokens")
534
+ out.append(f"- **Packed Token Volume:** ~{allocated_tokens:,} tokens ({allocated_tokens/max(budget,1)*100:.1f}% capacity)")
535
+ out.append(f"- **Raw Codebase Tokens:** ~{raw_total:,} tokens (**{max(0.0, (1 - allocated_tokens/max(raw_total,1))*100):.1f}% reduction**)")
536
+ out.append(f"- **Files Included:** {len(packed_entries)} files ({tier_summary})\n")
537
+
538
+ # Manifest Table
539
+ out.append("### 📑 Context Manifest")
540
+ out.append("| File | Tier | Language | Tokens | Status |")
541
+ out.append("| :--- | :---: | :---: | :---: | :--- |")
542
+ for e in packed_entries:
543
+ tok = e.tier_tokens.get(e.selected_tier, 0)
544
+ status = "Full Body" if e.selected_tier == "T-1" else "AST Skeleton"
545
+ out.append(f"| `{e.rel_path}` | **{e.selected_tier}** | {e.lang} | ~{tok:,} | {status} |")
546
+ out.append("\n---\n")
547
+
548
+ # File Content Blocks
549
+ for e in packed_entries:
550
+ code = e.tier_versions.get(e.selected_tier, "")
551
+ out.append(f"<!-- FILE: {e.rel_path} [TIER: {e.selected_tier} | {e.lang}] -->")
552
+ out.append(f"```{e.lang or 'text'}\n// [T-Zero Context: {e.rel_path} ({e.selected_tier})]")
553
+ out.append(code.strip())
554
+ out.append("```\n")
555
+
556
+ return "\n".join(out).strip()
557
+
558
+
559
+ def pack_workspace(
560
+ workspace_dir: str = ".",
561
+ budget_tokens: int = 16000,
562
+ focus: str = "",
563
+ out_file: Optional[str] = None,
564
+ cache_aligned: bool = False,
565
+ ) -> PackResult:
566
+ """Convenience helper to pack workspace context into a budget and optionally write to disk."""
567
+ res = TokenBudgetPacker.pack(
568
+ workspace_dir=workspace_dir,
569
+ budget_tokens=budget_tokens,
570
+ focus=focus,
571
+ cache_aligned=cache_aligned,
572
+ )
573
+ if out_file:
574
+ out_path = os.path.join(workspace_dir, out_file) if not os.path.isabs(out_file) else out_file
575
+ with open(out_path, "w", encoding="utf-8") as f:
576
+ f.write(res.bundle_text)
577
+ return res