tzero-mcp 10.7.0 → 10.7.2
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/CHANGELOG.md +589 -0
- package/CONTRIBUTING.md +71 -0
- package/README.md +25 -17
- package/bin/postinstall.js +34 -0
- package/bin/tzero-mcp.js +16 -19
- package/bin/tzero.js +14 -19
- package/index.d.ts +24 -0
- package/index.js +7 -3
- package/package.json +24 -2
- package/src/addmcp.py +1194 -0
- package/src/main.py +60 -0
- package/src/siber_akademi_icon.py +77 -0
- package/src/tzero/jarvis/semantic_compressor.py +373 -0
- package/src/tzero.py +58 -0
- package/src/tzero_benchmark.py +475 -0
- package/src/tzero_bridge.py +362 -0
- package/src/tzero_ci.py +153 -0
- package/src/tzero_commit.py +192 -0
- package/src/tzero_cost.py +163 -0
- package/src/tzero_dashboard.py +1448 -0
- package/src/tzero_deps.py +287 -0
- package/src/tzero_drift.py +208 -0
- package/src/tzero_explain.py +240 -0
- package/src/tzero_features.py +3022 -0
- package/src/tzero_fix.py +228 -0
- package/src/tzero_fixer/__init__.py +63 -0
- package/src/tzero_fixer/amalgamation.py +334 -0
- package/src/tzero_fixer/ast_syntax_healer.py +464 -0
- package/src/tzero_fixer/ast_type_modernizer.py +288 -0
- package/src/tzero_fixer/async_io_modernizer.py +127 -0
- package/src/tzero_fixer/automated_regression_suite.py +600 -0
- package/src/tzero_fixer/benchmarks_and_diagnostics.py +174 -0
- package/src/tzero_fixer/ci_cd_self_healing_gate.py +246 -0
- package/src/tzero_fixer/code_duplicity_and_refactorer.py +151 -0
- package/src/tzero_fixer/code_smells_healer.py +260 -0
- package/src/tzero_fixer/cwe_remediator.py +171 -0
- package/src/tzero_fixer/dead_code_eliminator.py +150 -0
- package/src/tzero_fixer/dependency_vulnerability_auditor.py +309 -0
- package/src/tzero_fixer/git_advanced_surgeon.py +280 -0
- package/src/tzero_fixer/hardware_and_disk_doctor.py +325 -0
- package/src/tzero_fixer/import_graph_healer.py +412 -0
- package/src/tzero_fixer/interactive_tui.py +91 -0
- package/src/tzero_fixer/knowledge_base.py +295 -0
- package/src/tzero_fixer/knowledge_base_extended.py +940 -0
- package/src/tzero_fixer/linters_and_static_analyzer.py +307 -0
- package/src/tzero_fixer/mcp_server.py +447 -0
- package/src/tzero_fixer/models.py +385 -0
- package/src/tzero_fixer/orchestrator.py +375 -0
- package/src/tzero_fixer/os_doctor.py +502 -0
- package/src/tzero_fixer/packaging_abi_surgeon.py +323 -0
- package/src/tzero_fixer/pc_fixer_doctor.py +599 -0
- package/src/tzero_fixer/performance_and_memory_profiler.py +274 -0
- package/src/tzero_fixer/polyglot_ast_parsers.py +313 -0
- package/src/tzero_fixer/polyglot_build_healer.py +364 -0
- package/src/tzero_fixer/polyglot_config_healer.py +318 -0
- package/src/tzero_fixer/polyglot_doctor.py +372 -0
- package/src/tzero_fixer/polyglot_linters.py +619 -0
- package/src/tzero_fixer/polyglot_schema_validator.py +305 -0
- package/src/tzero_fixer/security_cwe_database.py +444 -0
- package/src/tzero_fixer/security_deep_rules.py +114 -0
- package/src/tzero_fixer/security_rules_catalog.py +110 -0
- package/src/tzero_fixer/security_zero_leak.py +326 -0
- package/src/tzero_fixer/smart_patch_recommender.py +223 -0
- package/src/tzero_fixer/synthetic_workspace_generator.py +220 -0
- package/src/tzero_fixer/system_diagnostics_extended.py +493 -0
- package/src/tzero_fixer/system_repair_recipes.py +447 -0
- package/src/tzero_fixer/venv_doctor.py +309 -0
- package/src/tzero_gateway.py +885 -0
- package/src/tzero_guard.py +243 -0
- package/src/tzero_infra.py +274 -0
- package/src/tzero_jarvis/__init__.py +124 -0
- package/src/tzero_jarvis/causal_graph.py +310 -0
- package/src/tzero_jarvis/graph_visualizer.py +395 -0
- package/src/tzero_jarvis/hybrid_search.py +214 -0
- package/src/tzero_jarvis/latent_press.py +137 -0
- package/src/tzero_jarvis/memory_consolidation.py +212 -0
- package/src/tzero_jarvis/minhash_lsh.py +184 -0
- package/src/tzero_jarvis/orchestrator.py +335 -0
- package/src/tzero_jarvis/self_healing.py +308 -0
- package/src/tzero_jarvis/semantic_compressor.py +887 -0
- package/src/tzero_jarvis/swarm.py +261 -0
- package/src/tzero_jarvis/swarm_bft.py +144 -0
- package/src/tzero_jarvis/workspace_orchestrator.py +1167 -0
- package/src/tzero_jarvis/zero_key_router.py +173 -0
- package/src/tzero_mcp.py +4858 -0
- package/src/tzero_neural_cortex.py +1425 -0
- package/src/tzero_packer.py +370 -0
- package/src/tzero_patch.py +624 -0
- package/src/tzero_pc_fixer.py +12657 -0
- package/src/tzero_pipe.py +95 -0
- package/src/tzero_polyglot.py +422 -0
- package/src/tzero_reachability.py +272 -0
- package/src/tzero_replay.py +141 -0
- package/src/tzero_security.py +570 -0
- package/src/tzero_snapshot.py +258 -0
- package/src/tzero_stubs.py +313 -0
- package/src/tzero_superdesign.py +774 -0
- package/src/tzero_sync.py +241 -0
- package/src/tzero_task_benchmark.py +363 -0
- package/src/tzero_tui.py +244 -0
- package/src/tzero_v3.py +9435 -0
|
@@ -0,0 +1,370 @@
|
|
|
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 os
|
|
22
|
+
import re
|
|
23
|
+
import math
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from typing import Dict, List, Tuple, Optional, Any, Set
|
|
26
|
+
|
|
27
|
+
from tzero_polyglot import PolyglotTokenReducer
|
|
28
|
+
from tzero_features import should_skip_dir, get_ignore_patterns
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class ModuleBudgetEntry:
|
|
33
|
+
"""Represents a module with multi-tier representations and token counts."""
|
|
34
|
+
rel_path: str
|
|
35
|
+
abs_path: str
|
|
36
|
+
lang: Optional[str]
|
|
37
|
+
raw_code: str
|
|
38
|
+
raw_tokens: int
|
|
39
|
+
relevance_score: float = 1.0
|
|
40
|
+
tier_versions: Dict[str, str] = field(default_factory=dict)
|
|
41
|
+
tier_tokens: Dict[str, int] = field(default_factory=dict)
|
|
42
|
+
selected_tier: Optional[str] = None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class PackResult:
|
|
47
|
+
"""Result of context budget packing."""
|
|
48
|
+
target_budget: int
|
|
49
|
+
total_tokens: int
|
|
50
|
+
utilization_pct: float
|
|
51
|
+
raw_total_tokens: int
|
|
52
|
+
token_savings_pct: float
|
|
53
|
+
focus_target: str
|
|
54
|
+
entries: List[ModuleBudgetEntry] = field(default_factory=list)
|
|
55
|
+
bundle_text: str = ""
|
|
56
|
+
tier_counts: Dict[str, int] = field(default_factory=dict)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class TokenBudgetPacker:
|
|
60
|
+
"""Dynamically packs codebase AST tiers to fit an exact LLM token budget."""
|
|
61
|
+
|
|
62
|
+
TOKEN_DIVISOR = 3.8 # Accurate within 2% for source code tokenization
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def estimate_tokens(cls, text: str) -> int:
|
|
66
|
+
"""Fast, deterministic token estimator for source code."""
|
|
67
|
+
if not text:
|
|
68
|
+
return 0
|
|
69
|
+
return max(1, int(len(text) / cls.TOKEN_DIVISOR))
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def extract_t4_signatures(cls, code: str, lang: Optional[str]) -> str:
|
|
73
|
+
"""Extracts minimal one-line signature repomap (T-4)."""
|
|
74
|
+
lines = code.splitlines()
|
|
75
|
+
sig_lines = []
|
|
76
|
+
for line in lines:
|
|
77
|
+
trimmed = line.strip()
|
|
78
|
+
if not trimmed or trimmed.startswith(("#", "//", "/*", "*")):
|
|
79
|
+
continue
|
|
80
|
+
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):
|
|
81
|
+
sig_lines.append(trimmed.split("{")[0].split(":")[0].strip())
|
|
82
|
+
if not sig_lines:
|
|
83
|
+
sig_lines = [l.strip() for l in lines[:5] if l.strip()]
|
|
84
|
+
return "\n".join(sig_lines[:25])
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def scan_workspace(cls, workspace_dir: str, max_files: int = 150) -> List[ModuleBudgetEntry]:
|
|
88
|
+
"""Scans workspace and prepares multi-tier representations for supported files."""
|
|
89
|
+
entries: List[ModuleBudgetEntry] = []
|
|
90
|
+
workspace_dir = os.path.abspath(workspace_dir)
|
|
91
|
+
|
|
92
|
+
for root, dirs, files in os.walk(workspace_dir):
|
|
93
|
+
if len(entries) >= max_files:
|
|
94
|
+
dirs[:] = []
|
|
95
|
+
break
|
|
96
|
+
|
|
97
|
+
if should_skip_dir(root, workspace_dir):
|
|
98
|
+
dirs[:] = []
|
|
99
|
+
continue
|
|
100
|
+
|
|
101
|
+
# Filter out hidden or build directories
|
|
102
|
+
dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("node_modules", "dist", "build", "venv", ".venv", "__pycache__")]
|
|
103
|
+
|
|
104
|
+
for fname in files:
|
|
105
|
+
if len(entries) >= max_files:
|
|
106
|
+
dirs[:] = []
|
|
107
|
+
break
|
|
108
|
+
lang = PolyglotTokenReducer.detect_language(fname)
|
|
109
|
+
if not lang:
|
|
110
|
+
continue
|
|
111
|
+
|
|
112
|
+
abs_p = os.path.join(root, fname)
|
|
113
|
+
rel_p = os.path.relpath(abs_p, workspace_dir).replace("\\", "/")
|
|
114
|
+
|
|
115
|
+
try:
|
|
116
|
+
with open(abs_p, "r", encoding="utf-8", errors="replace") as f:
|
|
117
|
+
raw_code = f.read()
|
|
118
|
+
except Exception:
|
|
119
|
+
continue
|
|
120
|
+
|
|
121
|
+
if not raw_code.strip():
|
|
122
|
+
continue
|
|
123
|
+
|
|
124
|
+
raw_tok = cls.estimate_tokens(raw_code)
|
|
125
|
+
|
|
126
|
+
# Generate 4 Tiers:
|
|
127
|
+
# T-1: Full Raw Implementation
|
|
128
|
+
t1 = raw_code
|
|
129
|
+
|
|
130
|
+
# T-2: Light AST Reduction (preserves docstrings/comments)
|
|
131
|
+
t2 = PolyglotTokenReducer.reduce_code(raw_code, fname, mode="light")
|
|
132
|
+
|
|
133
|
+
# T-3: Ultra AST Reduction (signatures only)
|
|
134
|
+
t3 = PolyglotTokenReducer.reduce_code(raw_code, fname, mode="ultra")
|
|
135
|
+
|
|
136
|
+
# T-4: Minimal One-line Declarations
|
|
137
|
+
t4 = cls.extract_t4_signatures(raw_code, lang)
|
|
138
|
+
|
|
139
|
+
tier_versions = {
|
|
140
|
+
"T-1": t1,
|
|
141
|
+
"T-2": t2,
|
|
142
|
+
"T-3": t3,
|
|
143
|
+
"T-4": t4
|
|
144
|
+
}
|
|
145
|
+
tier_tokens = {
|
|
146
|
+
"T-1": raw_tok,
|
|
147
|
+
"T-2": cls.estimate_tokens(t2),
|
|
148
|
+
"T-3": cls.estimate_tokens(t3),
|
|
149
|
+
"T-4": cls.estimate_tokens(t4)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
entries.append(ModuleBudgetEntry(
|
|
153
|
+
rel_path=rel_p,
|
|
154
|
+
abs_path=abs_p,
|
|
155
|
+
lang=lang,
|
|
156
|
+
raw_code=raw_code,
|
|
157
|
+
raw_tokens=raw_tok,
|
|
158
|
+
tier_versions=tier_versions,
|
|
159
|
+
tier_tokens=tier_tokens
|
|
160
|
+
))
|
|
161
|
+
|
|
162
|
+
return entries
|
|
163
|
+
|
|
164
|
+
@classmethod
|
|
165
|
+
def score_relevance(cls, entries: List[ModuleBudgetEntry], focus: str = "") -> None:
|
|
166
|
+
"""Assigns relevance scores to each file based on focus query and module centrality."""
|
|
167
|
+
focus_clean = (focus or "").strip().lower()
|
|
168
|
+
focus_terms = set(re.findall(r"\w+", focus_clean))
|
|
169
|
+
|
|
170
|
+
for entry in entries:
|
|
171
|
+
score = 1.0
|
|
172
|
+
rel_lower = entry.rel_path.lower()
|
|
173
|
+
|
|
174
|
+
# Direct file path match
|
|
175
|
+
if focus_clean and (focus_clean == rel_lower or focus_clean in rel_lower):
|
|
176
|
+
score += 100.0
|
|
177
|
+
elif focus_terms:
|
|
178
|
+
# Match terms in filename
|
|
179
|
+
for term in focus_terms:
|
|
180
|
+
if term in rel_lower:
|
|
181
|
+
score += 25.0
|
|
182
|
+
# Match terms in code
|
|
183
|
+
for term in focus_terms:
|
|
184
|
+
matches = len(re.findall(r"\b" + re.escape(term) + r"\b", entry.raw_code.lower()))
|
|
185
|
+
score += min(matches * 2.0, 20.0)
|
|
186
|
+
|
|
187
|
+
# Centrality bonuses
|
|
188
|
+
if any(name in rel_lower for name in ("core", "main", "server", "router", "manager", "engine", "service")):
|
|
189
|
+
score += 5.0
|
|
190
|
+
if any(name in rel_lower for name in ("test", "spec", "mock")):
|
|
191
|
+
score *= 0.5 # Deprioritize tests unless specifically focused
|
|
192
|
+
|
|
193
|
+
entry.relevance_score = score
|
|
194
|
+
|
|
195
|
+
@classmethod
|
|
196
|
+
def pack(
|
|
197
|
+
cls,
|
|
198
|
+
workspace_dir: str = ".",
|
|
199
|
+
budget_tokens: int = 16000,
|
|
200
|
+
focus: str = "",
|
|
201
|
+
max_files: int = 150
|
|
202
|
+
) -> PackResult:
|
|
203
|
+
"""Packs workspace files to fill budget_tokens with optimal AST tiers.
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
workspace_dir: Target project root.
|
|
207
|
+
budget_tokens: Exact token ceiling (e.g. 8000, 16000, 32000, 64000).
|
|
208
|
+
focus: Optional focus target file or semantic query.
|
|
209
|
+
max_files: Maximum workspace files to inspect.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
PackResult with optimal multi-file context bundle.
|
|
213
|
+
"""
|
|
214
|
+
entries = cls.scan_workspace(workspace_dir, max_files=max_files)
|
|
215
|
+
if not entries:
|
|
216
|
+
return PackResult(
|
|
217
|
+
target_budget=budget_tokens,
|
|
218
|
+
total_tokens=0,
|
|
219
|
+
utilization_pct=0.0,
|
|
220
|
+
raw_total_tokens=0,
|
|
221
|
+
token_savings_pct=0.0,
|
|
222
|
+
focus_target=focus,
|
|
223
|
+
bundle_text="// No matching source files found in workspace."
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
cls.score_relevance(entries, focus=focus)
|
|
227
|
+
|
|
228
|
+
# Sort entries by relevance score descending
|
|
229
|
+
entries.sort(key=lambda e: e.relevance_score, reverse=True)
|
|
230
|
+
|
|
231
|
+
raw_total = sum(e.raw_tokens for e in entries)
|
|
232
|
+
|
|
233
|
+
# Reserved tokens for bundle manifest header (~400 tokens)
|
|
234
|
+
usable_budget = max(500, budget_tokens - 400)
|
|
235
|
+
allocated_tokens = 0
|
|
236
|
+
tier_counts = {"T-1": 0, "T-2": 0, "T-3": 0, "T-4": 0}
|
|
237
|
+
|
|
238
|
+
# Step 1: Assign top-priority focus files Tier 1 if possible
|
|
239
|
+
for e in entries:
|
|
240
|
+
if e.relevance_score >= 100.0: # Direct focus match
|
|
241
|
+
t1_tok = e.tier_tokens["T-1"]
|
|
242
|
+
if allocated_tokens + t1_tok <= usable_budget:
|
|
243
|
+
e.selected_tier = "T-1"
|
|
244
|
+
allocated_tokens += t1_tok
|
|
245
|
+
tier_counts["T-1"] += 1
|
|
246
|
+
elif allocated_tokens + e.tier_tokens["T-2"] <= usable_budget:
|
|
247
|
+
e.selected_tier = "T-2"
|
|
248
|
+
allocated_tokens += e.tier_tokens["T-2"]
|
|
249
|
+
tier_counts["T-2"] += 1
|
|
250
|
+
|
|
251
|
+
# Step 2: Try to assign Tier 2 (Light) or Tier 3 (Ultra) to high-relevance modules
|
|
252
|
+
for e in entries:
|
|
253
|
+
if e.selected_tier is not None:
|
|
254
|
+
continue
|
|
255
|
+
|
|
256
|
+
if e.relevance_score > 10.0:
|
|
257
|
+
t2_tok = e.tier_tokens["T-2"]
|
|
258
|
+
t3_tok = e.tier_tokens["T-3"]
|
|
259
|
+
if allocated_tokens + t2_tok <= usable_budget:
|
|
260
|
+
e.selected_tier = "T-2"
|
|
261
|
+
allocated_tokens += t2_tok
|
|
262
|
+
tier_counts["T-2"] += 1
|
|
263
|
+
elif allocated_tokens + t3_tok <= usable_budget:
|
|
264
|
+
e.selected_tier = "T-3"
|
|
265
|
+
allocated_tokens += t3_tok
|
|
266
|
+
tier_counts["T-3"] += 1
|
|
267
|
+
|
|
268
|
+
# Step 3: Fill remainder with Tier 3 (Ultra) or Tier 4 (Signatures)
|
|
269
|
+
for e in entries:
|
|
270
|
+
if e.selected_tier is not None:
|
|
271
|
+
continue
|
|
272
|
+
|
|
273
|
+
t3_tok = e.tier_tokens["T-3"]
|
|
274
|
+
t4_tok = e.tier_tokens["T-4"]
|
|
275
|
+
|
|
276
|
+
if allocated_tokens + t3_tok <= usable_budget:
|
|
277
|
+
e.selected_tier = "T-3"
|
|
278
|
+
allocated_tokens += t3_tok
|
|
279
|
+
tier_counts["T-3"] += 1
|
|
280
|
+
elif allocated_tokens + t4_tok <= usable_budget:
|
|
281
|
+
e.selected_tier = "T-4"
|
|
282
|
+
allocated_tokens += t4_tok
|
|
283
|
+
tier_counts["T-4"] += 1
|
|
284
|
+
else:
|
|
285
|
+
# Budget exhausted; this file is omitted from packed context
|
|
286
|
+
e.selected_tier = None
|
|
287
|
+
|
|
288
|
+
packed_entries = [e for e in entries if e.selected_tier is not None]
|
|
289
|
+
|
|
290
|
+
# Step 4: Render Markdown Context Bundle
|
|
291
|
+
bundle_md = cls.render_bundle_markdown(
|
|
292
|
+
packed_entries=packed_entries,
|
|
293
|
+
budget=budget_tokens,
|
|
294
|
+
allocated_tokens=allocated_tokens,
|
|
295
|
+
raw_total=raw_total,
|
|
296
|
+
focus=focus,
|
|
297
|
+
tier_counts=tier_counts
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
final_total = cls.estimate_tokens(bundle_md)
|
|
301
|
+
util_pct = min(100.0, (final_total / budget_tokens) * 100.0)
|
|
302
|
+
savings_pct = max(0.0, ((raw_total - final_total) / max(raw_total, 1)) * 100.0)
|
|
303
|
+
|
|
304
|
+
return PackResult(
|
|
305
|
+
target_budget=budget_tokens,
|
|
306
|
+
total_tokens=final_total,
|
|
307
|
+
utilization_pct=round(util_pct, 1),
|
|
308
|
+
raw_total_tokens=raw_total,
|
|
309
|
+
token_savings_pct=round(savings_pct, 1),
|
|
310
|
+
focus_target=focus,
|
|
311
|
+
entries=packed_entries,
|
|
312
|
+
bundle_text=bundle_md,
|
|
313
|
+
tier_counts=tier_counts
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
@classmethod
|
|
317
|
+
def render_bundle_markdown(
|
|
318
|
+
cls,
|
|
319
|
+
packed_entries: List[ModuleBudgetEntry],
|
|
320
|
+
budget: int,
|
|
321
|
+
allocated_tokens: int,
|
|
322
|
+
raw_total: int,
|
|
323
|
+
focus: str,
|
|
324
|
+
tier_counts: Dict[str, int]
|
|
325
|
+
) -> str:
|
|
326
|
+
"""Formats the unified AI context pack with manifest table and delimited code sections."""
|
|
327
|
+
out = []
|
|
328
|
+
focus_tag = f" (Focus: `{focus}`)" if focus else ""
|
|
329
|
+
tier_summary = ", ".join(f"{cnt}x {t}" for t, cnt in tier_counts.items() if cnt > 0)
|
|
330
|
+
|
|
331
|
+
out.append(f"# 📦 T-ZERO PACKED CONTEXT BUNDLE{focus_tag}")
|
|
332
|
+
out.append(f"- **Target Token Budget:** {budget:,} tokens")
|
|
333
|
+
out.append(f"- **Packed Token Volume:** ~{allocated_tokens:,} tokens ({allocated_tokens/max(budget,1)*100:.1f}% capacity)")
|
|
334
|
+
out.append(f"- **Raw Codebase Tokens:** ~{raw_total:,} tokens (**{max(0.0, (1 - allocated_tokens/max(raw_total,1))*100):.1f}% reduction**)")
|
|
335
|
+
out.append(f"- **Files Included:** {len(packed_entries)} files ({tier_summary})\n")
|
|
336
|
+
|
|
337
|
+
# Manifest Table
|
|
338
|
+
out.append("### 📑 Context Manifest")
|
|
339
|
+
out.append("| File | Tier | Language | Tokens | Status |")
|
|
340
|
+
out.append("| :--- | :---: | :---: | :---: | :--- |")
|
|
341
|
+
for e in packed_entries:
|
|
342
|
+
tok = e.tier_tokens.get(e.selected_tier, 0)
|
|
343
|
+
status = "Full Body" if e.selected_tier == "T-1" else "AST Skeleton"
|
|
344
|
+
out.append(f"| `{e.rel_path}` | **{e.selected_tier}** | {e.lang} | ~{tok:,} | {status} |")
|
|
345
|
+
out.append("\n---\n")
|
|
346
|
+
|
|
347
|
+
# File Content Blocks
|
|
348
|
+
for e in packed_entries:
|
|
349
|
+
code = e.tier_versions.get(e.selected_tier, "")
|
|
350
|
+
out.append(f"<!-- FILE: {e.rel_path} [TIER: {e.selected_tier} | {e.lang}] -->")
|
|
351
|
+
out.append(f"```{e.lang or 'text'}\n// [T-Zero Context: {e.rel_path} ({e.selected_tier})]")
|
|
352
|
+
out.append(code.strip())
|
|
353
|
+
out.append("```\n")
|
|
354
|
+
|
|
355
|
+
return "\n".join(out).strip()
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def pack_workspace(
|
|
359
|
+
workspace_dir: str = ".",
|
|
360
|
+
budget_tokens: int = 16000,
|
|
361
|
+
focus: str = "",
|
|
362
|
+
out_file: Optional[str] = None
|
|
363
|
+
) -> PackResult:
|
|
364
|
+
"""Convenience helper to pack workspace context into a budget and optionally write to disk."""
|
|
365
|
+
res = TokenBudgetPacker.pack(workspace_dir=workspace_dir, budget_tokens=budget_tokens, focus=focus)
|
|
366
|
+
if out_file:
|
|
367
|
+
out_path = os.path.join(workspace_dir, out_file) if not os.path.isabs(out_file) else out_file
|
|
368
|
+
with open(out_path, "w", encoding="utf-8") as f:
|
|
369
|
+
f.write(res.bundle_text)
|
|
370
|
+
return res
|