tokensafe 1.4.2 → 1.4.3

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/README.md CHANGED
@@ -133,8 +133,12 @@ TokenSafe is built from the ground up to support modern polyglot monorepos. Its
133
133
  | **Java & C#** | `.java`, `.cs` | Classes, records, methods with access modifiers (`public`, `protected`, `static`, `async`, `override`), generic return types (`Task<T>`, `List<E>`), `throws` | Method bodies folded; classes and interfaces remain structural |
134
134
  | **C & C++** | `.c`, `.cpp`, `.cc`, `.cxx`, `.h`, `.hpp` | Classes, structs, namespaces, scoped methods `ClassName::method`, `const`, `noexcept`, `override`, destructors | Functions folded; namespace and class hierarchies preserved |
135
135
  | **PHP, Kotlin, Swift** | `.php`, `.kt`, `.kts`, `.swift` | Classes, `function`, `fun`, `func` declarations with visibility modifiers | Function bodies folded into `{ /* ... */ }` |
136
+ | **CSS, SCSS, LESS, Tailwind** | `.css`, `.scss`, `.sass`, `.less` | **Design tokens (`:root`, `@theme`, CSS variables, `$var`, `@var`) 100% preserved**, container queries (`@media`, `@supports`, `@container`, `@layer`) kept open | Component selectors, `@keyframes`, and mixins folded into `{ /* ... */ }` unless matching `target_symbol` |
136
137
 
137
138
  ### Key Engine Guarantees:
139
+ - **Design Token & Palette Preservation**: When skeletonizing stylesheets, TokenSafe **always preserves all design tokens** (`:root { ... }`, Tailwind v4 `@theme { ... }`, CSS variables `--*`, SCSS `$vars`) so agents never hallucinate colors, radii, or fonts, while pruning 90%+ of bloated component styles.
140
+ - **Strict Arrow Function Parser**: Arrow functions strictly require `=>` before any `{` can be considered a function body; destructuring parameters (`({ a, b }: Props) =>`) and parenthesized ternary expressions (`const x = (flag) ? { a: 1 } : { b: 2 }`) are never corrupted.
141
+ - **Directory Tree Optimization (`tokensafe:list_dir`)**: Replaces verbose and noisy terminal `ls -la` commands with a compact, depth-bounded markdown tree without permissions, timestamps, or lockfiles.
138
142
  - **Graph-Guided Neighborhood Slicing**: When your AI agent inspects a function or component (via `tokensafe:smart_read_file(path, symbol="Target")`), TokenSafe automatically keeps the full implementation of the target **and its 1-hop callees/callers**, while collapsing all unrelated code.
139
143
  - **Comment & String Bracket Immunity**: Multi-line block comments (`/* ... */`, JSX `{/* ... */}`), template strings (`` `${...}` ``), and escaped quotes are tracked in a dedicated token lexer (`BraceLexer`), guaranteeing zero bracket desynchronization.
140
144
  - **Control-Flow Statement Immunity**: Statements like `if (...)`, `catch (err) {`, `for (...)`, and `while (...)` are strictly protected and never corrupted into placeholders.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "1.4.2",
3
+ "version": "1.4.3",
4
4
  "description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
5
5
  "main": "bin/tokensafe.js",
6
6
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agy-token-optimizer",
3
3
  "displayName": "TokenSafe",
4
- "version": "1.4.2",
4
+ "version": "1.4.3",
5
5
  "description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/rules/AGENTS.md CHANGED
@@ -31,6 +31,8 @@ Execute the specified action directly based on these extracted parameters.
31
31
  3. **Architecture Discovery**: Before executing multi-file exploration, ALWAYS call `tokensafe:get_architecture_graph(project_path)` to locate God Nodes and dependency topology in < 250 tokens without file crawling.
32
32
  4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.
33
33
  5. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
34
+ 6. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path, depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens).
35
+ 7. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
34
36
 
35
37
  ### 4. Turn Token Savings Footer (Proof-of-Savings)
36
38
  At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer:
@@ -126,4 +126,11 @@ class CommandSanitizer:
126
126
  est_saved = 2500
127
127
  return new_cmd, est_saved, "Sanitized grep directories and capped output to 30 matches"
128
128
 
129
+ # 7. ls command optimization (Replace verbose permissions/timestamps with compact single-column format)
130
+ if re.search(r"\bls\b", cmd):
131
+ if re.search(r"\bls\s+-[a-zA-Z]*(l|a)[a-zA-Z]*\b", cmd):
132
+ new_cmd = re.sub(r"\bls\s+-[a-zA-Z]+\b", "ls -1 -p", cmd)
133
+ est_saved = 380
134
+ return new_cmd, est_saved, "Replaced verbose ls flags with compact, secret-safe format (-1 -p)"
135
+
129
136
  return None, 0, ""
package/src/mcp_server.py CHANGED
@@ -8,6 +8,7 @@ import sys
8
8
  import os
9
9
  import json
10
10
  import traceback
11
+ import fnmatch
11
12
  from typing import Tuple, Optional
12
13
 
13
14
  # Ensure project root in sys.path
@@ -30,7 +31,7 @@ from src.guard import TokenSafeGuard
30
31
 
31
32
  SERVER_INFO = {
32
33
  "name": "tokensafe-mcp",
33
- "version": "1.4.2"
34
+ "version": "1.4.3"
34
35
  }
35
36
 
36
37
  TOOLS = [
@@ -121,9 +122,118 @@ TOOLS = [
121
122
  "file_path": {"type": "string", "description": "Optional: File path being written or modified"}
122
123
  }
123
124
  }
125
+ },
126
+ {
127
+ "name": "list_dir",
128
+ "description": "Returns a clean, token-efficient directory tree up to depth N without permissions, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces verbose ls -la.",
129
+ "inputSchema": {
130
+ "type": "object",
131
+ "properties": {
132
+ "path": {"type": "string", "description": "Path to the directory (relative to project root or absolute)"},
133
+ "depth": {"type": "integer", "description": "Maximum traversal depth (default: 2, max: 4)"},
134
+ "max_entries": {"type": "integer", "description": "Maximum entries to display before pruning (default: 80)"}
135
+ },
136
+ "required": ["path"]
137
+ }
124
138
  }
125
139
  ]
126
140
 
141
+ def format_file_size(size_bytes: int) -> str:
142
+ if size_bytes < 1024:
143
+ return f"{size_bytes} B"
144
+ elif size_bytes < 1024 * 1024:
145
+ return f"{size_bytes / 1024:.1f} KB"
146
+ else:
147
+ return f"{size_bytes / (1024 * 1024):.1f} MB"
148
+
149
+ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) -> str:
150
+ """
151
+ Builds a clean, compact markdown tree for dir_path.
152
+ Ignores heavy folders (node_modules, dist, .git, etc.) and redacts sensitive files (.env*).
153
+ """
154
+ IGNORE_DIRS = {
155
+ 'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
156
+ '__pycache__', '.turbo', '.vite', '.output', '.bunny', 'data',
157
+ '.venv', 'venv', '.cache', '.idea', '.vscode'
158
+ }
159
+ IGNORE_FILES = {
160
+ '*.lock', '*.lockb', '*.map', '.DS_Store', 'Thumbs.db', 'package-lock.json',
161
+ 'pnpm-lock.yaml', 'yarn.lock', 'Cargo.lock', 'composer.lock'
162
+ }
163
+ SECRET_FILES = {
164
+ '.env', '.env.local', '.env.production', '.env.staging', '.env.development'
165
+ }
166
+
167
+ if not os.path.exists(dir_path):
168
+ return f"Error: Directory not found: {dir_path}"
169
+ if not os.path.isdir(dir_path):
170
+ return f"Error: Path is not a directory: {dir_path}"
171
+
172
+ base_name = os.path.basename(os.path.abspath(dir_path)) or dir_path
173
+ lines = [f"📁 **{base_name}/** (max depth: {max_depth})"]
174
+ entries_count = 0
175
+
176
+ def _traverse(curr_dir: str, prefix: str, current_depth: int):
177
+ nonlocal entries_count
178
+ if current_depth > max_depth or entries_count >= max_entries:
179
+ return
180
+
181
+ try:
182
+ items = sorted(os.listdir(curr_dir))
183
+ except Exception as e:
184
+ lines.append(f"{prefix}└── [Permission Denied: {e}]")
185
+ return
186
+
187
+ dirs = []
188
+ files = []
189
+ for it in items:
190
+ if it.startswith('.') and it not in SECRET_FILES and it != '.gitignore':
191
+ continue
192
+ full_p = os.path.join(curr_dir, it)
193
+ if os.path.isdir(full_p):
194
+ if it in IGNORE_DIRS:
195
+ continue
196
+ dirs.append(it)
197
+ else:
198
+ files.append(it)
199
+
200
+ all_items = [(d, True) for d in dirs] + [(f, False) for f in files]
201
+ total_items = len(all_items)
202
+
203
+ for i, (name, is_dir) in enumerate(all_items):
204
+ if entries_count >= max_entries:
205
+ lines.append(f"{prefix}└── ... ({total_items - i} more items omitted for token efficiency)")
206
+ break
207
+
208
+ is_last = (i == total_items - 1)
209
+ pointer = "└── " if is_last else "├── "
210
+ extension_prefix = " " if is_last else "│ "
211
+ item_path = os.path.join(curr_dir, name)
212
+
213
+ if is_dir:
214
+ entries_count += 1
215
+ lines.append(f"{prefix}{pointer}📁 {name}/")
216
+ _traverse(item_path, prefix + extension_prefix, current_depth + 1)
217
+ else:
218
+ if name in SECRET_FILES:
219
+ lines.append(f"{prefix}{pointer}🔒 {name} [PROTECTED SECRET]")
220
+ entries_count += 1
221
+ continue
222
+ if any(fnmatch.fnmatch(name, pat) for pat in IGNORE_FILES):
223
+ continue
224
+ try:
225
+ sz = os.path.getsize(item_path)
226
+ sz_str = format_file_size(sz)
227
+ except Exception:
228
+ sz_str = ""
229
+ entries_count += 1
230
+ size_label = f" ({sz_str})" if sz_str else ""
231
+ lines.append(f"{prefix}{pointer}{name}{size_label}")
232
+
233
+ _traverse(dir_path, "", 1)
234
+ lines.append("\n*Pruned noisy directories (node_modules, dist, .git) & lockfiles to conserve tokens.*")
235
+ return "\n".join(lines)
236
+
127
237
  def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
128
238
  """
129
239
  Safely resolves the target project root without falling back to system root dirs.
@@ -413,6 +523,29 @@ def handle_tool_call(name: str, args: dict) -> dict:
413
523
  )
414
524
  return {"content": [{"type": "text", "text": surface_md}]}
415
525
 
526
+ elif name == "list_dir":
527
+ path = args.get("path", "")
528
+ if not path:
529
+ return {"isError": True, "content": [{"type": "text", "text": "Error: 'path' argument is required for list_dir."}]}
530
+
531
+ # Resolve path relative to current working directory or absolute
532
+ abs_path = os.path.abspath(path)
533
+ depth = min(4, max(1, int(args.get("depth", 2))))
534
+ max_entries = min(150, max(10, int(args.get("max_entries", 80))))
535
+
536
+ tree_output = build_dir_tree(abs_path, max_depth=depth, max_entries=max_entries)
537
+ tree_tokens = count_tokens(tree_output)
538
+ # Estimate equivalent tokens from multiple verbose ls -la calls (at least ~800 tokens)
539
+ est_orig_tokens = max(800, tree_tokens * 6)
540
+ tracker.record_event(
541
+ session_id="mcp_session",
542
+ event_type="DIR_LIST",
543
+ original_tokens=est_orig_tokens,
544
+ optimized_tokens=tree_tokens,
545
+ details={"path": os.path.basename(abs_path) or abs_path, "depth": depth, "tokens_saved": est_orig_tokens - tree_tokens}
546
+ )
547
+ return {"content": [{"type": "text", "text": tree_output}]}
548
+
416
549
  return {"isError": True, "content": [{"type": "text", "text": f"Unknown tool: {name}"}]}
417
550
 
418
551
  def run_mcp_server():
@@ -36,13 +36,31 @@ RUST_FN_REGEX = re.compile(
36
36
  )
37
37
 
38
38
  # 4. Arrow function / React component: const Foo = (...) => { or export const Foo: React.FC<Props> = (...) => {
39
+ # Supports single-line return types, generics, React.memo, useCallback
39
40
  ARROW_FN_REGEX = re.compile(
40
- r'^(?:export\s+)?(?:const|let|var)\s+([a-zA-Z0-9_$]+)(?:\s*:\s*[^=]+)?\s*=\s*(?:async\s*)?(?:React\.(?:memo|forwardRef)\s*\()?(?:useCallback\s*\()?(?:(?:\([^)]*\)|[a-zA-Z0-9_$]+)\s*=>|function\b)'
41
+ r'^(?:export\s+)?(?:default\s+)?(?:const|let|var)\s+([a-zA-Z0-9_$]+)'
42
+ r'(?:\s*:\s*[^=]+)?\s*=\s*'
43
+ r'(?:async\s*)?'
44
+ r'(?:React\.(?:memo|forwardRef)\s*\()?'
45
+ r'(?:useCallback\s*\()?'
46
+ r'(?:'
47
+ r'(?:<[^>]+>\s*)?'
48
+ r'(?:\([^)]*\)|[a-zA-Z0-9_$]+)'
49
+ r'(?:\s*:\s*[^=>]+)?'
50
+ r'\s*=>'
51
+ r'|function\b'
52
+ r')'
41
53
  )
42
54
 
43
55
  # 4b. Multi-line arrow function start: const Foo: React.FC<Props> = (
44
56
  ARROW_MULTILINE_START = re.compile(
45
- r'^(?:export\s+)?(?:const|let|var)\s+([a-zA-Z0-9_$]+)(?:\s*:\s*[^=]+)?\s*=\s*(?:async\s*)?(?:React\.(?:memo|forwardRef)\s*\()?(?:useCallback\s*\()?\s*\('
57
+ r'^(?:export\s+)?(?:default\s+)?(?:const|let|var)\s+([a-zA-Z0-9_$]+)'
58
+ r'(?:\s*:\s*[^=]+)?\s*=\s*'
59
+ r'(?:async\s*)?'
60
+ r'(?:React\.(?:memo|forwardRef)\s*\()?'
61
+ r'(?:useCallback\s*\()?\s*'
62
+ r'(?:<[^>]+>\s*)?'
63
+ r'\('
46
64
  )
47
65
 
48
66
  # 5. Method definition (Java, C#, C++, TS, PHP)
@@ -105,6 +123,8 @@ class Skeletonizer:
105
123
  ".go", ".java", ".rs", ".cpp", ".cc", ".cxx", ".c", ".h", ".hpp", ".cs", ".php", ".kt", ".swift"
106
124
  ):
107
125
  return cls._skeletonize_braces(code, ext, keep_symbols=keep_symbols)
126
+ elif ext in (".css", ".scss", ".sass", ".less"):
127
+ return cls._skeletonize_css(code, ext, keep_symbols=keep_symbols)
108
128
  return code
109
129
 
110
130
  @classmethod
@@ -165,7 +185,9 @@ class Skeletonizer:
165
185
 
166
186
  m = ARROW_MULTILINE_START.match(line_clean)
167
187
  if m and not line_clean.endswith(";"):
168
- return (m.group(1), "arrow_multiline")
188
+ # Multi-line parameter list MUST have unclosed parentheses on this line (unless '=>' is present)
189
+ if line_clean.count("(") > line_clean.count(")") or "=>" in line_clean:
190
+ return (m.group(1), "arrow_multiline")
169
191
 
170
192
  m = METHOD_REGEX.match(line_clean)
171
193
  if m:
@@ -198,12 +220,13 @@ class Skeletonizer:
198
220
  pending_header_lines = []
199
221
  pending_name = None
200
222
  pending_kind = None
223
+ arrow_seen = False
201
224
 
202
225
  comment_token = "/* ... */" if ext != ".py" else "..."
203
226
 
204
227
  for line in lines:
205
228
  raw_line = line
206
- line_clean = line.strip()
229
+ clean_line = lexer.clean_line(line).strip()
207
230
 
208
231
  # 1. If currently skipping a folded function body
209
232
  if in_folding:
@@ -224,58 +247,141 @@ class Skeletonizer:
224
247
  # 2. If accumulating a multi-line header
225
248
  if pending_header_lines:
226
249
  pending_header_lines.append(raw_line)
227
- if "=>" in line_clean or "{" in line_clean:
228
- fn_name = pending_name
229
- should_keep = keep_symbols is not None and fn_name in keep_symbols
230
250
 
231
- last_brace_idx = raw_line.rfind("{")
232
- if last_brace_idx != -1:
233
- sig_lines = pending_header_lines[:-1] + [raw_line[:last_brace_idx]]
251
+ if pending_kind == "arrow_multiline":
252
+ if "=>" in clean_line:
253
+ arrow_seen = True
254
+
255
+ has_body_brace = False
256
+ body_brace_idx = -1
257
+ if arrow_seen:
258
+ if "=>" in clean_line:
259
+ arrow_idx = clean_line.find("=>")
260
+ body_brace_idx = clean_line.find("{", arrow_idx + 2)
261
+ if body_brace_idx != -1:
262
+ has_body_brace = True
263
+ elif "{" in clean_line:
264
+ body_brace_idx = clean_line.find("{")
265
+ has_body_brace = True
266
+
267
+ if has_body_brace:
268
+ fn_name = pending_name
269
+ should_keep = keep_symbols is not None and fn_name in keep_symbols
270
+
271
+ sig_lines = pending_header_lines[:-1] + [raw_line[:body_brace_idx]]
234
272
  temp_lexer = BraceLexer()
235
273
  sig_open = sum(temp_lexer.count_braces(sl)[0] for sl in sig_lines)
236
274
  sig_close = sum(temp_lexer.count_braces(sl)[1] for sl in sig_lines)
237
275
  base_depth = current_depth + (sig_open - sig_close)
238
- else:
239
- base_depth = current_depth
240
276
 
241
- if should_keep:
277
+ if should_keep:
278
+ out.extend(pending_header_lines)
279
+ for phl in pending_header_lines:
280
+ op, cl = lexer.count_braces(phl)
281
+ current_depth += op - cl
282
+ else:
283
+ folded_head = raw_line[:body_brace_idx] + f"{{ {comment_token} }}"
284
+ if raw_line.rstrip().endswith(";"):
285
+ folded_head += ";"
286
+ elif raw_line.rstrip().endswith(","):
287
+ folded_head += ","
288
+ pending_header_lines[-1] = folded_head
289
+ out.extend(pending_header_lines)
290
+ fold_depth = base_depth
291
+ current_depth = base_depth + 1
292
+ in_folding = True
293
+
294
+ pending_header_lines = []
295
+ pending_name = None
296
+ pending_kind = None
297
+ arrow_seen = False
298
+ continue
299
+ elif ";" in clean_line and not has_body_brace:
300
+ # Non-function variable assignment or ternary expression (e.g. gramBalanceDeduct)
242
301
  out.extend(pending_header_lines)
243
302
  for phl in pending_header_lines:
244
303
  op, cl = lexer.count_braces(phl)
245
304
  current_depth += op - cl
246
- else:
247
- folded_last_line = re.sub(r'\{.*$', f'{{ {comment_token} }}', raw_line)
248
- pending_header_lines[-1] = folded_last_line
305
+ pending_header_lines = []
306
+ pending_name = None
307
+ pending_kind = None
308
+ arrow_seen = False
309
+ continue
310
+ elif len(pending_header_lines) > 25:
249
311
  out.extend(pending_header_lines)
250
- fold_depth = base_depth
251
- current_depth = base_depth + 1
252
- in_folding = True
253
-
254
- pending_header_lines = []
255
- pending_name = None
256
- pending_kind = None
257
- continue
258
- elif ";" in line_clean and not ("{" in line_clean or "=>" in line_clean):
259
- out.extend(pending_header_lines)
260
- for phl in pending_header_lines:
261
- op, cl = lexer.count_braces(phl)
262
- current_depth += op - cl
263
- pending_header_lines = []
264
- pending_name = None
265
- pending_kind = None
266
- continue
312
+ for phl in pending_header_lines:
313
+ op, cl = lexer.count_braces(phl)
314
+ current_depth += op - cl
315
+ pending_header_lines = []
316
+ pending_name = None
317
+ pending_kind = None
318
+ arrow_seen = False
319
+ continue
320
+ else:
321
+ continue
267
322
  else:
268
- continue
323
+ # Non-arrow multiline (function foo(, method, func)
324
+ if "{" in clean_line:
325
+ body_brace_idx = raw_line.rfind("{")
326
+ fn_name = pending_name
327
+ should_keep = keep_symbols is not None and fn_name in keep_symbols
328
+
329
+ sig_lines = pending_header_lines[:-1] + [raw_line[:body_brace_idx]]
330
+ temp_lexer = BraceLexer()
331
+ sig_open = sum(temp_lexer.count_braces(sl)[0] for sl in sig_lines)
332
+ sig_close = sum(temp_lexer.count_braces(sl)[1] for sl in sig_lines)
333
+ base_depth = current_depth + (sig_open - sig_close)
334
+
335
+ if should_keep:
336
+ out.extend(pending_header_lines)
337
+ for phl in pending_header_lines:
338
+ op, cl = lexer.count_braces(phl)
339
+ current_depth += op - cl
340
+ else:
341
+ folded_last_line = re.sub(r'\{.*$', f'{{ {comment_token} }}', raw_line)
342
+ pending_header_lines[-1] = folded_last_line
343
+ out.extend(pending_header_lines)
344
+ fold_depth = base_depth
345
+ current_depth = base_depth + 1
346
+ in_folding = True
347
+
348
+ pending_header_lines = []
349
+ pending_name = None
350
+ pending_kind = None
351
+ continue
352
+ elif ";" in clean_line and "{" not in clean_line:
353
+ out.extend(pending_header_lines)
354
+ for phl in pending_header_lines:
355
+ op, cl = lexer.count_braces(phl)
356
+ current_depth += op - cl
357
+ pending_header_lines = []
358
+ pending_name = None
359
+ pending_kind = None
360
+ continue
361
+ else:
362
+ continue
269
363
 
270
364
  # 3. Check for function start
271
365
  fn_info = cls._extract_fn(raw_line)
272
366
  if fn_info:
273
367
  name, kind = fn_info
274
368
 
275
- if (kind in ('arrow_multiline', 'arrow_fn')) and "=>" not in raw_line:
369
+ if kind == 'arrow_multiline':
370
+ clean = lexer.clean_line(raw_line)
371
+ if "=>" in clean and clean.find("{") > clean.find("=>"):
372
+ kind = 'arrow_fn'
373
+ else:
374
+ pending_header_lines = [raw_line]
375
+ pending_name = name
376
+ pending_kind = 'arrow_multiline'
377
+ arrow_seen = "=>" in clean
378
+ continue
379
+
380
+ if kind == 'arrow_fn' and "=>" not in raw_line:
276
381
  pending_header_lines = [raw_line]
277
382
  pending_name = name
278
383
  pending_kind = 'arrow_multiline'
384
+ arrow_seen = False
279
385
  continue
280
386
 
281
387
  if "{" in raw_line:
@@ -287,6 +393,8 @@ class Skeletonizer:
287
393
  current_depth += open_b - close_b
288
394
  else:
289
395
  folded_line = re.sub(r'\{.*$', f'{{ {comment_token} }}', raw_line)
396
+ if raw_line.rstrip().endswith(";"):
397
+ folded_line += ";"
290
398
  out.append(folded_line)
291
399
  open_b_head, _ = lexer.count_braces(raw_line[:raw_line.find("{") + 1])
292
400
  fold_depth = current_depth + open_b_head - 1
@@ -302,6 +410,137 @@ class Skeletonizer:
302
410
 
303
411
  return "\n".join(out)
304
412
 
413
+ @classmethod
414
+ def _skeletonize_css(cls, code: str, ext: str, keep_symbols: Optional[Set[str]] = None) -> str:
415
+ """
416
+ Specialized CSS / SCSS / SASS / LESS AST skeletonizer.
417
+ Design tokens (:root, @theme, html, body, $variables, @variables) are ALWAYS preserved in full
418
+ so AI agents always possess the complete project design palette and variables.
419
+ Container at-rules (@media, @supports, @container, @layer) preserve structure and track depth.
420
+ Component selectors and mixins are folded into '{ /* ... */ }' unless matching keep_symbols.
421
+ """
422
+ lines = code.splitlines()
423
+ out = []
424
+ lexer = BraceLexer()
425
+ in_folding = False
426
+ fold_depth = 0
427
+ current_depth = 0
428
+
429
+ CONTAINER_RULES = ("@media", "@supports", "@container", "@layer", "@document")
430
+ TOKEN_SELECTORS = (":root", "@theme", "html", "body")
431
+
432
+ pending_sel = []
433
+
434
+ for line in lines:
435
+ raw_line = line
436
+ clean_line = lexer.clean_line(line).strip()
437
+
438
+ if in_folding:
439
+ open_b, close_b = lexer.count_braces(raw_line)
440
+ current_depth += open_b - close_b
441
+ if current_depth <= fold_depth:
442
+ in_folding = False
443
+ trailing = ""
444
+ idx = raw_line.rfind("}")
445
+ if idx != -1 and idx < len(raw_line) - 1:
446
+ suffix = raw_line[idx + 1:].strip()
447
+ if suffix.startswith(";") or suffix.startswith(","):
448
+ trailing = suffix
449
+ if trailing and out:
450
+ out[-1] = out[-1] + trailing
451
+ continue
452
+
453
+ if pending_sel:
454
+ pending_sel.append(raw_line)
455
+ if "{" in clean_line:
456
+ full_sel = " ".join(s.strip() for s in pending_sel)
457
+ brace_idx = raw_line.find("{")
458
+ is_container = any(full_sel.strip().startswith(c) for c in CONTAINER_RULES)
459
+ is_token = any(ts in full_sel for ts in TOKEN_SELECTORS)
460
+
461
+ matched_symbol = False
462
+ if keep_symbols:
463
+ for sym in keep_symbols:
464
+ clean_sym = sym.lstrip(".#")
465
+ if clean_sym and (clean_sym in full_sel or sym in full_sel):
466
+ matched_symbol = True
467
+ break
468
+
469
+ should_keep = is_container or is_token or matched_symbol
470
+ if should_keep:
471
+ out.extend(pending_sel)
472
+ for pl in pending_sel:
473
+ op, cl = lexer.count_braces(pl)
474
+ current_depth += op - cl
475
+ else:
476
+ head = raw_line[:brace_idx] + "{ /* ... */ }"
477
+ if raw_line.rstrip().endswith(";"):
478
+ head += ";"
479
+ pending_sel[-1] = head
480
+ out.extend(pending_sel)
481
+ open_b_head, _ = lexer.count_braces(raw_line[:brace_idx + 1])
482
+ fold_depth = current_depth + open_b_head - 1
483
+ open_b, close_b = lexer.count_braces(raw_line)
484
+ current_depth += open_b - close_b
485
+ if current_depth > fold_depth:
486
+ in_folding = True
487
+ pending_sel = []
488
+ elif ";" in clean_line and "{" not in clean_line:
489
+ out.extend(pending_sel)
490
+ for pl in pending_sel:
491
+ op, cl = lexer.count_braces(pl)
492
+ current_depth += op - cl
493
+ pending_sel = []
494
+ continue
495
+
496
+ if "{" in clean_line:
497
+ is_container = any(clean_line.startswith(c) for c in CONTAINER_RULES)
498
+ is_token = any(ts in clean_line for ts in TOKEN_SELECTORS)
499
+
500
+ matched_symbol = False
501
+ if keep_symbols:
502
+ for sym in keep_symbols:
503
+ clean_sym = sym.lstrip(".#")
504
+ if clean_sym and (clean_sym in clean_line or sym in clean_line):
505
+ matched_symbol = True
506
+ break
507
+
508
+ should_keep = is_container or is_token or matched_symbol
509
+ open_b, close_b = lexer.count_braces(raw_line)
510
+
511
+ if should_keep:
512
+ out.append(raw_line)
513
+ current_depth += open_b - close_b
514
+ else:
515
+ brace_idx = raw_line.find("{")
516
+ folded = raw_line[:brace_idx] + "{ /* ... */ }"
517
+ if raw_line.rstrip().endswith(";"):
518
+ folded += ";"
519
+ out.append(folded)
520
+ open_b_head, _ = lexer.count_braces(raw_line[:brace_idx + 1])
521
+ fold_depth = current_depth + open_b_head - 1
522
+ current_depth += open_b - close_b
523
+ if current_depth > fold_depth:
524
+ in_folding = True
525
+ continue
526
+
527
+ # Closing braces or standalone operators
528
+ if clean_line.startswith("}"):
529
+ out.append(raw_line)
530
+ open_b, close_b = lexer.count_braces(raw_line)
531
+ current_depth += open_b - close_b
532
+ continue
533
+
534
+ if clean_line and not clean_line.endswith(";") and not clean_line.startswith("//") and not clean_line.startswith("/*") and not clean_line.startswith("*"):
535
+ pending_sel = [raw_line]
536
+ continue
537
+
538
+ out.append(raw_line)
539
+ open_b, close_b = lexer.count_braces(raw_line)
540
+ current_depth += open_b - close_b
541
+
542
+ return "\n".join(out)
543
+
305
544
  @classmethod
306
545
  def get_skeleton_file(cls, original_path: str, target_symbol: Optional[str] = None) -> Tuple[Optional[str], int, int]:
307
546
  """