comptext-codex 5.0.0__py3-none-any.whl

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.
@@ -0,0 +1,50 @@
1
+ """CompText Codex - Domain-Specific Language for efficient LLM interaction.
2
+
3
+ Migration from Notion/YAML to SQLite-based architecture provides:
4
+ - ~10x faster startup (no YAML parsing)
5
+ - Queryable command/module catalog
6
+ - Single-file database (codex.db)
7
+ - Type-safe metadata via dataclasses
8
+ """
9
+
10
+ from .token_reduction import calculate_reduction, token_count
11
+ from .token_report import build_token_report, load_commands, load_modules
12
+ from .parser import CompTextParser, CompTextCommand, parse
13
+ from .executor import CompTextExecutor, ExecutionResult, execute
14
+ from .repl import CompTextREPL
15
+ from .store import CodexStore
16
+ from .registry import (
17
+ registry,
18
+ codex_module,
19
+ codex_command,
20
+ ensure_modules_loaded,
21
+ ModuleMeta,
22
+ CommandMeta,
23
+ )
24
+
25
+ __all__ = [
26
+ # Token utilities
27
+ "token_count",
28
+ "calculate_reduction",
29
+ "build_token_report",
30
+ "load_commands",
31
+ "load_modules",
32
+ # Core DSL
33
+ "CompTextParser",
34
+ "CompTextCommand",
35
+ "CompTextExecutor",
36
+ "ExecutionResult",
37
+ "CompTextREPL",
38
+ "parse",
39
+ "execute",
40
+ # New: SQLite Store & Registry
41
+ "CodexStore",
42
+ "registry",
43
+ "codex_module",
44
+ "codex_command",
45
+ "ensure_modules_loaded",
46
+ "ModuleMeta",
47
+ "CommandMeta",
48
+ ]
49
+
50
+ __version__ = "4.0.0"
comptext_codex/cli.py ADDED
@@ -0,0 +1,91 @@
1
+ """CLI entrypoint for CompText Codex utilities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import click
8
+
9
+ from .token_reduction import main as run_token_benchmark
10
+ from .token_report import (
11
+ build_token_report,
12
+ load_commands,
13
+ load_modules,
14
+ render_text_report,
15
+ report_as_json,
16
+ )
17
+
18
+
19
+ @click.group()
20
+ def main() -> None:
21
+ """CompText Codex command-line tools."""
22
+
23
+
24
+ @main.command("token-report")
25
+ @click.option(
26
+ "--codex-dir",
27
+ default="codex",
28
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
29
+ help="Path to the codex directory.",
30
+ )
31
+ @click.option(
32
+ "--module",
33
+ "module_filter",
34
+ default=None,
35
+ help="Filter the report to a specific module code.",
36
+ )
37
+ @click.option(
38
+ "--format",
39
+ "output_format",
40
+ type=click.Choice(["text", "json"], case_sensitive=False),
41
+ default="text",
42
+ help="Output format for the report.",
43
+ )
44
+ def token_report(
45
+ codex_dir: Path, module_filter: str | None, output_format: str
46
+ ) -> None:
47
+ """Generate a token usage report for the codex."""
48
+ commands = load_commands(codex_dir)
49
+ if module_filter:
50
+ commands = [cmd for cmd in commands if cmd.get("module") == module_filter]
51
+ # If no commands found for the filter, continue with empty list (graceful handling)
52
+ # This allows the report to show "Total commands: 0"
53
+
54
+ modules = load_modules(codex_dir)
55
+ report = build_token_report(commands, modules)
56
+
57
+ if output_format.lower() == "json":
58
+ click.echo(report_as_json(report))
59
+ else:
60
+ click.echo(render_text_report(report))
61
+
62
+
63
+ @main.command("token-benchmark")
64
+ @click.option(
65
+ "--output",
66
+ default="TOKEN_REDUCTION_RESULTS.md",
67
+ type=click.Path(dir_okay=False, path_type=Path),
68
+ help="Where to write the token reduction benchmark report.",
69
+ )
70
+ def token_benchmark(output: Path) -> None:
71
+ """Run the token reduction benchmark suite and write the markdown report."""
72
+ run_token_benchmark(output_path=output)
73
+
74
+
75
+ @main.command("repl")
76
+ @click.option(
77
+ "--codex-dir",
78
+ default="codex",
79
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
80
+ help="Path to the codex directory.",
81
+ )
82
+ def repl(codex_dir: Path) -> None:
83
+ """Start an interactive REPL session for CompText commands."""
84
+ from .repl import CompTextREPL
85
+
86
+ repl_session = CompTextREPL(codex_dir=str(codex_dir))
87
+ repl_session.run()
88
+
89
+
90
+ if __name__ == "__main__":
91
+ main()
@@ -0,0 +1,330 @@
1
+ """CompText V5.0 ULTRA CLI - Interactive Command Line Interface."""
2
+
3
+ import sys
4
+ import json
5
+ from typing import Optional
6
+ import click
7
+ from rich.console import Console
8
+ from rich.table import Table
9
+ from rich.panel import Panel
10
+ from rich.syntax import Syntax
11
+ from rich import print as rprint
12
+
13
+ from .parser_v5 import CompTextParserV5, CompTextCommandV5
14
+
15
+
16
+ console = Console()
17
+
18
+
19
+ @click.group()
20
+ @click.version_option(version="5.0.0", prog_name="CompText ULTRA")
21
+ def cli():
22
+ """CompText V5.0 ULTRA - 94% Token Reduction Protocol"""
23
+ pass
24
+
25
+
26
+ @cli.command()
27
+ @click.argument('command', required=False)
28
+ @click.option('--format', '-f', type=click.Choice(['json', 'table', 'text']), default='table',
29
+ help='Output format')
30
+ @click.option('--v4', is_flag=True, help='Show V4 equivalent')
31
+ @click.option('--stats', is_flag=True, help='Show token statistics')
32
+ @click.option('--natural', '-n', help='Natural language for comparison')
33
+ def parse(command: Optional[str], format: str, v4: bool, stats: bool, natural: Optional[str]):
34
+ """Parse a V5.0 ULTRA command.
35
+
36
+ Examples:
37
+ comptext parse "C;P:FIB"
38
+ comptext parse "B:[D:SUM]|[C;P:FIB]|[E;C:WHY]" --v4
39
+ comptext parse "T;P;R:FIB" --stats --natural "Write unit tests"
40
+ """
41
+ if not command:
42
+ console.print("[red]Error: Command required[/red]")
43
+ sys.exit(1)
44
+
45
+ parser = CompTextParserV5()
46
+
47
+ try:
48
+ results = parser.parse(command)
49
+
50
+ if format == 'json':
51
+ output = []
52
+ for cmd in results:
53
+ output.append({
54
+ 'command': cmd.command,
55
+ 'language': cmd.language,
56
+ 'modifiers': cmd.modifiers,
57
+ 'task': cmd.task,
58
+ 'raw': cmd.raw
59
+ })
60
+ console.print_json(json.dumps(output, indent=2))
61
+
62
+ elif format == 'table':
63
+ table = Table(title="Parsed V5.0 ULTRA Commands")
64
+ table.add_column("Command", style="cyan")
65
+ table.add_column("Language", style="magenta")
66
+ table.add_column("Modifiers", style="yellow")
67
+ table.add_column("Task", style="green")
68
+
69
+ for cmd in results:
70
+ table.add_row(
71
+ parser.COMMANDS.get(cmd.command, cmd.command),
72
+ parser.LANGUAGES.get(cmd.language, cmd.language) if cmd.language else "-",
73
+ ", ".join([parser.MODIFIERS.get(m, m) for m in cmd.modifiers]) if cmd.modifiers else "-",
74
+ cmd.task or "-"
75
+ )
76
+
77
+ console.print(table)
78
+
79
+ if v4:
80
+ console.print("\n[bold]V4.0 Format:[/bold]")
81
+ for i, cmd in enumerate(results):
82
+ v4_format = parser.to_v4_format(cmd)
83
+ console.print(f" [{i+1}] {v4_format}")
84
+
85
+ if stats and natural:
86
+ console.print("\n[bold]Token Statistics:[/bold]")
87
+ token_stats = parser.calculate_token_reduction(natural, command)
88
+ stats_table = Table(show_header=False)
89
+ stats_table.add_row("Natural Language", f"{token_stats['natural_tokens']} tokens")
90
+ stats_table.add_row("V5.0 ULTRA", f"{token_stats['v5_tokens']} tokens")
91
+ stats_table.add_row("Tokens Saved", f"{token_stats['tokens_saved']} tokens")
92
+ stats_table.add_row("Reduction", f"[green bold]{token_stats['reduction_percent']}%[/green bold]")
93
+ console.print(stats_table)
94
+
95
+ else: # text
96
+ for i, cmd in enumerate(results):
97
+ console.print(f"[{i+1}] {cmd.command} - {cmd.task}")
98
+
99
+ except Exception as e:
100
+ console.print(f"[red]Parse Error: {e}[/red]")
101
+ sys.exit(1)
102
+
103
+
104
+ @cli.command()
105
+ @click.argument('command')
106
+ @click.option('--language', '-l', help='Language (PYTHON, JAVASCRIPT, etc.)')
107
+ @click.option('--modifiers', '-m', multiple=True, help='Modifiers (ROBUST, CONCISE, etc.)')
108
+ @click.option('--task', '-t', help='Task name')
109
+ def encode(command: str, language: Optional[str], modifiers: tuple, task: Optional[str]):
110
+ """Encode a command to V5.0 ULTRA format.
111
+
112
+ Examples:
113
+ comptext encode CODE --language PYTHON --task FIB
114
+ comptext encode TEST --language PYTHON --modifiers ROBUST --task FIB
115
+ """
116
+ parser = CompTextParserV5()
117
+
118
+ try:
119
+ result = parser.encode(
120
+ command.upper(),
121
+ language.upper() if language else None,
122
+ [m.upper() for m in modifiers] if modifiers else None,
123
+ task
124
+ )
125
+ console.print(Panel(result, title="V5.0 ULTRA Encoded", border_style="green"))
126
+ except Exception as e:
127
+ console.print(f"[red]Encode Error: {e}[/red]")
128
+ sys.exit(1)
129
+
130
+
131
+ @cli.command()
132
+ @click.option('--natural', '-n', required=True, help='Natural language command')
133
+ @click.option('--v5', required=True, help='V5.0 ULTRA command')
134
+ def benchmark(natural: str, v5: str):
135
+ """Benchmark token reduction.
136
+
137
+ Example:
138
+ comptext benchmark -n "Write Python Fibonacci" -v "C;P:FIB"
139
+ """
140
+ parser = CompTextParserV5()
141
+
142
+ stats = parser.calculate_token_reduction(natural, v5)
143
+
144
+ table = Table(title="Token Reduction Benchmark", show_header=True)
145
+ table.add_column("Metric", style="cyan")
146
+ table.add_column("Value", style="white")
147
+
148
+ table.add_row("Natural Language", natural)
149
+ table.add_row("Natural Tokens", str(stats['natural_tokens']))
150
+ table.add_row("V5.0 ULTRA Command", v5)
151
+ table.add_row("V5 Tokens", str(stats['v5_tokens']))
152
+ table.add_row("Tokens Saved", f"[yellow]{stats['tokens_saved']}[/yellow]")
153
+ table.add_row("Reduction", f"[green bold]{stats['reduction_percent']}%[/green bold]")
154
+ table.add_row("Char Reduction", f"{stats['char_reduction']}%")
155
+
156
+ console.print(table)
157
+
158
+
159
+ @cli.command()
160
+ def reference():
161
+ """Display V5.0 ULTRA syntax reference."""
162
+
163
+ console.print(Panel.fit(
164
+ "[bold cyan]CompText V5.0 ULTRA - Quick Reference[/bold cyan]",
165
+ border_style="cyan"
166
+ ))
167
+
168
+ # Commands
169
+ cmd_table = Table(title="Commands (Single Char)", show_header=True)
170
+ cmd_table.add_column("Char", style="cyan")
171
+ cmd_table.add_column("Command", style="white")
172
+
173
+ parser = CompTextParserV5()
174
+ for char, full in parser.COMMANDS.items():
175
+ cmd_table.add_row(char, full)
176
+
177
+ console.print(cmd_table)
178
+
179
+ # Languages
180
+ lang_table = Table(title="Languages (Single Char)", show_header=True)
181
+ lang_table.add_column("Char", style="magenta")
182
+ lang_table.add_column("Language", style="white")
183
+
184
+ for char, full in parser.LANGUAGES.items():
185
+ lang_table.add_row(char, full)
186
+
187
+ console.print(lang_table)
188
+
189
+ # Modifiers
190
+ mod_table = Table(title="Modifiers (Single Char)", show_header=True)
191
+ mod_table.add_column("Char", style="yellow")
192
+ mod_table.add_column("Modifier", style="white")
193
+
194
+ for char, full in parser.MODIFIERS.items():
195
+ mod_table.add_row(char, full)
196
+
197
+ console.print(mod_table)
198
+
199
+ # Examples
200
+ console.print("\n[bold]Examples:[/bold]")
201
+ examples = [
202
+ ("C;P:FIB", "Code Python Fibonacci"),
203
+ ("T;P;R:FIB", "Test Python (Robust) Fibonacci"),
204
+ ("B:[D:SUM]|[C;P:FIB]|[E;C:WHY]", "Batch: Document + Code + Explain"),
205
+ ("B:[A:STRUCT]|[F;T:MEM]|[O;S:Q]|[D:API]", "Batch: Analyze + Fix + Optimize + Document"),
206
+ ]
207
+
208
+ for v5, desc in examples:
209
+ console.print(f" [cyan]{v5}[/cyan]")
210
+ console.print(f" {desc}\n")
211
+
212
+
213
+ @cli.command()
214
+ def interactive():
215
+ """Start interactive V5.0 ULTRA shell."""
216
+
217
+ parser = CompTextParserV5()
218
+
219
+ console.print(Panel.fit(
220
+ "[bold cyan]CompText V5.0 ULTRA - Interactive Shell[/bold cyan]\n"
221
+ "Type V5 commands or 'help' for reference\n"
222
+ "Type 'exit' to quit",
223
+ border_style="cyan"
224
+ ))
225
+
226
+ while True:
227
+ try:
228
+ cmd = console.input("\n[bold green]v5>[/bold green] ")
229
+
230
+ if not cmd.strip():
231
+ continue
232
+
233
+ if cmd.lower() in ['exit', 'quit', 'q']:
234
+ console.print("[yellow]Goodbye![/yellow]")
235
+ break
236
+
237
+ if cmd.lower() == 'help':
238
+ console.print("\n[bold]Quick Commands:[/bold]")
239
+ console.print(" help - Show this help")
240
+ console.print(" ref - Show syntax reference")
241
+ console.print(" exit - Exit shell")
242
+ console.print("\n[bold]Try these:[/bold]")
243
+ console.print(" C;P:FIB")
244
+ console.print(" B:[D:SUM]|[C;P:FIB]|[E;C:WHY]")
245
+ continue
246
+
247
+ if cmd.lower() == 'ref':
248
+ reference.invoke(click.Context(reference))
249
+ continue
250
+
251
+ # Parse command
252
+ results = parser.parse(cmd)
253
+
254
+ table = Table(show_header=True, header_style="bold cyan")
255
+ table.add_column("Command")
256
+ table.add_column("Language")
257
+ table.add_column("Modifiers")
258
+ table.add_column("Task")
259
+
260
+ for result in results:
261
+ table.add_row(
262
+ parser.COMMANDS.get(result.command, result.command or "?"),
263
+ parser.LANGUAGES.get(result.language, result.language) if result.language else "-",
264
+ ", ".join([parser.MODIFIERS.get(m, m) for m in result.modifiers]) if result.modifiers else "-",
265
+ result.task or "-"
266
+ )
267
+
268
+ console.print(table)
269
+
270
+ # Show V4 equivalent
271
+ console.print("\n[dim]V4.0 Equivalent:[/dim]")
272
+ for i, r in enumerate(results):
273
+ console.print(f" [{i+1}] [dim]{parser.to_v4_format(r)}[/dim]")
274
+
275
+ except KeyboardInterrupt:
276
+ console.print("\n[yellow]Use 'exit' to quit[/yellow]")
277
+ except Exception as e:
278
+ console.print(f"[red]Error: {e}[/red]")
279
+
280
+
281
+ @cli.command()
282
+ def examples():
283
+ """Show real-world V5.0 ULTRA examples with benchmarks."""
284
+
285
+ parser = CompTextParserV5()
286
+
287
+ console.print(Panel.fit(
288
+ "[bold cyan]CompText V5.0 ULTRA - Real-World Examples[/bold cyan]",
289
+ border_style="cyan"
290
+ ))
291
+
292
+ examples = [
293
+ {
294
+ "name": "Simple Code Generation",
295
+ "natural": "Write a Python function for Fibonacci",
296
+ "v5": "C;P:FIB"
297
+ },
298
+ {
299
+ "name": "Test Generation with Modifiers",
300
+ "natural": "Write comprehensive unit tests for the Fibonacci function in Python with edge cases",
301
+ "v5": "T;P;R:FIB"
302
+ },
303
+ {
304
+ "name": "Multi-Task Batch",
305
+ "natural": "Summarize the repository, write Python Fibonacci, and explain why CompText is fast",
306
+ "v5": "B:[D:SUM]|[C;P:FIB]|[E;C:WHY]"
307
+ },
308
+ {
309
+ "name": "Complex Workflow",
310
+ "natural": "Analyze the codebase structure, fix TypeScript memory leaks, optimize database queries, and generate API documentation",
311
+ "v5": "B:[A:STRUCT]|[F;T:MEM]|[O;S:Q]|[D:API]"
312
+ }
313
+ ]
314
+
315
+ for ex in examples:
316
+ stats = parser.calculate_token_reduction(ex['natural'], ex['v5'])
317
+
318
+ console.print(f"\n[bold yellow]{ex['name']}[/bold yellow]")
319
+ console.print(f"[dim]Natural:[/dim] {ex['natural']}")
320
+ console.print(f"[dim]V5.0:[/dim] [cyan]{ex['v5']}[/cyan]")
321
+ console.print(f"[green]Reduction: {stats['reduction_percent']}% ({stats['natural_tokens']} -> {stats['v5_tokens']} tokens)[/green]")
322
+
323
+
324
+ def main():
325
+ """Main CLI entry point."""
326
+ cli()
327
+
328
+
329
+ if __name__ == '__main__':
330
+ main()